XdmfHDF5Controller.cpp 14.3 KB
Newer Older
Kenneth Leiter's avatar
Kenneth Leiter committed
1
/*****************************************************************************/
2
/*                                    Xdmf                                   */
Kenneth Leiter's avatar
Kenneth Leiter committed
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/*                       eXtensible Data Model and Format                    */
/*                                                                           */
/*  Id : XdmfHDF5Controller.cpp                                              */
/*                                                                           */
/*  Author:                                                                  */
/*     Kenneth Leiter                                                        */
/*     kenneth.leiter@arl.army.mil                                           */
/*     US Army Research Laboratory                                           */
/*     Aberdeen Proving Ground, MD                                           */
/*                                                                           */
/*     Copyright @ 2011 US Army Research Laboratory                          */
/*     All Rights Reserved                                                   */
/*     See Copyright.txt for details                                         */
/*                                                                           */
/*     This software is distributed WITHOUT ANY WARRANTY; without            */
/*     even the implied warranty of MERCHANTABILITY or FITNESS               */
/*     FOR A PARTICULAR PURPOSE.  See the above copyright notice             */
/*     for more information.                                                 */
/*                                                                           */
/*****************************************************************************/
23

24
#include <H5public.h>
25
#include <hdf5.h>
26
#include <numeric>
27
#include <sstream>
28
#include "string.h"
29
#include "XdmfArray.hpp"
30
#include "XdmfArrayType.hpp"
31
#include "XdmfError.hpp"
32
#include "XdmfHDF5Controller.hpp"
33
#include "XdmfSystemUtils.hpp"
34

35 36 37 38
unsigned int XdmfHDF5Controller::mMaxOpenedFiles = 0;
static std::map<std::string, hid_t> mOpenFiles;
std::map<std::string, unsigned int> XdmfHDF5Controller::mOpenFileUsage;

39
shared_ptr<XdmfHDF5Controller>
40 41
XdmfHDF5Controller::New(const std::string & hdf5FilePath,
                        const std::string & dataSetPath,
42
                        const shared_ptr<const XdmfArrayType> & type,
43 44
                        const std::vector<unsigned int> & start,
                        const std::vector<unsigned int> & stride,
45 46
                        const std::vector<unsigned int> & dimensions,
                        const std::vector<unsigned int> & dataspaceDimensions)
47
{
48 49 50 51 52 53 54 55 56
  shared_ptr<XdmfHDF5Controller> 
    p(new XdmfHDF5Controller(hdf5FilePath,
                             dataSetPath,
                             type,
                             start,
                             stride,
                             dimensions,
                             dataspaceDimensions));
  return p;
57 58
}

59 60
XdmfHDF5Controller::XdmfHDF5Controller(const std::string & hdf5FilePath,
                                       const std::string & dataSetPath,
61
                                       const shared_ptr<const XdmfArrayType> & type,
62 63
                                       const std::vector<unsigned int> & start,
                                       const std::vector<unsigned int> & stride,
64 65
                                       const std::vector<unsigned int> & dimensions,
                                       const std::vector<unsigned int> & dataspaceDimensions) :
66 67
  XdmfHeavyDataController(hdf5FilePath,
                          type,
68 69 70 71
                          start,
                          stride, 
                          dimensions,
                          dataspaceDimensions),
72
  mDataSetPath(dataSetPath),
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
  mDataSetPrefix(""),
  mDataSetId(-1)
{
  unsigned int i = 0;
  for (; i < mDataSetPath.size(); ++i) {
    if (mDataSetPath[(mDataSetPath.size() - 1) - i] != '0' &&
        mDataSetPath[(mDataSetPath.size() - 1) - i] != '1' &&
        mDataSetPath[(mDataSetPath.size() - 1) - i] != '2' &&
        mDataSetPath[(mDataSetPath.size() - 1) - i] != '3' &&
        mDataSetPath[(mDataSetPath.size() - 1) - i] != '4' &&
        mDataSetPath[(mDataSetPath.size() - 1) - i] != '5' &&
        mDataSetPath[(mDataSetPath.size() - 1) - i] != '6' &&
        mDataSetPath[(mDataSetPath.size() - 1) - i] != '7' &&
        mDataSetPath[(mDataSetPath.size() - 1) - i] != '8' &&
        mDataSetPath[(mDataSetPath.size() - 1) - i] != '9') {
      break;
    }
  }
91
  unsigned int endOfPrefix = static_cast<unsigned int>(mDataSetPath.size()) - i;
92 93 94 95 96 97
  mDataSetPrefix = mDataSetPath.substr(0, endOfPrefix);
  if (mDataSetPrefix.compare(mDataSetPath) != 0) {
    mDataSetId = atoi(mDataSetPath.substr(endOfPrefix).c_str());
  }
}

98 99 100 101
XdmfHDF5Controller::~XdmfHDF5Controller()
{
}

102 103 104 105 106 107 108 109 110 111 112 113
void
XdmfHDF5Controller::closeFiles()
{
  for (std::map<std::string, hid_t>::iterator closeIter = mOpenFiles.begin();
       closeIter != mOpenFiles.end();
       ++closeIter) {
    H5Fclose(closeIter->second);
  }
  mOpenFiles.clear();
  mOpenFileUsage.clear();
}

114 115 116 117 118 119
std::string
XdmfHDF5Controller::getDataSetPath() const
{
  return mDataSetPath;
}

120 121
const std::string
XdmfHDF5Controller::getDataSetPrefix() const
122
{
123
  return mDataSetPrefix;
124 125
}

126 127
int
XdmfHDF5Controller::getDataSetId() const
128
{
129 130 131 132 133 134 135
  return mDataSetId;
}

std::string
XdmfHDF5Controller::getDescriptor() const
{
  return ":" + mDataSetPath;
136 137
}

138 139
std::string
XdmfHDF5Controller::getName() const
140
{
141
  return "HDF";
142
}
143

144 145 146 147 148 149
unsigned int
XdmfHDF5Controller::getMaxOpenedFiles()
{
  return XdmfHDF5Controller::mMaxOpenedFiles;
}

150 151 152 153 154 155
void 
XdmfHDF5Controller::getProperties(std::map<std::string, std::string> & collectedProperties) const
{
  collectedProperties["Format"] = this->getName();
}

156 157
void
XdmfHDF5Controller::read(XdmfArray * const array)
158
{
159
  this->read(array, H5P_DEFAULT);
160 161
}

162 163
void
XdmfHDF5Controller::read(XdmfArray * const array, const int fapl)
164
{
165
  herr_t status;
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
  hid_t hdf5Handle;
  if (XdmfHDF5Controller::mMaxOpenedFiles == 0) {
    hdf5Handle = H5Fopen(mFilePath.c_str(), H5F_ACC_RDONLY, fapl);
  }
  else {
    std::map<std::string, hid_t>::iterator checkOpen = mOpenFiles.find(mFilePath);
    if (checkOpen == mOpenFiles.end()) {
      // If the number of open files would become larger than allowed
      if (mOpenFiles.size() + 1 > mMaxOpenedFiles) {
        // Close least used one
        std::map<std::string, unsigned int>::iterator walker = mOpenFileUsage.begin();
        std::string oldestFile = walker->first;
        while (walker != mOpenFileUsage.end()) {
          // We want the file with the fewest accesses
          // If two are tied, we use the older one
          if (mOpenFileUsage[oldestFile] > walker->second) {
            oldestFile = walker->first;
          }
          ++walker;
        }
        status = H5Fclose(mOpenFiles[oldestFile]);
        mOpenFiles.erase(oldestFile);
        mOpenFileUsage.erase(oldestFile);
      }
      hdf5Handle = H5Fopen(mFilePath.c_str(), H5F_ACC_RDONLY, fapl);
      mOpenFiles[mFilePath] = hdf5Handle;
      mOpenFileUsage[mFilePath] = 1;
    }
    else {
      hdf5Handle = checkOpen->second;
      mOpenFileUsage[mFilePath]++;
    }
  }
199

200 201 202 203 204 205 206 207 208 209 210 211
  const hid_t dataset = H5Dopen(hdf5Handle, mDataSetPath.c_str(), H5P_DEFAULT);
  const hid_t dataspace = H5Dget_space(dataset);

  const unsigned int dataspaceDims = H5Sget_simple_extent_ndims(dataspace);
  const std::vector<hsize_t> count(mDimensions.begin(), mDimensions.end());

  if(dataspaceDims != mDimensions.size()) {
    // special case where the number of dimensions of the hdf5 dataset
    // does not equal the number of dimensions in the light data
    // description - in this case we cannot properly take a hyperslab
    // selection, so we assume we are reading the entire dataset and
    // check whether that is ok to do
212
    const int numberValuesHDF5 = static_cast<int>(H5Sget_select_npoints(dataspace));
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
    const int numberValuesXdmf = 
      std::accumulate(mDimensions.begin(),
                      mDimensions.end(),
                      1,
                      std::multiplies<unsigned int>());
    if(numberValuesHDF5 != numberValuesXdmf) {
      XdmfError::message(XdmfError::FATAL,
                         "Number of dimensions in light data description in "
                         "Xdmf does not match number of dimensions in hdf5 "
                         "file.");
    }
  }
  else {
    const std::vector<hsize_t> start(mStart.begin(), mStart.end());
    const std::vector<hsize_t> stride(mStride.begin(), mStride.end());

    status = H5Sselect_hyperslab(dataspace,
                                 H5S_SELECT_SET,
                                 &start[0],
                                 &stride[0],
                                 &count[0],
                                 NULL);
  }
236

237
  const hssize_t numVals = H5Sget_select_npoints(dataspace);
238
  hid_t memspace = H5Screate_simple(static_cast<int>(mDimensions.size()),
239 240
                                    &count[0],
                                    NULL);
241 242

  /* status = H5Sselect_hyperslab(memspace,
243 244 245 246 247
     H5S_SELECT_SET,
     &memStart[0],
     &memStride[0],
     &memCount[0],
     NULL);*/
248

249
  hid_t datatype = H5T_NO_CLASS;
250
  bool closeDatatype = false;
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
  if(mType == XdmfArrayType::Int8()) {
    datatype = H5T_NATIVE_CHAR;
  }
  else if(mType == XdmfArrayType::Int16()) {
    datatype = H5T_NATIVE_SHORT;
  }
  else if(mType == XdmfArrayType::Int32()) {
    datatype = H5T_NATIVE_INT;
  }
  else if(mType == XdmfArrayType::Int64()) {
    datatype = H5T_NATIVE_LONG;
  }
  else if(mType == XdmfArrayType::Float32()) {
    datatype = H5T_NATIVE_FLOAT;
  }
  else if(mType == XdmfArrayType::Float64()) {
    datatype = H5T_NATIVE_DOUBLE;
  }
  else if(mType == XdmfArrayType::UInt8()) {
    datatype = H5T_NATIVE_UCHAR;
  }
  else if(mType == XdmfArrayType::UInt16()) {
    datatype = H5T_NATIVE_USHORT;
  }
  else if(mType == XdmfArrayType::UInt32()) {
    datatype = H5T_NATIVE_UINT;
  }
278 279
  else if(mType == XdmfArrayType::String()) {
    datatype = H5Tcopy(H5T_C_S1);
280
    H5Tset_size(datatype, H5T_VARIABLE);
281 282
    closeDatatype = true;
  }
283
  else {
284 285 286
    XdmfError::message(XdmfError::FATAL,
                       "Unknown XdmfArrayType encountered in hdf5 "
                       "controller.");
287
  }
288

289 290
  array->initialize(mType, mDimensions);

291
  if(numVals != array->getSize()) {
292 293 294 295 296
    std::stringstream errOut;
    errOut << "Number of values in hdf5 dataset (" << numVals;
    errOut << ")\ndoes not match allocated size in XdmfArray (" << array->getSize() << ").";
    XdmfError::message(XdmfError::FATAL,
                       errOut.str());
297
  }
298
  if(closeDatatype) {
299
    char ** data = new char*[numVals];
300 301
    status = H5Dread(dataset,
                     datatype,
302 303
                     memspace,
                     dataspace,
304
                     H5P_DEFAULT,
305 306
                     data);
    for(hssize_t i=0; i<numVals; ++i) {
307
      array->insert<std::string>(static_cast<unsigned int>(i), data[i]);
308
    }
309 310 311
    status = H5Dvlen_reclaim(datatype,
                             dataspace,
                             H5P_DEFAULT,
312 313 314 315 316 317 318 319 320 321 322
                             data);
    delete [] data;
  }
  else {
    status = H5Dread(dataset,
                     datatype,
                     memspace,
                     dataspace,
                     H5P_DEFAULT,
                     array->getValuesInternal());
  }
323

324
  status = H5Sclose(dataspace);
325
  status = H5Sclose(memspace);
326
  status = H5Dclose(dataset);
327 328 329
  if(closeDatatype) {
    status = H5Tclose(datatype);
  }
330 331
  if (XdmfHDF5Controller::mMaxOpenedFiles == 0) {
    status = H5Fclose(hdf5Handle);
332 333 334
    if(status < 0) {
      XdmfError::message(XdmfError::FATAL, "Error in H5Fclose");
    }
335 336 337 338 339 340 341
  }
}

void
XdmfHDF5Controller::setMaxOpenedFiles(unsigned int newMax)
{
  XdmfHDF5Controller::mMaxOpenedFiles = newMax;
342
}
343 344 345 346 347 348 349 350 351 352 353 354 355 356

// C Wrappers

XDMFHDF5CONTROLLER * XdmfHDF5ControllerNew(char * hdf5FilePath,
                                           char * dataSetPath,
                                           int type,
                                           unsigned int * start,
                                           unsigned int * stride,
                                           unsigned int * dimensions,
                                           unsigned int * dataspaceDimensions,
                                           unsigned int numDims,
                                           int * status)
{
  XDMF_ERROR_WRAP_START(status)
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
  std::vector<unsigned int> startVector(start, start + numDims);
  std::vector<unsigned int> strideVector(stride, stride + numDims);
  std::vector<unsigned int> dimVector(dimensions, dimensions + numDims);
  std::vector<unsigned int> dataspaceVector(dataspaceDimensions, dataspaceDimensions + numDims);
  shared_ptr<const XdmfArrayType> buildType = shared_ptr<XdmfArrayType>();
  switch (type) {
  case XDMF_ARRAY_TYPE_UINT8:
    buildType = XdmfArrayType::UInt8();
    break;
  case XDMF_ARRAY_TYPE_UINT16:
    buildType = XdmfArrayType::UInt16();
    break;
  case XDMF_ARRAY_TYPE_UINT32:
    buildType = XdmfArrayType::UInt32();
    break;
  case XDMF_ARRAY_TYPE_INT8:
    buildType = XdmfArrayType::Int8();
    break;
  case XDMF_ARRAY_TYPE_INT16:
    buildType = XdmfArrayType::Int16();
    break;
  case XDMF_ARRAY_TYPE_INT32:
    buildType = XdmfArrayType::Int32();
    break;
  case XDMF_ARRAY_TYPE_INT64:
    buildType = XdmfArrayType::Int64();
    break;
  case XDMF_ARRAY_TYPE_FLOAT32:
    buildType = XdmfArrayType::Float32();
    break;
  case XDMF_ARRAY_TYPE_FLOAT64:
    buildType = XdmfArrayType::Float64();
    break;
  default:
    XdmfError::message(XdmfError::FATAL,
		       "Error: Invalid ArrayType.");
    break;
394
  }
395 396 397 398 399 400 401 402
  shared_ptr<XdmfHDF5Controller> * generatedController = new shared_ptr<XdmfHDF5Controller>(XdmfHDF5Controller::New(hdf5FilePath, 
														    dataSetPath, 
														    buildType, 
														    startVector, 
														    strideVector, 
														    dimVector, 
														    dataspaceVector));
  return (XDMFHDF5CONTROLLER *) generatedController;
403 404 405 406 407 408
  XDMF_ERROR_WRAP_END(status)
  return NULL;
}

char * XdmfHDF5ControllerGetDataSetPath(XDMFHDF5CONTROLLER * controller)
{
409 410
  shared_ptr<XdmfHDF5Controller> & refController = *(shared_ptr<XdmfHDF5Controller> *)controller;
  char * returnPointer = strdup(refController->getDataSetPath().c_str());
411 412 413 414 415 416
  return returnPointer;
}

// C Wrappers for parent classes are generated by macros

XDMF_HEAVYCONTROLLER_C_CHILD_WRAPPER(XdmfHDF5Controller, XDMFHDF5CONTROLLER)