DOLFINx 0.12.0.0
DOLFINx C++
Loading...
Searching...
No Matches
utils.h
1// Copyright (C) 2019-2021 Garth N. Wells and 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 "BoundingBoxTree.h"
10#include "gjk.h"
11#include <algorithm>
12#include <array>
13#include <concepts>
14#include <cstdint>
15#include <deque>
16#include <dolfinx/graph/AdjacencyList.h>
17#include <dolfinx/mesh/Mesh.h>
18#include <map>
19#include <numeric>
20#include <span>
21#include <vector>
22
23namespace dolfinx::geometry
24{
28template <std::floating_point T>
30{
31 std::vector<int> src_owner;
33 std::vector<int>
35 std::vector<T> dest_points;
36 std::vector<std::int32_t>
39};
40
51template <std::floating_point T>
52std::vector<T> shortest_vector(const mesh::Mesh<T>& mesh, int dim,
53 std::span<const std::int32_t> entities,
54 std::span<const T> points)
55{
56 const int tdim = mesh.topology()->dim();
57 const mesh::Geometry<T>& geometry = mesh.geometry();
58
59 std::span<const T> geom_dofs = geometry.x();
60 auto x_dofmap = geometry.dofmaps().front();
61 std::vector<T> shortest_vectors;
62 shortest_vectors.reserve(3 * entities.size());
63 if (dim == tdim)
64 {
65 for (std::size_t e = 0; e < entities.size(); e++)
66 {
67 // Check that we have sent in valid entities, i.e. that they exist in the
68 // local dofmap. One gets a cryptical memory segfault if entities is -1
69 assert(entities[e] >= 0);
70 auto dofs = md::submdspan(x_dofmap, entities[e], md::full_extent);
71 std::vector<T> nodes(3 * dofs.size());
72 for (std::size_t i = 0; i < dofs.size(); ++i)
73 {
74 const std::int32_t pos = 3 * dofs[i];
75 for (std::size_t j = 0; j < 3; ++j)
76 nodes[3 * i + j] = geom_dofs[pos + j];
77 }
78
79 std::array<T, 3> d
80 = compute_distance_gjk<T>(points.subspan(3 * e, 3), nodes);
81 shortest_vectors.insert(shortest_vectors.end(), d.begin(), d.end());
82 }
83 }
84 else
85 {
86 mesh.topology_mutable()->create_connectivity(dim, tdim);
87 mesh.topology_mutable()->create_connectivity(tdim, dim);
88 auto e_to_c = mesh.topology()->connectivity(dim, tdim);
89 assert(e_to_c);
90 auto c_to_e = mesh.topology_mutable()->connectivity(tdim, dim);
91 assert(c_to_e);
92 for (std::size_t e = 0; e < entities.size(); e++)
93 {
94 const std::int32_t index = entities[e];
95
96 // Find attached cell
97 assert(e_to_c->num_links(index) > 0);
98 const std::int32_t c = e_to_c->links(index)[0];
99
100 // Find local number of entity wrt cell
101 auto cell_entities = c_to_e->links(c);
102 auto it0 = std::find(cell_entities.begin(), cell_entities.end(), index);
103 assert(it0 != cell_entities.end());
104 const int local_cell_entity
105 = std::ranges::distance(cell_entities.begin(), it0);
106
107 // Tabulate geometry dofs for the entity
108 auto dofs = md::submdspan(x_dofmap, c, md::full_extent);
109 const std::vector<int> entity_dofs
110 = geometry.cmaps().front().create_dof_layout().entity_closure_dofs(
111 dim, local_cell_entity);
112 std::vector<T> nodes(3 * entity_dofs.size());
113 for (std::size_t i = 0; i < entity_dofs.size(); i++)
114 {
115 const std::int32_t pos = 3 * dofs[entity_dofs[i]];
116 for (std::size_t j = 0; j < 3; ++j)
117 nodes[3 * i + j] = geom_dofs[pos + j];
118 }
119
120 std::array<T, 3> d
121 = compute_distance_gjk<T>(points.subspan(3 * e, 3), nodes);
122 shortest_vectors.insert(shortest_vectors.end(), d.begin(), d.end());
123 }
124 }
125
126 return shortest_vectors;
127}
128
135template <std::floating_point T>
136T compute_squared_distance_bbox(std::span<const T, 6> b,
137 std::span<const T, 3> x)
138{
139 auto b0 = b.template subspan<0, 3>();
140 auto b1 = b.template subspan<3, 3>();
141 return std::transform_reduce(x.begin(), x.end(), b0.begin(), 0.0,
142 std::plus<>{},
143 [](auto x, auto b)
144 {
145 auto dx = x - b;
146 return dx > 0 ? 0 : dx * dx;
147 })
148 + std::transform_reduce(x.begin(), x.end(), b1.begin(), 0.0,
149 std::plus<>{},
150 [](auto x, auto b)
151 {
152 auto dx = x - b;
153 return dx < 0 ? 0 : dx * dx;
154 });
155}
156
172template <std::floating_point T>
173std::vector<T> squared_distance(const mesh::Mesh<T>& mesh, int dim,
174 std::span<const std::int32_t> entities,
175 std::span<const T> points)
176{
177 std::vector<T> v = shortest_vector(mesh, dim, entities, points);
178 std::vector<T> d(v.size() / 3, 0);
179 for (std::size_t i = 0; i < d.size(); ++i)
180 for (std::size_t j = 0; j < 3; ++j)
181 d[i] += v[3 * i + j] * v[3 * i + j];
182 return d;
183}
184
185namespace impl
186{
188constexpr bool is_leaf(std::array<int, 2> bbox)
189{
190 // Leaf nodes are marked by setting child_0 equal to child_1
191 return bbox[0] == bbox[1];
192}
193
198template <std::floating_point T>
199constexpr bool point_in_bbox(std::span<const T, 6> b, std::span<const T, 3> x)
200{
201 constexpr T rtol = 1e-14;
202 bool in = true;
203 for (std::size_t i = 0; i < 3; i++)
204 {
205 T eps = rtol * (b[i + 3] - b[i]);
206 in &= (x[i] >= (b[i] - eps)) && (x[i] <= (b[i + 3] + eps));
207 if (!in)
208 break;
209 }
210
211 return in;
212}
213
217template <std::floating_point T>
218constexpr bool bbox_in_bbox(std::span<const T, 6> a, std::span<const T, 6> b)
219{
220 constexpr T rtol = 1e-14;
221 auto a0 = a.template subspan<0, 3>();
222 auto a1 = a.template subspan<3, 3>();
223 auto b0 = b.template subspan<0, 3>();
224 auto b1 = b.template subspan<3, 3>();
225
226 bool in = true;
227 for (std::size_t i = 0; i < 3; i++)
228 {
229 T eps = rtol * (b1[i] - b0[i]);
230 in &= a1[i] >= (b0[i] - eps);
231 in &= a0[i] <= (b1[i] + eps);
232 }
233
234 return in;
235}
236
238template <std::floating_point T>
239std::pair<std::int32_t, T>
240_compute_closest_entity(const geometry::BoundingBoxTree<T>& tree,
241 std::span<const T, 3> point, std::int32_t node,
242 const mesh::Mesh<T>& mesh, std::int32_t closest_entity,
243 T R2)
244{
245 // Get children of current bounding box node (child_1 denotes entity
246 // index for leaves)
247 const std::array<int, 2> bbox = tree.bbox(node);
248 T r2;
249 if (is_leaf(bbox))
250 {
251 // If point cloud tree the exact distance is easy to compute
252 if (tree.tdim() == 0)
253 {
254 std::array<T, 6> diff = tree.get_bbox(node);
255 for (std::size_t k = 0; k < 3; ++k)
256 diff[k] -= point[k];
257 r2 = diff[0] * diff[0] + diff[1] * diff[1] + diff[2] * diff[2];
258 }
259 else
260 {
261 r2 = compute_squared_distance_bbox<T>(tree.get_bbox(node), point);
262
263 // If bounding box closer than previous closest entity, use gjk to
264 // obtain exact distance to the convex hull of the entity
265 if (r2 <= R2)
266 {
267 r2 = squared_distance<T>(mesh, tree.tdim(),
268 std::span(std::next(bbox.begin(), 1), 1),
269 point)
270 .front();
271 }
272 }
273
274 // If entity is closer than best result so far, return it
275 if (r2 <= R2)
276 {
277 closest_entity = bbox.back();
278 R2 = r2;
279 }
280
281 return {closest_entity, R2};
282 }
283 else
284 {
285 // If bounding box is outside radius, then don't search further
286 r2 = compute_squared_distance_bbox<T>(tree.get_bbox(node), point);
287 if (r2 > R2)
288 return {closest_entity, R2};
289
290 // Check both children. We use R2 (as opposed to r2), as a bounding
291 // box can be closer than the actual entity.
292 std::pair<int, T> p0 = _compute_closest_entity(tree, point, bbox.front(),
293 mesh, closest_entity, R2);
294 std::pair<int, T> p1 = _compute_closest_entity(tree, point, bbox.back(),
295 mesh, p0.first, p0.second);
296 return p1;
297 }
298}
299
305template <std::floating_point T>
306void _compute_collisions_point(const geometry::BoundingBoxTree<T>& tree,
307 std::span<const T, 3> p,
308 std::vector<std::int32_t>& entities)
309{
310 std::deque<std::int32_t> stack;
311 std::int32_t next = tree.num_bboxes() - 1;
312 std::span<const T> coords = tree.bbox_coordinates();
313 auto view_bbox = [&coords](std::size_t node)
314 { return std::span<const T, 6>(coords.data() + 6 * node, 6); };
315 while (next != -1)
316 {
317 if (std::array bbox = tree.bbox(next);
318 is_leaf(bbox) and point_in_bbox(view_bbox(next), p))
319 {
320 // If box is a leaf node then add it to the list of colliding
321 // entities
322 entities.push_back(bbox[1]);
323 next = -1;
324 }
325 else
326 {
327 // Check whether the point collides with child nodes (left and
328 // right)
329 bool left = point_in_bbox(view_bbox(bbox[0]), p);
330 bool right = point_in_bbox(view_bbox(bbox[1]), p);
331 if (left and right)
332 {
333 // If the point collides with both child nodes, add the right
334 // node to the stack (for later visiting) and continue the tree
335 // traversal with the left subtree
336 stack.push_back(bbox[1]);
337 next = bbox[0];
338 }
339 else if (left)
340 {
341 // Traverse the current node's left subtree
342 next = bbox[0];
343 }
344 else if (right)
345 {
346 // Traverse the current node's right subtree
347 next = bbox[1];
348 }
349 else
350 next = -1;
351 }
352
353 // If tree traversal reaches a dead end (box is a leaf node or no
354 // collision detected), check the stack for deferred subtrees
355 if (next == -1 and !stack.empty())
356 {
357 next = stack.back();
358 stack.pop_back();
359 }
360 }
361}
362
363// Compute collisions with tree (recursive)
364template <std::floating_point T>
365void _compute_collisions_tree(const geometry::BoundingBoxTree<T>& A,
366 const geometry::BoundingBoxTree<T>& B,
367 std::int32_t node_A, std::int32_t node_B,
368 std::vector<std::int32_t>& entities)
369{
370 // If bounding boxes don't collide, then don't search further
371 if (!bbox_in_bbox<T>(A.get_bbox(node_A), B.get_bbox(node_B)))
372 return;
373
374 // Get bounding boxes for current nodes
375 const std::array<std::int32_t, 2> bbox_A = A.bbox(node_A);
376 const std::array<std::int32_t, 2> bbox_B = B.bbox(node_B);
377
378 // Check whether we've reached a leaf in A or B
379 const bool is_leaf_A = is_leaf(bbox_A);
380 const bool is_leaf_B = is_leaf(bbox_B);
381 if (is_leaf_A and is_leaf_B)
382 {
383 // If both boxes are leaves (which we know collide), then add them
384 // child_1 denotes entity for leaves
385 entities.push_back(bbox_A[1]);
386 entities.push_back(bbox_B[1]);
387 }
388 else if (is_leaf_A)
389 {
390 // If we reached the leaf in A, then descend B
391 _compute_collisions_tree(A, B, node_A, bbox_B[0], entities);
392 _compute_collisions_tree(A, B, node_A, bbox_B[1], entities);
393 }
394 else if (is_leaf_B)
395 {
396 // If we reached the leaf in B, then descend A
397 _compute_collisions_tree(A, B, bbox_A[0], node_B, entities);
398 _compute_collisions_tree(A, B, bbox_A[1], node_B, entities);
399 }
400 else if (node_A > node_B)
401 {
402 // At this point, we know neither is a leaf so descend the largest
403 // tree first. Note that nodes are added in reverse order with the
404 // top bounding box at the end so the largest tree (the one with the
405 // the most boxes left to traverse) has the largest node number.
406 _compute_collisions_tree(A, B, bbox_A[0], node_B, entities);
407 _compute_collisions_tree(A, B, bbox_A[1], node_B, entities);
408 }
409 else
410 {
411 _compute_collisions_tree(A, B, node_A, bbox_B[0], entities);
412 _compute_collisions_tree(A, B, node_A, bbox_B[1], entities);
413 }
414
415 // Note that cases above can be collected in fewer cases but this way
416 // the logic is easier to follow.
417}
418
419} // namespace impl
420
427template <std::floating_point T>
429 std::span<const std::int32_t> entities)
430{
431 spdlog::info("Building point search tree to accelerate distance queries for "
432 "a given topological dimension and subset of entities.");
433
434 const std::vector<T> midpoints
435 = mesh::compute_midpoints(mesh, tdim, entities);
436 std::vector<std::pair<std::array<T, 3>, std::int32_t>> points(
437 entities.size());
438 for (std::size_t i = 0; i < points.size(); ++i)
439 {
440 for (std::size_t j = 0; j < 3; ++j)
441 points[i].first[j] = midpoints[3 * i + j];
442 points[i].second = entities[i];
443 }
444
445 // Build tree
446 return BoundingBoxTree(points);
447}
448
454template <std::floating_point T>
455std::vector<std::int32_t> compute_collisions(const BoundingBoxTree<T>& tree0,
456 const BoundingBoxTree<T>& tree1)
457{
458 // Call recursive find function
459 std::vector<std::int32_t> entities;
460 if (tree0.num_bboxes() > 0 and tree1.num_bboxes() > 0)
461 {
462 impl::_compute_collisions_tree(tree0, tree1, tree0.num_bboxes() - 1,
463 tree1.num_bboxes() - 1, entities);
464 }
465
466 return entities;
467}
468
479template <std::floating_point T>
481compute_collisions(const BoundingBoxTree<T>& tree, std::span<const T> points)
482{
483 if (tree.num_bboxes() > 0)
484 {
485 std::vector<std::int32_t> entities, offsets(points.size() / 3 + 1, 0);
486 entities.reserve(points.size() / 3);
487 for (std::size_t p = 0; p < points.size() / 3; ++p)
488 {
489 impl::_compute_collisions_point(
490 tree, std::span<const T, 3>(points.data() + 3 * p, 3), entities);
491 offsets[p + 1] = entities.size();
492 }
493
494 return graph::AdjacencyList(std::move(entities), std::move(offsets));
495 }
496 else
497 {
499 std::vector<std::int32_t>(),
500 std::vector<std::int32_t>(points.size() / 3 + 1, 0));
501 }
502}
503
521template <std::floating_point T>
523 std::span<const std::int32_t> cells,
524 std::array<T, 3> point, T tol)
525{
526 if (cells.empty())
527 return -1;
528 else
529 {
530 const mesh::Geometry<T>& geometry = mesh.geometry();
531 std::span<const T> geom_dofs = geometry.x();
532 auto x_dofmap = geometry.dofmaps().front();
533 const std::size_t num_nodes = x_dofmap.extent(1);
534 std::vector<T> coordinate_dofs(num_nodes * 3);
535 for (auto cell : cells)
536 {
537 auto dofs = md::submdspan(x_dofmap, cell, md::full_extent);
538 for (std::size_t i = 0; i < num_nodes; ++i)
539 {
540 std::copy_n(std::next(geom_dofs.begin(), 3 * dofs[i]), 3,
541 std::next(coordinate_dofs.begin(), 3 * i));
542 }
543
544 std::array<T, 3> shortest_vector
545 = compute_distance_gjk<T>(point, coordinate_dofs);
546 T d2 = std::reduce(shortest_vector.begin(), shortest_vector.end(), T(0),
547 [](auto d, auto e) { return d + e * e; });
548 if (d2 < tol)
549 return cell;
550 }
551
552 return -1;
553 }
554}
555
568template <std::floating_point T>
569std::vector<std::int32_t>
571 const BoundingBoxTree<T>& midpoint_tree,
572 const mesh::Mesh<T>& mesh, std::span<const T> points)
573{
574 if (tree.num_bboxes() == 0)
575 return std::vector<std::int32_t>(points.size() / 3, -1);
576
577 std::vector<std::int32_t> entities;
578 entities.reserve(points.size() / 3);
579 for (std::size_t i = 0; i < points.size() / 3; ++i)
580 {
581 // Use midpoint tree to find initial closest entity to the point.
582 // Start by using a leaf node as the initial guess for the input
583 // entity
584 std::array<int, 2> leaf0 = midpoint_tree.bbox(0);
585 assert(impl::is_leaf(leaf0));
586 std::array<T, 6> diff = midpoint_tree.get_bbox(0);
587 for (std::size_t k = 0; k < 3; ++k)
588 diff[k] -= points[3 * i + k];
589 T R2 = diff[0] * diff[0] + diff[1] * diff[1] + diff[2] * diff[2];
590
591 // Use a recursive search through the bounding box tree
592 // to find determine the entity with the closest midpoint.
593 // As the midpoint tree only consist of points, the distance
594 // queries are lightweight.
595 const auto [m_index, m_distance2] = impl::_compute_closest_entity(
596 midpoint_tree, std::span<const T, 3>(points.data() + 3 * i, 3),
597 midpoint_tree.num_bboxes() - 1, mesh, leaf0[0], R2);
598
599 // Use a recursives search through the bounding box tree to
600 // determine which entity is actually closest.
601 // Uses the entity with the closest midpoint as initial guess, and
602 // the distance from the midpoint to the point of interest as the
603 // initial search radius.
604 const auto [index, distance2] = impl::_compute_closest_entity(
605 tree, std::span<const T, 3>(points.data() + 3 * i, 3),
606 tree.num_bboxes() - 1, mesh, m_index, m_distance2);
607
608 entities.push_back(index);
609 }
610
611 return entities;
612}
613
629template <std::floating_point T>
631 const mesh::Mesh<T>& mesh,
632 const graph::AdjacencyList<std::int32_t>& candidate_cells,
633 std::span<const T> points)
634{
635 std::vector<std::int32_t> offsets = {0};
636 offsets.reserve(candidate_cells.num_nodes() + 1);
637 std::vector<std::int32_t> colliding_cells;
638 constexpr T eps2 = 1e-12;
639 const int tdim = mesh.topology()->dim();
640 for (std::int32_t i = 0; i < candidate_cells.num_nodes(); i++)
641 {
642 auto cells = candidate_cells.links(i);
643 std::vector<T> _point(3 * cells.size());
644 for (std::size_t j = 0; j < cells.size(); ++j)
645 for (std::size_t k = 0; k < 3; ++k)
646 _point[3 * j + k] = points[3 * i + k];
647
648 std::vector distances_sq = squared_distance<T>(mesh, tdim, cells, _point);
649 for (std::size_t j = 0; j < cells.size(); j++)
650 if (distances_sq[j] < eps2)
651 colliding_cells.push_back(cells[j]);
652
653 offsets.push_back(colliding_cells.size());
654 }
655
656 return graph::AdjacencyList(std::move(colliding_cells), std::move(offsets));
657}
658
682template <std::floating_point T>
683PointOwnershipData<T>
684determine_point_ownership(const mesh::Mesh<T>& mesh, std::span<const T> points,
685 T padding,
686 std::optional<std::span<const std::int32_t>> cells)
687{
688 MPI_Comm comm = mesh.comm();
689
690 const int tdim = mesh.topology()->dim();
691
692 std::vector<std::int32_t> local_cells;
693 if (not(cells.has_value()))
694 {
695 auto cell_map = mesh.topology()->index_map(tdim);
696 local_cells.resize(cell_map->size_local());
697 std::iota(local_cells.begin(), local_cells.end(), 0);
698 cells
699 = std::span<const std::int32_t>(local_cells.data(), local_cells.size());
700 }
701 // Create a global bounding-box tree to find candidate processes with
702 // cells that could collide with the points
703 BoundingBoxTree bb(mesh, tdim, padding, cells.value());
704 BoundingBoxTree global_bbtree = bb.create_global_tree(comm);
705
706 // Compute collisions:
707 // For each point in `points` get the processes it should be sent to
708 graph::AdjacencyList collisions = compute_collisions(global_bbtree, points);
709
710 // Get unique list of outgoing ranks
711 std::vector<std::int32_t> out_ranks = collisions.array();
712 std::ranges::sort(out_ranks);
713 auto [unique_end, range_end] = std::ranges::unique(out_ranks);
714 out_ranks.erase(unique_end, range_end);
715
716 // Compute incoming edges (source processes)
717 std::vector in_ranks = dolfinx::MPI::compute_graph_edges_nbx(comm, out_ranks);
718 std::ranges::sort(in_ranks);
719
720 // Create neighborhood communicator in forward direction
721 MPI_Comm forward_comm;
722 MPI_Dist_graph_create_adjacent(
723 comm, in_ranks.size(), in_ranks.data(), MPI_UNWEIGHTED, out_ranks.size(),
724 out_ranks.data(), MPI_UNWEIGHTED, MPI_INFO_NULL, false, &forward_comm);
725
726 // Compute map from global mpi rank to neighbor rank, "collisions"
727 // uses global rank
728 std::map<std::int32_t, std::int32_t> rank_to_neighbor;
729 for (std::size_t i = 0; i < out_ranks.size(); i++)
730 rank_to_neighbor[out_ranks[i]] = i;
731
732 // Count the number of points to send per neighbor process
733 std::vector<std::int32_t> send_sizes(out_ranks.size());
734 for (std::size_t i = 0; i < points.size() / 3; ++i)
735 for (auto p : collisions.links(i))
736 send_sizes[rank_to_neighbor[p]] += 3;
737
738 // Compute receive sizes
739 std::vector<std::int32_t> recv_sizes(in_ranks.size());
740 send_sizes.reserve(1);
741 recv_sizes.reserve(1);
742 MPI_Request sizes_request;
743 MPI_Ineighbor_alltoall(send_sizes.data(), 1, MPI_INT, recv_sizes.data(), 1,
744 MPI_INT, forward_comm, &sizes_request);
745
746 // Compute sending offsets
747 std::vector<std::int32_t> send_offsets(send_sizes.size() + 1, 0);
748 std::partial_sum(send_sizes.begin(), send_sizes.end(),
749 std::next(send_offsets.begin(), 1));
750
751 // Pack data to send and store unpack map
752 std::vector<T> send_data(send_offsets.back());
753 std::vector<std::int32_t> counter(send_sizes.size(), 0);
754 // unpack map: [index in adj list][pos in x]
755 std::vector<std::int32_t> unpack_map(send_offsets.back() / 3);
756 for (std::size_t i = 0; i < points.size(); i += 3)
757 {
758 for (auto p : collisions.links(i / 3))
759 {
760 int neighbor = rank_to_neighbor[p];
761 int pos = send_offsets[neighbor] + counter[neighbor];
762 auto it = std::next(send_data.begin(), pos);
763 std::copy_n(std::next(points.begin(), i), 3, it);
764 unpack_map[pos / 3] = i / 3;
765 counter[neighbor] += 3;
766 }
767 }
768
769 MPI_Wait(&sizes_request, MPI_STATUS_IGNORE);
770 std::vector<std::int32_t> recv_offsets(in_ranks.size() + 1, 0);
771 std::partial_sum(recv_sizes.begin(), recv_sizes.end(),
772 std::next(recv_offsets.begin(), 1));
773
774 std::vector<T> received_points((std::size_t)recv_offsets.back());
775 MPI_Neighbor_alltoallv(
776 send_data.data(), send_sizes.data(), send_offsets.data(),
777 dolfinx::MPI::mpi_t<T>, received_points.data(), recv_sizes.data(),
778 recv_offsets.data(), dolfinx::MPI::mpi_t<T>, forward_comm);
779
780 // Get mesh geometry for closest entity
781 const mesh::Geometry<T>& geometry = mesh.geometry();
782 std::span<const T> geom_dofs = geometry.x();
783 auto x_dofmap = geometry.dofmaps().front();
784
785 // Compute candidate cells for collisions (and extrapolation)
786 const graph::AdjacencyList<std::int32_t> candidate_collisions
787 = compute_collisions(bb, std::span<const T>(received_points.data(),
788 received_points.size()));
789
790 // Each process checks which points collide with a cell on the process
791 const int rank = dolfinx::MPI::rank(comm);
792 std::vector<std::int32_t> cell_indicator(received_points.size() / 3);
793 std::vector<std::int32_t> closest_cells(received_points.size() / 3);
794 for (std::size_t p = 0; p < received_points.size(); p += 3)
795 {
796 std::array<T, 3> point;
797 std::copy_n(std::next(received_points.begin(), p), 3, point.begin());
798 // Find first colliding cell among the cells with colliding bounding boxes
799 const int colliding_cell = geometry::compute_first_colliding_cell(
800 mesh, candidate_collisions.links(p / 3), point,
801 10 * std::numeric_limits<T>::epsilon());
802 // If a collding cell is found, store the rank of the current process
803 // which will be sent back to the owner of the point
804 cell_indicator[p / 3] = (colliding_cell >= 0) ? rank : -1;
805 // Store the cell index for lookup once the owning processes has determined
806 // the ownership of the point
807 closest_cells[p / 3] = colliding_cell;
808 }
809
810 // Create neighborhood communicator in the reverse direction: send
811 // back col to requesting processes
812 MPI_Comm reverse_comm;
813 MPI_Dist_graph_create_adjacent(
814 comm, out_ranks.size(), out_ranks.data(), MPI_UNWEIGHTED, in_ranks.size(),
815 in_ranks.data(), MPI_UNWEIGHTED, MPI_INFO_NULL, false, &reverse_comm);
816
817 // Reuse sizes and offsets from first communication set
818 // but divide by three
819 {
820 auto rescale = [](auto& x)
821 { std::ranges::transform(x, x.begin(), [](auto e) { return (e / 3); }); };
822 rescale(recv_sizes);
823 rescale(recv_offsets);
824 rescale(send_sizes);
825 rescale(send_offsets);
826
827 // The communication is reversed, so swap recv to send offsets
828 std::swap(recv_sizes, send_sizes);
829 std::swap(recv_offsets, send_offsets);
830 }
831
832 std::vector<std::int32_t> recv_ranks(recv_offsets.back());
833 MPI_Neighbor_alltoallv(cell_indicator.data(), send_sizes.data(),
834 send_offsets.data(), MPI_INT32_T, recv_ranks.data(),
835 recv_sizes.data(), recv_offsets.data(), MPI_INT32_T,
836 reverse_comm);
837
838 std::vector<int> point_owners(points.size() / 3, -1);
839 for (std::size_t i = 0; i < unpack_map.size(); i++)
840 {
841 const std::int32_t pos = unpack_map[i];
842 // Only insert new owner if no owner has previously been found
843 if (recv_ranks[i] >= 0 && point_owners[pos] == -1)
844 point_owners[pos] = recv_ranks[i];
845 }
846
847 // Create extrapolation marker for those points already sent to other
848 // process
849 std::vector<std::uint8_t> send_extrapolate(recv_offsets.back());
850 for (std::int32_t i = 0; i < recv_offsets.back(); i++)
851 {
852 const std::int32_t pos = unpack_map[i];
853 send_extrapolate[i] = point_owners[pos] == -1;
854 }
855
856 // Swap communication direction, to send extrapolation marker to other
857 // processes
858 std::swap(send_sizes, recv_sizes);
859 std::swap(send_offsets, recv_offsets);
860 std::vector<std::uint8_t> dest_extrapolate(recv_offsets.back());
861 MPI_Neighbor_alltoallv(send_extrapolate.data(), send_sizes.data(),
862 send_offsets.data(), MPI_UINT8_T,
863 dest_extrapolate.data(), recv_sizes.data(),
864 recv_offsets.data(), MPI_UINT8_T, forward_comm);
865
866 std::vector<T> squared_distances(received_points.size() / 3, -1);
867
868 for (std::size_t i = 0; i < dest_extrapolate.size(); i++)
869 {
870 if (dest_extrapolate[i] == 1)
871 {
872 assert(closest_cells[i] == -1);
873 std::array<T, 3> point;
874 std::copy_n(std::next(received_points.begin(), 3 * i), 3, point.begin());
875
876 // Find shortest distance among cells with colliding bounding box
877 T shortest_distance = std::numeric_limits<T>::max();
878 std::int32_t closest_cell = -1;
879 for (auto cell : candidate_collisions.links(i))
880 {
881 auto dofs = md::submdspan(x_dofmap, cell, md::full_extent);
882 std::vector<T> nodes(3 * dofs.size());
883 for (std::size_t j = 0; j < dofs.size(); ++j)
884 {
885 const int pos = 3 * dofs[j];
886 for (std::size_t k = 0; k < 3; ++k)
887 nodes[3 * j + k] = geom_dofs[pos + k];
888 }
889 const std::array<T, 3> d = compute_distance_gjk<T>(
890 std::span<const T>(point.data(), point.size()), nodes);
891 if (T current_distance = d[0] * d[0] + d[1] * d[1] + d[2] * d[2];
892 current_distance < shortest_distance)
893 {
894 shortest_distance = current_distance;
895 closest_cell = cell;
896 }
897 }
898 closest_cells[i] = closest_cell;
899 squared_distances[i] = shortest_distance;
900 }
901 }
902
903 std::swap(recv_sizes, send_sizes);
904 std::swap(recv_offsets, send_offsets);
905
906 // Get distances from closest entity of points that were on the other process
907 std::vector<T> recv_distances(recv_offsets.back());
908 MPI_Neighbor_alltoallv(
909 squared_distances.data(), send_sizes.data(), send_offsets.data(),
910 dolfinx::MPI::mpi_t<T>, recv_distances.data(), recv_sizes.data(),
911 recv_offsets.data(), dolfinx::MPI::mpi_t<T>, reverse_comm);
912
913 // Update point ownership with extrapolation information
914 std::vector<T> closest_distance(point_owners.size(),
915 std::numeric_limits<T>::max());
916 for (std::size_t i = 0; i < out_ranks.size(); i++)
917 {
918 for (std::int32_t j = recv_offsets[i]; j < recv_offsets[i + 1]; j++)
919 {
920 const std::int32_t pos = unpack_map[j];
921 auto current_dist = recv_distances[j];
922 // Update if closer than previous guess and was found
923 if (auto d = closest_distance[pos];
924 (current_dist > 0) and (current_dist < d))
925 {
926 point_owners[pos] = out_ranks[i];
927 closest_distance[pos] = current_dist;
928 }
929 }
930 }
931
932 // Communication is reversed again to send dest ranks to all processes
933 std::swap(send_sizes, recv_sizes);
934 std::swap(send_offsets, recv_offsets);
935
936 // Pack ownership data
937 std::vector<std::int32_t> send_owners(send_offsets.back());
938 std::ranges::fill(counter, 0);
939 for (std::size_t i = 0; i < points.size() / 3; ++i)
940 {
941 for (auto p : collisions.links(i))
942 {
943 int neighbor = rank_to_neighbor[p];
944 send_owners[send_offsets[neighbor] + counter[neighbor]++]
945 = point_owners[i];
946 }
947 }
948
949 // Send ownership info
950 std::vector<std::int32_t> dest_ranks(recv_offsets.back());
951 MPI_Neighbor_alltoallv(send_owners.data(), send_sizes.data(),
952 send_offsets.data(), MPI_INT32_T, dest_ranks.data(),
953 recv_sizes.data(), recv_offsets.data(), MPI_INT32_T,
954 forward_comm);
955
956 // Unpack dest ranks if point owner is this rank
957 std::vector<int> owned_recv_ranks;
958 owned_recv_ranks.reserve(recv_offsets.back());
959 std::vector<T> owned_recv_points;
960 std::vector<std::int32_t> owned_recv_cells;
961 for (std::size_t i = 0; i < in_ranks.size(); i++)
962 {
963 for (std::int32_t j = recv_offsets[i]; j < recv_offsets[i + 1]; j++)
964 {
965 if (rank == dest_ranks[j])
966 {
967 owned_recv_ranks.push_back(in_ranks[i]);
968 owned_recv_points.insert(
969 owned_recv_points.end(), std::next(received_points.cbegin(), 3 * j),
970 std::next(received_points.cbegin(), 3 * (j + 1)));
971 owned_recv_cells.push_back(closest_cells[j]);
972 }
973 }
974 }
975
976 MPI_Comm_free(&forward_comm);
977 MPI_Comm_free(&reverse_comm);
978 return PointOwnershipData<T>{.src_owner = std::move(point_owners),
979 .dest_owners = std::move(owned_recv_ranks),
980 .dest_points = std::move(owned_recv_points),
981 .dest_cells = std::move(owned_recv_cells)};
982}
983
984} // namespace dolfinx::geometry
Definition BoundingBoxTree.h:208
BoundingBoxTree create_global_tree(MPI_Comm comm) const
Definition BoundingBoxTree.h:337
std::int32_t num_bboxes() const
Return number of bounding boxes.
Definition BoundingBoxTree.h:373
std::array< T, 6 > get_bbox(std::size_t node) const
Return bounding box coordinates for a given node in the tree,.
Definition BoundingBoxTree.h:325
std::array< std::int32_t, 2 > bbox(std::size_t node) const
Definition BoundingBoxTree.h:407
This class provides a static adjacency list data structure.
Definition AdjacencyList.h:41
const std::vector< LinkData > & array() const
Return contiguous array of links for all nodes (const version).
Definition AdjacencyList.h:188
std::span< LinkData > links(std::size_t node)
Get the links (edges) for given node.
Definition AdjacencyList.h:169
std::int32_t num_nodes() const
Get the number of nodes.
Definition AdjacencyList.h:154
Geometry stores the geometry imposed on a mesh.
Definition Geometry.h:37
A Mesh consists of a set of connected and numbered mesh topological entities, and geometry data.
Definition Mesh.h:23
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
int rank(MPI_Comm comm)
Return process rank for the communicator.
Definition MPI.cpp:73
Geometry data structures and algorithms.
Definition BoundingBoxTree.h:24
std::vector< T > squared_distance(const mesh::Mesh< T > &mesh, int dim, std::span< const std::int32_t > entities, std::span< const T > points)
Compute the squared distance between a point and a mesh entity.
Definition utils.h:173
std::vector< std::int32_t > compute_collisions(const BoundingBoxTree< T > &tree0, const BoundingBoxTree< T > &tree1)
Compute all collisions between two bounding box trees.
Definition utils.h:455
std::int32_t compute_first_colliding_cell(const mesh::Mesh< T > &mesh, std::span< const std::int32_t > cells, std::array< T, 3 > point, T tol)
Given a set of cells, find the first one that collides with a point.
Definition utils.h:522
T compute_squared_distance_bbox(std::span< const T, 6 > b, std::span< const T, 3 > x)
Compute squared distance between point and bounding box.
Definition utils.h:136
graph::AdjacencyList< std::int32_t > compute_colliding_cells(const mesh::Mesh< T > &mesh, const graph::AdjacencyList< std::int32_t > &candidate_cells, std::span< const T > points)
Compute which cells collide with a point.
Definition utils.h:630
std::vector< T > shortest_vector(const mesh::Mesh< T > &mesh, int dim, std::span< const std::int32_t > entities, std::span< const T > points)
Compute the shortest vector from a mesh entity to a point.
Definition utils.h:52
BoundingBoxTree< T > create_midpoint_tree(const mesh::Mesh< T > &mesh, int tdim, std::span< const std::int32_t > entities)
Create a bounding box tree for the midpoints of a subset of entities.
Definition utils.h:428
PointOwnershipData< T > determine_point_ownership(const mesh::Mesh< T > &mesh, std::span< const T > points, T padding, std::optional< std::span< const std::int32_t > > cells)
Given a set of points, determine which process is colliding, using the GJK algorithm on cells to dete...
Definition utils.h:684
std::vector< std::int32_t > compute_closest_entity(const BoundingBoxTree< T > &tree, const BoundingBoxTree< T > &midpoint_tree, const mesh::Mesh< T > &mesh, std::span< const T > points)
Compute closest mesh entity to a point.
Definition utils.h:570
std::array< T, 3 > compute_distance_gjk(std::span< const T > p0, std::span< const T > q0)
Compute the distance between two convex bodies p0 and q0, each defined by a set of points.
Definition gjk.h:369
Mesh data structures and algorithms on meshes.
Definition DofMap.h:32
std::vector< T > compute_midpoints(const Mesh< T > &mesh, int dim, std::span< const std::int32_t > entities)
Compute the midpoints for mesh entities of a given dimension.
Definition utils.h:608
Information on the ownership of points distributed across processes.
Definition utils.h:30
std::vector< T > dest_points
Points that are owned by current process.
Definition utils.h:35
std::vector< std::int32_t > dest_cells
Definition utils.h:37
std::vector< int > dest_owners
Ranks that sent dest_points to current process.
Definition utils.h:34
std::vector< int > src_owner
Definition utils.h:31