Пример #1
0
/* read attribute value */
char* H5Dataset_read_attr_value(hid_t aid)
{
    hid_t asid=-1, atid=-1;
    int i, rank;
    hsize_t *dims;
    size_t size=1;
    char *attr_buf=NULL;
  
    asid = H5Aget_space(aid);
    atid = H5Aget_type(aid);
    rank = H5Sget_simple_extent_ndims(asid);

    if (rank > 0) {
        dims = (hsize_t *)malloc(rank * sizeof(hsize_t));
        H5Sget_simple_extent_dims(asid, dims, NULL);
        for (i=0; i<rank; i++) {
            size *= (size_t)dims[i];
            free(dims);
        }
        size *= H5Tget_size(atid);
        attr_buf = (char *)malloc(size);

        if (H5Aread( aid, atid, attr_buf) < 0) {
            free(attr_buf);
            attr_buf = NULL;
        }

    }
    
    if( atid > 0) H5Tclose(atid);
    if (asid > 0) H5Sclose(asid);
 
    return attr_buf;
}
Пример #2
0
escdf_errno_t utils_hdf5_check_attr(hid_t loc_id, const char *name,
                                    hsize_t *dims, unsigned int ndims,
                                    hid_t *attr_pt)
{
    hid_t attr_id, dtspace_id;

    if ((attr_id = H5Aopen(loc_id, name, H5P_DEFAULT)) < 0)
        RETURN_WITH_ERROR(attr_id);

    /* Check space dimensions. */
    if ((dtspace_id = H5Aget_space(attr_id)) < 0) {
        DEFER_FUNC_ERROR(dtspace_id);
        goto cleanup_attr;
    }
    if (utils_hdf5_check_shape(dtspace_id, dims, ndims) != ESCDF_SUCCESS) {
        goto cleanup_dtspace;
    }
    H5Sclose(dtspace_id);
    if (attr_pt)
        *attr_pt = attr_id;
    else
        H5Aclose(attr_id);
    return ESCDF_SUCCESS;

    cleanup_dtspace:
    H5Sclose(dtspace_id);
    cleanup_attr:
    H5Aclose(attr_id);
    return ESCDF_ERROR;
}
// JRC: This fat interface may not scale?  What about
// scalar attributes?
herr_t VsH5Attribute::getDoubleVectorValue(std::vector<double>* dvals) {
  herr_t err = 0;
  size_t npoints;
  hid_t atype = H5Aget_type(getId());
  H5T_class_t type = H5Tget_class(atype);
  hid_t aspace = H5Aget_space(getId());
  size_t rank = H5Sget_simple_extent_ndims(aspace);

  if (type != H5T_FLOAT) {
    VsLog::warningLog() <<"VsH5Attribute::getDoubleVectorValue() - Requested attribute " <<getShortName()
         <<" is not a floating point vector." <<std::endl;
    dvals->resize(0);
    return -1;
  }
  
  if (rank == 0) {
    dvals->resize(1);
    double v;
    err = H5Aread(getId(), H5T_NATIVE_DOUBLE, &v);
    (*dvals)[0] = v;
    return err;
  }
  
  // rank>0
  npoints = H5Sget_simple_extent_npoints(aspace);
  double* v = new double[npoints];
  err = H5Aread(getId(), H5T_NATIVE_DOUBLE, v);
  dvals->resize(npoints);
  for (size_t i = 0; i<npoints; ++i) {
    (*dvals)[i] = v[i];
  }
  delete [] v;
  
  return err;
}
Пример #4
0
/*-------------------------------------------------------------*/
static void validateFloat3Attribute(pNXVcontext self,
	hid_t dpField, char *name)
{
	hid_t attID, attType, attSpace;
	H5T_class_t h5class;
	hsize_t dims[2], maxDims[2];
	char fname[512];

	memset(fname,0,sizeof(fname));

	H5Iget_name(dpField,fname,sizeof(fname));

	if(!H5LTfind_attribute(dpField,name)){
			NXVsetLog(self,"sev","error");
			NXVprintLog(self,"message",
				"Missing attribute %s on %s",
				name, fname);
			NXVlog(self);
			self->errCount++;
	} else {
		attID = H5Aopen(dpField,name,H5P_DEFAULT);
		assert(attID >= 0);
		attType = H5Aget_type(attID);
		assert(attType >= 0);
		h5class = H5Tget_class(attType);
		if(h5class != H5T_FLOAT){
			NXVsetLog(self,"sev","error");
			NXVprintLog(self,"message",
				"%s attribute on %s is of wrong type, expected float",
				name, fname);
			NXVlog(self);
			self->errCount++;
		} else {
			attSpace = H5Aget_space(attID);
			if(H5Sget_simple_extent_ndims(attSpace) != 1){
				NXVsetLog(self,"sev","error");
				NXVprintLog(self,"message",
					"%s attribute on %s is of wrong rank, expected 1",
					name, fname);
				NXVlog(self);
				self->errCount++;
			} else {
				H5Sget_simple_extent_dims(attSpace,dims,maxDims);
				if(dims[0] != 3){
					NXVsetLog(self,"sev","error");
					NXVprintLog(self,"message",
						"%s attribute on %s is of wrong size, expected 3",
						name, fname);
					NXVlog(self);
					self->errCount++;
				}
			}
			H5Sclose(attSpace);
		}
		H5Tclose(attType);
		H5Aclose(attID);
	}
}
Пример #5
0
/* fetch num_cols and the col for a particular trackname */
void get_cols(chromosome_t *chromosome, char *trackname, hsize_t *num_cols,
              hsize_t *col) {
  hid_t attr, root, dataspace, datatype;
  hsize_t data_size, cell_size, num_cells;
  char *attr_data;

  /* Tracknames are stored in the attributes of the root group of each file */
  root = H5Gopen(chromosome->h5group, "/", H5P_DEFAULT);
  assert(root >= 0);

  attr = H5Aopen_name(root, "tracknames");
  assert(attr >= 0);

  dataspace = H5Aget_space(attr);
  assert(dataspace >= 0);

  assert(H5Sget_simple_extent_dims(dataspace, num_cols, NULL) == 1);
  assert(H5Sclose(dataspace) >= 0);

  if (trackname && col) {
    datatype = H5Aget_type(attr);
    assert(datatype >= 0);
    assert(H5Tget_class(datatype) == H5T_STRING);

    cell_size = H5Tget_size(datatype);
    assert(cell_size > 0);

    data_size = H5Aget_storage_size(attr);
    assert(data_size > 0);

    num_cells = data_size / cell_size;

    /* allocate room for tracknames */
    attr_data = xmalloc(data_size);
    assert(attr_data);

    assert(H5Aread(attr, datatype, attr_data) >= 0);

    *col = 0;
    for (*col = 0; *col <= num_cells; (*col)++) {
      if (*col == num_cells) {
        fprintf(stderr, "can't find trackname: %s\n", trackname);
        free(attr_data);
        exit(EXIT_FAILURE);
      } else {
        if (!strncmp(attr_data + (*col * cell_size), trackname, cell_size)) {
          break;
        }
      }
    }

    /* clean up read tracknames */
    free(attr_data);
  }

  assert(H5Aclose(attr) >= 0);
}
Пример #6
0
H5Dataspace & H5Attribute::getSpace()
{
    hid_t space = H5Aget_space(attr);
    if (space < 0)
    {
        throw H5Exception(__LINE__, __FILE__, _("Cannot get the attribute dataspace"));
    }

    return *new H5Dataspace(*this, space);
}
Пример #7
0
/*
 * Class:     hdf_hdf5lib_H5
 * Method:    H5Aget_space
 * Signature: (J)J
 */
JNIEXPORT jlong JNICALL
Java_hdf_hdf5lib_H5__1H5Aget_1space
    (JNIEnv *env, jclass clss, jlong attr_id)
{
    hid_t retVal = -1;

    retVal = H5Aget_space((hid_t)attr_id);
    if (retVal < 0)
        h5libraryError(env);

    return (jlong)retVal;
} /* end Java_hdf_hdf5lib_H5__1H5Aget_1space */
Пример #8
0
static herr_t get_attribute_info(hid_t obj_id,
                                 const char *attr_name,
                                 hsize_t *dims,
                                 H5T_class_t *type_class,
                                 size_t *type_size,
                                 hid_t *type_id)
{
    hid_t attr_id;
    hid_t space_id;
    herr_t status;
    int rank;

    /* Open the attribute. */
    attr_id = H5Aopen_name(obj_id, attr_name);
    if (attr_id < 0)
        return -1;

    /* Get an identifier for the datatype. */
    *type_id = H5Aget_type(attr_id);

    /* Get the class. */
    *type_class = H5Tget_class(*type_id);

    /* Get the size. */
    *type_size = H5Tget_size(*type_id);

    /* Get the dataspace handle */
    space_id = H5Aget_space(attr_id);
    if (space_id < 0)
        goto out;

    /* Get dimensions */
    rank = H5Sget_simple_extent_dims(space_id, dims, NULL);
    if (rank < 0)
        goto out;

    /* Terminate access to the dataspace */
    status = H5Sclose(space_id);
    if (status < 0)
        goto out;

    /* End access to the attribute */
    status = H5Aclose(attr_id);
    if (status < 0)
        goto out;

    return 0;
out:
    H5Tclose(*type_id);
    H5Aclose(attr_id);
    return -1;
}
Пример #9
0
void
ReadStringsT( hid_t iParent,
              const std::string &iAttrName,
              size_t iNumStrings,
              StringT *oStrings )
{
    ABCA_ASSERT( iParent >= 0, "Invalid parent in ReadStringsT" );

    // Open the attribute.
    hid_t attrId = H5Aopen( iParent, iAttrName.c_str(), H5P_DEFAULT );
    ABCA_ASSERT( attrId >= 0,
                 "Couldn't open attribute named: " << iAttrName );
    AttrCloser attrCloser( attrId );

    // Checking code.
    {
        hid_t attrFtype = H5Aget_type( attrId );
        DtypeCloser dtypeCloser( attrFtype );

        hid_t nativeDtype = GetNativeDtype<CharT>();
        ABCA_ASSERT( H5Tget_class( attrFtype ) ==
                     H5Tget_class( nativeDtype ) &&

                     H5Tget_sign( attrFtype ) ==
                     H5Tget_sign( nativeDtype ),

                     "Invalid datatype for stringT" );
    }

    hid_t attrSpace = H5Aget_space( attrId );
    ABCA_ASSERT( attrSpace >= 0,
                 "Couldn't get dataspace for attribute: " << iAttrName );
    DspaceCloser dspaceCloser( attrSpace );

    hssize_t numPoints = H5Sget_simple_extent_npoints( attrSpace );
    ABCA_ASSERT( numPoints > 0,
                 "Degenerate string dimensions in ReadStringsT" );

    // Create temporary char storage buffer.
    std::vector<CharT> charStorage( ( size_t )( 1 + numPoints ),
                                    ( CharT )0 );

    // Read into it.
    herr_t status = H5Aread( attrId, GetNativeDtype<CharT>(),
                             ( void * )&charStorage.front() );
    ABCA_ASSERT( status >= 0, "Couldn't read from attribute: " << iAttrName );

    // Extract 'em.
    ExtractStrings( oStrings, ( const CharT * )&charStorage.front(),
                    1 + numPoints, iNumStrings );
}
Пример #10
0
void getDims(hid_t id, bool isDataset, std::vector<int>& dims) {
  hid_t space;
  if (!isDataset) space = H5Aget_space(id);
  else space = H5Dget_space(id);
  size_t rank = H5Sget_simple_extent_ndims(space);
  std::vector<hsize_t> sdim(rank);
  if (rank > 0) {
    H5Sget_simple_extent_dims(space, &sdim[0], NULL);
  }
  dims.resize(rank);
  for (size_t i = 0; i < rank; ++i) {
    dims[i] = sdim[i];
  }
}
Пример #11
0
/*----------------------------------------------------------------------------
 * Name:        h5aget_space_c
 * Purpose:     Call H5Aget_space to get attribute's dataspace
 * Inputs:      attr_id - attribute identifier
 * Outputs:     space_id - dataspace identifier
 * Returns:     0 on success, -1 on failure
 * Programmer:  Elena Pourmal
 *              Thursday, August 12, 1999
 * Modifications:
 *---------------------------------------------------------------------------*/
int_f
nh5aget_space_c (hid_t_f *attr_id, hid_t_f *space_id)
{
    int_f ret_value=0;          /* Return value */

     /*
      * Call H5Aget_space function.
      */
     if ((*space_id = (hid_t_f)H5Aget_space((hid_t)*attr_id)) < 0)
         HGOTO_DONE(FAIL);

done:
     return ret_value;
}
Пример #12
0
estatus_t
e5_read_attr_list(
    hid_t e5_group_id, e5_attr* e5_attr_list)
{
    int i;
    estatus_t status = E5_SUCCESS;

    hid_t h5_type;
    hid_t h5_native_type;
    hid_t h5_space;

    hid_t e5_attribute_id;

    for(i = 0; e5_attr_list && e5_attr_list[i].name != 0; i++)
    {
        e5_attr *attr = &e5_attr_list[i];
        if(attr->name == 0 || strlen(attr->name) < 1)
            continue;

        e5_info(e5_group_id, "Reading attribute [name='%s']\n", attr->name);

        if(H5Aexists(e5_group_id, attr->name) <= 0)
        {
            status = E5_INVALID_ATTRIBUTE;
            e5_error(e5_group_id, status, "Invalid name requested for attribute [type='%d', name='%s', value='%p']\n",  attr->type, attr->name, attr->value);
            continue;
        }

        e5_attribute_id = H5Aopen(e5_group_id, attr->name, H5P_DEFAULT);
        h5_type = H5Aget_type(e5_attribute_id);
        h5_space = H5Aget_space(e5_attribute_id);
        h5_native_type = e5_get_native_h5_type(h5_type);

        attr->type = e5_convert_hdf_type(h5_type);
        if(e5_is_valid_type(attr->type) != E5_TRUE)
        {
            status = E5_INVALID_TYPE;
            e5_error(e5_group_id, status, "Invalid type requested for attribute [type='%d', name='%s', value='%p']\n",  attr->type, attr->name, attr->value);
            continue;
        }

        H5Aread(e5_attribute_id, h5_native_type, attr->value);
        H5Aclose(e5_attribute_id);

        e5_info(e5_group_id, "Read attribute [type='%s', name='%s', value='%p']\n",
            e5_typename(attr->type), attr->name, attr->value);
    }
    return status;
}
Пример #13
0
//-*****************************************************************************
void
ReadTimeSamples( hid_t iParent,
                 std::vector <  AbcA::TimeSamplingPtr > & oTimeSamples )
{
    oTimeSamples.clear();
    // add the intrinsic default sampling
    AbcA::TimeSamplingPtr ts( new AbcA::TimeSampling() );
    oTimeSamples.push_back( ts );

    uint32_t i = 1;
    AbcA::TimeSamplingType tst;
    std::string tstname = "1";

    // keep trying to read till we can't find anymore
    while ( ReadTimeSamplingType( iParent, tstname, tst ) )
    {
        // try to open the time samples attribute
        std::string timeName = tstname + ".time";
        hid_t aid = H5Aopen( iParent, timeName.c_str(), H5P_DEFAULT );
        ABCA_ASSERT( aid >= 0,
                     "Couldn't open time samples named: " << timeName );
        AttrCloser attrCloser( aid );

        // figure out how big it is
        hid_t sid = H5Aget_space( aid );
        ABCA_ASSERT( sid >= 0,
                     "Couldn't get dataspace for time samples: " << timeName );
        DspaceCloser dspaceCloser( sid );

        hssize_t numPoints = H5Sget_simple_extent_npoints( sid );
        ABCA_ASSERT( numPoints > 0, "No time samples data: " << timeName );
        std::vector < chrono_t > times(numPoints);

        // do the read
        herr_t status = H5Aread( aid, H5T_NATIVE_DOUBLE, &(times.front()) );
        ABCA_ASSERT( status >= 0, "Can't read time samples: " << timeName );

        // create the TimeSampling and add it to our vector
        ts.reset( new AbcA::TimeSampling(tst, times) );
        oTimeSamples.push_back( ts );

        // increment to try and read the next one
        i++;
        std::stringstream strm;
        strm << i;
        tstname = strm.str();
    }
}
Пример #14
0
static int
NC4_get_propattr(NC_HDF5_FILE_INFO_T* h5)
{
    int ncstat = NC_NOERR;
    size_t size;
    H5T_class_t t_class;
    hid_t grp = -1;
    hid_t attid = -1;
    hid_t aspace = -1;
    hid_t atype = -1;
    hid_t ntype = -1;
    herr_t herr = 0;
    char* text = NULL;

    /* Get root group */
    grp = h5->root_grp->hdf_grpid; /* get root group */
    /* Try to extract the NCPROPS attribute */
    if(H5Aexists(grp,NCPROPS) > 0) { /* Does exist */
        attid = H5Aopen_name(grp, NCPROPS);
	herr = -1;
	aspace = H5Aget_space(attid); /* dimensions of attribute data */
        atype = H5Aget_type(attid);
	/* Verify that atype and size */
	t_class = H5Tget_class(atype);
	if(t_class != H5T_STRING) {ncstat = NC_EATTMETA; goto done;}
        size = H5Tget_size(atype);
	if(size == 0) goto done;
	text = (char*)malloc(size+1);
	if(text == NULL)
	    {ncstat = NC_ENOMEM; goto done;}
        HCHECK((ntype = H5Tget_native_type(atype, H5T_DIR_ASCEND)));
        HCHECK((H5Aread(attid, ntype, text)));
	/* Make sure its null terminated */
	text[size] = '\0';
	/* Try to parse text */
	ncstat = NC4_properties_parse(&h5->fileinfo->propattr,text);
	herr = 0;
    }
done:
    if(attid >= 0) HCHECK((H5Aclose(attid)));
    if(aspace >= 0) HCHECK((H5Sclose(aspace)));
    if(ntype >= 0) HCHECK((H5Tclose(ntype)));
    if(atype >= 0) HCHECK((H5Tclose(atype)));
    if(text != NULL) free(text);
    return ncstat;
}
Пример #15
0
void
ReadStringT<std::string,char>( hid_t iParent,
                               const std::string &iAttrName,
                               std::string &oString )
{
    ABCA_ASSERT( iParent >= 0, "Invalid parent in ReadStringT" );

    // Open the attribute.
    hid_t attrId = H5Aopen( iParent, iAttrName.c_str(), H5P_DEFAULT );
    ABCA_ASSERT( attrId >= 0,
                 "Couldn't open attribute named: " << iAttrName );
    AttrCloser attrCloser( attrId );

    // Checking code.
    hid_t attrFtype = H5Aget_type( attrId );
    DtypeCloser dtypeCloser( attrFtype );

    ssize_t numChars = H5Tget_size( attrFtype );
    ABCA_ASSERT( numChars >= 0,
                 "ReadStringT() H5Aget_size() failed" );

    // Read and check space
    {
        hid_t attrSpace = H5Aget_space( attrId );
        ABCA_ASSERT( attrSpace >= 0,
                     "Couldn't get dataspace for attribute: " << iAttrName );
        DspaceCloser dspaceCloser( attrSpace );
        
        H5S_class_t attrSpaceClass = H5Sget_simple_extent_type( attrSpace );
        ABCA_ASSERT( attrSpaceClass == H5S_SCALAR,
                     "Tried to read non-scalar attribute: " << iAttrName
                     << " as scalar" );
    }

    // Create temporary char storage buffer.
    std::vector<char> charStorage( ( size_t )( 1 + numChars ),
                                   ( char )0 );

    // Read into it.
    herr_t status = H5Aread( attrId, attrFtype,
                             ( void * )&charStorage.front() );
    ABCA_ASSERT( status >= 0, "Couldn't read from attribute: " << iAttrName );

    // Return it.
    oString = ( const char * )&charStorage.front();
}
Пример #16
0
hdf5_dataspace::hdf5_dataspace(hdf5_annotation const& annotation)
    :
      hdf5_object(H5Aget_space(annotation.get_id()))
{
    if(annotation.get_id() < 0) {
        boost::serialization::throw_exception(
            hdf5_archive_exception(
                hdf5_archive_exception::hdf5_archive_annotation_access_error
            )
        );
    }
    if(get_id() < 0) {
        boost::serialization::throw_exception(
            hdf5_archive_exception(
                hdf5_archive_exception::hdf5_archive_dataspace_access_error
            )
        );
    }
}
Пример #17
0
void h5_att_str(hid_t file_id, char *group, char *name, char *value)
{
  int ii, kk;
  void *buf = NULL;
  hid_t attr_id;
  H5O_info_t object_info;
  char *attr_name = (char *) MALLOC(sizeof(char)*50);

  H5Oget_info_by_name(file_id, group, &object_info, H5P_DEFAULT);
  for (ii=0; ii<object_info.num_attrs; ii++) {
    attr_id = H5Aopen_by_idx(file_id, group, H5_INDEX_NAME, H5_ITER_NATIVE, ii,
      H5P_DEFAULT, H5P_DEFAULT);
    H5Aget_name(attr_id, 50, attr_name);
    if (strcmp_case(name, attr_name) == 0) {
      hid_t attr_type = H5Aget_type(attr_id);
      H5T_class_t data_type = H5Tget_native_type(attr_type, H5T_DIR_DEFAULT);
      size_t data_size = H5Tget_size(data_type);
      hid_t attr_space = H5Aget_space(attr_id);
      hsize_t dims[H5S_MAX_RANK];
      int rank = H5Sget_simple_extent_dims(attr_space, dims, NULL);
      hsize_t elements = 1;
      for (kk=0; kk<rank; kk++)
        elements *= dims[kk];
      buf = (void *) MALLOC((unsigned)(elements*data_size));
      H5Aread(attr_id, attr_type, buf);
      H5Tclose(attr_type);
      H5Tclose(data_type);
      H5Sclose(attr_space);
    }
    else {
      H5Aclose(attr_id);
      continue;
    }
    H5Aclose(attr_id);
  }
  if (buf) {
    strcpy(value, buf);
    FREE(buf);
  }
  else
    strcpy(value, "???");
  FREE(attr_name);
}
Пример #18
0
static int
NC4_get_propattr(NC_HDF5_FILE_INFO_T* h5)
{
    int ncstat = NC_NOERR;
    size_t size;
    H5T_class_t t_class;	
    char text[NCPROPS_LENGTH+1];
    hid_t grp = -1;
    hid_t attid = -1;
    hid_t aspace = -1;
    hid_t atype = -1;
    hid_t ntype = -1;
    herr_t herr = 0;

    /* Get root group */
    grp = h5->root_grp->hdf_grpid; /* get root group */
    /* Try to extract the NCPROPS attribute */
    attid = H5Aopen_name(grp, NCPROPS);
    if(attid >= 0) {
	herr = -1;
	aspace = H5Aget_space(attid); /* dimensions of attribute data */
        atype = H5Aget_type(attid);
	/* Verify that atype and size */
	t_class = H5Tget_class(atype);
	if(t_class != H5T_STRING) {ncstat = NC_EATTMETA; goto done;}
        size = H5Tget_size(atype);
	if(size != NCPROPS_LENGTH) {ncstat = NC_EATTMETA; goto done;}
        HCHECK((ntype = H5Tget_native_type(atype, H5T_DIR_ASCEND)));
        HCHECK((H5Aread(attid, ntype, text)));
	/* Try to parse text */
	strncpy(h5->fileinfo->propattr.text,text,NCPROPS_LENGTH);
	h5->fileinfo->propattr.text[NCPROPS_LENGTH-1] = '\0';
	ncstat = NC4_properties_parse(&h5->fileinfo->propattr);
	herr = 0;
    }    
done:
    if(attid >= 0) HCHECK((H5Aclose(attid)));
    if(aspace >= 0) HCHECK((H5Sclose(aspace)));
    if(ntype >= 0) HCHECK((H5Tclose(ntype)));
    if(atype >= 0) HCHECK((H5Tclose(atype)));
    return ncstat;
}
herr_t VsH5Attribute::getStringValue(std::string* val) {
  hid_t atype = H5Aget_type(getId());
  H5T_class_t type = H5Tget_class(atype);
  hid_t aspace = H5Aget_space(getId());
  size_t rank = H5Sget_simple_extent_ndims(aspace);
  
  if (type != H5T_STRING) {
    VsLog::warningLog() <<"VsH5Attribute::getStringValue() - Requested attribute " <<getShortName()
       <<" is not a string value." <<std::endl;
    val->clear();
    return -1;
  }
  
  //Yes, this is correct (rank != 0)
  if (rank != 0) {
    VsLog::warningLog() <<"VsH5Attribute::getStringValue() - Requested attribute " <<getShortName()
           <<" is not a string value." <<std::endl;
    val->clear();
    return -1;
  }
  
  size_t len = H5Aget_storage_size(getId());
  val->resize(len);
  char* v = new char[len];
  herr_t err = H5Aread(getId(), atype, v);
  // JRC: is this right?
  // err = H5Aread(id, H5T_NATIVE_CHAR, v);
  for (size_t i = 0; i < len; ++i) {
     if (v[i] == 0) {
       //This happens when a program (IDL, HdfView) declares a string of length 5
       //and uses the 5th character for the null terminator
       //In h5dump this shows up as a string "mesh" being declared as 5 characters
       //If dumped to a terminal, it prints like so: "mesh^@"
       VsLog::warningLog() <<"VsH5Attribute::getStringValue() - Found null char inside string attribute: " <<getFullName() <<std::endl;
       val->resize(i);
       break;
     }
     (*val)[i] = v[i];
  }
  delete [] v;
  return err;
}
Пример #20
0
static int find_attr(hid_t attr_id, const char *name, void *op_data)
{
  hid_t obj, type;
  int status;
  h5item *parent = (h5item *)op_data;
  h5item *item = (h5item *)malloc(sizeof(h5item));
  h5item *itm;
  item->item_type = -1;
  item->name=strcpy(malloc(strlen(name)+1),name);
  item->child = 0;
  item->brother = 0;
  item->parent = parent;
  item->obj = 0;
  item->attribute = 0;
  if(parent) {
    if (parent->attribute == NULL)
      {
	parent->attribute = item;
      }
    else
      {
	for (itm = parent->attribute; itm->brother; itm = itm->brother);
	itm->brother = item;
      }
  }
  if ((obj = H5Aopen_name(attr_id,name)) >= 0) {
    int size;
    char dtype;
    int htype = 42;
    int is_signed;
    hsize_t ds_dims[64];
    hid_t space = H5Aget_space(obj);
    int n_ds_dims = H5Sget_simple_extent_dims(space,ds_dims,0);
    size_t precision;
    H5Sclose(space);
    item->obj = obj;
  }
  return 0;
}
Пример #21
0
 /// Return the attribute name of obj, and "" if the attribute does not exist.
 void h5_read_attribute(hid_t id, std::string const &name, std::string & s) {
  s = "";

  // if the attribute is not present, return 0
  if (H5LTfind_attribute(id, name.c_str()) == 0) return; // not present

  attribute attr = H5Aopen(id, name.c_str(), H5P_DEFAULT);
  if (!attr.is_valid()) TRIQS_RUNTIME_ERROR << "Cannot open the attribute " << name;

  dataspace space = H5Aget_space(attr);

  int rank = H5Sget_simple_extent_ndims(space);
  if (rank != 0) TRIQS_RUNTIME_ERROR << "Reading a string attribute and got rank !=0";

  datatype strdatatype = H5Aget_type(attr);

  std::vector<char> buf(H5Aget_storage_size(attr) + 1, 0x00);
  auto err = H5Aread(attr, strdatatype, (void *)(&buf[0]));
  if (err < 0) TRIQS_RUNTIME_ERROR << "Cannot read the attribute " << name;

  s.append(&(buf.front()));
 }
// JRC: This fat interface may not scale?  What about
// scalar attributes?
herr_t VsH5Attribute::getIntVectorValue(std::vector<int>* ivals) {
  herr_t err;
  size_t npoints;
  hid_t atype = H5Aget_type(getId());
  H5T_class_t type = H5Tget_class(atype);
  hid_t aspace = H5Aget_space(getId());
  size_t rank = H5Sget_simple_extent_ndims(aspace);

  if (type != H5T_INTEGER) {
    VsLog::warningLog() <<"VsH5Attribute::getIntVectorValue() - Requested attribute " <<getShortName()
        <<" is not an integer vector." <<std::endl;
     ivals->resize(0);
     return -1;
  }
  
  if (rank == 0) {
    ivals->resize(1);
    int v;
    // err = H5Aread(id, atype, &v);
    err = H5Aread(getId(), H5T_NATIVE_INT, &v);
    (*ivals)[0] = v;
    return err;
  }
  
  // rank>0
  npoints = H5Sget_simple_extent_npoints(aspace);
  int* v = new int[npoints];
  err = H5Aread(getId(), H5T_NATIVE_INT, v);
  ivals->resize(npoints);
  for (size_t i = 0; i<npoints; ++i) {
    (*ivals)[i] = v[i];
  }
  delete [] v;
  
  return err;
}
Пример #23
0
int
main (void)
{
    hid_t       file, filetype, memtype, space, dset, attr;
                                    /* Handles */
    herr_t      status;
    hvl_t       wdata[2],           /* Array of vlen structures */
                *rdata;             /* Pointer to vlen structures */
    hsize_t     dims[1] = {2};
    int         *ptr,
                ndims,
                i, j;

    /*
     * Initialize variable-length data.  wdata[0] is a countdown of
     * length LEN0, wdata[1] is a Fibonacci sequence of length LEN1.
     */
    wdata[0].len = LEN0;
    ptr = (int *) malloc (wdata[0].len * sizeof (int));
    for (i=0; i<wdata[0].len; i++)
        ptr[i] = wdata[0].len - i;       /* 3 2 1 */
    wdata[0].p = (void *) ptr;

    wdata[1].len = LEN1;
    ptr = (int *) malloc (wdata[1].len * sizeof (int));
    ptr[0] = 1;
    ptr[1] = 1;
    for (i=2; i<wdata[1].len; i++)
        ptr[i] = ptr[i-1] + ptr[i-2];   /* 1 1 2 3 5 8 etc. */
    wdata[1].p = (void *) ptr;

    /*
     * Create a new file using the default properties.
     */
    file = H5Fcreate (FILE, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);

    /*
     * Create variable-length datatype for file and memory.
     */
    filetype = H5Tvlen_create (H5T_STD_I32LE);
    memtype = H5Tvlen_create (H5T_NATIVE_INT);

    /*
     * Create dataset with a scalar dataspace.
     */
    space = H5Screate (H5S_SCALAR);
    dset = H5Dcreate (file, DATASET, H5T_STD_I32LE, space, H5P_DEFAULT);
    status = H5Sclose (space);

    /*
     * Create dataspace.  Setting maximum size to NULL sets the maximum
     * size to be the current size.
     */
    space = H5Screate_simple (1, dims, NULL);

    /*
     * Create the attribute and write the variable-length data to it
     */
    attr = H5Acreate (dset, ATTRIBUTE, filetype, space, H5P_DEFAULT);
    status = H5Awrite (attr, memtype, wdata);

    /*
     * Close and release resources.  Note the use of H5Dvlen_reclaim
     * removes the need to manually free() the previously malloc'ed
     * data.
     */
    status = H5Dvlen_reclaim (memtype, space, H5P_DEFAULT, wdata);
    status = H5Aclose (attr);
    status = H5Dclose (dset);
    status = H5Sclose (space);
    status = H5Tclose (filetype);
    status = H5Tclose (memtype);
    status = H5Fclose (file);


    /*
     * Now we begin the read section of this example.  Here we assume
     * the attribute has the same name and rank, but can have any size.
     * Therefore we must allocate a new array to read in data using
     * malloc().
     */

    /*
     * Open file, dataset, and attribute.
     */
    file = H5Fopen (FILE, H5F_ACC_RDONLY, H5P_DEFAULT);
    dset = H5Dopen (file, DATASET);
    attr = H5Aopen_name (dset, ATTRIBUTE);

    /*
     * Get dataspace and allocate memory for array of vlen structures.
     * This does not actually allocate memory for the vlen data, that
     * will be done by the library.
     */
    space = H5Aget_space (attr);
    ndims = H5Sget_simple_extent_dims (space, dims, NULL);
    rdata = (hvl_t *) malloc (dims[0] * sizeof (hvl_t));

    /*
     * Create the memory datatype.
     */
    memtype = H5Tvlen_create (H5T_NATIVE_INT);

    /*
     * Read the data.
     */
    status = H5Aread (attr, memtype, rdata);

    /*
     * Output the variable-length data to the screen.
     */
    for (i=0; i<dims[0]; i++) {
        printf ("%s[%u]:\n  {",ATTRIBUTE,i);
        ptr = rdata[i].p;
        for (j=0; j<rdata[i].len; j++) {
            printf (" %d", ptr[j]);
            if ( (j+1) < rdata[i].len )
                printf (",");
        }
        printf (" }\n");
    }

    /*
     * Close and release resources.  Note we must still free the
     * top-level pointer "rdata", as H5Dvlen_reclaim only frees the
     * actual variable-length data, and not the structures themselves.
     */
    status = H5Dvlen_reclaim (memtype, space, H5P_DEFAULT, rdata);
    free (rdata);
    status = H5Aclose (attr);
    status = H5Dclose (dset);
    status = H5Sclose (space);
    status = H5Tclose (memtype);
    status = H5Fclose (file);

    return 0;
}
Пример #24
0
int hdf5read(char *name, struct descriptor_xd *xd)
{
  hid_t obj,type;
  H5G_stat_t statbuf;
  int item_type;
  int idx = 0;
  int status = FindItem(name, &obj, &item_type);
  if (status & 1)
  {
    if (item_type == H5G_DATASET) {
      int size;
      char dtype;
      int htype = 42;
      int is_signed;
      hsize_t ds_dims[64];
      hid_t space = H5Dget_space(obj);
      int n_ds_dims = H5Sget_simple_extent_dims(space,ds_dims,0);
      size_t precision;
      H5Sclose(space);
      type = H5Dget_type(obj);
      switch (H5Tget_class(type))
	{
	case H5T_COMPOUND:
	  {
            printf("Compound data is not supported, skipping\n");
            break;
          }
	case H5T_INTEGER:
	  precision = H5Tget_precision(type);
	  is_signed = (H5Tget_sign(type) != H5T_SGN_NONE);
          size = precision/8;
	  switch (precision)
            {
	    case 8:
              dtype = is_signed ? DTYPE_B : DTYPE_BU;
              htype = is_signed ? H5T_NATIVE_CHAR : H5T_NATIVE_UCHAR;
	      break;
	    case 16: 
              dtype = is_signed ? DTYPE_W : DTYPE_WU;
              htype = is_signed ? H5T_NATIVE_SHORT : H5T_NATIVE_USHORT;
	      break;
	    case 32: 
              dtype = is_signed ? DTYPE_L : DTYPE_LU;
              htype = is_signed ? H5T_NATIVE_INT : H5T_NATIVE_UINT;
	      break;
	    case 64: 
              dtype = is_signed ? DTYPE_Q : DTYPE_QU;
              htype = is_signed ? H5T_NATIVE_LLONG : H5T_NATIVE_ULLONG;
	      break;
	    default: 
	      dtype = 0;
	      break;
            }
	  PutData(obj, dtype, htype, size, n_ds_dims, ds_dims,0,xd);
	  break;
	case H5T_FLOAT:
	  precision = H5Tget_precision(type);
          size = precision/8;
	  switch (precision)
	    {
	    case 32: 
              dtype = DTYPE_NATIVE_FLOAT;
              htype = H5T_NATIVE_FLOAT;
	      break;
	    case 64: 
              dtype = DTYPE_NATIVE_DOUBLE;
              htype = H5T_NATIVE_DOUBLE;
              break;
	    default:
	      dtype = 0;
	      break;
            }
	  PutData(obj, dtype, htype, size, n_ds_dims, ds_dims,0,xd);
	  break;
	case H5T_TIME:
	  printf("dataset is time ---- UNSUPPORTED\n"); break;
	case H5T_STRING:
	  {
	    int slen = H5Tget_size(type);
	    hid_t st_id;
	    if (slen < 0) {
	      printf("Badly formed string attribute\n");
	      return;
	    }
#if H5_VERS_MAJOR>=1&&H5_VERS_MINOR>=6&&H5_VERS_RELEASE>=1
	    if(H5Tis_variable_str(type)) {                    
	      st_id = H5Tcopy (H5T_C_S1);
	      H5Tset_size(st_id, H5T_VARIABLE);
	    } else {
#endif
	      st_id = H5Tcopy (type);
	      H5Tset_cset(st_id, H5T_CSET_ASCII);
#if H5_VERS_MAJOR>=1&&H5_VERS_MINOR>=6&&H5_VERS_RELEASE>=1
	    } 
#endif	  
            if (H5Tget_size(st_id) > slen) {
	      slen = H5Tget_size(st_id);
	    }
	      H5Tset_size (st_id, slen);
	      PutData(obj, DTYPE_T, st_id, slen, n_ds_dims, ds_dims, 0, xd); 
	  }		
/*        printf("dataset is string\n"); */
/* 	  dtype = DTYPE_T; */
/* 	  htype = H5T_STRING; */
/* 	  PutData(obj, dtype, htype, 0, 0, 0, 1, xd); */
	  break;
	case H5T_BITFIELD:
	  printf("dataset is bitfield ---- UNSUPPORTED\n"); break;
	case H5T_OPAQUE:
	  printf("dataset is opaque ---- UNSUPPORTED\n"); break;
        case H5T_ARRAY:
	  printf("dataset is array ---- UNSUPPORTED\n"); break;
        case H5T_VLEN:
	  printf("dataset is vlen ---- UNSUPPORTED\n"); break;
        }
      H5Tclose(type);
    }
    else {
      int size;
      char dtype;
      int htype = 42;
      int is_signed;
      hsize_t ds_dims[64];
      hid_t space = H5Aget_space(obj);
      int n_ds_dims = H5Sget_simple_extent_dims(space,ds_dims,0);
      size_t precision;
      H5Sclose(space);
      type = H5Aget_type(obj);
      switch (H5Tget_class(type))
	{
	case H5T_COMPOUND:
	{
	  printf("Compound data is not supported, skipping\n");
	  break;
	}
	case H5T_INTEGER:
	  precision = H5Tget_precision(type);
	  is_signed = (H5Tget_sign(type) != H5T_SGN_NONE);
	  size = precision/8;
	  switch (precision)
	    {
	    case 8:
	      dtype = is_signed ? DTYPE_B : DTYPE_BU;
	      htype = is_signed ? H5T_NATIVE_CHAR : H5T_NATIVE_UCHAR;
	      break;
	    case 16: 
	      dtype = is_signed ? DTYPE_W : DTYPE_WU;
	      htype = is_signed ? H5T_NATIVE_SHORT : H5T_NATIVE_USHORT;
	      break;
	    case 32: 
	      dtype = is_signed ? DTYPE_L : DTYPE_LU;
	      htype = is_signed ? H5T_NATIVE_INT : H5T_NATIVE_UINT;
	      break;
	    case 64: 
	      dtype = is_signed ? DTYPE_Q : DTYPE_QU;
	      htype = is_signed ? H5T_NATIVE_LLONG : H5T_NATIVE_ULLONG;
	      break;
	    default: 
	      dtype = 0;
	      break;
	    }
	  PutData(obj, dtype, htype, size, n_ds_dims, ds_dims, 1, xd);
	  break;
	case H5T_FLOAT:
	  precision = H5Tget_precision(type);
	  size = precision/8;
	  switch (precision)
	    {
	    case 32: 
	      dtype = DTYPE_NATIVE_FLOAT;
	      htype = H5T_NATIVE_FLOAT;
	      break;
	    case 64: 
	      dtype = DTYPE_NATIVE_DOUBLE;
	      htype = H5T_NATIVE_DOUBLE;
	      break;
	    default:
	      dtype = 0;
	      break;
	    }
	  PutData(obj, dtype, htype, size, n_ds_dims, ds_dims,1, xd);
	  break;
	case H5T_TIME:
	  printf("dataset is time ---- UNSUPPORTED\n"); break;
	case H5T_STRING:
	  {
	    int slen = H5Tget_size(type);
	    hid_t st_id;
	    if (slen < 0) {
	      printf("Badly formed string attribute\n");
	      return;
	    }
#if H5_VERS_MAJOR>=1&&H5_VERS_MINOR>=6&&H5_VERS_RELEASE>=1
	    if(H5Tis_variable_str(type)) {                    
	      st_id = H5Tcopy (H5T_C_S1);
	      H5Tset_size(st_id, H5T_VARIABLE);
	    } else {
#endif
	      st_id = H5Tcopy (type);
	      H5Tset_cset(st_id, H5T_CSET_ASCII);
#if H5_VERS_MAJOR>=1&&H5_VERS_MINOR>=6&&H5_VERS_RELEASE>=1
	    } 
#endif	  
            if (H5Tget_size(st_id) > slen) {
	      slen = H5Tget_size(st_id);
	    }
	      H5Tset_size (st_id, slen);
	      PutData(obj, DTYPE_T, st_id, slen, n_ds_dims, ds_dims, 1, xd); 
	  }		
/* 	  dtype = DTYPE_T; */
/* 	  htype = H5T_STRING; */
/* 	  PutData(obj, dtype, htype, 0, 0, 0, 1, xd); */
	  break;
	case H5T_BITFIELD:
	  printf("dataset is bitfield ---- UNSUPPORTED\n"); break;
	case H5T_OPAQUE:
	  printf("dataset is opaque ---- UNSUPPORTED\n"); break;
	case H5T_ARRAY:
	  printf("dataset is array ---- UNSUPPORTED\n"); break;
	case H5T_VLEN:
	  printf("dataset is vlen ---- UNSUPPORTED\n"); break;
	}
      H5Tclose(type);
    }
  }
  return status;
}
Пример #25
0
int
main (void)
{
    hid_t       file, space, dset, obj, attr;   /* Handles */
    herr_t      status;
    hsize_t     dims[1] = {DIM0};
    hobj_ref_t  wdata[DIM0],                    /* Write buffer */
                *rdata;                         /* Read buffer */
    H5G_obj_t   objtype;
    ssize_t     size;
    char        *name;
    int         ndims,
                i;

    /*
     * Create a new file using the default properties.
     */
    file = H5Fcreate (FILE, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);

    /*
     * Create a dataset with a scalar dataspace.
     */
    space = H5Screate (H5S_SCALAR);
    obj = H5Dcreate (file, "DS2", H5T_STD_I32LE, space, H5P_DEFAULT);
    status = H5Dclose (obj);
    status = H5Sclose (space);

    /*
     * Create a group.
     */
    obj = H5Gcreate (file, "G1", H5P_DEFAULT);
    status = H5Gclose (obj);

    /*
     * Create references to the previously created objects.  Passing -1
     * as space_id causes this parameter to be ignored.  Other values
     * besides valid dataspaces result in an error.
     */
    status = H5Rcreate (&wdata[0], file, "G1", H5R_OBJECT, -1);
    status = H5Rcreate (&wdata[1], file, "DS2", H5R_OBJECT, -1);

    /*
     * Create dataset with a scalar dataspace to serve as the parent
     * for the attribute.
     */
    space = H5Screate (H5S_SCALAR);
    dset = H5Dcreate (file, DATASET, H5T_STD_I32LE, space, H5P_DEFAULT);
    status = H5Sclose (space);

    /*
     * Create dataspace.  Setting maximum size to NULL sets the maximum
     * size to be the current size.
     */
    space = H5Screate_simple (1, dims, NULL);

    /*
     * Create the attribute and write the object references to it.
     */
    attr = H5Acreate (dset, ATTRIBUTE, H5T_STD_REF_OBJ, space, H5P_DEFAULT);
    status = H5Awrite (attr, H5T_STD_REF_OBJ, wdata);

    /*
     * Close and release resources.
     */
    status = H5Aclose (attr);
    status = H5Dclose (dset);
    status = H5Sclose (space);
    status = H5Fclose (file);


    /*
     * Now we begin the read section of this example.  Here we assume
     * the attribute has the same name and rank, but can have any size.
     * Therefore we must allocate a new array to read in data using
     * malloc().
     */

    /*
     * Open file, dataset, and attribute.
     */
    file = H5Fopen (FILE, H5F_ACC_RDONLY, H5P_DEFAULT);
    dset = H5Dopen (file, DATASET);
    attr = H5Aopen_name (dset, ATTRIBUTE);

    /*
     * Get dataspace and allocate memory for read buffer.
     */
    space = H5Aget_space (attr);
    ndims = H5Sget_simple_extent_dims (space, dims, NULL);
    rdata = (hobj_ref_t *) malloc (dims[0] * sizeof (hobj_ref_t));

    /*
     * Read the data.
     */
    status = H5Aread (attr, H5T_STD_REF_OBJ, rdata);

    /*
     * Output the data to the screen.
     */
    for (i=0; i<dims[0]; i++) {
        printf ("%s[%d]:\n  ->", ATTRIBUTE, i);

        /*
         * Open the referenced object, get its name and type.
         */
        obj = H5Rdereference (dset, H5R_OBJECT, &rdata[i]);
        objtype = H5Rget_obj_type (dset, H5R_OBJECT, &rdata[i]);

        /*
         * Get the length of the name, allocate space, then retrieve
         * the name.
         */
        size = 1 + H5Iget_name (obj, NULL, 0);
        if (size > 1) {
            name = (char *) malloc (size);
            size = 1 + H5Iget_name (obj, name, size);
        }

        /*
         * Print the object type and close the object.
         */
        switch (objtype) {
            case H5G_GROUP:
                printf ("Group");
                status = H5Gclose (obj);
                break;
            case H5G_DATASET:
                printf ("Dataset");
                status = H5Dclose (obj);
                break;
            case H5G_TYPE:
                printf ("Named Datatype");
                status = H5Tclose (obj);
        }

        /*
         * Print the name and deallocate space for the name.
         */
        if (size > 1) {
            printf (": %s", name);
            free (name);
        }
        printf ("\n");
    }

    /*
     * Close and release resources.
     */
    free (rdata);
    status = H5Aclose (attr);
    status = H5Dclose (dset);
    status = H5Sclose (space);
    status = H5Fclose (file);

    return 0;
}
Пример #26
0
static herr_t
trav_attr(hid_t
#ifndef H5TRAV_PRINT_SPACE
UNUSED
#endif /* H5TRAV_PRINT_SPACE */
obj, const char *attr_name, const H5A_info_t UNUSED *ainfo, void *op_data)
{
    char               *buf;

    buf = (char*)op_data;
    if((strlen(buf)==1) && (*buf=='/'))
        printf(" %-10s %s%s", "attribute", buf, attr_name);
    else
        printf(" %-10s %s/%s", "attribute", buf, attr_name);

#ifdef H5TRAV_PRINT_SPACE
    if(trav_verbosity < 2) {
#endif
        printf("\n");
#ifdef H5TRAV_PRINT_SPACE
    }
    else {
        hid_t               attr = -1;
        hid_t               space = -1;
        hsize_t             size[H5S_MAX_RANK];
        int                 ndims;
        int                 i;
        H5S_class_t         space_type;

        if((attr = H5Aopen(obj, attr_name, H5P_DEFAULT))) {
            space = H5Aget_space(attr);

            /* Data space */
            ndims = H5Sget_simple_extent_dims(space, size, NULL);
            space_type = H5Sget_simple_extent_type(space);
            switch(space_type) {
                case H5S_SCALAR:
                    /* scalar dataspace */
                    printf(" scalar\n");
                    break;

                case H5S_SIMPLE:
                    /* simple dataspace */
                    printf(" {");
                    for (i=0; i<ndims; i++) {
                        printf("%s" HSIZE_T_FORMAT, i?", ":"", size[i]);
                    }
                    printf("}\n");
                    break;

                case H5S_NULL:
                    /* null dataspace */
                    printf(" null\n");
                    break;

                default:
                    /* Unknown dataspace type */
                    printf(" unknown\n");
                    break;
            } /* end switch */

            H5Sclose(space);
            H5Aclose(attr);
        }
    }
#endif

    return(0);
}
Пример #27
0
int
main (void)
{
    hid_t       file, filetype, memtype, space, dset, attr;
                                            /* Handles */
    herr_t      status;
    hsize_t     dims[1] = {DIM0};
    char        *wdata[DIM0] = {"Parting", "is such", "sweet", "sorrow."},
                                            /* Write buffer */
                **rdata;                    /* Read buffer */
    int         ndims,
                i;

    /*
     * Create a new file using the default properties.
     */
    file = H5Fcreate (FILE, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);

    /*
     * Create file and memory datatypes.  For this example we will save
     * the strings as FORTRAN strings.
     */
    filetype = H5Tcopy (H5T_FORTRAN_S1);
    status = H5Tset_size (filetype, H5T_VARIABLE);
    memtype = H5Tcopy (H5T_C_S1);
    status = H5Tset_size (memtype, H5T_VARIABLE);

    /*
     * Create dataset with a null dataspace.
     */
    space = H5Screate (H5S_NULL);
    dset = H5Dcreate (file, DATASET, H5T_STD_I32LE, space, H5P_DEFAULT,
                H5P_DEFAULT, H5P_DEFAULT);
    status = H5Sclose (space);

    /*
     * Create dataspace.  Setting maximum size to NULL sets the maximum
     * size to be the current size.
     */
    space = H5Screate_simple (1, dims, NULL);

    /*
     * Create the attribute and write the variable-length string data
     * to it.
     */
    attr = H5Acreate (dset, ATTRIBUTE, filetype, space, H5P_DEFAULT,
                H5P_DEFAULT);
    status = H5Awrite (attr, memtype, wdata);

    /*
     * Close and release resources.
     */
    status = H5Aclose (attr);
    status = H5Dclose (dset);
    status = H5Sclose (space);
    status = H5Tclose (filetype);
    status = H5Tclose (memtype);
    status = H5Fclose (file);


    /*
     * Now we begin the read section of this example.  Here we assume
     * the attribute has the same name and rank, but can have any size.
     * Therefore we must allocate a new array to read in data using
     * malloc().
     */

    /*
     * Open file, dataset, and attribute.
     */
    file = H5Fopen (FILE, H5F_ACC_RDONLY, H5P_DEFAULT);
    dset = H5Dopen (file, DATASET, H5P_DEFAULT);
    attr = H5Aopen (dset, ATTRIBUTE, H5P_DEFAULT);

    /*
     * Get the datatype.
     */
    filetype = H5Aget_type (attr);

    /*
     * Get dataspace and allocate memory for read buffer.
     */
    space = H5Aget_space (attr);
    ndims = H5Sget_simple_extent_dims (space, dims, NULL);
    rdata = (char **) malloc (dims[0] * sizeof (char *));

    /*
     * Create the memory datatype.
     */
    memtype = H5Tcopy (H5T_C_S1);
    status = H5Tset_size (memtype, H5T_VARIABLE);

    /*
     * Read the data.
     */
    status = H5Aread (attr, memtype, rdata);

    /*
     * Output the data to the screen.
     */
    for (i=0; i<dims[0]; i++)
        printf ("%s[%d]: %s\n", ATTRIBUTE, i, rdata[i]);

    /*
     * Close and release resources.  Note that H5Dvlen_reclaim works
     * for variable-length strings as well as variable-length arrays.
     * Also note that we must still free the array of pointers stored
     * in rdata, as H5Tvlen_reclaim only frees the data these point to.
     */
    status = H5Dvlen_reclaim (memtype, space, H5P_DEFAULT, rdata);
    free (rdata);
    status = H5Aclose (attr);
    status = H5Dclose (dset);
    status = H5Sclose (space);
    status = H5Tclose (filetype);
    status = H5Tclose (memtype);
    status = H5Fclose (file);

    return 0;
}
Пример #28
0
int
NC4_write_ncproperties(NC_FILE_INFO_T* h5)
{
    int retval = NC_NOERR;
    hid_t hdf5grpid = -1;
    hid_t attid = -1;
    hid_t aspace = -1;
    hid_t atype = -1;
    char* text = NULL;
    size_t len = 0;

    LOG((3, "%s", __func__));

    /* If the file is read-only, return an error. */
    if (h5->no_write)
    {retval = NC_EPERM; goto done;}

    hdf5grpid = ((NC_HDF5_GRP_INFO_T *)(h5->root_grp->format_grp_info))->hdf_grpid;

    if(H5Aexists(hdf5grpid,NCPROPS) > 0) /* Already exists, no overwrite */
        goto done;

    /* Build the attribute string */
    if((retval = NC4_buildpropinfo(&h5->provenance->propattr,&text)))
        goto done;

    /* Build the HDF5 string type */
    if ((atype = H5Tcopy(H5T_C_S1)) < 0)
    {retval = NC_EHDFERR; goto done;}
    if (H5Tset_strpad(atype, H5T_STR_NULLTERM) < 0)
    {retval = NC_EHDFERR; goto done;}
    if(H5Tset_cset(atype, H5T_CSET_ASCII) < 0)
    {retval = NC_EHDFERR; goto done;}
    len = strlen(text);
    if(H5Tset_size(atype, len) < 0)
    {retval = NC_EFILEMETA; goto done;}

    /* Create NCPROPS attribute */
    if((aspace = H5Screate(H5S_SCALAR)) < 0)
    {retval = NC_EFILEMETA; goto done;}
    if ((attid = H5Acreate(hdf5grpid, NCPROPS, atype, aspace, H5P_DEFAULT)) < 0)
    {retval = NC_EFILEMETA; goto done;}
    if (H5Awrite(attid, atype, text) < 0)
    {retval = NC_EFILEMETA; goto done;}

/* Verify */
#if 0
    {
        hid_t spacev, typev;
        hsize_t dsize, tsize;
        typev = H5Aget_type(attid);
        spacev = H5Aget_space(attid);
        dsize = H5Aget_storage_size(attid);
        tsize = H5Tget_size(typev);
        fprintf(stderr,"dsize=%lu tsize=%lu\n",(unsigned long)dsize,(unsigned long)tsize);
    }
#endif

done:
    if(text != NULL) free(text);
    /* Close out the HDF5 objects */
    if(attid > 0 && H5Aclose(attid) < 0) retval = NC_EHDFERR;
    if(aspace > 0 && H5Sclose(aspace) < 0) retval = NC_EHDFERR;
    if(atype > 0 && H5Tclose(atype) < 0) retval = NC_EHDFERR;

    /* For certain errors, actually fail, else log that attribute was invalid and ignore */
    switch (retval) {
    case NC_ENOMEM:
    case NC_EHDFERR:
    case NC_EPERM:
    case NC_EFILEMETA:
    case NC_NOERR:
        break;
    default:
        LOG((0,"Invalid _NCProperties attribute"));
        retval = NC_NOERR;
        break;
    }
    return retval;
}
Пример #29
0
hsize_t diff_attr(hid_t loc1_id,
                  hid_t loc2_id,
                  const char *path1,
                  const char *path2,
                  diff_opt_t *options)
{
    hid_t      attr1_id=-1;     /* attr ID */
    hid_t      attr2_id=-1;     /* attr ID */
    hid_t      space1_id=-1;    /* space ID */
    hid_t      space2_id=-1;    /* space ID */
    hid_t      ftype1_id=-1;    /* file data type ID */
    hid_t      ftype2_id=-1;    /* file data type ID */
    hid_t      mtype1_id=-1;    /* memory data type ID */
    hid_t      mtype2_id=-1;    /* memory data type ID */
    size_t     msize1;          /* memory size of memory type */
    size_t     msize2;          /* memory size of memory type */
    void       *buf1=NULL;      /* data buffer */
    void       *buf2=NULL;      /* data buffer */
    hsize_t    nelmts1;         /* number of elements in dataset */
    int        rank1;           /* rank of dataset */
    int        rank2;           /* rank of dataset */
    hsize_t    dims1[H5S_MAX_RANK];/* dimensions of dataset */
    hsize_t    dims2[H5S_MAX_RANK];/* dimensions of dataset */
    char       name1[512];
    char       name2[512];
    char       np1[512];
    char       np2[512];
    H5O_info_t oinfo1, oinfo2;     /* Object info */
    unsigned   u;                  /* Local index variable */
    hsize_t    nfound = 0;
    hsize_t    nfound_total = 0;
    int       j;

    if(H5Oget_info(loc1_id, &oinfo1) < 0)
        goto error;
    if(H5Oget_info(loc2_id, &oinfo2) < 0)
        goto error;

    if(oinfo1.num_attrs != oinfo2.num_attrs)
        return 1;

    for( u = 0; u < (unsigned)oinfo1.num_attrs; u++)
    {
        /* reset buffers for every attribute, we might goto out and call free */
        buf1 = NULL;
        buf2 = NULL;

        /* open attribute */
        if((attr1_id = H5Aopen_by_idx(loc1_id, ".", H5_INDEX_CRT_ORDER, H5_ITER_INC, (hsize_t)u, H5P_DEFAULT, H5P_DEFAULT)) < 0)
            goto error;
        /* get name */
        if(H5Aget_name(attr1_id, 255, name1) < 0)
            goto error;

        /* use the name on the first file to open the second file */
        H5E_BEGIN_TRY
        {
            if((attr2_id = H5Aopen(loc2_id, name1, H5P_DEFAULT)) < 0)
                goto error;
        } H5E_END_TRY;

        /* get name */
        if(H5Aget_name(attr2_id, 255, name2) < 0)
            goto error;

        /* get the datatypes  */
        if ((ftype1_id = H5Aget_type(attr1_id)) < 0)
            goto error;
        if ((ftype2_id = H5Aget_type(attr2_id)) < 0)
            goto error;
        if ((mtype1_id = h5tools_get_native_type(ftype1_id))<0)
            goto error;
        if ((mtype2_id = h5tools_get_native_type(ftype2_id))<0)
            goto error;
        if ((msize1 = H5Tget_size(mtype1_id))==0)
            goto error;
        if ((msize2 = H5Tget_size(mtype2_id))==0)
            goto error;

        /* get the dataspace   */
        if ((space1_id = H5Aget_space(attr1_id)) < 0)
            goto error;
        if ((space2_id = H5Aget_space(attr2_id)) < 0)
            goto error;

        /* get dimensions  */
        if ( (rank1 = H5Sget_simple_extent_dims(space1_id, dims1, NULL)) < 0 )
            goto error;
        if ( (rank2 = H5Sget_simple_extent_dims(space2_id, dims2, NULL)) < 0 )
            goto error;


       /*-------------------------------------------------------------------------
        * check for comparable TYPE and SPACE
        *-------------------------------------------------------------------------
        */

        if ( msize1 != msize2
            ||
            diff_can_type(ftype1_id,
            ftype2_id,
            rank1,
            rank2,
            dims1,
            dims2,
            NULL,
            NULL,
            name1,
            name2,
            options,
            0)!=1)
        {


            if (H5Tclose(ftype1_id)<0)
                goto error;
            if (H5Tclose(ftype2_id)<0)
                goto error;
            if (H5Sclose(space1_id)<0)
                goto error;
            if (H5Sclose(space2_id)<0)
                goto error;
            if (H5Aclose(attr1_id)<0)
                goto error;
            if (H5Aclose(attr2_id)<0)
                goto error;
            if (H5Tclose(mtype1_id)<0)
                goto error;
            if (H5Tclose(mtype2_id)<0)
                goto error;

            continue;


        }


        /*-------------------------------------------------------------------------
        * read
        *-------------------------------------------------------------------------
        */
        nelmts1=1;
        for (j=0; j<rank1; j++)
            nelmts1*=dims1[j];

        buf1=(void *) HDmalloc((unsigned)(nelmts1*msize1));
        buf2=(void *) HDmalloc((unsigned)(nelmts1*msize2));
        if ( buf1==NULL || buf2==NULL){
            parallel_print( "cannot read into memory\n" );
            goto error;
        }
        if (H5Aread(attr1_id,mtype1_id,buf1)<0)
            goto error;
        if (H5Aread(attr2_id,mtype2_id,buf2)<0)
            goto error;

        /* format output string */
        sprintf(np1,"%s of <%s>",name1,path1);
        sprintf(np2,"%s of <%s>",name2,path2);

        /*-------------------------------------------------------------------------
        * array compare
        *-------------------------------------------------------------------------
        */

        /* always print name */
        if (options->m_verbose)
        {
            do_print_objname ("attribute", np1, np2);
            nfound = diff_array(buf1,
                buf2,
                nelmts1,
                (hsize_t)0,
                rank1,
                dims1,
                options,
                np1,
                np2,
                mtype1_id,
                attr1_id,
                attr2_id);
            print_found(nfound);

        }
        /* check first if we have differences */
        else
        {
            if (options->m_quiet==0)
            {
                /* shut up temporarily */
                options->m_quiet=1;
                nfound = diff_array(buf1,
                    buf2,
                    nelmts1,
                    (hsize_t)0,
                    rank1,
                    dims1,
                    options,
                    np1,
                    np2,
                    mtype1_id,
                    attr1_id,
                    attr2_id);
                /* print again */
                options->m_quiet=0;
                if (nfound)
                {
                    do_print_objname ("attribute", np1, np2);
                    nfound = diff_array(buf1,
                        buf2,
                        nelmts1,
                        (hsize_t)0,
                        rank1,
                        dims1,
                        options,
                        np1,
                        np2,
                        mtype1_id,
                        attr1_id,
                        attr2_id);
                    print_found(nfound);
                } /*if*/
            } /*if*/
            /* in quiet mode, just count differences */
            else
            {
                nfound = diff_array(buf1,
                    buf2,
                    nelmts1,
                    (hsize_t)0,
                    rank1,
                    dims1,
                    options,
                    np1,
                    np2,
                    mtype1_id,
                    attr1_id,
                    attr2_id);
            } /*else quiet */
        } /*else verbose */


       /*-------------------------------------------------------------------------
        * close
        *-------------------------------------------------------------------------
        */

        if (H5Tclose(ftype1_id)<0)
            goto error;
        if (H5Tclose(ftype2_id)<0)
            goto error;
        if (H5Sclose(space1_id)<0)
            goto error;
        if (H5Sclose(space2_id)<0)
            goto error;
        if (H5Aclose(attr1_id)<0)
            goto error;
        if (H5Aclose(attr2_id)<0)
            goto error;
        if (H5Tclose(mtype1_id)<0)
            goto error;
        if (H5Tclose(mtype2_id)<0)
            goto error;

        if (buf1)
            HDfree(buf1);
        if (buf2)
            HDfree(buf2);

        nfound_total += nfound;
 } /* u */

 return nfound_total;

error:
 H5E_BEGIN_TRY {
     H5Tclose(ftype1_id);
     H5Tclose(ftype2_id);
     H5Tclose(mtype1_id);
     H5Tclose(mtype2_id);
     H5Sclose(space1_id);
     H5Sclose(space2_id);
     H5Aclose(attr1_id);
     H5Aclose(attr2_id);
     if (buf1)
         HDfree(buf1);
     if (buf2)
         HDfree(buf2);
 } H5E_END_TRY;

 options->err_stat=1;
 return nfound_total;
}
Пример #30
0
/* HDF5 Specific attribute read/write of _NCProperties */
int
NC4_read_ncproperties(NC_FILE_INFO_T* h5)
{
    int retval = NC_NOERR;
    hid_t hdf5grpid = -1;
    hid_t attid = -1;
    hid_t aspace = -1;
    hid_t atype = -1;
    hid_t ntype = -1;
    char* text = NULL;
    H5T_class_t t_class;
    hsize_t size;

    LOG((3, "%s", __func__));

    hdf5grpid = ((NC_HDF5_GRP_INFO_T *)(h5->root_grp->format_grp_info))->hdf_grpid;

    if(H5Aexists(hdf5grpid,NCPROPS) <= 0) { /* Does not exist */
        /* File did not contain a _NCProperties attribute */
        retval=NC4_get_provenance(h5,NULL,&globalpropinfo);
        goto done;
    }

    /* NCPROPS Attribute exists, make sure it is legitimate */
    attid = H5Aopen_name(hdf5grpid, NCPROPS);
    assert(attid > 0);
    aspace = H5Aget_space(attid);
    atype = H5Aget_type(attid);
    /* Verify atype and size */
    t_class = H5Tget_class(atype);
    if(t_class != H5T_STRING)
    {retval = NC_EINVAL; goto done;}
    size = H5Tget_size(atype);
    if(size == 0)
    {retval = NC_EINVAL; goto done;}
    text = (char*)malloc(1+(size_t)size);
    if(text == NULL)
    {retval = NC_ENOMEM; goto done;}
    if((ntype = H5Tget_native_type(atype, H5T_DIR_DEFAULT)) < 0)
    {retval = NC_EHDFERR; goto done;}
    if((H5Aread(attid, ntype, text)) < 0)
    {retval = NC_EHDFERR; goto done;}
    /* Make sure its null terminated */
    text[(size_t)size] = '\0';
    /* Process the _NCProperties value */
    if((retval = NC4_get_provenance(h5, text, &globalpropinfo)))
        goto done;

done:
    if(text != NULL) free(text);
    /* Close out the HDF5 objects */
    if(attid > 0 && H5Aclose(attid) < 0) retval = NC_EHDFERR;
    if(aspace > 0 && H5Sclose(aspace) < 0) retval = NC_EHDFERR;
    if(atype > 0 && H5Tclose(atype) < 0) retval = NC_EHDFERR;
    if(ntype > 0 && H5Tclose(ntype) < 0) retval = NC_EHDFERR;

    /* For certain errors, actually fail, else log that attribute was invalid and ignore */
    if(retval != NC_NOERR) {
        if(retval != NC_ENOMEM && retval != NC_EHDFERR) {
            LOG((0,"Invalid _NCProperties attribute: ignored"));
            retval = NC_NOERR;
        }
    }
    return retval;
}