34 proxy(group g, std::string
const &key, std::string
const &g_path,
char mode) : g{std::move(g)}, _key{key}, g_path{g_path}, mode{mode} {}
38 return out << fmt::format(
"h5 proxy {} : path = {}, key ={}. ", (p.
is_group() ?
"[Group]" :
"Dataset"), p.g_path, p._key);
46 proxy(std::string
const &name,
char mode) : g{file(name, mode)}, _key{
"/"}, mode{mode} {}
53 [[nodiscard]] std::string path()
const {
return g_path +
"/" + _key; }
59 [[nodiscard]]
bool is_group()
const {
return g.has_subgroup(_key); }
62 [[nodiscard]]
bool has_group(
const std::string &name)
const {
return g.has_subgroup(name); }
67 std::cerr << fmt::format(
"{} is not a group", g_path) << std::endl;
68 throw std::runtime_error{fmt::format(
"{} is not a group", g_path)};
75 operator group()
const {
77 if ((mode ==
'r') or (g.has_key(_key)))
return g.open_group(_key);
78 return g.create_group(_key);
88 auto gg = group(*
this);
89 if (!gg.has_key(key))
throw std::runtime_error{fmt::format(
"{} is not a key of {}", key, g_path)};
90 return {std::move(gg), key, path(), mode};
97 template <
typename T> [[nodiscard]] T
as()
const {
98 static_assert(not std::is_reference_v<T>);
99 if constexpr (std::is_same_v<T, group>)
102 return ::h5::read<T>(g, _key);
107 template <
typename T> [[nodiscard]]
friend T
as(
proxy const &x) {
return x.
as<T>(); }
110 template <
typename T>
friend bool is(
proxy const &x) {
111 dataset ds = x.g.open_dataset(x._key);
112 datatype ty = H5Dget_type(ds);
113 return ty == h5::detail::hid_t_of<T>();
118 template <
typename T>
friend void operator<<(T &&lhs,
proxy const &x) { ::h5::read(x.g, x._key, lhs); }
126 if (mode ==
'r')
throw std::runtime_error{
"Read only file. Can not write."};
127 ::h5::write(g, _key, x);
135 explicit operator int()
const {
return as<int>(); }
136 explicit operator long()
const {
return as<long>(); }
137 explicit operator double()
const {
return as<double>(); }
138 explicit operator dcomplex()
const {
return as<dcomplex>(); }
146 generator<proxy> get_children()
const {
147 for (
auto key : group(*this).get_all_subgroup_dataset_names()) co_yield (*this)[key];
149 mutable std::shared_ptr<generator<proxy>> children;
156 if (not children) children = std::make_shared<generator<proxy>>(get_children());
157 return children->begin();
159 [[nodiscard]]
auto end()
const {
161 return children->end();
167 [[nodiscard]]
auto _read_transform()
const {
169 return std::views::transform([self = *
this](
auto &&key) {
return self[key]; });
177 [[nodiscard]]
auto groups()
const {
return group(*this).get_all_subgroup_names() | _read_transform(); }
180 [[nodiscard]]
auto datasets()
const {
return group(*this).get_all_dataset_names() | _read_transform(); }
183 [[nodiscard]]
auto keys()
const {
return group(*this).get_all_subgroup_dataset_names(); }
189 auto y = group(x).get_all_subgroup_dataset_names();
190 std::ranges::sort(y, pred);
191 return std::move(y) | x._read_transform();