Debian Codegraph @

avogadro/io/hdf5dataformat.cpp

raw
1 /******************************************************************************
2 This source file is part of the Avogadro project.
3 This source code is released under the 3-Clause BSD License, (see "LICENSE").
4 ******************************************************************************/
5
6 #include "hdf5dataformat.h"
7
8 #include "hdf5.h"
9
10 #include <avogadro/core/array.h>
11
12 #include <algorithm>
13 #include <cstdio>
14
15 namespace Avogadro {
16 namespace Io {
17
18 // Exclude from Doxygen:
19 /// @cond
20 class Hdf5DataFormat::ResizeContainer
21 {
22 public:
23 virtual ~ResizeContainer(){};
24 virtual bool resize(const std::vector<int>& dims) = 0;
25 virtual void* dataPointer() = 0;
26
27 protected:
28 int dimsToNumberOfElements(const std::vector<int>& vec)
29 {
30 if (vec.empty())
31 return 0;
32 int result = vec.front();
33 for (size_t i = 1; i < vec.size(); ++i)
34 result *= vec[i];
35 return result;
36 }
37 };
38
39 // Internal storage. Used to keep HDF5 stuff out of the header.
40 class Hdf5DataFormat::Private
41 {
42 public:
43 Private() : fileId(H5I_INVALID_HID), threshold(1024) {}
44
45 std::string filename;
46 hid_t fileId;
47
48 size_t threshold;
49 };
50
51 namespace {
52
53 // Build up a list of absolute paths to all datasets in the file. To be used
54 // with H5Ovisit (see Hdf5DataFormat::datasets()).
55 class ListDatasetsVisitor
56 {
57 public:
58 std::vector<std::string> datasets;
59 static herr_t operation(hid_t /*o_id*/, const char* name,
60 const H5O_info_t* object_info, void* op_data)
61 {
62 // If this object isn't a dataset, continue
63 if (object_info->type != H5O_TYPE_DATASET)
64 return 0;
65
66 ListDatasetsVisitor* self = reinterpret_cast<ListDatasetsVisitor*>(op_data);
67 self->datasets.push_back(std::string(name));
68 return 0;
69 }
70 };
71
72 class ResizeMatrixX : public Avogadro::Io::Hdf5DataFormat::ResizeContainer
73 {
74 MatrixX& m_data;
75
76 public:
77 ResizeMatrixX(MatrixX& data) : m_data(data) {}
78 bool resize(const std::vector<int>& dims) override
79 {
80 if (dims.size() != 2)
81 return false;
82 m_data.resize(dims[0], dims[1]);
83 return true;
84 }
85 void* dataPointer() override { return m_data.data(); }
86 };
87
88 class ResizeVector : public Avogadro::Io::Hdf5DataFormat::ResizeContainer
89 {
90 std::vector<double>& m_data;
91
92 public:
93 ResizeVector(std::vector<double>& data) : m_data(data) {}
94 bool resize(const std::vector<int>& dims) override
95 {
96 m_data.resize(dimsToNumberOfElements(dims));
97 return true;
98 }
99 void* dataPointer() override { return &m_data[0]; }
100 };
101
102 class ResizeArray : public Avogadro::Io::Hdf5DataFormat::ResizeContainer
103 {
104 Avogadro::Core::Array<double>& m_data;
105
106 public:
107 ResizeArray(Avogadro::Core::Array<double>& data) : m_data(data) {}
108 bool resize(const std::vector<int>& dims) override
109 {
110 m_data.resize(dimsToNumberOfElements(dims));
111 return true;
112 }
113 void* dataPointer() override { return &m_data[0]; }
114 };
115
116 } // end unnamed namespace
117
118 // end doxygen exclude:
119 /// @endcond
120
121 Hdf5DataFormat::Hdf5DataFormat() : d(new Private()) {}
122
123 Hdf5DataFormat::~Hdf5DataFormat()
124 {
125 if (isOpen())
126 closeFile();
127 delete d;
128 }
129
130 bool Hdf5DataFormat::isOpen() const
131 {
132 return d->fileId != H5I_INVALID_HID;
133 }
134
135 bool Hdf5DataFormat::openFile(const std::string& filename_,
136 Hdf5DataFormat::OpenMode mode)
137 {
138 // File already open?
139 if (isOpen())
140 return false;
141
142 switch (mode) {
143 case ReadOnly:
144 // File must exist -- check first before attempting to open
145 if (FILE* handle = fopen(filename_.c_str(), "r")) {
146 // File exists, pass it off to H5Fopen
147 fclose(handle);
148 d->fileId = H5Fopen(filename_.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);
149 } else {
150 // File doesn't exist
151 return false;
152 }
153 break;
154 case ReadWriteTruncate:
155 // Create new file:
156 d->fileId =
157 H5Fcreate(filename_.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
158 break;
159 case ReadWriteAppend:
160 // Test if the file exists:
161 if (FILE* handle = fopen(filename_.c_str(), "r")) {
162 // Exists! Use open
163 fclose(handle);
164 d->fileId = H5Fopen(filename_.c_str(), H5F_ACC_RDWR, H5P_DEFAULT);
165 } else {
166 // File doesn't exist yet. Create it.
167 d->fileId =
168 H5Fcreate(filename_.c_str(), H5F_ACC_EXCL, H5P_DEFAULT, H5P_DEFAULT);
169 }
170 break;
171 }
172
173 // Error opening if file id is negative
174 if (d->fileId < 0) {
175 d->fileId = H5I_INVALID_HID;
176 return false;
177 }
178
179 d->filename = filename_;
180 return true;
181 }
182
183 std::string Hdf5DataFormat::filename() const
184 {
185 return d->filename;
186 }
187
188 bool Hdf5DataFormat::closeFile()
189 {
190 // Is there a file open?
191 if (!isOpen())
192 return false;
193
194 herr_t err = H5Fclose(d->fileId);
195 if (err < 0)
196 return false;
197
198 d->fileId = H5I_INVALID_HID;
199 d->filename.clear();
200 return true;
201 }
202
203 void Hdf5DataFormat::setThreshold(size_t bytes)
204 {
205 d->threshold = bytes;
206 }
207
208 size_t Hdf5DataFormat::threshold() const
209 {
210 return d->threshold;
211 }
212
213 bool Hdf5DataFormat::exceedsThreshold(size_t bytes) const
214 {
215 return bytes > d->threshold;
216 }
217
218 bool Hdf5DataFormat::exceedsThreshold(const MatrixX& data) const
219 {
220 return exceedsThreshold(data.rows() * data.cols() * sizeof(double));
221 }
222
223 bool Hdf5DataFormat::exceedsThreshold(const std::vector<double>& data) const
224 {
225 return exceedsThreshold(data.size() * sizeof(double));
226 }
227
228 bool Hdf5DataFormat::exceedsThreshold(const Core::Array<double>& data) const
229 {
230 return exceedsThreshold(data.size() * sizeof(double));
231 }
232
233 bool Hdf5DataFormat::datasetExists(const std::string& path) const
234 {
235 if (!isOpen())
236 return false;
237
238 // "/" cannot be a valid dataset, and this function must take an absolute path
239 if (path.size() < 2)
240 return false;
241
242 // Verify that all paths leading to the target exist, one by one (grr...)
243 size_t slashIndex = 0;
244 do {
245 slashIndex = path.find('/', slashIndex + 1);
246 if (slashIndex != std::string::npos) {
247 htri_t exists =
248 H5Lexists(d->fileId, path.substr(0, slashIndex).c_str(), H5P_DEFAULT);
249 if (exists != 1)
250 return false;
251 }
252 } while (slashIndex != std::string::npos);
253
254 // Verify that the deepest link exists
255 if (H5Lexists(d->fileId, path.c_str(), H5P_DEFAULT) != 1)
256 return false;
257
258 // Verify that the deepest link resolves to an object
259 if (H5Oexists_by_name(d->fileId, path.c_str(), H5P_DEFAULT) != 1)
260 return false;
261
262 // See if the object is a dataset
263 H5O_info_t info;
264 if (H5Oget_info_by_name(d->fileId, path.c_str(), &info, H5P_DEFAULT) < 0)
265 return false;
266
267 return info.type == H5O_TYPE_DATASET;
268 }
269
270 bool Hdf5DataFormat::removeDataset(const std::string& path) const
271 {
272 if (!isOpen())
273 return false;
274
275 return H5Ldelete(d->fileId, path.c_str(), H5P_DEFAULT) >= 0;
276 }
277
278 std::vector<int> Hdf5DataFormat::datasetDimensions(
279 const std::string& path) const
280 {
281 std::vector<int> result;
282 if (!isOpen())
283 return result;
284
285 if (!datasetExists(path))
286 return result;
287
288 // Open dataset
289 hid_t dataset_id = H5Dopen(d->fileId, path.c_str(), H5P_DEFAULT);
290 if (dataset_id < 0)
291 return result;
292
293 // Lookup dimensions
294 // Get dataspace for dataset
295 hid_t dataspace_id = H5Dget_space(dataset_id);
296 if (dataset_id < 0) {
297 H5Dclose(dataset_id);
298 return result;
299 }
300
301 // Get number of dimensions.
302 int ndims = H5Sget_simple_extent_ndims(dataspace_id);
303 if (ndims <= 0) {
304 H5Sclose(dataspace_id);
305 H5Dclose(dataset_id);
306 return result;
307 }
308
309 // Get actual dimensions.
310 hsize_t* hdims = new hsize_t[ndims];
311 int checkDims = H5Sget_simple_extent_dims(dataspace_id, hdims, nullptr);
312
313 // Copy dimensions if successful.
314 if (checkDims == ndims) {
315 result.resize(ndims);
316 std::copy(hdims, hdims + ndims, result.begin());
317 }
318
319 // Cleanup.
320 delete[] hdims;
321 H5Sclose(dataspace_id);
322 H5Dclose(dataset_id);
323
324 return result;
325 }
326
327 bool Hdf5DataFormat::writeRawDataset(const std::string& path,
328 const double data[], int ndims,
329 size_t dims[]) const
330 {
331 if (!isOpen())
332 return false;
333
334 // Remove old data set if it exists.
335 if (datasetExists(path)) {
336 if (!removeDataset(path))
337 return false;
338 }
339
340 // Get dimensions of data.
341 hsize_t* hdims = new hsize_t[ndims];
342 for (int i = 0; i < ndims; ++i) {
343 hdims[i] = static_cast<hsize_t>(dims[i]);
344 }
345
346 // Create a dataspace description.
347 hid_t dataspace_id = H5Screate_simple(ndims, hdims, nullptr);
348 delete[] hdims;
349 if (dataspace_id < 0)
350 return false;
351
352 // Create any intermediate groups if needed:
353 hid_t lcpl_id = H5Pcreate(H5P_LINK_CREATE);
354 if (lcpl_id == -1 || H5Pset_create_intermediate_group(lcpl_id, 1) < 0) {
355 H5Sclose(dataspace_id);
356 return false;
357 }
358
359 // Create the dataset.
360 hid_t dataset_id = H5Dcreate(d->fileId, path.c_str(), H5T_NATIVE_DOUBLE,
361 dataspace_id, lcpl_id, H5P_DEFAULT, H5P_DEFAULT);
362 if (dataset_id < 0) {
363 H5Sclose(dataspace_id);
364 return false;
365 }
366
367 // Write the actual data.
368 herr_t err = H5Dwrite(dataset_id, H5T_NATIVE_DOUBLE, H5S_ALL, dataspace_id,
369 H5P_DEFAULT, data);
370
371 // Cleanup.
372 H5Dclose(dataset_id);
373 H5Sclose(dataspace_id);
374
375 if (err < 0)
376 return false;
377
378 return true;
379 }
380
381 bool Hdf5DataFormat::writeDataset(const std::string& path,
382 const MatrixX& data) const
383 {
384 size_t dims[2] = { static_cast<size_t>(data.rows()),
385 static_cast<size_t>(data.cols()) };
386 // Transpose data -- Eigen uses column-major ordering.
387 return this->writeRawDataset(path, data.transpose().data(), 2, dims);
388 }
389
390 bool Hdf5DataFormat::writeDataset(const std::string& path,
391 const std::vector<double>& data, int ndims,
392 size_t* dims) const
393 {
394 size_t size = data.size();
395 return this->writeRawDataset(path, &(data[0]), ndims, dims ? dims : &size);
396 }
397
398 bool Hdf5DataFormat::writeDataset(const std::string& path,
399 const Core::Array<double>& data, int ndims,
400 size_t* dims) const
401 {
402 size_t size = data.size();
403 return this->writeRawDataset(path, &(data[0]), ndims, dims ? dims : &size);
404 }
405
406 std::vector<int> Hdf5DataFormat::readRawDataset(
407 const std::string& path, ResizeContainer& container) const
408 {
409 std::vector<int> result;
410 if (!isOpen())
411 return result;
412
413 if (!datasetExists(path))
414 return result;
415
416 // Open dataset
417 hid_t dataset_id = H5Dopen(d->fileId, path.c_str(), H5P_DEFAULT);
418 if (dataset_id < 0)
419 return result;
420
421 // Lookup dimensions
422 // Get dataspace for dataset
423 hid_t dataspace_id = H5Dget_space(dataset_id);
424 if (dataset_id < 0) {
425 H5Dclose(dataset_id);
426 return result;
427 }
428
429 // Get number of dimensions.
430 int ndims = H5Sget_simple_extent_ndims(dataspace_id);
431 if (ndims <= 0) {
432 H5Sclose(dataspace_id);
433 H5Dclose(dataset_id);
434 return result;
435 }
436
437 // Get actual dimensions.
438 hsize_t* hdims = new hsize_t[ndims];
439 if (H5Sget_simple_extent_dims(dataspace_id, hdims, nullptr) != ndims) {
440 delete[] hdims;
441 H5Sclose(dataspace_id);
442 H5Dclose(dataset_id);
443 return result;
444 }
445
446 result.reserve(ndims);
447 for (int i = 0; i < ndims; ++i) {
448 result.push_back(static_cast<int>(hdims[i]));
449 }
450 delete[] hdims;
451
452 // Allocate and read into data.
453 if (!container.resize(result)) {
454 result.clear();
455 H5Sclose(dataspace_id);
456 H5Dclose(dataset_id);
457 return result;
458 }
459
460 if (H5Dread(dataset_id, H5T_NATIVE_DOUBLE, H5S_ALL, dataspace_id, H5P_DEFAULT,
461 container.dataPointer()) < 0) {
462 result.clear();
463 H5Sclose(dataspace_id);
464 H5Dclose(dataset_id);
465 return result;
466 }
467
468 // Cleanup
469 H5Sclose(dataspace_id);
470 H5Dclose(dataset_id);
471
472 return result;
473 }
474
475 bool Hdf5DataFormat::readDataset(const std::string& path, MatrixX& data) const
476 {
477 ResizeMatrixX container(data);
478 return !readRawDataset(path, container).empty();
479 }
480
481 std::vector<int> Hdf5DataFormat::readDataset(const std::string& path,
482 std::vector<double>& data) const
483 {
484 ResizeVector container(data);
485 return readRawDataset(path, container);
486 }
487
488 std::vector<int> Hdf5DataFormat::readDataset(const std::string& path,
489 Core::Array<double>& data) const
490 {
491 ResizeArray container(data);
492 return readRawDataset(path, container);
493 }
494
495 std::vector<std::string> Hdf5DataFormat::datasets() const
496 {
497 if (!isOpen())
498 return std::vector<std::string>();
499
500 ListDatasetsVisitor visitor;
501 herr_t code = H5Ovisit(d->fileId, H5_INDEX_NAME, H5_ITER_INC,
502 &visitor.operation, &visitor);
503
504 if (code < 0)
505 return std::vector<std::string>();
506 return visitor.datasets;
507 }
508
509 } // namespace Io
510 } // namespace Avogadro