Last active
November 5, 2020 11:00
-
-
Save markdouthwaite/93e09c346c1b5dc19089b999b79ffec2 to your computer and use it in GitHub Desktop.
A simple Go module for writing a single array of 64 bit floating point numbers to a HDF5 formatted file (with attributes).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"gonum.org/v1/hdf5" | |
"math/rand" | |
"time" | |
) | |
// generate an array of random numbers in range | |
func randomFloat64(low float64, high float64, size int) []float64 { | |
res := make([]float64, size) | |
for i := range res { | |
res[i] = low + rand.Float64() * (high - low) | |
} | |
return res | |
} | |
// write image data to HDF5 file | |
func writeImageData(fileName string, image []float64, height int, width int) { | |
// create a new HDF5 file | |
file, err := hdf5.CreateFile(fileName, hdf5.F_ACC_TRUNC) | |
if err != nil { | |
panic(err) | |
} | |
defer file.Close() | |
// create a Dataspace of size 'len(image)' | |
dims := []uint{uint(len(image))} | |
space, err := hdf5.CreateSimpleDataspace(dims, nil) | |
if err != nil { | |
panic("Failed to create image Dataspace") | |
} | |
// create a Datatype from the image type | |
dtype, err := hdf5.NewDatatypeFromValue(image[0]) | |
if err != nil { | |
panic("Failed to create dtype") | |
} | |
// create the Dataset itself | |
dataset, err := file.CreateDataset("data", dtype, space) | |
// write the image data to the dataset | |
err = dataset.Write(&image) | |
if err != nil { | |
panic("Failed to write image data") | |
} | |
scalar, err := hdf5.CreateDataspace(hdf5.S_SCALAR) | |
if err != nil { | |
panic("Failed to create scalar dataspace") | |
} | |
var timestamp = time.Now().UnixNano() / 1000000000 // time in seconds | |
heightAttr, err := dataset.CreateAttribute("height", hdf5.T_NATIVE_UINT32, scalar) | |
heightAttr.Write(&height, hdf5.T_NATIVE_UINT32) | |
heightAttr.Close() | |
widthAttr, err := dataset.CreateAttribute("width", hdf5.T_NATIVE_UINT32, scalar) | |
widthAttr.Write(&width, hdf5.T_NATIVE_UINT32) | |
widthAttr.Close() | |
timeAttr, err := dataset.CreateAttribute("timestamp", hdf5.T_NATIVE_FLOAT, scalar) | |
timeAttr.Write(×tamp, hdf5.T_NATIVE_FLOAT) | |
timeAttr.Close() | |
// close dataset & file | |
dataset.Close() | |
file.Close() | |
} | |
func main(){ | |
height := 10 | |
width := 10 | |
arr := randomFloat64(0.0, 1.0, height * width) | |
writeImageData("alt.h5", arr, height, width) | |
fmt.Println(arr) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment