zoziha (zuo.zhihua@qq.com)
哈爾濱工程大學(xué) 船舶工程學(xué)院 船舶與海洋結(jié)構(gòu)物設(shè)計(jì)制造 在讀博士
2022年3月 深圳市羅湖區(qū)
摘要
我在gitee上設(shè)置了一個(gè)HDF5-Fortran的庫(kù),目前主要適用于msys2-gfortran-11環(huán)境。
這里介紹一下它的簡(jiǎn)單用法。
運(yùn)行環(huán)境:Windows 10, i5 8250u, Msys2 GFortran 11, HDF5 1.12.1
??
hdf5-fortran: A collection of commonly used functions for HDF5 datebase for Fortran. (gitee.com)
基本思路
當(dāng)我們向HDF5寫(xiě)入數(shù)據(jù)的時(shí)候,我們比較容易。
但當(dāng)我們從HDF5讀入數(shù)據(jù)的時(shí)候,我們需要從HDF5文件中查找數(shù)據(jù)的類(lèi)型、維度、rank等等信息,才能有信息讀取正確的數(shù)據(jù)。
并且,除了寫(xiě)入數(shù)據(jù),HDF5還要組別的概念,大體是分區(qū) / 文件夾的意思。
HDF5-Fortran
我在國(guó)內(nèi)的HDF5-Fortran庫(kù)幾乎完全搬運(yùn)的geospace-code/h5fortran。
主要方便自己寫(xiě)HDF5。
program example2
! 引入例程
use h5fortran, only: hdf5_file, hsize_t
implicit none(type, external)
character(:), allocatable :: filename
integer :: i32
integer(hsize_t), allocatable :: i(:)
type(hdf5_file) :: h5f
real :: y(2,2)
filename = 'h5fortran_example2.h5'
! 數(shù)據(jù)寫(xiě)入hdf5文件
call h5f%open(filename, action='w')
call h5f%write('/x', 123)
call h5f%write_group('/z') ! 創(chuàng)建一個(gè)組`/z`
call h5f%write('/z/y', reshape([real :: 1, 2, 3, 4], [2, 2]))
call h5f%close()
call h5f%open(filename, action='r')
call h5f%read('/x', i32)
call h5f%shape('/z/y', i) ! 查看數(shù)據(jù)形狀
print *, i
call h5f%read('/z/y', y)
if (i32 /= 123) error stop 'incorrect value read'
print *, y(1, 1)
print *, 'OK: example 2'
end program
以上示例,嘗試寫(xiě)入一些數(shù)據(jù)和讀取對(duì)應(yīng)數(shù)據(jù),大致完成了閉環(huán)讀寫(xiě)HDF5的操作。
h5dump
HDF5還提供了一系列小工具,如h5dump,我們可以通過(guò)這個(gè)小工具查看文件內(nèi)容:
$ h5dump -g z h5fortran_example2.h5
HDF5 "h5fortran_example2.h5" {
GROUP "z" {
DATASET "y" {
DATATYPE H5T_IEEE_F32LE
DATASPACE SIMPLE { ( 2, 2 ) / ( 2, 2 ) }
DATA {
(0,0): 1, 2,
(1,0): 3, 4
}
}
}
}
不會(huì)h5dump的操作,可以通過(guò)
h5dump --help查找快速幫助。
小結(jié)
更詳細(xì)的HDF5操作,還是得多用和讀對(duì)應(yīng)幫助文檔。
HDF5是著名的科學(xué)數(shù)據(jù)存儲(chǔ)格式,它主要存儲(chǔ)整型和浮點(diǎn)型數(shù)據(jù),在與軟件數(shù)據(jù)交互性上相對(duì)可靠,而且是以二進(jìn)制存儲(chǔ),適合大數(shù)據(jù)、快速讀寫(xiě)等應(yīng)用場(chǎng)景。