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