【问题标题】:How to write a dataset of Null Terminated Fixed Length Strings with h5py如何使用 h5py 编写空终止固定长度字符串的数据集
【发布时间】:2016-07-19 07:16:26
【问题描述】:

我有一个 C++ 示例,我正在尝试使用 h5py 进行重现,但它没有按预期工作。我正在使用 h5py 获得空填充字符串,我期望空终止的字符串。

这是我的 C++ 驱动程序...

main.cpp

#include <hdf5.h>

int main(void) {
    auto file = H5Fcreate("test-c.h5", H5F_ACC_TRUNC,
            H5P_DEFAULT, H5P_DEFAULT);
    char strings[5][64] = {
        "please work 0",
        "please work 1",
        "please work 2",
        "please work 3",
        "please work 4"};
    auto H5T_C_S1_64 = H5Tcopy (H5T_C_S1);
    H5Tset_size(H5T_C_S1_64, 64);
    hsize_t dims[1] = {5};
    auto dataspace = H5Screate_simple(1, dims, NULL);
    auto dataset = H5Dcreate(file, "test dataset", H5T_C_S1_64, dataspace,
            H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
    H5Dwrite (dataset, H5T_C_S1_64, H5S_ALL, H5S_ALL, H5P_DEFAULT, strings);
    H5Dclose(dataset);
    H5Sclose(dataspace);
    H5Tclose(H5T_C_S1_64);
    H5Fclose(file);
    return 0;
}

我使用以下 SCons 脚本构建。

SConstruct

env = Environment()
env.Append(LIBS=['hdf5'],
           CPPFLAGS=['-std=c++11'])
env.Program('writeh5', 'main.cpp')

这是我的 python 脚本,我试图用它写出相同的 hdf5 文件。

main.py

import h5py

hdf5 = h5py.File('test-p.h5', 'w')
H5T_C_S1_64 = h5py.h5t.C_S1.copy()
H5T_C_S1_64.set_size(64)
print "Null Terminated String: %s" % (
    H5T_C_S1_64.get_strpad() == h5py.h5t.STR_NULLTERM)
dataset = hdf5.create_dataset('test dataset', (5,),
                              data=['please work %s' % n for n in xrange(5)],
                              dtype=H5T_C_S1_64)
hdf5.close()

我使用的是 python v2.7.11,我已经用 h5py v2.5.0 和 v2.6.0 进行了尝试,结果相同。

>> python --version
Python 2.7.11

>> python -c "import h5py; print h5py.version.version"
2.5.0

>> tree
.
├── main.cpp
├── main.py
└── SConstruct

0 directories, 3 files

>> scons
scons: Reading SConscript files ...
scons: done reading SConscript files.
scons: Building targets ...
g++ -o main.o -c -std=c++11 main.cpp
g++ -o writeh5 main.o -lhdf5
scons: done building targets.

>> tree
.
├── main.cpp
├── main.o
├── main.py
├── SConstruct
└── writeh5

0 directories, 5 files

>> ./writeh5 

>> tree
.
├── main.cpp
├── main.o
├── main.py
├── SConstruct
├── test-c.h5
└── writeh5

0 directories, 6 files

>> python main.py
Null Terminated String: True

>> tree
.
├── main.cpp
├── main.o
├── main.py
├── SConstruct
├── test-c.h5
├── test-p.h5
└── writeh5

0 directories, 7 files

>> h5dump test-c.h5 
HDF5 "test-c.h5" {
GROUP "/" {
   DATASET "test dataset" {
      DATATYPE  H5T_STRING {
         STRSIZE 64;
         STRPAD H5T_STR_NULLTERM;
         CSET H5T_CSET_ASCII;
         CTYPE H5T_C_S1;
      }
      DATASPACE  SIMPLE { ( 5 ) / ( 5 ) }
      DATA {
      (0): "please work 0", "please work 1", "please work 2",
      (3): "please work 3", "please work 4"
      }
   }
}
}

>> h5dump test-p.h5
HDF5 "test-p.h5" {
GROUP "/" {
   DATASET "test dataset" {
      DATATYPE  H5T_STRING {
         STRSIZE 64;
         STRPAD H5T_STR_NULLPAD;
         CSET H5T_CSET_ASCII;
         CTYPE H5T_C_S1;
      }
      DATASPACE  SIMPLE { ( 5 ) / ( 5 ) }
      DATA {
      (0): "please work 0\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000",
      (1): "please work 1\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000",
      (2): "please work 2\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000",
      (3): "please work 3\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000",
      (4): "please work 4\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"
      }
   }
}
}

正如您从上面的输出中看到的,在使用 h5py 时,我仍然以空填充的固定长度字符串结束,即使我指定我想要空终止的固定长度字符串。

那么如何修改我的 python 脚本以在数据集中以空终止的固定长度字符串结束?如果是h5py的bug,有什么解决办法吗?

提前感谢您的帮助。

【问题讨论】:

    标签: python h5py


    【解决方案1】:

    编辑:找到适用于以下“香草”h5py 的解决方案

    在h5py源码中有如下cython code

    cdef TypeStringID _c_string(dtype dt):
        # Strings (fixed-length)
        cdef hid_t tid
    
        tid = H5Tcopy(H5T_C_S1)
        H5Tset_size(tid, dt.itemsize)
        H5Tset_strpad(tid, H5T_STR_NULLPAD)
        return TypeStringID(tid)
    

    我不完全确定它的作用。然而,在注释掉H5Tset_strpad(tid, H5T_STR_NULLPAD) 的行并编译库之后,问题似乎解决了,而python2 setup.py test 没有报告任何意外的失败测试。它是唯一一个不在可变长度字符串上下文中引用H5T_C_S1 的函数。看起来有点像错误。

    因此,一种(hacky)方法是在脚本目录中执行以下命令。

    $ https://github.com/h5py/h5py h5py-source
    $ mkdir fake-root
    $ sed -i '/H5Tset_strpad(tid, H5T_STR_NULLPAD)/d' h5py-source/h5py/h5t.pyx
    $ (cd h5py-source; python2 setup.py install --root fake-root)
    $ mv fake-root/usr/lib/python2.7/site-packages/h5py .
    

    然后,当导入h5py 时,您本地目录中的h5py 将覆盖系统范围内安装的版本。您可能最好在用户站点包、虚拟环境中使用安装或打开问题。

    请注意,应用此修复程序可能会以意想不到的方式破坏事情(我以前从未使用过 hdf5 并且不知道这可能会产生什么影响)。真正的解决方案可能涉及从 dt 加载 strpad。

    编辑

    我做了更多的研究:

    documentation 只列出了 3 种支持的字符串,零填充的固定长度字符串和两种不同的可变长度字符串。没有提到零终止的字符串。所以看起来 h5py 公共 api 不支持以 null 结尾的字符串(即使代码中提到了 null c 字符串)。

    接下来,dtype 参数应该是一个有效的 numpy dtype。没有明确提及对 H5T 的支持。然而,不知何故,H5T 类型仍然被解释为字符串。更改填充不会更改在TypeStringID 中收到的dtype 的任何属性。

    在 dataset.py:736 中发生了 numpy dtype 到 h5t 类型的转换:

    if isinstance(dtype, Datatype):                                                                              
        # Named types are used as-is                                            
        tid = dtype.id                                                          
        dtype = tid.dtype  # Following code needs this                          
    else:                                                                       
        # Validate dtype                                                        
        if dtype is None and data is None:                                      
            dtype = numpy.dtype("=f4")                                          
        elif dtype is None and data is not None:                                
            dtype = data.dtype                                                  
        else:                                                                   
            dtype = numpy.dtype(dtype)                                                                        
        tid = h5t.py_create(dtype, logical=1)
    

    其中numpy.dtype(H5T_C_S1) 给出了一个带有kind='S' 的dtype。 接下来,对h5t.py_create(dtype, logical=1) 的调用将其从上面分派给_c_string(dt)。因此,修复确实会破坏事情,因为所有固定长度的字符串最终都会被空终止。

    但是,这也显示了一种更好的解决方案。通过从 H5T tid 构造 dtype,我们可以绕过 numpy.dtype 转换。

    此代码在普通 h5py 安装中正常工作:

    import h5py
    
    hdf5 = h5py.File('test-p.h5', 'w')
    
    tid = h5py.h5t.C_S1.copy()
    tid.set_size(64)
    H5T_C_S1_64 = h5py.Datatype(tid)
    
    dataset = hdf5.create_dataset('test dataset', (5,),
                                  data=['please work %s' % n for n in range(5)],
                                  dtype=H5T_C_S1_64)
    hdf5.close()
    

    这也允许您使用任何您想要的填充方案。但是,我找不到它的文档,所以 api 将来可能会改变。

    【讨论】:

    • 它确实看起来像H5Tset_strpad(tid, H5T_STR_NULLPAD) 行上的一个错误,将字符串填充硬编码为空填充,但我的猜测是该行应该是H5Tset_strpad(tid, dt.strpad) 或类似的东西。您的修复对我来说不是一个可行的解决方案,但看起来您确实找到了错误的原因。
    • @KennethE.Bellock 我找到了一个无需更改 h5py 即可工作的解决方案。这可行吗?
    • 太棒了!它完美地工作!感谢@Lennart 的原始答案和编辑,这正是我想要的。
    猜你喜欢
    • 2015-06-14
    • 1970-01-01
    • 2016-01-19
    • 2018-09-20
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    • 2020-01-14
    • 2011-12-07
    相关资源
    最近更新 更多