DOLFINx 0.12.0.0
DOLFINx C++
Loading...
Searching...
No Matches
utils.h
1// Copyright (C) 2012-2024 Chris N. Richardson, Garth N. Wells, 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 <array>
10#include <basix/mdspan.hpp>
11#include <boost/unordered/unordered_flat_map.hpp>
12#include <dolfinx/common/types.h>
13#include <dolfinx/fem/ElementDofLayout.h>
14#include <dolfinx/mesh/Topology.h>
15#include <dolfinx/mesh/cell_types.h>
16#include <mpi.h>
17#include <span>
18#include <utility>
19#include <vector>
20
21namespace dolfinx
22{
23
24namespace io
25{
26
61template <typename T>
62std::pair<std::vector<std::int32_t>, std::vector<T>> distribute_entity_data(
63 const mesh::Topology& topology, std::span<const std::int64_t> nodes_g,
64 std::int64_t num_nodes_g, const fem::ElementDofLayout& cmap_dof_layout,
65 md::mdspan<const std::int32_t, md::dextents<std::size_t, 2>> xdofmap,
66 int entity_dim,
67 md::mdspan<const std::int64_t, md::dextents<std::size_t, 2>> entities,
68 std::span<const T> data)
69{
70 assert(entities.extent(0) == data.size());
71
72 spdlog::info("XDMF distribute entity data");
73 mesh::CellType cell_type = topology.cell_type();
74
75 // Get layout of dofs on 0th cell entity of dimension entity_dim
76 std::vector<int> cell_vertex_dofs;
77 for (int i = 0; i < mesh::cell_num_entities(cell_type, 0); ++i)
78 {
79 const std::vector<int>& local_index = cmap_dof_layout.entity_dofs(0, i);
80 assert(local_index.size() == 1);
81 cell_vertex_dofs.push_back(local_index[0]);
82 }
83
84 // -- A. Convert from list of entities by 'nodes' to list of entities
85 // by 'vertex nodes'
86 auto to_vertex_entities
87 = [](const fem::ElementDofLayout& layout, int dim,
88 std::span<const int> vertex_dofs, mesh::CellType type, auto ents)
89 {
90 // Use ElementDofLayout of the cell to get vertex dof indices (local
91 // to a cell), i.e. build a map from local vertex index to associated
92 // local dof index
93 const std::vector<int>& entity_layout = layout.entity_closure_dofs(dim, 0);
94 std::vector<int> entity_vertex_dofs;
95 for (std::size_t i = 0; i < vertex_dofs.size(); ++i)
96 {
97 auto it = std::find(entity_layout.begin(), entity_layout.end(),
98 vertex_dofs[i]);
99 if (it != entity_layout.end())
100 entity_vertex_dofs.push_back(
101 std::ranges::distance(entity_layout.begin(), it));
102 }
103
104 const std::size_t num_vert_per_e
106
107 assert(ents.extent(1) == entity_layout.size());
108 std::vector<std::int64_t> entities_v(ents.extent(0) * num_vert_per_e);
109 for (std::size_t e = 0; e < ents.extent(0); ++e)
110 {
111 std::span entity(entities_v.data() + e * num_vert_per_e, num_vert_per_e);
112 for (std::size_t i = 0; i < num_vert_per_e; ++i)
113 entity[i] = ents(e, entity_vertex_dofs[i]);
114 std::ranges::sort(entity);
115 }
116
117 std::array shape{ents.extent(0), num_vert_per_e};
118 return std::pair(std::move(entities_v), shape);
119 };
120 const auto [entities_v_b, shapev] = to_vertex_entities(
121 cmap_dof_layout, entity_dim, cell_vertex_dofs, cell_type, entities);
122
123 md::mdspan<const std::int64_t, md::dextents<std::size_t, 2>> entities_v(
124 entities_v_b.data(), shapev);
125
126 MPI_Comm comm = topology.comm();
127 MPI_Datatype compound_type;
128 MPI_Type_contiguous(entities_v.extent(1), MPI_INT64_T, &compound_type);
129 MPI_Type_commit(&compound_type);
130
131 // -- B. Send entities and entity data to postmaster
132 auto send_entities_to_postmaster
133 = [](MPI_Comm pm_comm, MPI_Datatype pm_compound_type,
134 std::int64_t pm_num_nodes_g, auto pm_entities,
135 std::span<const T> pm_data)
136 {
137 const int size = dolfinx::MPI::size(pm_comm);
138
139 // Determine destination by index of first vertex
140 std::vector<int> dest0;
141 dest0.reserve(pm_entities.extent(0));
142 for (std::size_t e = 0; e < pm_entities.extent(0); ++e)
143 {
144 dest0.push_back(
145 dolfinx::MPI::index_owner(size, pm_entities(e, 0), pm_num_nodes_g));
146 }
147 std::vector<int> perm(dest0.size());
148 std::iota(perm.begin(), perm.end(), 0);
149 std::ranges::sort(perm, [&dest0](auto x0, auto x1)
150 { return dest0[x0] < dest0[x1]; });
151
152 // Note: dest[perm[i]] is ordered with increasing i
153 // Build list of neighbour dest ranks and count number of entities to
154 // send to each post office
155 std::vector<int> dest;
156 std::vector<std::int32_t> num_items_send;
157 {
158 auto it = perm.begin();
159 while (it != perm.end())
160 {
161 dest.push_back(dest0[*it]);
162 auto it1
163 = std::find_if(it, perm.end(), [&dest0, r = dest.back()](auto idx)
164 { return dest0[idx] != r; });
165 num_items_send.push_back(std::ranges::distance(it, it1));
166 it = it1;
167 }
168 }
169
170 // Compute send displacements
171 std::vector<int> send_disp(num_items_send.size() + 1, 0);
172 std::partial_sum(num_items_send.begin(), num_items_send.end(),
173 std::next(send_disp.begin()));
174
175 // Determine src ranks. Sort ranks so that ownership determination is
176 // deterministic for a given number of ranks.
177 std::vector<int> src = dolfinx::MPI::compute_graph_edges_nbx(pm_comm, dest);
178 std::ranges::sort(src);
179
180 // Create neighbourhood communicator for sending data to post
181 // offices
182 MPI_Comm comm0;
183 int err = MPI_Dist_graph_create_adjacent(
184 pm_comm, src.size(), src.data(), MPI_UNWEIGHTED, dest.size(),
185 dest.data(), MPI_UNWEIGHTED, MPI_INFO_NULL, false, &comm0);
186 dolfinx::MPI::check_error(pm_comm, err);
187
188 // Send number of items to post offices (destinations)
189 std::vector<int> num_items_recv(src.size());
190 num_items_send.reserve(1);
191 num_items_recv.reserve(1);
192 MPI_Neighbor_alltoall(num_items_send.data(), 1, MPI_INT,
193 num_items_recv.data(), 1, MPI_INT, comm0);
194 dolfinx::MPI::check_error(pm_comm, err);
195
196 // Compute receive displacements
197 std::vector<int> recv_disp(num_items_recv.size() + 1, 0);
198 std::partial_sum(num_items_recv.begin(), num_items_recv.end(),
199 std::next(recv_disp.begin()));
200
201 // Prepare send buffer
202 std::vector<std::int64_t> send_buffer;
203 std::vector<T> send_values_buffer;
204 send_buffer.reserve(pm_entities.size());
205 send_values_buffer.reserve(pm_data.size());
206 for (std::size_t e = 0; e < pm_entities.extent(0); ++e)
207 {
208 auto idx = perm[e];
209 auto it
210 = std::next(pm_entities.data_handle(), idx * pm_entities.extent(1));
211 send_buffer.insert(send_buffer.end(), it, it + pm_entities.extent(1));
212 send_values_buffer.push_back(pm_data[idx]);
213 }
214
215 std::vector<std::int64_t> recv_buffer(recv_disp.back()
216 * pm_entities.extent(1));
217 err = MPI_Neighbor_alltoallv(send_buffer.data(), num_items_send.data(),
218 send_disp.data(), pm_compound_type,
219 recv_buffer.data(), num_items_recv.data(),
220 recv_disp.data(), pm_compound_type, comm0);
221 dolfinx::MPI::check_error(pm_comm, err);
222 std::vector<T> recv_values_buffer(recv_disp.back());
223 err = MPI_Neighbor_alltoallv(
224 send_values_buffer.data(), num_items_send.data(), send_disp.data(),
225 dolfinx::MPI::mpi_t<T>, recv_values_buffer.data(),
226 num_items_recv.data(), recv_disp.data(), dolfinx::MPI::mpi_t<T>, comm0);
227 dolfinx::MPI::check_error(pm_comm, err);
228 err = MPI_Comm_free(&comm0);
229 dolfinx::MPI::check_error(pm_comm, err);
230
231 std::array shape{recv_buffer.size() / (pm_entities.extent(1)),
232 (pm_entities.extent(1))};
233 return std::tuple<std::vector<std::int64_t>, std::vector<T>,
234 std::array<std::size_t, 2>>(
235 std::move(recv_buffer), std::move(recv_values_buffer), shape);
236 };
237 const auto [entitiesp_b, entitiesp_v, shapep] = send_entities_to_postmaster(
238 comm, compound_type, num_nodes_g, entities_v, data);
239 md::mdspan<const std::int64_t, md::dextents<std::size_t, 2>> entitiesp(
240 entitiesp_b.data(), shapep);
241
242 // -- C. Send mesh global indices to postmaster
243 auto indices_to_postoffice = [](MPI_Comm po_comm, std::int64_t num_nodes,
244 std::span<const std::int64_t> indices)
245 {
246 int size = dolfinx::MPI::size(po_comm);
247 std::vector<std::pair<int, std::int64_t>> dest_to_index;
248 std::ranges::transform(
249 indices, std::back_inserter(dest_to_index),
250 [size, num_nodes](auto n)
251 {
252 return std::pair(dolfinx::MPI::index_owner(size, n, num_nodes), n);
253 });
254 std::ranges::sort(dest_to_index);
255
256 // Build list of neighbour dest ranks and count number of indices to
257 // send to each post office
258 std::vector<int> dest;
259 std::vector<std::int32_t> num_items_send;
260 {
261 auto it = dest_to_index.begin();
262 while (it != dest_to_index.end())
263 {
264 dest.push_back(it->first);
265 auto it1
266 = std::find_if(it, dest_to_index.end(), [r = dest.back()](auto idx)
267 { return idx.first != r; });
268 num_items_send.push_back(std::ranges::distance(it, it1));
269 it = it1;
270 }
271 }
272
273 // Compute send displacements
274 std::vector<int> send_disp(num_items_send.size() + 1, 0);
275 std::partial_sum(num_items_send.begin(), num_items_send.end(),
276 std::next(send_disp.begin()));
277
278 // Determine src ranks. Sort ranks so that ownership determination is
279 // deterministic for a given number of ranks.
280 std::vector<int> src = dolfinx::MPI::compute_graph_edges_nbx(po_comm, dest);
281 std::ranges::sort(src);
282
283 // Create neighbourhood communicator for sending data to post offices
284 MPI_Comm comm0;
285 int err = MPI_Dist_graph_create_adjacent(
286 po_comm, src.size(), src.data(), MPI_UNWEIGHTED, dest.size(),
287 dest.data(), MPI_UNWEIGHTED, MPI_INFO_NULL, false, &comm0);
288 dolfinx::MPI::check_error(po_comm, err);
289
290 // Send number of items to post offices (destination) that I will be
291 // sending
292 std::vector<int> num_items_recv(src.size());
293 num_items_send.reserve(1);
294 num_items_recv.reserve(1);
295 MPI_Neighbor_alltoall(num_items_send.data(), 1, MPI_INT,
296 num_items_recv.data(), 1, MPI_INT, comm0);
297 dolfinx::MPI::check_error(po_comm, err);
298
299 // Compute receive displacements
300 std::vector<int> recv_disp(num_items_recv.size() + 1, 0);
301 std::partial_sum(num_items_recv.begin(), num_items_recv.end(),
302 std::next(recv_disp.begin()));
303
304 // Prepare send buffer
305 std::vector<std::int64_t> send_buffer;
306 send_buffer.reserve(indices.size());
307 std::ranges::transform(dest_to_index, std::back_inserter(send_buffer),
308 [](auto x) { return x.second; });
309
310 std::vector<std::int64_t> recv_buffer(recv_disp.back());
311 err = MPI_Neighbor_alltoallv(send_buffer.data(), num_items_send.data(),
312 send_disp.data(), MPI_INT64_T,
313 recv_buffer.data(), num_items_recv.data(),
314 recv_disp.data(), MPI_INT64_T, comm0);
315 dolfinx::MPI::check_error(po_comm, err);
316 err = MPI_Comm_free(&comm0);
317 dolfinx::MPI::check_error(po_comm, err);
318 return std::tuple(std::move(recv_buffer), std::move(recv_disp),
319 std::move(src), std::move(dest));
320 };
321 const auto [nodes_g_p, nodes_g_p_disp, post_src, post_dest]
322 = indices_to_postoffice(comm, num_nodes_g, nodes_g);
323
324 // D. Send entities to possible owners, based on first entity index
325 auto candidate_ranks
326 = [](MPI_Comm cr_comm, MPI_Datatype cr_compound_type,
327 std::span<const std::int64_t> indices_recv,
328 std::span<const int> indices_recv_disp, std::span<const int> src,
329 std::span<const int> dest, auto entities, std::span<const T> cr_data)
330 {
331 // Build map from received global node indices to neighbourhood
332 // ranks that have the node
333 std::multimap<std::int64_t, int> node_to_rank;
334 for (std::size_t i = 0; i < indices_recv_disp.size() - 1; ++i)
335 for (int j = indices_recv_disp[i]; j < indices_recv_disp[i + 1]; ++j)
336 node_to_rank.insert({indices_recv[j], i});
337
338 std::vector<std::vector<std::int64_t>> send_data(dest.size());
339 std::vector<std::vector<T>> send_values(dest.size());
340 for (std::size_t e = 0; e < entities.extent(0); ++e)
341 {
342 std::span e_recv(entities.data_handle() + e * entities.extent(1),
343 entities.extent(1));
344 auto [it0, it1] = node_to_rank.equal_range(entities(e, 0));
345 for (auto it = it0; it != it1; ++it)
346 {
347 int p = it->second;
348 send_data[p].insert(send_data[p].end(), e_recv.begin(), e_recv.end());
349 send_values[p].push_back(cr_data[e]);
350 }
351 }
352
353 MPI_Comm comm0;
354 int err = MPI_Dist_graph_create_adjacent(
355 cr_comm, src.size(), src.data(), MPI_UNWEIGHTED, dest.size(),
356 dest.data(), MPI_UNWEIGHTED, MPI_INFO_NULL, false, &comm0);
357 dolfinx::MPI::check_error(cr_comm, err);
358
359 std::vector<int> num_items_send;
360 num_items_send.reserve(send_data.size());
361 for (auto& x : send_data)
362 num_items_send.push_back(x.size() / entities.extent(1));
363
364 std::vector<int> num_items_recv(src.size());
365 num_items_send.reserve(1);
366 num_items_recv.reserve(1);
367 err = MPI_Neighbor_alltoall(num_items_send.data(), 1, MPI_INT,
368 num_items_recv.data(), 1, MPI_INT, comm0);
369 dolfinx::MPI::check_error(cr_comm, err);
370
371 // Compute send displacements
372 std::vector<std::int32_t> send_disp(num_items_send.size() + 1, 0);
373 std::partial_sum(num_items_send.begin(), num_items_send.end(),
374 std::next(send_disp.begin()));
375
376 // Compute receive displacements
377 std::vector<std::int32_t> recv_disp(num_items_recv.size() + 1, 0);
378 std::partial_sum(num_items_recv.begin(), num_items_recv.end(),
379 std::next(recv_disp.begin()));
380
381 // Prepare send buffers
382 std::vector<std::int64_t> send_buffer;
383 std::vector<T> send_values_buffer;
384 for (auto& x : send_data)
385 send_buffer.insert(send_buffer.end(), x.begin(), x.end());
386 for (auto& v : send_values)
387 send_values_buffer.insert(send_values_buffer.end(), v.begin(), v.end());
388 std::vector<std::int64_t> recv_buffer(entities.extent(1)
389 * recv_disp.back());
390 err = MPI_Neighbor_alltoallv(send_buffer.data(), num_items_send.data(),
391 send_disp.data(), cr_compound_type,
392 recv_buffer.data(), num_items_recv.data(),
393 recv_disp.data(), cr_compound_type, comm0);
394
395 dolfinx::MPI::check_error(cr_comm, err);
396
397 std::vector<T> recv_values_buffer(recv_disp.back());
398 err = MPI_Neighbor_alltoallv(
399 send_values_buffer.data(), num_items_send.data(), send_disp.data(),
400 dolfinx::MPI::mpi_t<T>, recv_values_buffer.data(),
401 num_items_recv.data(), recv_disp.data(), dolfinx::MPI::mpi_t<T>, comm0);
402
403 dolfinx::MPI::check_error(cr_comm, err);
404
405 err = MPI_Comm_free(&comm0);
406 dolfinx::MPI::check_error(cr_comm, err);
407
408 std::array shape{recv_buffer.size() / entities.extent(1),
409 entities.extent(1)};
410 return std::tuple<std::vector<std::int64_t>, std::vector<T>,
411 std::array<std::size_t, 2>>(
412 std::move(recv_buffer), std::move(recv_values_buffer), shape);
413 };
414 // NOTE: src and dest are transposed here because we're reversing the
415 // direction of communication
416 const auto [entities_data_b, entities_values, shape_eb]
417 = candidate_ranks(comm, compound_type, nodes_g_p, nodes_g_p_disp,
418 post_dest, post_src, entitiesp, std::span(entitiesp_v));
419 md::mdspan<const std::int64_t, md::dextents<std::size_t, 2>> entities_data(
420 entities_data_b.data(), shape_eb);
421
422 // -- E. From the received (key, value) data, determine which keys
423 // (entities) are on this process.
424 //
425 // TODO: We have already received possibly tagged entities from other
426 // ranks, so we could use the received data to avoid creating
427 // the std::map for *all* entities and just for candidate
428 // entities.
429 auto select_entities = [](const mesh::Topology& topo, auto xdofmap,
430 std::span<const std::int64_t> nodes,
431 std::span<const int> cell_vertex_dofs,
432 auto entities_data, std::span<const T> values)
433 {
434 spdlog::info("XDMF build map");
435 auto c_to_v = topo.connectivity(topo.dim(), 0);
436 if (!c_to_v)
437 throw std::runtime_error("Missing cell-vertex connectivity.");
438
439 // Map input node indices to local vertices.
440 boost::unordered_flat_map<std::int64_t, std::int32_t> input_idx_to_vertex;
441 input_idx_to_vertex.reserve(c_to_v->num_nodes() * cell_vertex_dofs.size());
442 for (int c = 0; c < c_to_v->num_nodes(); ++c)
443 {
444 auto vertices = c_to_v->links(c);
445 std::span xdofs(xdofmap.data_handle() + c * xdofmap.extent(1),
446 xdofmap.extent(1));
447 for (std::size_t v = 0; v < vertices.size(); ++v)
448 input_idx_to_vertex[nodes[xdofs[cell_vertex_dofs[v]]]] = vertices[v];
449 }
450
451 std::vector<std::int32_t> local_entities;
452 std::vector<T> local_data;
453 local_entities.reserve(entities_data.extent(0) * entities_data.extent(1));
454 local_data.reserve(entities_data.extent(0));
455 std::vector<std::int32_t> entity(entities_data.extent(1));
456 for (std::size_t e = 0; e < entities_data.extent(0); ++e)
457 {
458 bool entity_found = true;
459 for (std::size_t i = 0; i < entities_data.extent(1); ++i)
460 {
461 if (auto it = input_idx_to_vertex.find(entities_data(e, i));
462 it == input_idx_to_vertex.end())
463 {
464 // As soon as this received index is not in locally owned
465 // input global indices skip the entire entity
466 entity_found = false;
467 break;
468 }
469 else
470 entity[i] = it->second;
471 }
472
473 if (entity_found)
474 {
475 local_entities.insert(local_entities.end(), entity.begin(),
476 entity.end());
477 local_data.push_back(values[e]);
478 }
479 }
480
481 return std::pair(std::move(local_entities), std::move(local_data));
482 };
483
484 MPI_Type_free(&compound_type);
485
486 return select_entities(topology, xdofmap, nodes_g, cell_vertex_dofs,
487 entities_data, std::span(entities_values));
488}
489//-----------------------------------------------------------------------------}
490
491} // namespace io
492} // namespace dolfinx
Definition ElementDofLayout.h:31
const std::vector< int > & entity_closure_dofs(int dim, int entity_index) const
Definition ElementDofLayout.cpp:65
const std::vector< int > & entity_dofs(int dim, int entity_index) const
Definition ElementDofLayout.cpp:58
Topology stores the topology of a mesh, consisting of mesh entities and connectivity (incidence relat...
Definition Topology.h:49
CellType cell_type() const
Cell type.
Definition Topology.cpp:888
std::shared_ptr< const graph::AdjacencyList< std::int32_t > > connectivity(std::array< int, 2 > d0, std::array< int, 2 > d1) const
Get the connectivity from entities of topological dimension d0 to dimension d1.
Definition Topology.cpp:939
int dim() const noexcept
Topological dimension of the mesh.
Definition Topology.cpp:878
MPI_Comm comm() const
Mesh MPI communicator.
Definition Topology.cpp:1161
MPI_Datatype mpi_t
Retrieves the MPI data type associated to the provided type.
Definition MPI.h:326
void check_error(MPI_Comm comm, int code) noexcept
Check MPI error code. If the error code is not equal to MPI_SUCCESS, then std::abort is called.
Definition MPI.cpp:89
std::vector< int > compute_graph_edges_nbx(MPI_Comm comm, std::span< const int > edges, int tag=static_cast< int >(tag::consensus_nbx))
Determine incoming graph edges using the NBX consensus algorithm.
Definition MPI.cpp:294
constexpr int index_owner(int size, std::size_t index, std::size_t N)
Return which rank owns index in global range [0, N - 1] (inverse of MPI::local_range).
Definition MPI.h:98
int size(MPI_Comm comm)
Definition MPI.cpp:81
Support for file IO.
Definition ADIOS2Writers.h:43
std::pair< std::vector< std::int32_t >, std::vector< T > > distribute_entity_data(const mesh::Topology &topology, std::span< const std::int64_t > nodes_g, std::int64_t num_nodes_g, const fem::ElementDofLayout &cmap_dof_layout, md::mdspan< const std::int32_t, md::dextents< std::size_t, 2 > > xdofmap, int entity_dim, md::mdspan< const std::int64_t, md::dextents< std::size_t, 2 > > entities, std::span< const T > data)
Get owned entities and associated data from input entities defined by global 'node' indices.
Definition utils.h:62
CellType
Cell type identifier.
Definition cell_types.h:24
int cell_num_entities(CellType type, int dim)
Number of entities of dimension.
Definition cell_types.cpp:97
CellType cell_entity_type(CellType type, int d, int index)
Return type of cell for entity of dimension d at given entity index.
Definition cell_types.h:113
Top-level namespace.
Definition defines.h:12