Beispiel #1
0
bool loadStackHDF5( const char* fileName, Image4DSimple& img )
{
#ifdef USE_HDF5
    H5::Exception::dontPrint();
    H5::H5File file( fileName, H5F_ACC_RDONLY );

    for ( size_t i = 0; i < file.getObjCount(); i++ )
    {
        H5std_string name = file.getObjnameByIdx( i );
        if ( name == "Channels" )
        {
            H5::Group channels = file.openGroup( name );

            // Grab the attributes
            H5::Attribute attr = channels.openAttribute( "width" );
            H5::DataType type = attr.getDataType();
            long width, height;
            attr.read( type, &width );
            attr.close();

            attr = channels.openAttribute( "height" );
            attr.read( type, &height );
            attr.close();

            int num_channels = 0;
            // Count the number of channels
            for ( size_t obj = 0; obj < channels.getNumObjs(); obj++ )
                if ( channels.getObjTypeByIdx( obj ) == H5G_DATASET )
                    num_channels++;

            int channel_idx = 0;
            for ( size_t obj = 0; obj < channels.getNumObjs(); obj++ )
            {
                if ( channels.getObjTypeByIdx( obj ) == H5G_DATASET )
                {
                    H5std_string ds_name = channels.getObjnameByIdx( obj );
                    H5::DataSet data = channels.openDataSet( ds_name );
                    uint8_t* buffer = new uint8_t[ data.getStorageSize() ];
                    data.read( buffer, data.getDataType() );
                    QByteArray qbarray( ( const char* )buffer, data.getStorageSize() );
                    data.close();

                    if ( !loadIndexedStackFFMpeg( &qbarray, img, channel_idx++, num_channels,
                                                  width, height ) )
                    {
                        v3d_msg( "Error happened in HDF file reading. Stop. \n", false );
                        return false;
                    }

                    delete [] buffer;
                }
            }
        }
    }

#endif

    return true;
}
Beispiel #2
0
bool exists_attribute_of_type(H5::Group const& group, string name, bool mandatory = true)
{
    if (h5xx::exists_attribute(group, name)) {
        return h5xx::has_type<T>(group.openAttribute(name));
    }
    else {
        return !mandatory;
    }
}
Beispiel #3
0
 int Initialize(H5::Group &object, const std::string & attributeName) {
     try {
         attribute = object.openAttribute(attributeName.c_str());
     }
     catch (H5::Exception e) {
         cout << "ERROR. Could not open attribute " << attributeName << endl;
         exit(1);
     }
     isInitialized  = true;
     return 1;
 }
Beispiel #4
0
std::string read_string_attr(H5::H5File &f, H5::Group &group, const char *name)
{
  std::string strreadbuf ("");
  
  H5::Attribute attr = group.openAttribute(name);
  
  H5::StrType strdatatype(H5::PredType::C_S1, attr.getStorageSize());
  
  attr.read(strdatatype, strreadbuf);
  
  return strreadbuf;
}
Beispiel #5
0
      void ReadAttrib(const std::string& name, T& value, const H5::DataType& dType){
         //attributes are clunky in HDF5++ implementation - this is a workaround
         //template is required to pass the proper value type

         //access the built-in root group and create a new attribute for it.
         H5::Group rootGroup = file_->openGroup("/");
         H5::Attribute attrib = rootGroup.openAttribute(name);

         //write the value to the attribute and close
         attrib.read(dType,reinterpret_cast<void*>(&value));
         attrib.close();
      }
Beispiel #6
0
void Bundle2::loadParameters(H5::H5File& file) {
	H5::Group root = file.openGroup("/");

	// Checking version
	unsigned int fileVersion;
	H5::Attribute attr = root.openAttribute("version");
	attr.read(H5::PredType::NATIVE_UINT, &fileVersion);
	attr.close();

	if(fileVersion != version_) throw std::runtime_error("Incompatible bundle version!");

	// Reading number of cameras
	hsize_t count;
	H5::Group frame0Group = root.openGroup("POI/Frame 0000");
	attr = frame0Group.openAttribute("count");
	attr.read(H5::PredType::NATIVE_HSIZE, &count);
	attr.close();
	frame0Group.close();

	numCameras_ = count;

	// Reading parameters
	unsigned char r2;
	attr = root.openAttribute("reduce2");
	attr.read(H5::PredType::NATIVE_UCHAR, &r2);
	attr.close();

	parameters_.reduce2 = (r2 == 1);

	attr = root.openAttribute("xROI");
	attr.read(H5::PredType::NATIVE_UINT, &parameters_.xROI);
	attr.close();

	attr = root.openAttribute("yROI");
	attr.read(H5::PredType::NATIVE_UINT, &parameters_.yROI);
	attr.close();

	root.close();
}
Beispiel #7
0
void StateSet::init_from_datafile(std::string filename) {
	// open other file read-only
	H5::H5File otherfile;
	otherfile.openFile(filename, H5F_ACC_RDONLY);
	H5::Group otherroot = otherfile.openGroup("/");
	// check that grid properties match
	int othersx, othersy, otherN;
	double otherdx;
	otherroot.openAttribute("num_states").read(H5::PredType::NATIVE_INT, &otherN);
	otherroot.openAttribute("grid_sizex").read(H5::PredType::NATIVE_INT, &othersx);
	otherroot.openAttribute("grid_sizex").read(H5::PredType::NATIVE_INT, &othersy);
	otherroot.openAttribute("grid_delta").read(H5::PredType::NATIVE_DOUBLE, &otherdx);
	if (static_cast<int>(N) != otherN)
		throw GeneralError("Cannot copy state data from datafile: value for num_states does not match.");
	if (static_cast<int>(datalayout.sizex) != othersx)
		throw GeneralError("Cannot copy state data from datafile: value for grid_sizex does not match.");
	if (static_cast<int>(datalayout.sizey) != othersy)
		throw GeneralError("Cannot copy state data from datafile: value for grid_sizey does not match.");
	if (datalayout.dx != otherdx)
		throw GeneralError("Cannot copy state data from datafile: value for grid_delta does not match.");
	// copy data
	H5::DataSet other_states_data = otherfile.openDataSet("/states");
	other_states_data.read(state_array->get_dataptr(), other_states_data.getArrayType());
}
	/**
	 * @param attribute
	 * @return
	 */
	bool HDF5FileReader::doesAttributeExist(const std::string& attribute)
	{
		bool exists = false;
		H5::Group group = this->current_file->openGroup("/");
		try
		{
			group.openAttribute(attribute);
			exists = true;
		} catch (H5::AttributeIException& e)
		{
			exists = false;
		}
		return exists;

	}
Beispiel #9
0
static void attributes_append_group(Attributes &attrs, H5::Group &g, cpath basename, cpath group_path)
{     
  for(uint i=0;i<g.getNumObjs();i++) {
    
    char g_name[1024];
    g.getObjnameByIdx(hsize_t(i), g_name, 1024);
    cpath name = group_path / g_name;
    
    H5G_stat_t stat;
    g.getObjinfo(g_name, false, stat);
    
    if (stat.type == H5G_GROUP) {
      H5::Group sub = g.openGroup(g_name);
      attributes_append_group(attrs, sub, basename, name);
    }
    else if (stat.type == H5G_LINK)
    {
      //FIXME we assume soft link!
      Attribute attr;
      char attr_name[1024];
      char link[1024];
      
      attr.setName(remove_prefix(name, basename));
      
      H5L_info_t info;
      H5Lget_val(g.getId(), g_name, link, 1024, H5P_DEFAULT);
      attr.setLink(remove_prefix(link, basename));
      
      attrs.append(attr);
    }
  }
  
  
  for(int i=0;i<g.getNumAttrs();i++) {
    H5::Attribute h5attr = g.openAttribute(i);
    Attribute attr;
    BaseType type;
    char name[1024];
    
    H5Aget_name(h5attr.getId(), 1024, name);
    read_attr(&attr, g, basename, group_path, name, type);
    
    attrs.append(attr);
  }
}
Beispiel #10
0
   const std::string ReadStrAttrib(const std::string& name){
      //attributes are clunky in HDF5++ implementation - this is a workaround
      //template is required to pass the proper value type

      std::string value;
      value.resize( STRING_ATTRIB_SIZE );

      H5::StrType strType(0, STRING_ATTRIB_SIZE );
      //access the built-in root group and create a new attribute for it.
      H5::Group rootGroup = file_->openGroup("/");
      H5::Attribute attrib = rootGroup.openAttribute(name);

      //write the value to the attribute and close
      attrib.read(strType,value);
      attrib.close();

      return value;
   }
Beispiel #11
0
static void read_attr(Attribute *attr, H5::Group g, cpath basename, cpath group_path, cpath name, BaseType &type)
{
  int total = 1;
  H5::Attribute h5attr = g.openAttribute(name.generic_string().c_str());
    
  type =  toBaseType(H5Aget_type(h5attr.getId()));
  
  H5::DataSpace space = h5attr.getSpace();
  int dimcount = space.getSimpleExtentNdims();

  hsize_t *dims = new hsize_t[dimcount];
  hsize_t *maxdims = new hsize_t[dimcount];
  
  space.getSimpleExtentDims(dims, maxdims);
  for(int i=0;i<dimcount;i++)
    total *= dims[i];
  
  group_path = remove_prefix(group_path, basename);
  name = group_path / name;
  
  //legacy attribute reading
  if (dimcount == 1) {
    void *buf = malloc(baseType_size(type)*total);
    
    h5attr.read(toH5NativeDataType(type), buf);
    
    attr->set<hsize_t>(name, dimcount, dims, type, buf);
  }
  else {
    Mat m;
    Mat_H5AttrRead(m, h5attr);
    attr->setName(name);
    attr->set(m);
  }

  delete[] dims;
  delete[] maxdims;
}
Beispiel #12
0
Bundle2::Bundle2(const boost::filesystem::path& fileName, bool loadGeometry):
	version_(BUNDLE_VERSION), poiFirstFrame_(0) {
	// Opening file
	H5::H5File bundleFile;
	bundleFile.openFile(fileName.string(), H5F_ACC_RDONLY);
	loadParameters(bundleFile);

	// Loading POI
	H5::Group poiGroup = bundleFile.openGroup("/POI");

	hsize_t count;
	H5::Attribute attr = poiGroup.openAttribute("count");
	attr.read(H5::PredType::NATIVE_HSIZE, &count);
	attr.close();

	for(size_t frame = 0; frame < count; ++frame) {
		cout.flush();

		const std::string frameGroupName = boost::str(boost::format("Frame %1$04d") % frame);
		H5::Group frameGroup = poiGroup.openGroup(frameGroupName);

		addPOIFrame();
		for(size_t camera = 0; camera < numCameras_; ++camera)
			poi_[poi_.size() - 1][camera].load(frameGroup, camera);

		frameGroup.close();
	}

	poiGroup.close();

	// Loading frames
	H5::Group bundleGroup = bundleFile.openGroup("/Bundle");

	H5::Group framesGroup = bundleGroup.openGroup("Frames");

	attr = framesGroup.openAttribute("count");
	attr.read(H5::PredType::NATIVE_HSIZE, &count);
	attr.close();

	for(size_t frame = 0; frame < count; ++frame) {
		Frame* f = new Frame(framesGroup, frame, numCameras_);
		frames_.push_back(f);
	}

	framesGroup.close();

	// Loading tracks
	H5::DataSet tracksDataset = bundleGroup.openDataSet("Tracks");

	hsize_t tracksDim[2];
	H5::DataSpace tracksDS = tracksDataset.getSpace();
	tracksDS.getSimpleExtentDims(tracksDim);
	tracksDS.close();

	for(size_t i = 0; i < tracksDim[0]; ++i) {
		size_t j = addTrack();
		tracks_[j]->load(tracksDataset, frames_, i);
	}

	tracksDataset.close();

	bundleGroup.close();

	if(loadGeometry && checkGeometry_(bundleFile)) loadGeometry_(bundleFile);

	bundleFile.close();
}
	/**
	 * @param attribute
	 * @return
	 */
	Attribute HDF5FileReader::getGlobalAttribute(const std::string& attribute)
	{
		//first, check if the attribute has already been requested. If so, return stored value
		boost::unordered_map<std::string, Attribute>::iterator iter = gAttributes.find(attribute);
		if (iter != gAttributes.end())
			return (*iter).second;

//		std::cout << "after search in getGlobalAttribute(const std::string& attribute)" << std::endl;
//		std::cout << "attribute: " << attribute << std::endl;
		H5::Group group = this->current_file->openGroup("/");
		H5::Attribute h5attribute = group.openAttribute(attribute);
		long attrNum = h5attribute.getId();
		H5::DataType dataType = h5attribute.getDataType();
//		std::cout << "attrNum after attribute: " << attrNum << std::endl;
		Attribute current_attribute;
		if (attrNum < 0)
		{
			std::cout << "attrNum: " << attrNum << " returned for " << attribute << std::endl;
		}
		else
		{
//			std::cout << "attribute: " << attribute << " attribute number: " << attrNum << std::endl;
//			std::cout << "attempting to get attribute without using attribute number\n";
			if (dataType.getClass() == H5T_STRING)
			{
				std::string attributeValue = "NULL";
				h5attribute.read(dataType, attributeValue);

				std::string attributeName = "";
				attributeName = h5attribute.getName();


				current_attribute.setAttributeName(attributeName);
				//std::cout << "name: '" << attributeName << "' string attributeBuffer: '" << attributeValue << "'"<< std::endl;
				current_attribute.setAttributeValue(attributeValue);
				gAttributeByID[(int)attrNum] = current_attribute;
				gAttributes[current_attribute.getAttributeName()] = current_attribute;
				//return attribute;
			} else if (dataType.getClass() == H5T_INTEGER)
			{
				//int attributeValue = 0.f;
				int attributeBuffer;// = new int[1];

				h5attribute.read(dataType, &attributeBuffer);
				std::string attributeName = "";
				attributeName = h5attribute.getName();
				current_attribute.setAttributeName(attributeName);
				//std::cout << "int attributeBuffer: '" << attributeBuffer << "'"<< std::endl;
				current_attribute.setAttributeValue(attributeBuffer);
				gAttributeByID[(int)attrNum] = current_attribute;
				gAttributes[current_attribute.getAttributeName()] = current_attribute;
				//return attribute;
			} else if (dataType.getClass() == H5T_FLOAT)//CDF_FLOAT
			{
				//int attributeValue = 0.f;
				float attributeValue;// = new int[1];

				h5attribute.read(dataType, &attributeValue);
				std::string attributeName = "";
				attributeName = h5attribute.getName();
				current_attribute.setAttributeName(attributeName);
				//std::cout << "float attributeBuffer: '" << attributeValue << "'"<< std::endl;

				current_attribute.setAttributeValue(attributeValue);
				gAttributeByID[(int)attrNum] = current_attribute;
				gAttributes[current_attribute.getAttributeName()] = current_attribute;
				//return attribute;
			}

		}//gAttributes[attribute] = current_attribute;
		return current_attribute;
//		return Attribute();
	}
	/**
	 * @param i The attribute number
	 * @return
	 */
	Attribute HDF5FileReader::getGlobalAttribute(long i)
	{

		std::cerr << "entered " << BOOST_CURRENT_FUNCTION << " i = " << (int)i << std::endl;
		H5::Group group = this->current_file->openGroup("/");
		std::cout<< "group assigned\n";
		H5::Attribute h5attribute = group.openAttribute((unsigned int)i);
		std::cout<< "attribute opened\n";
		H5::DataType dataType = h5attribute.getDataType();
		std::cout<< "dataType retrieved\n";
		Attribute attribute;
		std::cout << "checking dataType"<<std::endl;
		if (dataType.getClass() == H5T_STRING)
		{
			std::string attributeValue = "NULL";
			h5attribute.read(dataType, attributeValue);

			std::string attributeName = "";
			attributeName = h5attribute.getName();


			attribute.setAttributeName(attributeName);
			//std::cout << "name: '" << attributeName << "' string attributeBuffer: '" << attributeValue << "'"<< std::endl;
			attribute.setAttributeValue(attributeValue);
			gAttributeByID[i] = attribute;
			gAttributes[attribute.getAttributeName()] = attribute;
			//return attribute;
		} else if (dataType.getClass() == H5T_INTEGER)
		{
			//int attributeValue = 0.f;
			int attributeBuffer;// = new int[1];

			h5attribute.read(dataType, &attributeBuffer);
			std::string attributeName = "";
			attributeName = h5attribute.getName();
			attribute.setAttributeName(attributeName);
			//std::cout << "int attributeBuffer: '" << attributeBuffer << "'"<< std::endl;
			attribute.setAttributeValue(attributeBuffer);
			gAttributeByID[i] = attribute;
			gAttributes[attribute.getAttributeName()] = attribute;
			//return attribute;
		} else if (dataType.getClass() == H5T_FLOAT)//CDF_FLOAT
		{
			//int attributeValue = 0.f;
			float attributeValue;// = new int[1];

			h5attribute.read(dataType, &attributeValue);
			std::string attributeName = "";
			attributeName = h5attribute.getName();
			attribute.setAttributeName(attributeName);
			//std::cout << "float attributeBuffer: '" << attributeValue << "'"<< std::endl;

			attribute.setAttributeValue(attributeValue);
			gAttributeByID[i] = attribute;
			gAttributes[attribute.getAttributeName()] = attribute;
			//return attribute;
		}

		//std::cout << "added: " << i << " name: '" << attribute.getAttributeName() << "'" << endl;
		//std::cout << "Attribute: " << attribute.toString() << std::endl;
		return attribute;

	}
void load_particle_space(const H5::Group& root, Tspace_* space)
{
    typedef ParticleSpaceHDF5Traits traits_type;
    typedef typename traits_type::h5_species_struct h5_species_struct;
    typedef typename traits_type::h5_particle_struct h5_particle_struct;

    Real3 edge_lengths;
    const hsize_t dims[] = {3};
    const H5::ArrayType lengths_type(H5::PredType::NATIVE_DOUBLE, 1, dims);
    root.openAttribute("edge_lengths").read(lengths_type, &edge_lengths);
    space->reset(edge_lengths);

    double t;
    root.openAttribute("t").read(H5::PredType::IEEE_F64LE, &t);
    space->set_t(t);

    {
        H5::DataSet species_dset(root.openDataSet("species"));
        const unsigned int num_species(
            species_dset.getSpace().getSimpleExtentNpoints());
        boost::scoped_array<h5_species_struct> h5_species_table(
            new h5_species_struct[num_species]);
        species_dset.read(
            h5_species_table.get(), traits_type::get_species_comp_type());
        species_dset.close();

        H5::DataSet particle_dset(root.openDataSet("particles"));
        const unsigned int num_particles(
            particle_dset.getSpace().getSimpleExtentNpoints());
        boost::scoped_array<h5_particle_struct> h5_particle_table(
            new h5_particle_struct[num_particles]);
        particle_dset.read(
            h5_particle_table.get(), traits_type::get_particle_comp_type());
        particle_dset.close();

        typedef utils::get_mapper_mf<unsigned int, Species::serial_type>::type
            species_id_map_type;
        species_id_map_type species_id_map;
        for (unsigned int i(0); i < num_species; ++i)
        {
            species_id_map[h5_species_table[i].id] = h5_species_table[i].serial;
        }

        for (unsigned int i(0); i < num_particles; ++i)
        {
            space->update_particle(ParticleID(std::make_pair(h5_particle_table[i].lot, h5_particle_table[i].serial)), Particle(Species(species_id_map[h5_particle_table[i].sid]), Real3(h5_particle_table[i].posx, h5_particle_table[i].posy, h5_particle_table[i].posz), h5_particle_table[i].radius, h5_particle_table[i].D));
        }

        // boost::scoped_array<h5_particle_struct>
        //     h5_particle_table(new h5_particle_struct[num_particles]);
        // for (unsigned int i(0); i < num_particles; ++i)
        // {
        //     species_id_map_type::const_iterator
        //         it(species_id_map.find(particles[i].second.species_serial()));
        //     if (it == species_id_map.end())
        //     {
        //         species.push_back(particles[i].second.species());
        //         it = species_id_map.insert(
        //             std::make_pair(particles[i].second.species_serial(),
        //                            species.size())).first;
        //     }

        //     h5_particle_table[i].lot = particles[i].first.lot();
        //     h5_particle_table[i].serial = particles[i].first.serial();
        //     h5_particle_table[i].sid = (*it).second;
        //     h5_particle_table[i].posx = particles[i].second.position()[0];
        //     h5_particle_table[i].posy = particles[i].second.position()[1];
        //     h5_particle_table[i].posz = particles[i].second.position()[2];
        //     h5_particle_table[i].radius = particles[i].second.radius();
        //     h5_particle_table[i].D = particles[i].second.D();
        // }

        // boost::scoped_array<h5_species_struct>
        //     h5_species_table(new h5_species_struct[species.size()]);
        // for (unsigned int i(0); i < species.size(); ++i)
        // {
        //     h5_species_table[i].id = i + 1;
        //     std::strcpy(h5_species_table[i].serial,
        //                 species[i].serial().c_str());
        // }
    }
}
Beispiel #16
0
/*********************************************************
FunctionName:RecursiveVisitNode
FunctionDesc:递归创建Group
InputParam:
OutputParam:
Return:
Author:xiaowei.han
*********************************************************/
void RecursiveVisitNode(H5::Group& Node, Hdf5_Wrapper::LP_HDF5_DATA pData)
{
	using namespace H5;
	if (nullptr == pData)
	{
		return;
	}
	//获取节点名称
	pData->strKeyName = Utility::UTF8ToGB2312(Node.getObjName());
	//获取属性个数
	int nAttrNum = static_cast<int>(Node.getNumAttrs());
	for (int i = 0; i < nAttrNum; ++i)
	{
		auto childAttr = Node.openAttribute(i);

		//解析读取属性数据
		//获取数据类型
		auto AttrDataType = childAttr.getDataType();
		//获取数据类型大小
		unsigned int nDataByte = (unsigned int)AttrDataType.getSize();

		boost::scoped_ptr<CAbstractAttrHanlder> pHandler(CreateAttrHandler(childAttr.getTypeClass(), nDataByte));

		if (pHandler)
		{
			pHandler->ReadAttr(childAttr, AttrDataType, pData->AttributeArray);
		}
		childAttr.close();
	}

	//获取节点对象个数
	int nObjNum = static_cast<int>(Node.getNumObjs());

	//遍历子节点信息
	for (int i = 0; i < nObjNum; ++i)
	{
		//NECESSARY_LOG("the node name is [%s],the type is [%d].", Node.getObjnameByIdx(i).c_str(), Node.getObjTypeByIdx(i));
		auto SubNodeType = Node.getObjTypeByIdx(i);
		switch (SubNodeType)
		{
		case H5G_GROUP:
		{
			Hdf5_Wrapper::LP_HDF5_DATA pSubData = new Hdf5_Wrapper::HDF5_DATA;
			if (nullptr != pSubData)
			{
				//添加进去
				pData->SubDataArray.push_back(pSubData);
				auto ChildGroupNode = Node.openGroup(Node.getObjnameByIdx(i));
				RecursiveVisitNode(ChildGroupNode,pSubData);
				ChildGroupNode.close();
			}
		}
		break;
		case H5G_DATASET:
		{
			auto childDataset = Node.openDataSet(Node.getObjnameByIdx(i));

			Hdf5_Wrapper::LP_HDF5_DATA pSubData = new Hdf5_Wrapper::HDF5_DATA;
			if (nullptr != pSubData)
			{
				pSubData->strKeyName = childDataset.getObjName();
				//添加进去
				pData->SubDataArray.push_back(pSubData);
				//获取数据类型
				auto ChildDataSetDataType = childDataset.getDataType();
				//获取类型占用字节数
				unsigned int nDataByte = (unsigned int)ChildDataSetDataType.getSize();
				//判断数据类型
				boost::scoped_ptr<CAbstractDataTypeHandler> pHandlder(CDataTypeHandlerFactory::CreateDataTypeHandler(childDataset.getTypeClass(),nDataByte));
				if (pHandlder)
				{
					pHandlder->ReadDataSet(childDataset, pSubData);
				}
			}
		}
		break;
		default:
			break;
		}	
	}
}
Beispiel #17
0
//--------------------------------------------------------------------------------------------------
/// 
//--------------------------------------------------------------------------------------------------
TEST(DISABLED_HDFTests, BasicFileRead)
{
    std::string file_path = "D:/ResInsight/SourSim/PKMUNK_NOV_TEST_SS.sourpre.00001";

    try
    {
        H5::Exception::dontPrint();                                // Turn off auto-printing of failures to handle the errors appropriately

        H5::H5File file(file_path.c_str(), H5F_ACC_RDONLY);

        {
            H5::Group        timestep = file.openGroup("Timestep_00001");
            H5::Attribute    attr     = timestep.openAttribute("timestep");

            double timestep_value = 0.0;

            H5::DataType type = attr.getDataType();
            attr.read(type, &timestep_value);

            //std::cout << "Timestep value " << timestep_value << std::endl;
            EXPECT_NEAR(timestep_value, 1.0, 1e-1);
        }


        {
            // Group size is not an attribute!

            H5::Group GridFunctions = file.openGroup("Timestep_00001/GridParts/GridPart_00000/GridFunctions");

            hsize_t   group_size = GridFunctions.getNumObjs();

            //std::cout << "GridFunctions group_size " << group_size << std::endl;
            EXPECT_EQ(size_t(20), group_size);

/*            for (hsize_t i = 0; i < group_size; i++)
            {
                // H5std_string node_name = GridFunctions.getObjnameByIdx(i);     // crashes on VS2017 due to lib/heap/runtime differences to HDF5 VS2015 lib

                std::string node_name;
                node_name.resize(1024);

                ssize_t slen = GridFunctions.getObjnameByIdx(i, &node_name[0], 1023);

                node_name.resize(slen + 1);

                std::cout << "GridFunctions sub-node name " << node_name << std::endl;
            }
*/

            std::string first_subnode(1024, '\0');

            ssize_t slen = GridFunctions.getObjnameByIdx(0, &first_subnode[0], 1023);
            first_subnode.resize(slen + 1);

            EXPECT_TRUE(first_subnode.compare(0, slen, "GridFunction_00002") == 0);
        }


        {
            H5::Group        GridFunction_00002 = file.openGroup("Timestep_00001/GridParts/GridPart_00000/GridFunctions/GridFunction_00002");
            H5::Attribute    attr = GridFunction_00002.openAttribute("limits_max");

            double limits_max = 0.0;
        
            H5::DataType type = attr.getDataType();
            attr.read(type, &limits_max);

//            std::cout << "limits_max " << limits_max << std::endl;
            EXPECT_NEAR(limits_max, 0.3970204292629652, 1e-10);
        }


        {
            H5::Group        GridFunction_00002 = file.openGroup("Timestep_00001/GridParts/GridPart_00000/GridFunctions/GridFunction_00002");
            H5::DataSet        dataset = H5::DataSet(GridFunction_00002.openDataSet("values"));

            hsize_t dims[2];
            H5::DataSpace    dataspace = dataset.getSpace();
            dataspace.getSimpleExtentDims(dims, nullptr);

            std::vector<double> values;
            values.resize(dims[0]);
            dataset.read(values.data(), H5::PredType::NATIVE_DOUBLE);

/*            for (hsize_t i = 0; i < dims[0]; i++)
            {
                std::cout << "value " << i << " " << values[i] << std::endl;

            }
*/
            EXPECT_NEAR(values[0], 0.32356910366452146, 1e-10);
            EXPECT_NEAR(values[dims[0] - 1], 0.12200070891582514, 1e-10);
        }



    }  // end of try block
    
       
    catch (H5::FileIException error)        // catch failure caused by the H5File operations
    {
        std::cout << error.getCDetailMsg();
    }
    
    catch (H5::DataSetIException error)        // catch failure caused by the DataSet operations
    {
        std::cout << error.getCDetailMsg();
    }
    
    catch (H5::DataSpaceIException error)    // catch failure caused by the DataSpace operations
    {
        std::cout << error.getCDetailMsg(); 
    }
    
    catch (H5::DataTypeIException error)        // catch failure caused by the DataSpace operations
    {
        std::cout << error.getCDetailMsg();
    }

}
Beispiel #18
0
int main (int argc, char * argv[])
{

	long status = -1L;
	H5::H5File * current_file = NULL;

	try
	{
		current_file = new H5::H5File(argv[1], H5F_ACC_RDONLY);
	}
	catch(H5::Exception const& ex)
	{
		exit(1);
	}
	std::cout << "Opened file " << argv[1] << std::endl;

	long counts[1];
	std::vector<float>* variableData = new std::vector<float>();

	std::string variable = "rho";

	H5::Group group = current_file->openGroup("/");
	H5::Attribute attribute = group.openAttribute()
	/*H5::DataSet * dataset = new H5::DataSet(group.openDataSet(variable));

	H5::DataSpace dataspace = dataset->getSpace();
	int rank = dataspace.getSimpleExtentNdims(); //should be 1
	hsize_t count[1];
	hsize_t dims_out[1];
	hsize_t offset[1] = {0};
	int ndims = dataspace.getSimpleExtentDims(dims_out, NULL);
	std::cout << "dims_out[0]: " << dims_out[0] << " num dimensions: " << ndims << std::endl;
	float * buffer = new float[dims_out[0]];



	dataspace.selectHyperslab(H5S_SELECT_SET, dims_out, offset);

	hsize_t dim[] = {dims_out[0]};
	H5::DataSpace memspace( rank, dim);
	memspace.selectHyperslab(H5S_SELECT_SET, dim, offset);

	dataset->read(buffer, H5::PredType::NATIVE_FLOAT, memspace, dataspace);


	//add data to vector type, and delete original array
	variableData->reserve(dims_out[0]);
	for (int i = 0; i < dims_out[0]; i++)
	{
		variableData->push_back(buffer[i]);
	}


	delete[] buffer;
	delete dataset;
	std::cout << "finished reading " << variable << std::endl;
	std::cout << "size of variable: " << variableData->size() << std::endl;
	std::cout << "dims_out[0]: " << dims_out[0] << std::endl;
*/
	return 0;
}
Beispiel #19
0
void ossim_hdf5::printIterative( H5::H5File* file,
                                 const std::string& groupName,
                                 const std::string& prefix,
                                 ossim_uint32& recursedCount,
                                 std::ostream& out )
{
   if ( file && groupName.size() )
   {
      ++recursedCount;
      
      H5::Group* group = new H5::Group( file->openGroup(groupName) );

      // Print attributes:
      const ossim_uint32 ATTRS_COUNT = group->getNumAttrs();
      for ( ossim_uint32 aIdx = 0; aIdx < ATTRS_COUNT; ++aIdx )
      {
         H5::Attribute attr( group->openAttribute( aIdx ) );
         ossim_hdf5::printAttribute( attr, prefix, out );
         attr.close();
      }
      
      const hsize_t OBJ_COUNT = group->getNumObjs();
      for ( hsize_t i = 0; i < OBJ_COUNT; ++i )
      {
         std::string objName = group->getObjnameByIdx(i);

         if ( objName.size() )
         {
            char separator = '/';
            std::string combinedName;
            combine( groupName, objName, separator, combinedName );
            
            separator = '.';
            std::string combinedPrefix;
            combine( prefix, objName, separator, combinedPrefix );
            
            H5G_obj_t objType   = group->getObjTypeByIdx(i);

#if 0
            std::cout << "combinedName: " << combinedName
                      << "\ncombinedPrefix: " << combinedPrefix
                      << "\ngetObjnameByIdx[" << i << "]: " << objName
                      << "\ngetObjTypeByIdx[" << i << "]: " << objType
                      << std::endl;
#endif
            
            if ( objType == H5G_GROUP )
            {
               // Recursive call:
               if ( recursedCount < ossim_hdf5::MAX_RECURSION_LEVEL )
               {
                  ossim_hdf5::printIterative(
                     file, combinedName, combinedPrefix, recursedCount, out );
               }
               else
               {
                  ossimNotify(ossimNotifyLevel_WARN)
                     << "ossim_hdf5::printIterative WARNING!"
                     << "\nMax iterations reached!" << std::endl;
               }
            }
            else if ( objType == H5G_DATASET )
            {
               printObject( file, combinedName, combinedPrefix, out );
            }
            else
            {
               ossimNotify(ossimNotifyLevel_WARN)
                  << "ossim_hdf5::printIterative WARNING!"
                  << "\nUnhandled object type: " << objType << std::endl;
            }
         }
      }
      
      group->close();
      delete group;
      group = 0;
      --recursedCount;
      
   } // Matches: if ( file )
   
} // End: void ossim_hdf5::printIterative method.