Program Listing for File hdf_utils.h

↰ Return to documentation for file (framework/utils/hdf_utils.h)

// SPDX-FileCopyrightText: 2024 The OpenSn Authors <https://open-sn.github.io/opensn/>
// SPDX-License-Identifier: MIT

#pragma once

#include "hdf5.h"
#include <cstdint>
#include <vector>
#include <string>
#include <type_traits>
#include <utility>

namespace opensn
{
class H5FileHandle
{
public:
  explicit H5FileHandle(const hid_t file_id) : file_id_(file_id) {}

  H5FileHandle(const H5FileHandle&) = delete;
  H5FileHandle& operator=(const H5FileHandle&) = delete;

  H5FileHandle(H5FileHandle&& other) noexcept : file_id_(other.file_id_)
  {
    other.file_id_ = H5I_INVALID_HID;
  }

  H5FileHandle& operator=(H5FileHandle&& other) noexcept
  {
    if (this != &other)
    {
      Close();
      file_id_ = other.file_id_;
      other.file_id_ = H5I_INVALID_HID;
    }
    return *this;
  }

  ~H5FileHandle() { Close(); }

  hid_t Id() const { return file_id_; }

private:
  void Close()
  {
    if (file_id_ >= 0)
      H5Fclose(file_id_);
    file_id_ = H5I_INVALID_HID;
  }

  hid_t file_id_ = H5I_INVALID_HID;
};

/// Owns an HDF5 identifier and closes it with `close` when it goes out of scope.
class H5IdHandle
{
public:
  H5IdHandle(const hid_t id, herr_t (*close)(hid_t)) : id_(id), close_(close) {}

  H5IdHandle(const H5IdHandle&) = delete;
  H5IdHandle& operator=(const H5IdHandle&) = delete;
  H5IdHandle(H5IdHandle&&) = delete;
  H5IdHandle& operator=(H5IdHandle&&) = delete;

  ~H5IdHandle()
  {
    if (id_ >= 0)
      close_(id_);
  }

  hid_t Id() const { return id_; }

private:
  hid_t id_;
  herr_t (*close_)(hid_t);
};

template <typename T>
hid_t get_datatype();

/// Read a scalar attribute. Returns false if the attribute is missing, does not hold exactly one
/// element, or cannot be read.
template <typename T>
bool H5ReadAttribute(hid_t id, const std::string& name, T& value);

/// Return true if the open attribute holds exactly one element.
inline bool
H5AttributeHasOneElement(hid_t attribute)
{
  const hid_t dataspace = H5Aget_space(attribute);
  if (dataspace == H5I_INVALID_HID)
    return false;
  const bool one_element = H5Sget_simple_extent_npoints(dataspace) == 1;
  H5Sclose(dataspace);
  return one_element;
}

template <>
inline hid_t
get_datatype<char>()
{
  return H5T_NATIVE_CHAR;
}

template <>
inline hid_t
get_datatype<signed char>()
{
  return H5T_NATIVE_SCHAR;
}

template <>
inline hid_t
get_datatype<unsigned char>()
{
  return H5T_NATIVE_UCHAR;
}

template <>
inline hid_t
get_datatype<short>()
{
  return H5T_NATIVE_SHORT;
}

template <>
inline hid_t
get_datatype<unsigned short>()
{
  return H5T_NATIVE_USHORT;
}

template <>
inline hid_t
get_datatype<int>()
{
  return H5T_NATIVE_INT;
}

template <>
inline hid_t
get_datatype<unsigned int>()
{
  return H5T_NATIVE_UINT;
}

template <>
inline hid_t
get_datatype<long>()
{
  return H5T_NATIVE_LONG;
}

template <>
inline hid_t
get_datatype<unsigned long>()
{
  return H5T_NATIVE_ULONG;
}

template <>
inline hid_t
get_datatype<long long>()
{
  return H5T_NATIVE_LLONG;
}

template <>
inline hid_t
get_datatype<unsigned long long>()
{
  return H5T_NATIVE_ULLONG;
}

template <>
inline hid_t
get_datatype<float>()
{
  return H5T_NATIVE_FLOAT;
}

template <>
inline hid_t
get_datatype<double>()
{
  return H5T_NATIVE_DOUBLE;
}

template <>
inline hid_t
get_datatype<bool>()
{
  return H5T_NATIVE_UCHAR;
}

template <typename T>
bool
H5ReadOptionalAttribute(hid_t id, const std::string& name, T& value)
{
  if (H5Aexists(id, name.c_str()) <= 0)
    return true;
  return H5ReadAttribute<T>(id, name, value);
}

inline bool
H5Has(hid_t id, const std::string& name)
{
  return (H5Lexists(id, name.c_str(), H5P_DEFAULT) > 0);
}

inline bool
H5CreateGroup(hid_t id, const std::string& name)
{
  hid_t group = H5Gcreate2(id, name.c_str(), H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
  if (group < 0)
    return false;
  H5Gclose(group);
  return true;
}

template <typename T>
bool
H5WriteDataset1D(hid_t id, const std::string& name, const std::vector<T>& data)
{
  static_assert(
    !std::is_same_v<T, bool>,
    "H5WriteDataset1D does not support std::vector<bool>. Use std::vector<unsigned char>.");

  bool success = false;

  hsize_t dim[1] = {static_cast<hsize_t>(data.size())};
  auto dataspace = H5Screate_simple(1, dim, nullptr);
  if (dataspace != H5I_INVALID_HID)
  {
    auto dataset = H5Dcreate2(
      id, name.c_str(), get_datatype<T>(), dataspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
    if (dataset != H5I_INVALID_HID)
    {
      if (data.empty())
        success = true;
      else
      {
        if (H5Dwrite(dataset, get_datatype<T>(), H5S_ALL, H5S_ALL, H5P_DEFAULT, data.data()) >= 0)
          success = true;
      }
      H5Dclose(dataset);
    }
    H5Sclose(dataspace);
  }

  return success;
}

template <typename T>
bool
H5CreateAttribute(hid_t id, const std::string& name, const T& data)
{
  static_assert(!std::is_same_v<T, std::string>, "H5CreateAttribute does not support std::string.");

  bool success = false;

  auto dataspace = H5Screate(H5S_SCALAR);
  if (dataspace != H5I_INVALID_HID)
  {
    auto attribute =
      H5Acreate2(id, name.c_str(), get_datatype<T>(), dataspace, H5P_DEFAULT, H5P_DEFAULT);
    if (attribute != H5I_INVALID_HID)
    {
      if (H5Awrite(attribute, get_datatype<T>(), &data) >= 0)
        success = true;
      H5Aclose(attribute);
    }
    H5Sclose(dataspace);
  }

  return success;
}

template <typename T>
bool
H5ReadDataset1D(hid_t id, const std::string& name, std::vector<T>& data)
{
  static_assert(
    !std::is_same_v<T, bool>,
    "H5ReadDataset1D does not support std::vector<bool>. Use std::vector<unsigned char>.");

  bool success = false;

  data.clear();

  auto dataset = H5Dopen2(id, name.c_str(), H5P_DEFAULT);
  if (dataset != H5I_INVALID_HID)
  {
    auto dataspace = H5Dget_space(dataset);
    if (dataspace != H5I_INVALID_HID)
    {
      const int rank = H5Sget_simple_extent_ndims(dataspace);
      if (rank == 1)
      {
        const auto npoints = H5Sget_simple_extent_npoints(dataspace);
        if (npoints >= 0)
        {
          data.resize(static_cast<size_t>(npoints));
          if (npoints == 0 or
              H5Dread(dataset, get_datatype<T>(), H5S_ALL, H5S_ALL, H5P_DEFAULT, data.data()) >= 0)
          {
            success = true;
          }
          else
          {
            data.clear();
            data.shrink_to_fit();
          }
        }
      }
      H5Sclose(dataspace);
    }
    H5Dclose(dataset);

    if (success)
      return true;
  }

  if (H5Aexists(id, name.c_str()) > 0)
  {
    auto attribute = H5Aopen(id, name.c_str(), H5P_DEFAULT);
    if (attribute != H5I_INVALID_HID)
    {
      auto aspace = H5Aget_space(attribute);
      if (aspace != H5I_INVALID_HID)
      {
        const auto npoints = H5Sget_simple_extent_npoints(aspace);
        if (npoints >= 0)
        {
          data.resize(static_cast<size_t>(npoints));
          if (npoints == 0 or H5Aread(attribute, get_datatype<T>(), data.data()) >= 0)
          {
            success = true;
          }
          else
          {
            data.clear();
            data.shrink_to_fit();
          }
        }
        H5Sclose(aspace);
      }
      H5Aclose(attribute);
    }
  }

  return success;
}

/// Get the number of elements in the 1D dataset `name`. Returns false if it is not a 1D dataset.
inline bool
H5GetDataset1DSize(hid_t id, const std::string& name, std::uint64_t& size)
{
  bool success = false;

  auto dataset = H5Dopen2(id, name.c_str(), H5P_DEFAULT);
  if (dataset != H5I_INVALID_HID)
  {
    auto dataspace = H5Dget_space(dataset);
    if (dataspace != H5I_INVALID_HID)
    {
      const auto npoints = H5Sget_simple_extent_npoints(dataspace);
      if (H5Sget_simple_extent_ndims(dataspace) == 1 and npoints >= 0)
      {
        size = static_cast<std::uint64_t>(npoints);
        success = true;
      }
      H5Sclose(dataspace);
    }
    H5Dclose(dataset);
  }

  return success;
}

/**
 * Read parts of the 1D dataset `name`. Each range is a pair of the first element and the number
 * of elements. Ranges with no elements are ignored. The other ranges must be in increasing order,
 * must not overlap, and must lie within the dataset. `data` receives the elements of the ranges
 * one after the other, and only those, so a reader of a large dataset needs memory for its part
 * only. Returns false, with `data` empty, if `name` is not a 1D dataset, the ranges break these
 * rules, or the read fails.
 *
 * The ranges are read in batches of at most `max_ranges_per_read`. HDF5 merges each range added
 * to a selection with the ranges already in it, so one selection of n ranges costs O(n^2). The
 * batches bound this cost to O(n * max_ranges_per_read).
 */
template <typename T>
bool
H5ReadDataset1DRanges(hid_t id,
                      const std::string& name,
                      const std::vector<std::pair<std::uint64_t, std::uint64_t>>& ranges,
                      std::vector<T>& data)
{
  static_assert(
    !std::is_same_v<T, bool>,
    "H5ReadDataset1DRanges does not support std::vector<bool>. Use std::vector<unsigned char>.");
  constexpr size_t max_ranges_per_read = 1024;

  data.clear();
  const auto read = [&]()
  {
    const H5IdHandle dataset(H5Dopen2(id, name.c_str(), H5P_DEFAULT), H5Dclose);
    if (dataset.Id() == H5I_INVALID_HID)
      return false;
    const H5IdHandle file_space(H5Dget_space(dataset.Id()), H5Sclose);
    if (file_space.Id() == H5I_INVALID_HID)
      return false;
    const auto npoints = H5Sget_simple_extent_npoints(file_space.Id());
    if (H5Sget_simple_extent_ndims(file_space.Id()) != 1 or npoints < 0)
      return false;

    // Check the ranges and count their elements before allocating.
    const auto extent = static_cast<std::uint64_t>(npoints);
    std::uint64_t total = 0;
    std::uint64_t end_of_previous = 0;
    for (const auto& [first, count] : ranges)
    {
      if (count == 0)
        continue;
      if (first < end_of_previous or first > extent or count > extent - first)
        return false;
      end_of_previous = first + count;
      total += count;
    }
    if (total == 0)
      return true;
    if (total > data.max_size())
      return false;
    data.resize(static_cast<size_t>(total));

    // Each batch of ranges is one selection, read into the next part of `data`.
    size_t next = 0;
    std::uint64_t offset = 0;
    while (next < ranges.size())
    {
      if (H5Sselect_none(file_space.Id()) < 0)
        return false;
      std::uint64_t batch_total = 0;
      for (size_t num_selected = 0; next < ranges.size() and num_selected < max_ranges_per_read;
           ++next)
      {
        const auto& [first, count] = ranges[next];
        if (count == 0)
          continue;
        const hsize_t start = first;
        const hsize_t block = count;
        if (H5Sselect_hyperslab(file_space.Id(), H5S_SELECT_OR, &start, nullptr, &block, nullptr) <
            0)
          return false;
        batch_total += count;
        ++num_selected;
      }
      if (batch_total == 0)
        continue;
      const hsize_t memory_size = batch_total;
      const H5IdHandle memory_space(H5Screate_simple(1, &memory_size, nullptr), H5Sclose);
      if (memory_space.Id() == H5I_INVALID_HID or H5Dread(dataset.Id(),
                                                          get_datatype<T>(),
                                                          memory_space.Id(),
                                                          file_space.Id(),
                                                          H5P_DEFAULT,
                                                          data.data() + offset) < 0)
        return false;
      offset += batch_total;
    }
    return true;
  };

  if (not read())
  {
    data.clear();
    data.shrink_to_fit();
    return false;
  }
  return true;
}

template <typename T>
bool
H5ReadDataset2D(hid_t id, const std::string& name, std::vector<std::vector<T>>& data)
{
  static_assert(
    !std::is_same_v<T, bool>,
    "H5ReadDataset2D does not support std::vector<std::vector<bool>>. Use unsigned char.");

  bool success = false;
  data.clear();

  auto dataset = H5Dopen2(id, name.c_str(), H5P_DEFAULT);
  if (dataset == H5I_INVALID_HID)
    return false;

  auto dataspace = H5Dget_space(dataset);
  if (dataspace != H5I_INVALID_HID)
  {
    const int rank = H5Sget_simple_extent_ndims(dataspace);
    if (rank == 2)
    {
      hsize_t dims[2] = {0, 0};
      if (H5Sget_simple_extent_dims(dataspace, dims, nullptr) >= 0)
      {
        auto n0 = static_cast<size_t>(dims[0]);
        auto n1 = static_cast<size_t>(dims[1]);
        std::vector<T> flat_data(n0 * n1);
        if (flat_data.empty() or
            H5Dread(dataset, get_datatype<T>(), H5S_ALL, H5S_ALL, H5P_DEFAULT, flat_data.data()) >=
              0)
        {
          data.assign(n0, std::vector<T>(n1));
          for (size_t i = 0; i < n0; ++i)
            for (size_t j = 0; j < n1; ++j)
              data[i][j] = flat_data[i * n1 + j];
          success = true;
        }
      }
    }
    H5Sclose(dataspace);
  }

  H5Dclose(dataset);
  return success;
}

template <typename T>
bool
H5ReadAttribute(hid_t id, const std::string& name, T& value)
{
  bool success = false;

  if (H5Aexists(id, name.c_str()) > 0)
  {
    auto attribute = H5Aopen(id, name.c_str(), H5P_DEFAULT);
    if (attribute != H5I_INVALID_HID)
    {
      // A larger attribute would be read past the end of value.
      if (H5AttributeHasOneElement(attribute) and
          H5Aread(attribute, get_datatype<T>(), &value) >= 0)
        success = true;
      H5Aclose(attribute);
    }
  }

  return success;
}

template <>
inline bool
H5ReadAttribute<std::string>(hid_t id, const std::string& name, std::string& value)
{
  // NOTE: This implementation assumes the attribute was written as a
  // fixed-length C string and pads with a NUL terminator.

  bool success = false;

  if (H5Aexists(id, name.c_str()) <= 0)
    return false;

  auto attribute = H5Aopen(id, name.c_str(), H5P_DEFAULT);
  if (attribute == H5I_INVALID_HID)
    return false;

  auto size = static_cast<size_t>(H5Aget_storage_size(attribute));
  hid_t string_type = H5Tcopy(H5T_C_S1);
  if (string_type >= 0)
  {
    if (size == 0)
    {
      value.clear();
      success = true;
    }
    else
    {
      H5Tset_size(string_type, size + 1);
      H5Tset_strpad(string_type, H5T_STR_NULLTERM);
      std::vector<char> buffer(size + 1, '\0');
      if (H5Aread(attribute, string_type, buffer.data()) >= 0)
      {
        value = buffer.data();
        success = true;
      }
    }
    H5Tclose(string_type);
  }
  H5Aclose(attribute);

  return success;
}

template <>
inline bool
H5ReadAttribute<bool>(hid_t id, const std::string& name, bool& value)
{
  bool success = false;

  if (H5Aexists(id, name.c_str()) <= 0)
    return false;

  auto attribute = H5Aopen(id, name.c_str(), H5P_DEFAULT);
  if (attribute == H5I_INVALID_HID)
    return false;

  unsigned char tmp = 0;
  if (H5AttributeHasOneElement(attribute) and H5Aread(attribute, H5T_NATIVE_UCHAR, &tmp) >= 0)
  {
    value = static_cast<bool>(tmp);
    success = true;
  }
  H5Aclose(attribute);

  return success;
}

template <typename T>
bool
H5ReadGroupAttribute(hid_t id, const std::string& group_id, const std::string& name, T& value)
{
  bool success = false;

  auto group = H5Gopen2(id, group_id.c_str(), H5P_DEFAULT);
  if (group != H5I_INVALID_HID)
  {
    success = H5ReadAttribute<T>(group, name, value);
    H5Gclose(group);
  }

  return success;
}

template <>
inline bool
H5ReadGroupAttribute<std::string>(hid_t id,
                                  const std::string& group_id,
                                  const std::string& name,
                                  std::string& value)
{
  bool success = false;

  auto group = H5Gopen2(id, group_id.c_str(), H5P_DEFAULT);
  if (group != H5I_INVALID_HID)
  {
    success = H5ReadAttribute<std::string>(group, name, value);
    H5Gclose(group);
  }

  return success;
}

template <>
inline bool
H5ReadGroupAttribute<bool>(hid_t id,
                           const std::string& group_id,
                           const std::string& name,
                           bool& value)
{
  bool success = false;

  auto group = H5Gopen2(id, group_id.c_str(), H5P_DEFAULT);
  if (group != H5I_INVALID_HID)
  {
    success = H5ReadAttribute<bool>(group, name, value);
    H5Gclose(group);
  }

  return success;
}

} // namespace opensn