Пример #1
0
void write(const hid_attribute_adaptor& attrib, const std::string& value)
{
	hid_t attr_type_id = H5CPP_ERR_ON_NEG(H5Aget_type(attrib.id()));
	if(H5Tget_class(attr_type_id) != H5T_STRING)
		H5CPP_THROW("Attempted to set string value on non-string attribute '"
			<< object::get_name(attrib.id()) << '\'');

	const char* cstr = value.c_str();

	if(H5Tis_variable_str(attr_type_id))
		H5CPP_ERR_ON_NEG(H5Awrite(attrib.id(), attr_type_id, &cstr));
	else
	{
		std::size_t attriblen = H5Aget_storage_size(attrib.id());
		if(attriblen > value.length())
		{
			// avoid reading past end of value into unalloc'd mem
			std::vector<char> buf(attriblen,'\0');
			std::copy(cstr, cstr+value.length(), &buf[0]);
			H5CPP_ERR_ON_NEG(H5Awrite(attrib.id(), attr_type_id, &buf[0]));
		}
		else
			H5CPP_ERR_ON_NEG(H5Awrite(attrib.id(), attr_type_id, cstr));
	}
}
Пример #2
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);
}
Пример #3
0
/*
 * Class:     hdf_hdf5lib_H5
 * Method:    H5Aget_storage_size
 * Signature: (J)J
 */
JNIEXPORT jlong JNICALL
Java_hdf_hdf5lib_H5_H5Aget_1storage_1size
    (JNIEnv *env, jclass clss, jlong attr_id)
{
    hsize_t retVal = (hsize_t)-1;

    retVal = H5Aget_storage_size((hid_t)attr_id);
/* probably returns '0' if fails--don't do an exception */
    return (jlong)retVal;
} /* end Java_hdf_hdf5lib_H5_H5Aget_1storage_1size */
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;
}
Пример #5
0
int pioReadAttributeString(PIOObject pioObject,
						   const char* attr_name, char** attr_value)
{
	hid_t attr;
	size_t storage;
	
	if (pioHasAttribute(pioObject, attr_name))
	{
		attr = H5Aopen_name(pioObject.identifier, attr_name);
		storage = H5Aget_storage_size(attr);
		H5Aclose(attr);
		
		*attr_value = (char*)malloc( storage + sizeof(char));
		H5LTget_attribute_string(pioObject.identifier, ".",
								 attr_name, *attr_value);
		return 1;
	}
	else {
		return -1;
	}
}
Пример #6
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()));
 }
Пример #7
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;
}
Пример #8
0
std::string fast5_get_string_attribute(fast5_file& fh, const std::string& group_name, const std::string& attribute_name)
{
    hid_t group, attribute, attribute_type, native_type;
    std::string out;

    // according to http://hdf-forum.184993.n3.nabble.com/check-if-dataset-exists-td194725.html
    // we should use H5Lexists to check for the existence of a group/dataset using an arbitrary path
    // HDF5 1.8 returns 0 on the root group, so we explicitly check for it
    int ret = group_name == "/" ? 1 : H5Lexists(fh.hdf5_file, group_name.c_str(), H5P_DEFAULT);
    if(ret <= 0) {
        return "";
    }

    // Open the group containing the attribute we want
    group = H5Gopen(fh.hdf5_file, group_name.c_str(), H5P_DEFAULT);
    if(group < 0) {
#ifdef DEBUG_FAST5_IO
        fprintf(stderr, "could not open group %s\n", group_name.c_str());
#endif
        goto close_group;
    }

    // Ensure attribute exists
    ret = H5Aexists(group, attribute_name.c_str());
    if(ret <= 0) {
        goto close_group;
    }

    // Open the attribute
    attribute = H5Aopen(group, attribute_name.c_str(), H5P_DEFAULT);
    if(attribute < 0) {
#ifdef DEBUG_FAST5_IO
        fprintf(stderr, "could not open attribute: %s\n", attribute_name.c_str());
#endif
        goto close_attr;
    }

    // Get data type and check it is a fixed-length string
    attribute_type = H5Aget_type(attribute);
    if(attribute_type < 0) {
#ifdef DEBUG_FAST5_IO
        fprintf(stderr, "failed to get attribute type %s\n", attribute_name.c_str());
#endif
        goto close_type;
    }

    if(H5Tget_class(attribute_type) != H5T_STRING) {
#ifdef DEBUG_FAST5_IO
        fprintf(stderr, "attribute %s is not a string\n", attribute_name.c_str());
#endif
        goto close_type;
    }

    native_type = H5Tget_native_type(attribute_type, H5T_DIR_ASCEND);
    if(native_type < 0) {
#ifdef DEBUG_FAST5_IO
        fprintf(stderr, "failed to get native type for %s\n", attribute_name.c_str());
#endif
        goto close_native_type;
    }

    if(H5Tis_variable_str(attribute_type) > 0) {
        // variable length string
        char* buffer;
        ret = H5Aread(attribute, native_type, &buffer);
        if(ret < 0) {
            fprintf(stderr, "error reading attribute %s\n", attribute_name.c_str());
            exit(EXIT_FAILURE);
        }
        out = buffer;
        free(buffer);
        buffer = NULL;

    } else {
        // fixed length string
        size_t storage_size;
        char* buffer;

        // Get the storage size and allocate
        storage_size = H5Aget_storage_size(attribute);
        buffer = (char*)calloc(storage_size + 1, sizeof(char));

        // finally read the attribute
        ret = H5Aread(attribute, attribute_type, buffer);
        if(ret >= 0) {
            out = buffer;
        }

        // clean up
        free(buffer);
    }

close_native_type:
    H5Tclose(native_type);    
close_type:
    H5Tclose(attribute_type);
close_attr:
    H5Aclose(attribute);
close_group:
    H5Gclose(group);

    return out;
}
Пример #9
0
herr_t HDF5AttrIterate( hid_t hH5ObjID, 
			const char *AttrName, 
			void *pDS )
{
    hid_t           hAttrID;
    hid_t           hAttrTypeID;
    hid_t           hAttrNativeType;
    hid_t           hAttrSpace;

    char           *szData = NULL;
    hsize_t        nSize[64];
    unsigned int            nAttrElmts;
    hsize_t        nAttrSize;
    hsize_t        i;
    void           *buf = NULL;
    unsigned int             nAttrDims;


    HDF5Dataset    *poDS;
    char           *szTemp = (char*) CPLMalloc( 8192 );
    char           *szValue = NULL;

    poDS = (HDF5Dataset *) pDS;
    sprintf( szTemp, "%s:%s", poDS->poH5CurrentObject->pszName, 
	     AttrName );

    hAttrID          = H5Aopen_name( hH5ObjID, AttrName );
    hAttrTypeID      = H5Aget_type( hAttrID );
    hAttrNativeType  = H5Tget_native_type( hAttrTypeID, H5T_DIR_DEFAULT );
    hAttrSpace       = H5Aget_space( hAttrID );
    nAttrDims        = H5Sget_simple_extent_dims( hAttrSpace, nSize, NULL );

    if( H5Tget_class( hAttrNativeType ) == H5T_STRING ) {
        nAttrSize = H5Aget_storage_size( hAttrID );
	szData = (char*) CPLMalloc((size_t) (nAttrSize+1));
	szValue = (char*) CPLMalloc((size_t) (nAttrSize+1));
	H5Aread( hAttrID, hAttrNativeType, szData  );
	szData[nAttrSize]='\0';
	sprintf( szValue, "%s", szData );

    }
    else {
	nAttrElmts = 1;
	for( i=0; i < nAttrDims; i++ ) {
	    nAttrElmts *= (int) nSize[i];
	}
	if( nAttrElmts > 0 ){
	    buf = (void *) CPLMalloc( nAttrElmts*
				      H5Tget_size( hAttrNativeType ));
	    szData = (char*) CPLMalloc( 8192 );
	    szValue = (char*) CPLMalloc( MAX_METADATA_LEN );
	    szData[0]='\0';
	    szValue[0] ='\0';
	    H5Aread( hAttrID, hAttrNativeType, buf );
	}
	if( H5Tequal( H5T_NATIVE_CHAR, hAttrNativeType ) ){
	    for( i=0; i < nAttrElmts; i++ ) {
		sprintf( szData, "%c ", ((char *) buf)[i]);
		if( CPLStrlcat(szValue,szData,MAX_METADATA_LEN) >= MAX_METADATA_LEN )
		    CPLError( CE_Warning, CPLE_OutOfMemory,
			      "Header data too long. Truncated\n");
	    }
	}
	else if( H5Tequal( H5T_NATIVE_UCHAR,  hAttrNativeType ) ) {
	    for( i=0; i < nAttrElmts; i++ ) {
		sprintf( szData, "%c", ((char *) buf)[i] );
		if( CPLStrlcat(szValue,szData,MAX_METADATA_LEN) >= MAX_METADATA_LEN )
		    CPLError( CE_Warning, CPLE_OutOfMemory,
			      "Header data too long. Truncated\n");
	    }
	}
	else if( H5Tequal( H5T_NATIVE_SHORT,  hAttrNativeType ) ) {
	    for( i=0; i < nAttrElmts; i++ ) {
		sprintf( szData, "%d ", ((short *) buf)[i] );
		if( CPLStrlcat(szValue,szData,MAX_METADATA_LEN) >= MAX_METADATA_LEN )
		    CPLError( CE_Warning, CPLE_OutOfMemory,
			      "Header data too long. Truncated\n");
	    }
	}
	else if( H5Tequal( H5T_NATIVE_USHORT, hAttrNativeType ) ) {
	    for( i=0; i < nAttrElmts; i++ ) {
		sprintf( szData, "%ud ", ((unsigned short *) buf)[i] );
		if( CPLStrlcat(szValue,szData,MAX_METADATA_LEN) >= MAX_METADATA_LEN )
		    CPLError( CE_Warning, CPLE_OutOfMemory,
			      "Header data too long. Truncated\n");
	    }
	}
	else if( H5Tequal( H5T_NATIVE_INT,    hAttrNativeType ) ) {
	    for( i=0; i < nAttrElmts; i++ ) {
		sprintf( szData, "%d ", ((int *) buf)[i] );
		if( CPLStrlcat(szValue,szData,MAX_METADATA_LEN) >= MAX_METADATA_LEN )
		    CPLError( CE_Warning, CPLE_OutOfMemory,
			      "Header data too long. Truncated\n");
	    }
	}
	else if( H5Tequal( H5T_NATIVE_UINT,   hAttrNativeType ) ) {
	    for( i=0; i < nAttrElmts; i++ ) {
		sprintf( szData, "%ud ", ((unsigned int *) buf)[i] );
		if( CPLStrlcat(szValue,szData,MAX_METADATA_LEN) >= MAX_METADATA_LEN )
		    CPLError( CE_Warning, CPLE_OutOfMemory,
			      "Header data too long. Truncated\n");
	    }
	}
	else if( H5Tequal( H5T_NATIVE_LONG,   hAttrNativeType ) ) {
	    for( i=0; i < nAttrElmts; i++ ) {
		sprintf( szData, "%ld ", ((long *)buf)[i] );
		if( CPLStrlcat(szValue,szData,MAX_METADATA_LEN) >= MAX_METADATA_LEN )
		    CPLError( CE_Warning, CPLE_OutOfMemory,
			      "Header data too long. Truncated\n");
	    }
	}
	else if( H5Tequal( H5T_NATIVE_ULONG,  hAttrNativeType ) ) {
	    for( i=0; i < nAttrElmts; i++ ) {
		sprintf( szData, "%ld ", ((unsigned long *)buf)[i] );
		if( CPLStrlcat(szValue,szData,MAX_METADATA_LEN) >= MAX_METADATA_LEN )
		    CPLError( CE_Warning, CPLE_OutOfMemory,
			      "Header data too long. Truncated\n");
	    }
	}
	else if( H5Tequal( H5T_NATIVE_FLOAT,  hAttrNativeType ) ) {
	    for( i=0; i < nAttrElmts; i++ ) {
		sprintf( szData, "%f ",  ((float *)buf)[i] );
		if( CPLStrlcat(szValue,szData,MAX_METADATA_LEN) >= MAX_METADATA_LEN )
		    CPLError( CE_Warning, CPLE_OutOfMemory,
			      "Header data too long. Truncated\n");
	    }
	}
	else if( H5Tequal( H5T_NATIVE_DOUBLE, hAttrNativeType ) ) {
	    for( i=0; i < nAttrElmts; i++ ) {
		sprintf( szData, "%g ",  ((double *)buf)[i] );
		if( CPLStrlcat(szValue,szData,MAX_METADATA_LEN) >= MAX_METADATA_LEN )
		    CPLError( CE_Warning, CPLE_OutOfMemory,
			      "Header data too long. Truncated\n");
	    }
	}
	CPLFree( buf );

    }
    H5Sclose(hAttrSpace);
    H5Tclose(hAttrNativeType);
    H5Tclose(hAttrTypeID);
    H5Aclose( hAttrID );
    //printf( "%s = %s\n",szTemp, szValue );
    poDS->papszMetadata =
	CSLSetNameValue( poDS->papszMetadata, szTemp,  
			 CPLSPrintf( "%s", szValue ) );
    CPLFree( szTemp );
    CPLFree( szData );
    CPLFree( szValue );

    return 0;
}
Пример #10
0
static herr_t HDF5AttrIterate( hid_t hH5ObjID,
                               const char *pszAttrName,
                               // TODO(schwehr): void * -> HDF5Dataset *
                               void *pDS )
{
    char **papszTokens = nullptr;
    CPLString osKey;
    HDF5Dataset *const poDS = static_cast<HDF5Dataset *>(pDS);

    // Convert "/" into "_" for the path component
    const char *pszPath = poDS->poH5CurrentObject->pszUnderscorePath;
    if(pszPath != nullptr && strlen(pszPath) > 0)
    {
        papszTokens = CSLTokenizeString2(pszPath, "/", CSLT_HONOURSTRINGS);

        for( hsize_t i = 0; papszTokens != nullptr && papszTokens[i] != nullptr; ++i )
        {
            if( i != 0)
                osKey += '_';
            osKey += papszTokens[i];
        }
        CSLDestroy(papszTokens);
    }

    // Convert whitespaces into "_" for the attribute name component
    papszTokens = CSLTokenizeString2(
        pszAttrName, " ", CSLT_STRIPLEADSPACES | CSLT_STRIPENDSPACES);
    for( hsize_t i = 0; papszTokens != nullptr && papszTokens[i] != nullptr; ++i )
    {
        if(!osKey.empty())
            osKey += '_';
        osKey += papszTokens[i];
    }
    CSLDestroy(papszTokens);

    const hid_t hAttrID = H5Aopen_name(hH5ObjID, pszAttrName);
    const hid_t hAttrTypeID = H5Aget_type(hAttrID);
    const hid_t hAttrNativeType =
        H5Tget_native_type(hAttrTypeID, H5T_DIR_DEFAULT);
    const hid_t hAttrSpace = H5Aget_space(hAttrID);

    if( H5Tget_class(hAttrNativeType) == H5T_VLEN )
        return 0;

    hsize_t nSize[64] = {};
    const unsigned int nAttrDims =
        H5Sget_simple_extent_dims(hAttrSpace, nSize, nullptr);

    unsigned int nAttrElmts = 1;
    for( hsize_t i = 0; i < nAttrDims; i++ )
    {
        nAttrElmts *= static_cast<int>(nSize[i]);
    }

    char *szData = nullptr;
    hsize_t nAttrSize = 0;
    char *szValue = nullptr;

    if( H5Tget_class(hAttrNativeType) == H5T_STRING )
    {
        if ( H5Tis_variable_str(hAttrNativeType) )
        {
            char **papszStrings =
                static_cast<char **>(CPLMalloc(nAttrElmts * sizeof(char *)));

            // Read the values.
            H5Aread(hAttrID, hAttrNativeType, papszStrings);

            // Concatenate all values as one string separated by a space.
            CPLString osVal = papszStrings[0];
            for( hsize_t i = 1; i < nAttrElmts; i++ )
            {
                osVal += " ";
                osVal += papszStrings[i];
            }

            szValue = static_cast<char *>(CPLMalloc(osVal.length() + 1));
            strcpy(szValue, osVal.c_str());

            H5Dvlen_reclaim(hAttrNativeType, hAttrSpace, H5P_DEFAULT,
                            papszStrings);
            CPLFree(papszStrings);
        }
        else
        {
            nAttrSize = H5Aget_storage_size(hAttrID);
            szValue = static_cast<char *>(CPLMalloc((size_t)(nAttrSize + 1)));
            H5Aread(hAttrID, hAttrNativeType, szValue);
            szValue[nAttrSize] = '\0';
        }
    }
    else
    {
        const size_t nDataLen = 8192;
        void *buf = nullptr;

        if( nAttrElmts > 0 )
        {
            buf = CPLMalloc(nAttrElmts * H5Tget_size(hAttrNativeType));
            szData = static_cast<char *>(CPLMalloc(nDataLen));
            szValue = static_cast<char *>(CPLMalloc(MAX_METADATA_LEN));
            szData[0] = '\0';
            szValue[0] = '\0';
            H5Aread(hAttrID, hAttrNativeType, buf);
        }
        if( H5Tequal(H5T_NATIVE_CHAR, hAttrNativeType ) ||
            H5Tequal(H5T_NATIVE_SCHAR, hAttrNativeType) )
        {
            for( hsize_t i = 0; i < nAttrElmts; i++ )
            {
                snprintf(szData, nDataLen, "%c ", static_cast<char *>(buf)[i]);
                if( CPLStrlcat(szValue, szData, MAX_METADATA_LEN) >=
                    MAX_METADATA_LEN )
                    CPLError(CE_Warning, CPLE_OutOfMemory,
                             "Header data too long. Truncated");
            }
        }
        else if( H5Tequal(H5T_NATIVE_UCHAR, hAttrNativeType) )
        {
            for( hsize_t i = 0; i < nAttrElmts; i++ )
            {
                snprintf(szData, nDataLen, "%c", static_cast<char *>(buf)[i]);
                if( CPLStrlcat(szValue, szData, MAX_METADATA_LEN) >=
                    MAX_METADATA_LEN )
                    CPLError(CE_Warning, CPLE_OutOfMemory,
                             "Header data too long. Truncated");
            }
        }
        else if( H5Tequal(H5T_NATIVE_SHORT, hAttrNativeType) )
        {
            for( hsize_t i = 0; i < nAttrElmts; i++ )
            {
                snprintf(szData, nDataLen, "%d ", static_cast<short *>(buf)[i]);
                if( CPLStrlcat(szValue, szData, MAX_METADATA_LEN) >=
                    MAX_METADATA_LEN )
                    CPLError(CE_Warning, CPLE_OutOfMemory,
                             "Header data too long. Truncated");
            }
        }
        else if( H5Tequal(H5T_NATIVE_USHORT, hAttrNativeType) )
        {
            for( hsize_t i = 0; i < nAttrElmts; i++ )
            {
              snprintf(szData, nDataLen, "%ud ",
                       static_cast<unsigned short *>(buf)[i]);
                if( CPLStrlcat(szValue, szData, MAX_METADATA_LEN) >=
                    MAX_METADATA_LEN )
                    CPLError(CE_Warning, CPLE_OutOfMemory,
                             "Header data too long. Truncated");
            }
        }
        else if( H5Tequal(H5T_NATIVE_INT, hAttrNativeType) )
        {
            for( hsize_t i=0; i < nAttrElmts; i++ )
            {
                snprintf(szData, nDataLen, "%d ", static_cast<int *>(buf)[i]);
                if( CPLStrlcat(szValue, szData, MAX_METADATA_LEN) >=
                    MAX_METADATA_LEN )
                    CPLError(CE_Warning, CPLE_OutOfMemory,
                             "Header data too long. Truncated");
            }
        }
        else if( H5Tequal(H5T_NATIVE_UINT, hAttrNativeType) )
        {
            for( hsize_t i = 0; i < nAttrElmts; i++ )
            {
                snprintf(szData, nDataLen, "%ud ",
                         static_cast<unsigned int *>(buf)[i]);
                if( CPLStrlcat(szValue, szData, MAX_METADATA_LEN) >=
                    MAX_METADATA_LEN )
                    CPLError(CE_Warning, CPLE_OutOfMemory,
                             "Header data too long. Truncated");
            }
        }
        else if( H5Tequal(H5T_NATIVE_LONG, hAttrNativeType) )
        {
            for( hsize_t i = 0; i < nAttrElmts; i++ )
            {
                snprintf(szData, nDataLen, "%ld ", static_cast<long *>(buf)[i]);
                if( CPLStrlcat(szValue, szData, MAX_METADATA_LEN) >=
                    MAX_METADATA_LEN )
                    CPLError(CE_Warning, CPLE_OutOfMemory,
                             "Header data too long. Truncated");
            }
        }
        else if( H5Tequal(H5T_NATIVE_ULONG, hAttrNativeType) )
        {
            for( hsize_t i = 0; i < nAttrElmts; i++ ) {
                snprintf(szData, nDataLen, "%lu ",
                         static_cast<unsigned long *>(buf)[i]);
                if( CPLStrlcat(szValue, szData, MAX_METADATA_LEN) >=
                    MAX_METADATA_LEN )
                    CPLError(CE_Warning, CPLE_OutOfMemory,
                             "Header data too long. Truncated");
            }
        }
        else if( H5Tequal(H5T_NATIVE_FLOAT, hAttrNativeType) )
        {
            for( hsize_t i = 0; i < nAttrElmts; i++ )
            {
                CPLsnprintf(szData, nDataLen, "%.8g ",
                            static_cast<float *>(buf)[i]);
                if( CPLStrlcat(szValue, szData, MAX_METADATA_LEN) >=
                    MAX_METADATA_LEN )
                    CPLError(CE_Warning, CPLE_OutOfMemory,
                             "Header data too long. Truncated");
            }
        }
        else if( H5Tequal(H5T_NATIVE_DOUBLE, hAttrNativeType) )
        {
            for( hsize_t i = 0; i < nAttrElmts; i++ )
            {
                CPLsnprintf(szData, nDataLen, "%.15g ",
                            static_cast<double *>(buf)[i]);
                if( CPLStrlcat(szValue, szData, MAX_METADATA_LEN) >=
                    MAX_METADATA_LEN )
                    CPLError(CE_Warning, CPLE_OutOfMemory,
                             "Header data too long. Truncated");
            }
        }
        CPLFree(buf);
    }
    H5Sclose(hAttrSpace);
    H5Tclose(hAttrNativeType);
    H5Tclose(hAttrTypeID);
    H5Aclose(hAttrID);
    poDS->papszMetadata = CSLSetNameValue(poDS->papszMetadata, osKey, szValue);

    CPLFree(szData);
    CPLFree(szValue);

    return 0;
}
Пример #11
0
herr_t H5IMis_palette( hid_t loc_id,
                      const char *dset_name )
{
    hid_t      did;
    int        has_class;
    hid_t      atid;
    hid_t      aid = -1;
    char*      attr_data;    /* Name of attribute */
    hsize_t    storage_size; /* Size of storage for attribute */
    herr_t     ret;

    /* check the arguments */
    if (dset_name == NULL) 
      return -1;

    /* Assume initially fail condition */
    ret = -1;

    /* Open the dataset. */
    if((did = H5Dopen2(loc_id, dset_name, H5P_DEFAULT)) < 0)
        return -1;

    /* Try to find the attribute "CLASS" on the dataset */
    has_class = H5LT_find_attribute(did, "CLASS");

    if(has_class ==  0)
    {
        H5Dclose( did );
        return 0;
    }
    else if(has_class ==  1)
    {

        if((aid = H5Aopen(did, "CLASS", H5P_DEFAULT)) < 0)
            goto out;

        if((atid = H5Aget_type(aid)) < 0)
            goto out;

	/* check to make sure attribute is a string */
	if(H5T_STRING != H5Tget_class(atid))
	    goto out;

	/* check to make sure string is null-terminated */
	if(H5T_STR_NULLTERM != H5Tget_strpad(atid))
	    goto out;

	/* allocate buffer large enough to hold string */
	if((storage_size = H5Aget_storage_size(aid)) == 0)
	    goto out;

	attr_data = (char*)HDmalloc( (size_t)storage_size * sizeof(char) + 1);
	if(attr_data == NULL)
	    goto out;

        if(H5Aread(aid, atid, attr_data) < 0)
            goto out;

        if(HDstrncmp(attr_data, PALETTE_CLASS, MIN(HDstrlen(PALETTE_CLASS),HDstrlen(attr_data))) == 0)
            ret = 1;
        else
            ret = 0;

	HDfree(attr_data);

        if ( H5Tclose( atid ) < 0)
            goto out;

        if ( H5Aclose( aid ) < 0)
            goto out;

    }

    /* Close the dataset. */
    if ( H5Dclose( did ) < 0)
        return -1;

    return ret;

out:
    H5Dclose( did );
    return -1;

}
Пример #12
0
herr_t HDF5AttrIterate( hid_t hH5ObjID,
                        const char *pszAttrName,
                        void *pDS )
{
    hid_t           hAttrID;
    hid_t           hAttrTypeID;
    hid_t           hAttrNativeType;
    hid_t           hAttrSpace;

    char           *szData = NULL;
    hsize_t        nSize[64];
    unsigned int   nAttrElmts;
    hsize_t        nAttrSize;
    hsize_t        i;
    void           *buf = NULL;
    unsigned int   nAttrDims;

    char          **papszTokens;

    HDF5Dataset    *poDS;
    CPLString       osKey;
    char           *szValue = NULL;

    poDS = (HDF5Dataset *) pDS;

    // Convert "/" into "_" for the path component
    const char* pszPath = poDS->poH5CurrentObject->pszUnderscorePath;
    if(pszPath != NULL && strlen(pszPath) > 0)
    {
        papszTokens = CSLTokenizeString2( pszPath, "/", CSLT_HONOURSTRINGS );

        for( i = 0; papszTokens != NULL && papszTokens[i] != NULL; ++i )
        {
            if( i != 0)
                osKey += '_';
            osKey += papszTokens[i];
        }
        CSLDestroy( papszTokens );
    }

    // Convert whitespaces into "_" for the attribute name component
    papszTokens = CSLTokenizeString2( pszAttrName, " ",
                            CSLT_STRIPLEADSPACES | CSLT_STRIPENDSPACES );
    for( i = 0; papszTokens != NULL && papszTokens[i] != NULL; ++i )
    {
        if(!osKey.empty())
            osKey += '_';
        osKey += papszTokens[i];
    }
    CSLDestroy( papszTokens );

    hAttrID          = H5Aopen_name( hH5ObjID, pszAttrName );
    hAttrTypeID      = H5Aget_type( hAttrID );
    hAttrNativeType  = H5Tget_native_type( hAttrTypeID, H5T_DIR_DEFAULT );
    hAttrSpace       = H5Aget_space( hAttrID );
    nAttrDims        = H5Sget_simple_extent_dims( hAttrSpace, nSize, NULL );

    nAttrElmts = 1;
    for( i=0; i < nAttrDims; i++ ) {
        nAttrElmts *= (int) nSize[i];
    }

    if( H5Tget_class( hAttrNativeType ) == H5T_STRING )
    {
        if ( H5Tis_variable_str(hAttrNativeType) )
        {
            char** papszStrings;
            papszStrings = (char**) CPLMalloc( nAttrElmts * sizeof(char*) );

            // Read the values
            H5Aread( hAttrID, hAttrNativeType, papszStrings );

            // Concatenate all values as one string (separated by a space)
            CPLString osVal = papszStrings[0];
            for( i=1; i < nAttrElmts; i++ ) {
                osVal += " ";
                osVal += papszStrings[i];
            }

            szValue = (char*) CPLMalloc(osVal.length() + 1);
            strcpy( szValue, osVal.c_str() );

            H5Dvlen_reclaim( hAttrNativeType, hAttrSpace, H5P_DEFAULT,
                             papszStrings );
            CPLFree( papszStrings );
        }
        else
        {
            nAttrSize = H5Aget_storage_size( hAttrID );
            szValue = (char*) CPLMalloc((size_t) (nAttrSize+1));
            H5Aread( hAttrID, hAttrNativeType, szValue );
            szValue[nAttrSize] = '\0';
        }
    }
    else {
        if( nAttrElmts > 0 ) {
            buf = (void *) CPLMalloc( nAttrElmts*
                          H5Tget_size( hAttrNativeType ));
            szData = (char*) CPLMalloc( 8192 );
            szValue = (char*) CPLMalloc( MAX_METADATA_LEN );
            szData[0] = '\0';
            szValue[0] ='\0';
            H5Aread( hAttrID, hAttrNativeType, buf );
        }
        if( H5Tequal( H5T_NATIVE_CHAR, hAttrNativeType ) 
            || H5Tequal( H5T_NATIVE_SCHAR,  hAttrNativeType ) ) {
            for( i=0; i < nAttrElmts; i++ ) {
                sprintf( szData, "%c ", ((char *) buf)[i]);
                if( CPLStrlcat(szValue, szData, MAX_METADATA_LEN) >=
                                                            MAX_METADATA_LEN )
                    CPLError( CE_Warning, CPLE_OutOfMemory,
                              "Header data too long. Truncated\n");
            }
        }
        else if( H5Tequal( H5T_NATIVE_UCHAR,  hAttrNativeType ) ) {
            for( i=0; i < nAttrElmts; i++ ) {
                sprintf( szData, "%c", ((char *) buf)[i] );
                if( CPLStrlcat(szValue, szData, MAX_METADATA_LEN) >=
                                                            MAX_METADATA_LEN )
                    CPLError( CE_Warning, CPLE_OutOfMemory,
                              "Header data too long. Truncated\n");
            }
        }
        else if( H5Tequal( H5T_NATIVE_SHORT,  hAttrNativeType ) ) {
            for( i=0; i < nAttrElmts; i++ ) {
                sprintf( szData, "%d ", ((short *) buf)[i] );
                if( CPLStrlcat(szValue, szData, MAX_METADATA_LEN) >=
                                                            MAX_METADATA_LEN )
                    CPLError( CE_Warning, CPLE_OutOfMemory,
                              "Header data too long. Truncated\n");
            }
        }
        else if( H5Tequal( H5T_NATIVE_USHORT, hAttrNativeType ) ) {
            for( i=0; i < nAttrElmts; i++ ) {
                sprintf( szData, "%ud ", ((unsigned short *) buf)[i] );
                if( CPLStrlcat(szValue, szData, MAX_METADATA_LEN) >=
                                                            MAX_METADATA_LEN )
                    CPLError( CE_Warning, CPLE_OutOfMemory,
                              "Header data too long. Truncated\n");
            }
        }
        else if( H5Tequal( H5T_NATIVE_INT,    hAttrNativeType ) ) {
            for( i=0; i < nAttrElmts; i++ ) {
                sprintf( szData, "%d ", ((int *) buf)[i] );
                if( CPLStrlcat(szValue, szData, MAX_METADATA_LEN) >=
                                                            MAX_METADATA_LEN )
                    CPLError( CE_Warning, CPLE_OutOfMemory,
                              "Header data too long. Truncated\n");
            }
        }
        else if( H5Tequal( H5T_NATIVE_UINT,   hAttrNativeType ) ) {
            for( i=0; i < nAttrElmts; i++ ) {
                sprintf( szData, "%ud ", ((unsigned int *) buf)[i] );
                if( CPLStrlcat(szValue, szData, MAX_METADATA_LEN) >=
                                                            MAX_METADATA_LEN )
                    CPLError( CE_Warning, CPLE_OutOfMemory,
                              "Header data too long. Truncated\n");
            }
        }
        else if( H5Tequal( H5T_NATIVE_LONG,   hAttrNativeType ) ) {
            for( i=0; i < nAttrElmts; i++ ) {
                sprintf( szData, "%ld ", ((long *)buf)[i] );
                if( CPLStrlcat(szValue, szData, MAX_METADATA_LEN) >=
                                                            MAX_METADATA_LEN )
                    CPLError( CE_Warning, CPLE_OutOfMemory,
                              "Header data too long. Truncated\n");
            }
        }
        else if( H5Tequal( H5T_NATIVE_ULONG,  hAttrNativeType ) ) {
            for( i=0; i < nAttrElmts; i++ ) {
                sprintf( szData, "%ld ", ((unsigned long *)buf)[i] );
                if( CPLStrlcat(szValue, szData, MAX_METADATA_LEN) >=
                                                            MAX_METADATA_LEN )
                    CPLError( CE_Warning, CPLE_OutOfMemory,
                              "Header data too long. Truncated\n");
            }
        }
        else if( H5Tequal( H5T_NATIVE_FLOAT,  hAttrNativeType ) ) {
            for( i=0; i < nAttrElmts; i++ ) {
                CPLsprintf( szData, "%.8g ",  ((float *)buf)[i] );
                if( CPLStrlcat(szValue, szData, MAX_METADATA_LEN) >=
                                                            MAX_METADATA_LEN )
                    CPLError( CE_Warning, CPLE_OutOfMemory,
                              "Header data too long. Truncated\n");
            }
        }
        else if( H5Tequal( H5T_NATIVE_DOUBLE, hAttrNativeType ) ) {
            for( i=0; i < nAttrElmts; i++ ) {
                CPLsprintf( szData, "%.15g ",  ((double *)buf)[i] );
                if( CPLStrlcat(szValue, szData, MAX_METADATA_LEN) >=
                                                            MAX_METADATA_LEN )
                    CPLError( CE_Warning, CPLE_OutOfMemory,
                              "Header data too long. Truncated\n");
            }
        }
        CPLFree( buf );

    }
    H5Sclose(hAttrSpace);
    H5Tclose(hAttrNativeType);
    H5Tclose(hAttrTypeID);
    H5Aclose( hAttrID );
    poDS->papszMetadata = CSLSetNameValue( poDS->papszMetadata, osKey, szValue);

    CPLFree( szData );
    CPLFree( szValue );

    return 0;
}
Пример #13
0
// JRC: This fat interface may not scale?  What about
// scalar attributes?
herr_t getAttributeHelper(const hid_t id, std::string* sval, std::vector<int>* ivals,
    std::vector<float>* fvals) {

  herr_t err = 0;
  size_t npoints;
  hid_t atype = H5Aget_type(id);
  H5T_class_t type = H5Tget_class(atype);
  hid_t aspace = H5Aget_space(id);
  size_t rank = H5Sget_simple_extent_ndims(aspace);

  /*
   hsize_t sdim[rank];
   ret = H5Sget_simple_extent_dims(aspace, sdim, NULL);
   dims->resize(rank);
   for (size_t i = 0; i < rank; ++i)
   (*dims)[i] = sdim[i];
   */

  if (type == H5T_INTEGER) {
    if (rank == 0) {
      ivals->resize(1);
      int v;
      // err = H5Aread(id, atype, &v);
      err = H5Aread(id, H5T_NATIVE_INT, &v);
      (*ivals)[0] = v;
      return err;
    }
    // rank>0
    npoints = H5Sget_simple_extent_npoints(aspace);
    int* v = new int[npoints];
    err = H5Aread(id, H5T_NATIVE_INT, v);
    ivals->resize(npoints);
    for (size_t i = 0; i<npoints; ++i) {
      (*ivals)[i] = v[i];
    }
    delete v;
    return err;
  }

  if (type == H5T_FLOAT) {
    if (rank == 0) {
      fvals->resize(1);
      float v;
      err = H5Aread(id, H5T_NATIVE_FLOAT, &v);
      (*fvals)[0] = v;
      return err;
    }
    // rank>0
    npoints = H5Sget_simple_extent_npoints(aspace);
    float* v = new float[npoints];
    err = H5Aread(id, H5T_NATIVE_FLOAT, v);
    fvals->resize(npoints);
    for (size_t i = 0; i<npoints; ++i) {
      (*fvals)[i] = v[i];
    }
    delete v;
    return err;
  }

  if (type == H5T_STRING) {
    if (rank != 0) {
      return -1;
    }
    size_t len = H5Aget_storage_size(id);
    sval->resize(len);
    char* v = new char[len];
    err = H5Aread(id, atype, v);
    // JRC: is this right?
    // err = H5Aread(id, H5T_NATIVE_CHAR, v);
    for (size_t i = 0; i < len; ++i) {
      (*sval)[i] = v[i];
    }
    delete [] v;
    return err;
  }
  return err;

}
Пример #14
0
med_err _MEDattributeStringWr(med_idt pid,
			      const char * const attname,
			      const med_size attsize,
			      const char * const val)
{
  med_access_mode MED_ACCESS_MODE;
  med_idt _attid=0,aid=0;
  med_err _ret=-1;
  int     type_hdf=0;
  med_bool        _attmustbecreated= MED_FALSE;
  hsize_t         _attsize=0;
  med_size        _valsize=0;

  if ( (MED_ACCESS_MODE = _MEDmodeAcces(pid) ) == MED_ACC_UNDEF ) {
    MED_ERR_(_ret,MED_ERR_INVALID,MED_ERR_ACCESSMODE, "MED_ACC_UNDEF" );
    SSCRUTE(attname); goto ERROR;
  }

  _valsize=strlen(val);
  if (_valsize > attsize) {
    MED_ERR_(_ret,MED_ERR_INVALID,MED_ERR_ATTRIBUTE, attname );
    ISCRUTE_size(_valsize);ISCRUTE_size(attsize);goto ERROR;
  }

  if ((aid = H5Screate(H5S_SCALAR)) < 0){
    MED_ERR_(_ret,MED_ERR_CREATE,MED_ERR_DATASPACE, attname );
    ISCRUTE_id(aid);
  }

  if ( (type_hdf = H5Tcopy(H5T_C_S1)) < 0) {
    MED_ERR_(_ret,MED_ERR_CREATE,MED_ERR_HDFTYPE, MED_ERR_NAME_MSG );
    SSCRUTE("H5T_C_S1"); goto ERROR;
  }

  if ( H5Tset_size(type_hdf,_valsize+1) < 0) {
    MED_ERR_(_ret,MED_ERR_CREATE,MED_ERR_HDFTYPE, MED_ERR_NAME_MSG );
    SSCRUTE("H5T_C_S1"); goto ERROR;
  }

  if  ( (_attid=H5Aopen( pid, attname,H5P_DEFAULT ))  >= 0 )
    if ( MED_ACCESS_MODE == MED_ACC_RDEXT )  {
      MED_ERR_(_ret,MED_ERR_INVALID,MED_ERR_ACCESSMODE, "MED_ACC_RDEXT" );
      SSCRUTE(attname); goto ERROR;
    }

  if ( _attid > 0 ) {
    if ( (_attsize=H5Aget_storage_size(_attid) ) < 0 ) goto ERROR;
    if ( (_valsize+1)  > _attsize ) {
      if (H5Aclose(_attid) < 0) {
	MED_ERR_(_ret,MED_ERR_CLOSE,MED_ERR_ATTRIBUTE,"");
	ISCRUTE_id(_attid);
	goto ERROR;
      }
      if ( H5Adelete(pid,attname) < 0 ) goto ERROR;
      _attmustbecreated=MED_TRUE;
    }
  }

  if ( (_attid < 0) || _attmustbecreated )
    if ( (_attid=H5Acreate( pid, attname, type_hdf, aid,  H5P_DEFAULT )) < 0 ) {
      MED_ERR_(_ret,MED_ERR_CREATE,MED_ERR_ATTRIBUTE, attname );
      goto ERROR;
    }

  if ( H5Awrite(_attid,type_hdf,val) < 0) {
    MED_ERR_(_ret,MED_ERR_WRITE,MED_ERR_ATTRIBUTE, attname );
    goto ERROR;
  }

  _ret=0;

 ERROR:

  if (type_hdf > 0 ) if ( H5Tclose(type_hdf) < 0) {
    MED_ERR_(_ret,MED_ERR_CLOSE,MED_ERR_HDFTYPE, MED_ERR_ID_MSG );
    ISCRUTE_int(type_hdf);
  }

  if (aid > 0 ) if ( H5Sclose(aid) < 0) {
    MED_ERR_(_ret,MED_ERR_CLOSE,MED_ERR_DATASPACE, MED_ERR_ID_MSG );
    ISCRUTE_id(aid);
  }

  if (_attid >0) if ( H5Aclose(_attid) < 0) {
    MED_ERR_(_ret,MED_ERR_CLOSE,MED_ERR_ATTRIBUTE, MED_ERR_ID_MSG );
    ISCRUTE_id(_attid);
  }


  return _ret;
}