1 #ifndef MEDUSA_BITS_IO_HDF_EIGEN_HPP_
2 #define MEDUSA_BITS_IO_HDF_EIGEN_HPP_
16 template <
typename scalar_t>
17 Eigen::Matrix<scalar_t, Eigen::Dynamic, Eigen::Dynamic>
HDF::readEigen(
18 const std::string& dataset_name)
const {
19 assert_msg(H5Iis_valid(
group),
"Group id %d invalid. Did you open a group before reading?",
21 hid_t dataset = H5Dopen(
group, dataset_name.c_str(), H5P_DEFAULT);
22 assert_msg(dataset >= 0,
"Dataset '%s' could not be accessed in group '%s' in file '%s'.",
25 hid_t dataspace = H5Dget_space(dataset);
26 const int ndims = H5Sget_simple_extent_ndims(dataspace);
27 assert_msg(ndims <= 2,
"This function is for 1 and 2 dimensional arrays only.");
28 hsize_t dims[2] = {1, 1};
29 H5Sget_simple_extent_dims(dataspace, dims,
nullptr);
30 hsize_t cols = dims[0], rows = dims[1];
31 Eigen::Matrix<scalar_t, Eigen::Dynamic, Eigen::Dynamic> M(rows, cols);
33 hid_t type = H5Dget_type(dataset);
34 herr_t status = H5Dread(dataset, type, H5S_ALL, H5S_ALL, H5P_DEFAULT, M.data());
35 assert_msg(status >= 0,
"Failed reading dataset '%s' from group '%s' in file '%s'.",
45 template <
typename Derived>
46 void HDF::writeEigen(
const std::string& dataset_name,
const Eigen::MatrixBase<Derived>& value,
47 bool overwrite)
const {
48 typedef typename Eigen::MatrixBase<Derived>::Scalar
scalar_t;
49 if (value.IsRowMajor) {
51 Eigen::Matrix<scalar_t, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>(value),
55 hsize_t cols = value.cols();
56 hsize_t rows = value.rows();
57 if (std::is_same<double, scalar_t>::value) {
58 writeLinearArray<2>(dataset_name, value.eval().data(), {cols, rows},
59 H5T_NATIVE_DOUBLE, overwrite);
60 }
else if (std::is_same<float, scalar_t>::value) {
61 writeLinearArray<2>(dataset_name, value.eval().data(), {cols, rows},
62 H5T_NATIVE_FLOAT, overwrite);
63 }
else if (std::is_same<int, scalar_t>::value) {
64 writeLinearArray<2>(dataset_name, value.eval().data(), {cols, rows},
65 H5T_NATIVE_INT, overwrite);
67 assert_msg(
false,
"Only float, int and double types are supported.");
73 #endif // MEDUSA_BITS_IO_HDF_EIGEN_HPP_