2

我创建了一个包含 3 个双精度数和一个布尔值的数组,并使用以下方法numpy将它们写入文件h5py

import numpy as np
import h5py

data = np.zeros(10, dtype=[("THETA",np.double),("PHI",np.double),("PSI",np. double),("FLAG",np.bool)])

with h5py.File("testout.h5") as f:
    f.create_dataset("data", data=data)

h5py为布尔字段创建枚举类型:

HDF5 "testout.h5" {
GROUP "/" {
   DATASET "data" {
      DATATYPE  H5T_COMPOUND {
         H5T_IEEE_F64LE "THETA";
         H5T_IEEE_F64LE "PHI";
         H5T_IEEE_F64LE "PSI";
         H5T_ENUM {
            H5T_STD_I8LE;
            "FALSE"            0;
            "TRUE"             1;
         } "FLAG";
      }
      DATASPACE  SIMPLE { ( 10 ) / ( 10 ) }
   }
}
}

现在我需要使用 C 读取这个文件,事情变得复杂了:

typedef enum {
    false = 0;
    true
} bool;

typedef struct {
    double THETA, PHI, PSI;
    bool FLAG;
} pointing_t;

我不明白如何定义具有枚举的类型:

hid_t memtype = H5Tcreate (H5T_COMPOUND, sizeof(pointing_t));
H5Tinsert (memtype, "THETA", HOFFSET (pointing_t, THETA),  H5T_NATIVE_DOUBLE);
H5Tinsert (memtype, "PHI", HOFFSET (pointing_t, PHI),  H5T_NATIVE_DOUBLE);
H5Tinsert (memtype, "PSI", HOFFSET (pointing_t, PSI),  H5T_NATIVE_DOUBLE);
# this should be an ENUM!!
H5Tinsert (memtype, "FLAG", HOFFSET (pointing_t, FLAG),  H5T_NATIVE_DOUBLE);

我在 gist 上粘贴了一个完整的“不工作”示例,该示例尝试读取使用前面的 python 片段创建的 hdf5 文件:

http://gist.github.com/3168909

有人有建议吗?谢谢!

4

2 回答 2

4

处理此问题的更简单方法是使用 1 字节无符号字符来存储布尔类型。在 h5py 中,您可以通过调用以下命令来存储布尔数组

import h5py
import numpy as np

# Generate some boolean data

shape = (100, 100)
data = np.zeros(shape, dtype=np.bool)

# Save the boolean data as uchars

f = h5py.File('foo.h5')
dset = f.create_dataset('/bar', dtype='u1', shape=shape)
dset[:] = data[:]

In C/C++, you can read the uchars into a bool* array, and they will be interpreted correctly. This is because they are 1-byte, just like C/C++ boolean values, and anything with nonzero bits is interpreted in C/C++ as true.

于 2013-10-16T19:59:09.020 回答
2

找到了解决办法,需要在hdf5中创建一个枚举类型:

#define CPTR(VAR,CONST) ((VAR)=(CONST),&(VAR))
hid_t boolenumtype = H5Tcreate(H5T_ENUM, sizeof(bool));
status = H5Tenum_insert(boolenumtype, "FALSE",   CPTR(val, FALSE ));
printf ("H5Tenum_insert (FALSE): %i\n", status);
status = H5Tenum_insert(boolenumtype, "TRUE",   CPTR(val, TRUE ));
printf ("H5Tenum_insert (TRUE): %i\n", status);

然后将其添加到 memtype 中:

H5Tinsert (memtype, "FLAG", HOFFSET (pointing_t, FLAG),  boolenumtype);

github上的示例现在正在运行。

于 2012-07-24T11:01:11.743 回答