Fanning Software Consulting

Write Structure Variable to HDF5 File

QUESTION: It is extraordinarily easy to read a structure from an HDF5 file with the H5_PARSE function, with the READ_DATA keyword set, but unless I am very much mistaken, it is a lot harder to write an IDL structure variable to an HDF5 file. How do you do it anyway? I can't figure it out.

ANSWER: You are right. It is a lot harder. Thanks to Dave Haffner who explained it to us in an IDL newsgroup article. Here is how you do it.

First, create an IDL structure variable. It is essential that the structure not contain pointers, complex numbers, or object references, since these are not allowed in HDF5 files.

   IDL> struct = {name:"coyote", age:25, rascal:1B, salary:200000D, girlfriends:FltArr(546)}

To write a structure into an HDF5 file, you need to create compound data type. As with all HDF files, we first create a file identifier, since all communication with the file is done via the file identifier.

   IDL> filename = 'hdf5testfile.h5'
   IDL> fileID = H5F_CREATE(filename)

Next, we create a datatype object by supplying the structure as an argument. This will indicate that we wish to create a compound data type, with the types determined from the fields of the structure.

   IDL> datatypeID = H5T_IDL_CREATE(struct)

The next step is to create a simple (or, in this case, not so simple) data space. As an argument, we require the dimensions of the dataspace. In this case, with a single structure variable, the dimension is 1.

   IDL> dataspaceID = H5S_CREATE_SIMPLE(1)

Now we can create the dataset at a specified location, given as the first argument in the function below. The second argument is the name of the dataset in the file, and the third and fourth arguments are the data type identifier and data space identifier, respectively.

   IDL> datasetID = H5D_CREATE(fileID, 'mydata', datatypeID, dataspaceID)

Finally, we can write the structure into the file, and close the file.

   IDL> H5D_WRITE, datasetID, struct
   IDL> H5F_CLOSE, fileID

It is much easier to read the data out of the file. We simple do this.

   IDL> s = H5_PARSE('hdf5testfile.h5', /READ_DATA)
   IDL> HELP, s.mydata._DATA, /STRUCTURE
   ** Structure <25c8390>, 5 tags, length=2208, data length=2207, refs=2:
      NAME            STRING    'coyote'
      AGE             INT             25
      RASCAL          BYTE         1
      SALARY          DOUBLE           200000.00
      GIRLFRIENDS     FLOAT     Array[546]

Google
 
Web Coyote's Guide to IDL Programming