DOLFINx 0.12.0.0
DOLFINx C++
Loading...
Searching...
No Matches
xdmf_utils.h
1// Copyright (C) 2012-2024 Chris N. Richardson, Jørgen S. Dokken
2//
3// This file is part of DOLFINx (https://www.fenicsproject.org)
4//
5// SPDX-License-Identifier: LGPL-3.0-or-later
6
7#pragma once
8
9#include "HDF5Interface.h"
10#include <array>
11#include <basix/mdspan.hpp>
12#include <boost/algorithm/string.hpp>
13#include <boost/lexical_cast.hpp>
14#include <dolfinx/common/MPI.h>
15#include <dolfinx/common/types.h>
16#include <filesystem>
17#include <format>
18#include <iterator>
19#include <numeric>
20#include <pugixml.hpp>
21#include <span>
22#include <string>
23#include <string_view>
24#include <utility>
25#include <vector>
26
27namespace dolfinx
28{
29namespace fem
30{
31template <dolfinx::scalar T, std::floating_point U>
32class Function;
33} // namespace fem
34
35namespace fem
36{
37template <std::floating_point T>
40} // namespace fem
41
42namespace mesh
43{
44template <std::floating_point T>
45class Mesh;
46class Topology;
47enum class CellType : std::int8_t;
48} // namespace mesh
49
50namespace io::xdmf_utils
51{
52
55std::pair<std::string, int> get_cell_type(const pugi::xml_node& topology_node);
56
59std::array<std::string, 2> get_hdf5_paths(const pugi::xml_node& dataitem_node);
60
61std::filesystem::path
62get_hdf5_filename(const std::filesystem::path& xdmf_filename);
63
65std::vector<std::int64_t> get_dataset_shape(const pugi::xml_node& dataset_node);
66
68std::int64_t get_num_cells(const pugi::xml_node& topology_node);
69
71std::string vtk_cell_type_str(mesh::CellType cell_type, int num_nodes);
72
74template <typename T>
75void add_data_item(pugi::xml_node& xml_node, hid_t h5_id,
76 std::string_view h5_path, std::span<const T> x,
77 std::int64_t offset, const std::vector<std::int64_t>& shape,
78 std::string_view number_type, bool use_mpi_io)
79{
80 // Add DataItem node
81 assert(xml_node);
82 pugi::xml_node data_item_node = xml_node.append_child("DataItem");
83 assert(data_item_node);
84
85 // Add dimensions attribute
86 std::string dims;
87 for (auto d : shape)
88 std::format_to(std::back_inserter(dims), "{} ", d);
89 dims.pop_back();
90 data_item_node.append_attribute("Dimensions") = dims.c_str();
91
92 // Set type for topology data (needed by XDMF to prevent default to
93 // float)
94 if (!number_type.empty())
95 {
96 data_item_node.append_attribute("NumberType")
97 = std::string(number_type).c_str();
98 }
99
100 // Add format attribute
101 if (h5_id < 0)
102 {
103 data_item_node.append_attribute("Format") = "XML";
104 assert(shape.size() == 2);
105 std::string s;
106 for (std::size_t i = 0; i < x.size(); ++i)
107 {
108 if constexpr (std::floating_point<T>)
109 std::format_to(std::back_inserter(s), "{:.16}", x.data()[i]);
110 else
111 std::format_to(std::back_inserter(s), "{}", x.data()[i]);
112 s += ((i + 1) % shape[1] == 0 and shape[1] != 0) ? '\n' : ' ';
113 }
114
115 data_item_node.append_child(pugi::node_pcdata).set_value(s.c_str());
116 }
117 else
118 {
119 data_item_node.append_attribute("Format") = "HDF";
120
121 // Get name of HDF5 file, including path
122 const std::filesystem::path p = io::hdf5::get_filename(h5_id);
123 const std::filesystem::path filename = p.filename().c_str();
124
125 // Add HDF5 filename and HDF5 internal path to XML file
126 const std::string xdmf_path
127 = std::format("{}:{}", filename.string(), h5_path);
128 data_item_node.append_child(pugi::node_pcdata).set_value(xdmf_path.c_str());
129
130 // Compute data offset and range of values
131 std::int64_t local_shape0 = std::reduce(
132 std::next(shape.begin()), shape.end(), x.size(), std::divides{});
133
134 const std::array local_range{offset, offset + local_shape0};
135 io::hdf5::write_dataset(h5_id, h5_path, x.data(), local_range, shape,
136 use_mpi_io, false);
137
138 // Add partitioning attribute to dataset
139 // std::vector<std::size_t> partitions;
140 // std::vector<std::size_t> offset_tmp(1, offset);
141 // dolfinx::MPI::gather(comm, offset_tmp, partitions);
142 // dolfinx::MPI::broadcast(comm, partitions);
143 // io::hdf5::add_attribute(h5_id, h5_path, "partition", partitions);
144 }
145}
146
151template <typename T>
152std::vector<T> get_dataset(MPI_Comm comm, const pugi::xml_node& dataset_node,
153 hid_t h5_id,
154 std::array<std::int64_t, 2> range = {0, 0})
155{
156 // FIXME: Need to sort out dataset dimensions - can't depend on HDF5
157 // shape, and a Topology data item is not required to have a
158 // 'Dimensions' attribute since the dimensions can be determined from
159 // the number of cells and the cell type (for topology, one must
160 // supply cell type + (number of cells or dimensions)).
161 //
162 // A geometry data item must have 'Dimensions' attribute.
163
164 assert(dataset_node);
165 pugi::xml_attribute format_attr = dataset_node.attribute("Format");
166 assert(format_attr);
167
168 // Get data set shape from 'Dimensions' attribute (empty if not
169 // available)
170 const std::vector shape_xml = xdmf_utils::get_dataset_shape(dataset_node);
171
172 const std::string format = format_attr.as_string();
173 std::vector<T> data_vector;
174 // Only read ASCII on process 0
175 const int mpi_rank = dolfinx::MPI::rank(comm);
176 if (format == "XML")
177 {
178 if (mpi_rank == 0)
179 {
180 // Read data and trim any leading/trailing whitespace
181 pugi::xml_node data_node = dataset_node.first_child();
182 assert(data_node);
183 std::string data_str = data_node.value();
184
185 // Split data based on spaces and line breaks
186 std::vector<boost::iterator_range<std::string::iterator>> data_vector_str;
187 boost::split(data_vector_str, data_str, boost::is_any_of(" \n"));
188
189 // Add data to numerical vector
190 data_vector.reserve(data_vector_str.size());
191 for (auto& v : data_vector_str)
192 {
193 if (v.begin() != v.end())
194 data_vector.push_back(
195 boost::lexical_cast<T>(boost::copy_range<std::string>(v)));
196 }
197 }
198 }
199 else if (format == "HDF")
200 {
201 // Get file and data path
202 auto paths = xdmf_utils::get_hdf5_paths(dataset_node);
203
204 // Get data shape from HDF5 file
205 const std::vector shape_hdf5 = io::hdf5::get_dataset_shape(h5_id, paths[1]);
206
207 // FIXME: should we support empty data sets?
208 // Check that data set is not empty
209 assert(!shape_hdf5.empty());
210 assert(shape_hdf5[0] != 0);
211
212 // Determine range of data to read from HDF5 file. This is
213 // complicated by the XML Dimension attribute and the HDF5 storage
214 // possibly having different shapes, e.g. the HDF5 storage may be a
215 // flat array.
216
217 // If range = {0, 0} then no range is supplied and we must determine
218 // the range
219 if (range[0] == 0 and range[1] == 0)
220 {
221 if (shape_xml == shape_hdf5)
222 {
223 range = common::local_range(mpi_rank, shape_hdf5[0],
224 dolfinx::MPI::size(comm));
225 }
226 else if (!shape_xml.empty() and shape_hdf5.size() == 1)
227 {
228 // Size of dims > 0
229 std::int64_t d = std::reduce(shape_xml.begin(), shape_xml.end(),
230 std::int64_t(1), std::multiplies{});
231
232 // Check for data size consistency
233 if (d * shape_xml[0] != shape_hdf5[0])
234 {
235 throw std::runtime_error("Data size in XDMF/XML and size of HDF5 "
236 "dataset are inconsistent");
237 }
238
239 // Compute data range to read
240 range = common::local_range(mpi_rank, shape_xml[0],
241 dolfinx::MPI::rank(comm));
242 range[0] *= d;
243 range[1] *= d;
244 }
245 else
246 {
247 throw std::runtime_error("This combination of array shapes in XDMF and "
248 "HDF5 is not supported");
249 }
250 }
251
252 // Retrieve data
253 if (hid_t dset_id = io::hdf5::open_dataset(h5_id, paths[1]);
254 dset_id == H5I_INVALID_HID)
255 throw std::runtime_error("Failed to open HDF5 global dataset.");
256 else
257 {
258 data_vector = io::hdf5::read_dataset<T>(dset_id, range, true);
259 if (herr_t err = H5Dclose(dset_id); err < 0)
260 throw std::runtime_error("Failed to close HDF5 global dataset.");
261 }
262 }
263 else
264 throw std::runtime_error(
265 std::format("Storage format \"{}\" is unknown", format));
266
267 // Get dimensions for consistency (if available in DataItem node)
268 if (shape_xml.empty())
269 {
270 std::int64_t size = 1;
271 for (auto dim : shape_xml)
272 size *= dim;
273
274 std::int64_t size_global = 0;
275 const std::int64_t size_local = data_vector.size();
276 MPI_Allreduce(&size_local, &size_global, 1, MPI_INT64_T, MPI_SUM, comm);
277 if (size != size_global)
278 {
279 throw std::runtime_error(
280 "Data sizes in attribute and size of data read are inconsistent");
281 }
282 }
283
284 return data_vector;
285}
286
287} // namespace io::xdmf_utils
288} // namespace dolfinx
Definition CoordinateElement.h:38
Definition ElementDofLayout.h:31
Definition Function.h:47
A Mesh consists of a set of connected and numbered mesh topological entities, and geometry data.
Definition Mesh.h:23
Topology stores the topology of a mesh, consisting of mesh entities and connectivity (incidence relat...
Definition Topology.h:49
int size(MPI_Comm comm)
Definition MPI.cpp:72
int rank(MPI_Comm comm)
Return process rank for the communicator.
Definition MPI.cpp:64
constexpr std::array< std::int64_t, 2 > local_range(int index, std::int64_t N, int size)
Partition a global range [0, N - 1] across callers into non-overlapping sub-partitions of almost equa...
Definition local_range.h:26
Finite element method functionality.
Definition assemble_expression_impl.h:23
Mesh data structures and algorithms on meshes.
Definition DofMap.h:32
CellType
Cell type identifier.
Definition cell_types.h:22
Top-level namespace.
Definition defines.h:12