Example #1
0
void
DataSetIO::SaveDataSet(const DataSet& dataSet_, const std::string& filename_){
    // Get the relevant params
    hsize_t nEntries     = dataSet_.GetNEntries();
    hsize_t nObs  = dataSet_.GetNObservables();
    hsize_t nData = nObs * nEntries;

    // create colon separated string from list of observables
    std::vector<std::string> observableNames = dataSet_.GetObservableNames();
    if (observableNames.size() != nObs)
        throw HdfIOError("SaveDataSet::Require one name and one name only for each observable");
    

    // Set up files
    H5::H5File file(filename_, H5F_ACC_TRUNC);
    
    // Flatten data into 1D array
    // HDF5 likes c arrays. Here use a vector and pass pointer to first element 
    // memory guaranteed to be contiguous
    std::vector<double> flattenedData;
    std::vector<double> eventData;
    flattenedData.reserve(nData);
    for(size_t i = 0; i < nEntries; i++){
        eventData = dataSet_.GetEntry(i).GetData();
        flattenedData.insert(flattenedData.end(), eventData.begin(), eventData.end());
    }
    
    // Set up the data set
    // 1D, ndata long, called "observations". Saved as native doubles on this computer
    H5::DataSpace dataSpace(1, &nData);  
    H5::DataSet   theData(file.createDataSet("observations", H5::PredType::NATIVE_DOUBLE, dataSpace));
    
    //  Set up the attributes - the number of obs per event and the names of the observables
    //  64 chars max in str to save space
    H5::StrType   strType(H5::PredType::C_S1, 64);
    H5::DataSpace attSpace(H5S_SCALAR);
    H5::Attribute obsListAtt = theData.createAttribute("observed_quantities", strType, attSpace);
    obsListAtt.write(strType, FlattenStringVector(observableNames, fDelimiter));

    H5::Attribute countAtt = theData.createAttribute("n_observables",
                                                     H5::PredType::NATIVE_INT,
                                                     attSpace);
    countAtt.write(H5::PredType::NATIVE_INT, &nObs);

    //  Write the data
    theData.write(&flattenedData.at(0), H5::PredType::NATIVE_DOUBLE);
    
}