GridFormat 0.6.0
I/O-Library for grid-like data structures
Loading...
Searching...
No Matches
hdf_unstructured_grid_reader.hpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2022-2023 Dennis Gläser <dennis.glaeser@iws.uni-stuttgart.de>
2// SPDX-License-Identifier: MIT
8#ifndef GRIDFORMAT_VTK_HDF_UNSTRUCTURED_GRID_READER_HPP_
9#define GRIDFORMAT_VTK_HDF_UNSTRUCTURED_GRID_READER_HPP_
10#if GRIDFORMAT_HAVE_HIGH_FIVE
11
12#include <iterator>
13#include <optional>
14#include <algorithm>
15#include <type_traits>
16#include <concepts>
17#include <numeric>
18#include <utility>
19#include <cassert>
20
22#include <gridformat/common/range_field.hpp>
23#include <gridformat/common/field_transformations.hpp>
24#include <gridformat/common/concepts.hpp>
25#include <gridformat/common/exceptions.hpp>
27#include <gridformat/parallel/concepts.hpp>
30
31namespace GridFormat {
32
37template<Concepts::Communicator Communicator = NullCommunicator>
38class VTKHDFUnstructuredGridReader : public GridReader {
39 using HDF5File = HDF5::File<Communicator>;
40 static constexpr std::size_t vtk_space_dim = 3;
41 static constexpr bool read_rank_piece_only = !std::is_same_v<Communicator, NullCommunicator>;
42
43 public:
44 explicit VTKHDFUnstructuredGridReader() requires(std::is_same_v<Communicator, NullCommunicator>)
45 : _comm{}
46 {}
47
48 explicit VTKHDFUnstructuredGridReader(Communicator comm)
49 : _comm{comm}
50 {}
51
52 private:
53 std::string _name() const override {
54 if (_is_transient())
55 return "VTKHDFUnstructuredGridReader (transient)";
56 return "VTKHDFUnstructuredGridReader";
57 }
58
59 void _open(const std::string& filename, typename GridReader::FieldNames& field_names) override {
60 _close();
61 _file = HDF5File{filename, _comm, HDF5File::read_only};
62 const auto type = VTKHDF::get_file_type(_file.value());
63 if (type != "UnstructuredGrid")
64 throw ValueError("Incompatible VTK-HDF type: '" + type + "', expected 'UnstructuredGrid'.");
65
66 VTKHDF::check_version_compatibility(_file.value(), {2, 0});
67
68 if (_file->exists("VTKHDF/Steps"))
69 _file->visit_attribute("VTKHDF/Steps/NSteps", [&] (auto&& field) {
70 _num_steps.emplace();
71 field.export_to(_num_steps.value());
72 _step_index.emplace(0);
73 });
74
75 _compute_piece_offsets();
76 const auto copy_names_in = [&] (const std::string& group, auto& storage) {
77 if (_file->exists(group))
78 std::ranges::copy(_file->dataset_names_in(group), std::back_inserter(storage));
79 };
80 copy_names_in("VTKHDF/CellData", field_names.cell_fields);
81 copy_names_in("VTKHDF/PointData", field_names.point_fields);
82 copy_names_in("VTKHDF/FieldData", field_names.meta_data_fields);
83 }
84
85 void _close() override {
86 _file = {};
87 _num_cells = 0;
88 _num_points = 0;
89 _cell_offset = 0;
90 _point_offset = 0;
91 _num_steps = {};
92 _step_index = {};
93 }
94
95 void _compute_piece_offsets() {
96 _cell_offset = 0;
97 _point_offset = 0;
98 _check_communicator_size();
99 const auto num_step_cells = _number_of_all_piece_entities("Cells");
100 const auto num_step_points = _number_of_all_piece_entities("Points");
101 if constexpr (read_rank_piece_only) {
102 const auto my_rank = Parallel::rank(_comm);
103 _num_cells = num_step_cells.at(my_rank);
104 _num_points = num_step_points.at(my_rank);
105 _cell_offset += _accumulate_until(my_rank, num_step_cells);
106 _point_offset += _accumulate_until(my_rank, num_step_points);
107 } else {
108 _num_cells = _accumulate_until(num_step_cells.size(), num_step_cells);
109 _num_points = _accumulate_until(num_step_points.size(), num_step_points);
110 }
111 }
112
113 std::size_t _get_part_offset() const {
114 return _is_transient()
115 ? _access_file().template read_dataset_to<std::size_t>(
116 "/VTKHDF/Steps/PartOffsets",
117 HDF5::Slice{
118 .offset = {_step_index.value()},
119 .count = {1}
120 })
121 : std::size_t{0};
122 }
123
124 std::size_t _get_step_cells_offset() const {
125 return _is_transient()
126 ? _access_file().template read_dataset_to<std::size_t>(
127 "VTKHDF/Steps/CellOffsets",
128 HDF5::Slice{
129 .offset = {_step_index.value(), 0},
130 .count = {1, 1}
131 })
132 : std::size_t{0};
133 }
134
135 std::size_t _get_step_points_offset() const {
136 return _is_transient()
137 ? _access_file().template read_dataset_to<std::size_t>(
138 "VTKHDF/Steps/PointOffsets",
139 HDF5::Slice{
140 .offset = {_step_index.value()},
141 .count = {1}
142 })
143 : std::size_t{0};
144 }
145
146 std::size_t _get_connectivity_id_offset() const {
147 return _is_transient()
148 ? _access_file().template read_dataset_to<std::size_t>(
149 "VTKHDF/Steps/ConnectivityIdOffsets",
150 HDF5::Slice{
151 .offset = {_step_index.value(), 0},
152 .count = {1, 1}
153 })
154 : std::size_t{0};
155 }
156
157 std::size_t _get_cell_data_offset(std::string_view name) const {
158 return _is_transient()
159 ? _access_file().template read_dataset_to<std::size_t>(
160 "VTKHDF/Steps/CellDataOffsets/" + std::string{name},
161 HDF5::Slice{
162 .offset = {_step_index.value()},
163 .count = {1}
164 })
165 : std::size_t{0};
166 }
167
168 std::size_t _get_point_data_offset(std::string_view name) const {
169 return _is_transient()
170 ? _access_file().template read_dataset_to<std::size_t>(
171 "VTKHDF/Steps/PointDataOffsets/" + std::string{name},
172 HDF5::Slice{
173 .offset = {_step_index.value()},
174 .count = {1}
175 })
176 : std::size_t{0};
177 }
178
179 bool _is_sequence() const override {
180 return _is_transient();
181 }
182
183 std::size_t _number_of_steps() const override {
184 if (!_num_steps)
185 throw ValueError("No step information available");
186 return _num_steps.value();
187 }
188
189 double _time_at_step(std::size_t step_idx) const override {
190 if (step_idx >= _number_of_steps())
191 throw ValueError("Only " + as_string(_number_of_steps()) + " available");
192 return _access_file().template read_dataset_to<double>("/VTKHDF/Steps/Values", HDF5::Slice{
193 .offset = {step_idx},
194 .count = {1}
195 });
196 }
197
198 void _set_step(std::size_t step_idx, typename GridReader::FieldNames&) override {
199 if (step_idx >= _number_of_steps())
200 throw ValueError("Only " + as_string(_number_of_steps()) + " available");
201 if (step_idx != _step_index.value()) {
202 _compute_piece_offsets();
203 _step_index = step_idx;
204 }
205 }
206
207 std::size_t _number_of_cells() const override {
208 return _num_cells;
209 }
210
211 std::size_t _number_of_points() const override {
212 return _num_points;
213 }
214
215 std::size_t _number_of_pieces() const override {
216 return _number_of_current_pieces_in_file();
217 }
218
219 std::size_t _number_of_current_pieces_in_file() const {
220 if (_is_transient())
221 return _number_of_pieces_in_file_at_step(_step_index.value());
222 return _total_number_of_pieces();
223 }
224
225 std::size_t _total_number_of_pieces() const {
226 auto ncells = _access_file().get_dimensions("/VTKHDF/NumberOfCells");
227 if (!ncells) throw IOError("Missing dataset at '/VTKHDF/NumberOfCells'");
228 if (ncells->size() != 1) throw IOError("Unexpected dimension of '/VTKHDF/NumberOfCells'");
229 return ncells->at(0);
230 }
231
232 std::size_t _number_of_pieces_in_file_at_step(std::size_t step) const {
233 if (!_is_transient())
234 throw InvalidState("Step data only available in transient files");
235 if (const auto& file = _access_file(); file.exists("/VTKHDF/Steps/NumberOfParts"))
236 return file.template read_dataset_to<std::vector<std::size_t>>("/VTKHDF/Steps/NumberOfParts").at(step);
237
238 // all steps have the same number of parts
239 if (_total_number_of_pieces()%_num_steps.value() != 0)
240 throw IOError(
241 "Cannot deduce the number of pieces. "
242 "The dataset '/VTKHDF/Steps/NumberOfParts' is not available, "
243 "but the total number of pieces is not divisble by the number of steps"
244 );
245 return _total_number_of_pieces()/_num_steps.value();
246 }
247
248 void _check_communicator_size() const {
249 if constexpr (!std::is_same_v<Communicator, NullCommunicator>)
250 if (_number_of_current_pieces_in_file() != static_cast<std::size_t>(Parallel::size(_comm)))
251 throw SizeError(
252 "Can only read the file in parallel if the size of the communicator matches the size "
253 "of that used when writing the file. Please read in the file sequentially on one process "
254 "and distribute the grid yourself, or restart the parallel run with "
255 + std::to_string(_number_of_current_pieces_in_file()) + " processes."
256 );
257 }
258
259 void _visit_cells(const typename GridReader::CellVisitor& visitor) const override {
260 if constexpr (read_rank_piece_only)
261 _visit_cells_for_rank(Parallel::rank(_comm), 0, visitor);
262 else
263 std::ranges::for_each(
264 std::views::iota(std::size_t{0}, _number_of_current_pieces_in_file()),
265 [&] (int rank) mutable {
266 const auto [_, base_offset] = _number_of_entities_and_offset_at_rank(rank, "Points");
267 _visit_cells_for_rank(rank, base_offset, visitor);
268 }
269 );
270 }
271
272 void _visit_cells_for_rank(int piece_rank,
273 std::size_t point_base_offset,
274 const typename GridReader::CellVisitor& visitor) const {
275 const auto& file = _access_file();
276 const auto [my_num_cells, my_cell_offset] = _number_of_entities_and_offset_at_rank(piece_rank, "Cells");
277 const auto num_connectivity_ids = file.template read_dataset_to<std::vector<std::size_t>>(
278 "VTKHDF/NumberOfConnectivityIds",
279 HDF5::Slice{
280 .offset = {_get_part_offset()},
281 .count = {_number_of_current_pieces_in_file()}
282 }
283 );
284 const auto my_num_connectivity_ids = num_connectivity_ids.at(piece_rank);
285 const auto my_id_offset = std::accumulate(
286 num_connectivity_ids.begin(),
287 num_connectivity_ids.begin() + piece_rank,
288 std::size_t{0}
289 );
290
291 auto offsets = file.template read_dataset_to<std::vector<std::size_t>>("VTKHDF/Offsets", {{
292 // offsets have length num_cells+1, so we need to add +1 per rank to the cell offsets
293 .offset = {
294 _get_step_cells_offset() + _accumulate_over_pieces_until_step(_step_index.value_or(0), 1) // offset from step
295 + my_cell_offset + piece_rank // offset from this piece in the pieces of the current step
296 },
297 .count = {my_num_cells + 1}
298 }});
299 auto types = file.template read_dataset_to<std::vector<std::uint_least8_t>>(
300 "VTKHDF/Types",
301 {{.offset = {_get_step_cells_offset() + my_cell_offset}, .count = {my_num_cells}}}
302 );
303 auto connectivity = file.template read_dataset_to<std::vector<std::size_t>>(
304 "VTKHDF/Connectivity",
305 {{.offset = {_get_connectivity_id_offset() + my_id_offset}, .count = {my_num_connectivity_ids}}}
306 );
307
308 std::vector<std::size_t> corners;
309 for (std::size_t i = 0; i < types.size(); ++i) {
310 assert(i < offsets.size() - 1);
311 assert(offsets.at(i+1) > offsets.at(i));
312 const auto p0_offset = offsets.at(i);
313 const auto num_corners = offsets.at(i+1) - p0_offset;
314
315 corners.resize(num_corners);
316 for (std::size_t c = 0; c < num_corners; ++c)
317 corners[c] = connectivity.at(p0_offset + c) + point_base_offset;
318 visitor(VTK::cell_type(types.at(i)), corners);
319 }
320 }
321
322 FieldPtr _points() const override {
323 const std::string path = "VTKHDF/Points";
325 _file.value(),
326 MDLayout{{_num_points, vtk_space_dim}},
327 _file.value().get_precision(path).value(),
328 _serialization_callback(path, HDF5::Slice{
329 .offset = {_point_offset + _get_step_points_offset(), 0},
330 .count = {_num_points, vtk_space_dim}
331 })
332 });
333 }
334
335 FieldPtr _cell_field(std::string_view name) const override {
336 const std::string path = "VTKHDF/CellData/" + std::string{name};
337 const auto slice = _get_slice(path, _num_cells, _cell_offset + _get_cell_data_offset(name));
339 _file.value(),
340 MDLayout{slice.count},
341 _file.value().get_precision(path).value(),
342 _serialization_callback(path, slice)
343 });
344 }
345
346 FieldPtr _point_field(std::string_view name) const override {
347 const std::string path = "VTKHDF/PointData/" + std::string{name};
348 const auto slice = _get_slice(path, _num_points, _point_offset + _get_point_data_offset(name));
350 _file.value(),
351 MDLayout{slice.count},
352 _file.value().get_precision(path).value(),
353 _serialization_callback(path, slice)
354 });
355 }
356
357 FieldPtr _meta_data_field(std::string_view name) const override {
359 _file.value(),
360 std::string{name},
361 _is_transient() ? std::optional{_step_index.value()} : std::nullopt
362 );
363 }
364
365 template<Concepts::Scalar T>
366 T _read_rank_scalar(const std::string& path, const std::size_t base_offset = 0) const {
367 T result;
368 _file.value().visit_dataset(
369 path,
370 [&] (auto&& field) { field.export_to(result); },
371 HDF5::Slice{
372 .offset = {base_offset + static_cast<std::size_t>(Parallel::rank(_comm))},
373 .count = {1}
374 }
375 );
376 return result;
377 }
378
379 HDF5::Slice _get_slice(const std::string& path,
380 std::size_t count,
381 std::size_t offset) const {
382 auto ds_size = _file.value().get_dimensions(path).value();
383 auto ds_offset = ds_size;
384 std::ranges::fill(ds_offset, std::size_t{0});
385 ds_size.at(0) = count;
386 ds_offset.at(0) = offset;
387 return {.offset = ds_offset, .count = ds_size};
388 }
389
390 auto _serialization_callback(std::string path, std::optional<HDF5::Slice> slice = {}) const {
391 return [_p=std::move(path), _s=std::move(slice)] (const HDF5File& file) {
392 if (_s)
393 return file.visit_dataset(_p, [&] <typename F> (F&& f) { return f.serialized(); }, _s.value());
394 return file.visit_dataset(_p, [&] <typename F> (F&& f) { return f.serialized(); });
395 };
396 }
397
398 bool _is_transient() const {
399 return static_cast<bool>(_num_steps);
400 }
401
402 const HDF5File& _access_file() const {
403 if (!_file.has_value())
404 throw InvalidState("No file has been read");
405 return _file.value();
406 }
407
408 std::vector<std::size_t> _number_of_all_piece_entities(const std::string& entity_type) const {
409 return _access_file().template read_dataset_to<std::vector<std::size_t>>("/VTKHDF/NumberOf" + entity_type, {{
410 .offset = {_get_part_offset()},
411 .count = {_number_of_current_pieces_in_file()}
412 }});
413 }
414
415 template<std::integral T>
416 std::array<std::size_t, 2> _number_of_entities_and_offset_at_rank(T rank, const std::string& entity_type) const {
417 const auto entities = _number_of_all_piece_entities(entity_type);
418 return std::array{entities.at(rank), _accumulate_until(rank, entities)};
419 }
420
421 template<typename T>
422 T _accumulate_until(std::integral auto rank, const std::vector<T>& values) const {
423 return std::accumulate(values.begin(), values.begin() + rank, T{0});
424 }
425
426 std::size_t _accumulate_over_pieces_until_step(std::size_t step, std::size_t count_per_piece) const {
427 if (step == 0)
428 return 0;
429 if (!_is_transient())
430 throw InvalidState("Step data only available in transient files");
431
432 std::size_t result = 0;
433 std::ranges::for_each(std::views::iota(std::size_t{0}, step), [&] (std::size_t step_idx) {
434 const auto num_step_pieces = _number_of_pieces_in_file_at_step(step_idx);
435 result += count_per_piece*num_step_pieces;
436 });
437 return result;
438 }
439
440 Communicator _comm;
441 std::optional<HDF5File> _file;
442 std::size_t _num_cells = 0;
443 std::size_t _num_points = 0;
444 std::size_t _cell_offset = 0;
445 std::size_t _point_offset = 0;
446 std::optional<std::size_t> _num_steps;
447 std::optional<std::size_t> _step_index;
448};
449
450} // namespace GridFormat
451
452#endif // GRIDFORMAT_HAVE_HIGH_FIVE
453#endif // GRIDFORMAT_VTK_HDF_UNSTRUCTURED_GRID_READER_HPP_
const std::string & filename() const
Return the name of the opened grid file (empty string until open() is called).
Definition reader.hpp:92
std::string name() const
Return the name of this reader.
Definition reader.hpp:73
Field implementation that draws values from an open HDF5 file upon request.
Definition hdf_common.hpp:135
Abstract interface for fields of values that is used by writers/readers to store fields.
Base class for grid data readers.
FieldPtr make_field_ptr(F &&f)
Factory function for field pointers.
Definition field.hpp:211
std::shared_ptr< const Field > FieldPtr
Pointer type used by writers/readers for fields.
Definition field.hpp:205
Common functionality for writing VTK HDF files.
void check_version_compatibility(const HDF5::File< C > &file, const std::array< std::size_t, 2 > &supported)
Definition hdf_common.hpp:174
std::string get_file_type(const HDF5::File< C > &file)
Read the vtk-hdf file type from an hdf5 file.
Definition hdf_common.hpp:162
FieldPtr read_field_data(const HDF5::File< C > &file, const std::string &name, std::optional< std::size_t > step)
Read the field data array with the given name, at the given step for transient files.
Definition hdf_common.hpp:244
Definition reader.hpp:266
Common functionality for VTK writers.