[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: can structures be saved to an HDF file?



Henrik E. Nilsen wrote:
> It seems to me that it would be very useful to be able to save a whole
> structure to an HDF file.  Anyone know if such a routine exists?

The following program isn't fancy, but it's cheap.

;---cut here---
PRO HDF_SAVE_STRUCT, FILE, DATA

;- Check arguments
if n_elements(file) eq 0 then message, 'FILE is undefined'
if n_elements(data) eq 0 then message, 'DATA is undefined'

;- Get information about the input structure
info = size(data)
ndim = info[0]
type = info[ndim + 1]
if type ne 8 then message, 'DATA must be a structure'
ntags = n_tags(data)
names = tag_names(data)

;- Create the HDF file
hdfid = hdf_sd_start(file, /create)

;- Loop over each variable in the structure
for index = 0, ntags - 1 do begin

  ;- Get information about this variable
  info = size(data.(index))
  ndim = info[0]
  if ndim gt 0 then dims = [info[1:ndim]] else dims = [1]
  type = info[ndim + 1]
  nele = info[ndim + 2]

  ;- Create the variable if supported by HDF
  saveflag = 1
  case type of
    1  : varid = hdf_sd_create(hdfid, names[index], dims, /byte)
    2  : varid = hdf_sd_create(hdfid, names[index], dims, /int)
    3  : varid = hdf_sd_create(hdfid, names[index], dims, /long)
    4  : varid = hdf_sd_create(hdfid, names[index], dims, /float)
    5  : varid = hdf_sd_create(hdfid, names[index], dims, /double)
    7  : varid = hdf_sd_create(hdfid, names[index], $
           [strlen(data.(index))], /string)
    else : begin
      print, 'This variable type is not supported by HDF:'
      help, data.(index)
      saveflag = 0
    end
  endcase

  ;- Save the variable to the file
  if saveflag eq 1 then begin
    hdf_sd_adddata, varid, data.(index)
    hdf_sd_endaccess, varid
  endif

endfor

;- Close the HDF file
hdf_sd_end, hdfid

END
;---cut here---

IDL> data = {image:dist(256), name:'Test Image', flag:1, valid_range:[0L,
200L]}
IDL> hdf_save_struct, 'test.hdf', data
IDL> hdf_info, 'test.hdf'

Cheers,
Liam.
http://cimss.ssec.wisc.edu/~gumley