登录
首页 >  Golang >  Go问答

使用GO语言读取HDF5属性时,如何处理可能的两种不同数据类型?

来源:stackoverflow

时间:2024-03-25 13:15:44 146浏览 收藏

在使用 Go 语言读取 HDF5 属性时,需要处理两种不同的数据类型:双精度型和浮点型。Go 语言包“gonum.org/v1/hdf5”的读取方法“read”需要指定一个数据类型,但属性本身没有提供获取数据类型的方法。通过比较属性类型的标识符和 HDF5 标准数据类型标识符,可以确定属性类型。

问题内容

作为评估项目的一部分,我正在将现有的 c++ 应用程序移植到 go。作为此过程的一部分,我需要读取两个数据集属性,这些属性在某些文件中存储为双精度型,在某些文件中存储为浮点型。我用来处理这个问题的 c++ 代码如下所示(我们在 debian linux 上使用 libhdf5-cpp-100)。

const auto att = dataset.openattribute(attributename);
if (att.getdatatype() == h5::predtype::native_double) {
    att.read(att.getdatatype(), &attributevalue);
}
else if (att.getdatatype() == h5::predtype::native_float) {
    float temp = 0.f;
    att.read(att.getdatatype(), &temp);
    attributevalue = static_cast(temp);
}
else {
    // we throw an exception indicating we don't support the type
}

我的问题是我在 go 中编写等效内容时遇到困难。 (我使用的是包“gonum.org/v1/hdf5”。)读取方法看起来很简单:

func (s *attribute) read(data interface{}, dtype *datatype) error

但是我正在努力确定要作为数据类型传递的内容,因为属性类型似乎没有 getdatatype 方法。我看到的最接近的是:

func (s *attribute) gettype() identifier

但这并不返回数据类型,而是返回标识符。我尝试了以下比较,假设给定标识符我可以确定数据类型:

if attr.GetType().ID() == hdf5.T_NATIVE_DOUBLE.ID() {
    // handle as a double
}

但这不起作用。从 gettype() 返回的 id 与 double 或 float 的 id 不同。

我已经浏览了 https://godoc.org/gonum.org/v1/hdf5 的在线文档,但无法找到问题的解决方案。 (或者使用 go 读取 hdf5 属性的任何示例。)

有人成功做过这样的事情吗?或者大多数示例只是假设类型而不是查询它?


解决方案


我已经证实了我的怀疑,现在有了正确的答案。本质问题是我使用 c++ api 时出现了错误(这会导致在某些情况下只写入 double 的 1/2),而我本质上是试图在 go 中重复该错误。其实解决办法很简单。

传入属性 read 方法的属性类型不是属性的类型,而是您希望其在存储在内存中时转换为的类型。这意味着我的 c++ 代码应该更简单,因为不需要检查属性类型,也不需要 static_cast 它到结果。要读取和存储属性值,依靠 hdf5 执行转换,如果属性不可转换为双精度值,则抛出合适的异常,就像

const auto att = dataset.openattribute("my attribute name");
att.read(h5::predtype::native_double, &attributevalue);

go 版本需要更多工作,因为我们必须手动管理对象生命周期和错误条件,但就是这样。 (请注意,我假设“...处理错误...”也涉及提前退出,否则需要额外的 if 语句来检查 att 是否不为 nil。)

att, err := dataSet.OpenAttribute("my attribute name")
if err != nil {
    ...handle the error...
}

err = att.Read(&attributeValue, hdf5.T_NATIVE_DOUBLE)
if err != nil {
    ...handle the error...
}

err = att.Close()
if err != nil {
    ...handle the error...
}

以上就是《使用GO语言读取HDF5属性时,如何处理可能的两种不同数据类型?》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>