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寫入數(shù)據(jù)的時(shí)候属拾,我們比較容易冷溶。
但當(dāng)我們從HDF5讀入數(shù)據(jù)的時(shí)候,我們需要從HDF5文件中查找數(shù)據(jù)的類型纯衍、維度苗胀、rank等等信息,才能有信息讀取正確的數(shù)據(jù)柒巫。
并且,除了寫入數(shù)據(jù),HDF5還要組別的概念刨疼,大體是分區(qū) / 文件夾的意思。
HDF5-Fortran
我在國(guó)內(nèi)的HDF5-Fortran庫(kù)幾乎完全搬運(yùn)的geospace-code/h5fortran
亭畜。
主要方便自己寫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ù)寫入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
以上示例,嘗試寫入一些數(shù)據(jù)和讀取對(duì)應(yīng)數(shù)據(jù)劲藐,大致完成了閉環(huán)讀寫HDF5的操作樟凄。
h5dump
HDF5還提供了一系列小工具,如h5dump缝龄,我們可以通過這個(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的操作,可以通過
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ù)富纸、快速讀寫等應(yīng)用場(chǎng)景旨椒。