如何使用python3创建一个指向一个外部hdf5文件的链接数组



我想知道是否可以对hdf5/cxi文件执行以下操作:

  • 有一个外部h5文件,用于存储4D维度的numpy数组
  • 有另一个cxi文件,其中高度要求添加组,该组将包含h5文件的外部链接数组

预计cxi会得到这样的东西:

Group1/subgroup  {num, ExternalLink to h5 file}

其中num是所需的链接数组的长度。

我试着做:

import h5py as h5
import numpy as np
h5_file = sys.argv[1]
h5path = sys.argv[2]
cxi_file = sys.argv[3]
cxi_path = sys.argv[4]
num = sys.argv[5]
link = h5.ExternalLink(h5_file, h5path)
l = np.array([link] * num)
with h5.File(cxi_file, 'a') as f:
dset = f.create_dataset(cxi_path, (num,))
for i in range(num):
dset[i] = l[i]

但它没有起作用。我还尝试了dset = f.create_dataset(path_to_new_mask,data=l),并列出了这个长度为num的文件,但所有这些步骤都失败了。

如果有人能帮忙,我会非常高兴的。

kitsune_breeze,我回顾了问答;A和评论。有几个领域需要澄清。让我们从外部链接对象或区域引用开始。据我所知,您希望创建外部链接的数据集(也称为数组((每个链接引用不同的HDF5文件(。

Mahsa Hassankashi在4月19日给出的答案描述了如何创建dtype=h5py.ref_dtypedtype=h5py.regionref_dtype的数据集。第一个是对象引用,第二个是区域引用。它们与外部链接不同!此外,示例代码需要h5py 2.10.0,而您使用的是h5py 2.9.0.。(仅供参考,如果您选择使用对象或区域引用,2.9.0中有一个解决方案。(

坏消息是:根据我的测试,您无法创建HDF5外部链接的数据集(或np数组(。以下是查看原因的步骤:

In [1]: import h5py
In [2]: h5fw = h5py.File('SO_61290760.h5',mode='w')
# create an external link object
In [3]: link_obj = h5py.ExternalLink('file1.h5','/')
In [4]: type(link_obj)
Out[4]: h5py._hl.group.ExternalLink
In [5]: link_dtype = type(link_obj)
In [6]: h5fw.create_dataset("MyRefs", (10,), dtype=link_dtype)
Traceback (most recent call last):
...
TypeError: Object dtype dtype('O') has no native HDF5 equivalent

阅读h5py文档,对象和区域引用似乎也是dtype('O')数据类型,并且需要额外的元数据来实现它们。没有提到这是为外部链接做的。因此,我认为您无法创建一个外部链接数组(因为没有数据类型来支持它们(。

也就是说,你仍然可以创建从一个HDF5文件到多个HDF5的外部链接。这里有一个简单的例子(参见方法1:创建外部链接(
如何组合多个.h5文件?

如果您决定使用对象或区域引用,则需要在h5py 2.9.0中使用不同的数据类型规范。
对象引用
2.10.0使用:h5py.ref_dtype
2.9.0使用:h5py.special_dtype(ref=h5py.Reference)
区域引用:
2.10.0使用:h5py.regionref_dtype
2.9.0使用:h5py.special_dtype(ref=h5py.RegionReference)

下面的代码演示2.9.0:中的行为

In [9]: type(h5py.ref_dtype)
Traceback (most recent call last):
...
AttributeError: module 'h5py' has no attribute 'ref_dtype'
In [10]: type(h5py.special_dtype(ref=h5py.Reference))
Out[10]: numpy.dtype
In [11]: type(h5py.regionref_dtype)
Traceback (most recent call last):
...   
AttributeError: module 'h5py' has no attribute 'regionref_dtype'
In [12]: type(h5py.special_dtype(ref=h5py.RegionReference))
Out[12]: numpy.dtype
In [13]: dset = h5fw.create_dataset("MyRefs", (10,), dtype=h5py.special_dtype(ref=h5py.Reference))
In [14]: dset.dtype
Out[14]: dtype('O')

试试

myfile = h5py.File('foo.hdf5','w')
myfile['ext link'] = h5py.ExternalLink("otherfile.hdf5", "/path/to/resource")
dset = f.create_dataset("MyRefs", (100,), dtype=h5py.ref_dtype)

或者:

dset = f.create_dataset("ref", (2,), dtype=h5py.regionref_dtype)
  1. http://docs.h5py.org/en/stable/refs.html#storing-数据集中的引用
  2. http://docs.h5py.org/en/latest/high/group.html#external-链接

相关内容

最新更新