DOLFINx 0.12.0.0
DOLFINx C++
Loading...
Searching...
No Matches
BoundingBoxTree.h
1// Copyright (C) 2013-2022 Chris N. Richardson, Anders Logg, Garth N. Wells,
2// Jørgen S. Dokken, Sarah Roggendorf
3//
4// This file is part of DOLFINx (https://www.fenicsproject.org)
5//
6// SPDX-License-Identifier: LGPL-3.0-or-later
7
8#pragma once
9
10#include <algorithm>
11#include <array>
12#include <cassert>
13#include <cstdint>
14#include <dolfinx/mesh/utils.h>
15#include <format>
16#include <iterator>
17#include <mpi.h>
18#include <optional>
19#include <span>
20#include <string>
21#include <vector>
22
24{
25namespace impl_bb
26{
27//-----------------------------------------------------------------------------
28// Compute bounding box of mesh entity. The bounding box is defined by (lower
29// left corner, top right corner). Storage flattened row-major
30template <std::floating_point T>
31std::array<T, 6> compute_bbox_of_entity(const mesh::Mesh<T>& mesh, int dim,
32 std::int32_t index)
33{
34 // Get the geometrical indices for the mesh entity
35 std::span<const T> xg = mesh.geometry().x();
36
37 // FIXME: return of small dynamic array is expensive
38 std::span<const std::int32_t> entity(&index, 1);
39 const std::vector<std::int32_t> vertex_indices
40 = mesh::entities_to_geometry(mesh, dim, entity, false).first;
41
42 std::array<T, 6> b;
43 std::span<T, 3> b0(b.data(), 3);
44 std::span<T, 3> b1(b.data() + 3, 3);
45
46 std::copy_n(std::next(xg.begin(), 3 * vertex_indices.front()), 3, b0.begin());
47 std::copy_n(std::next(xg.begin(), 3 * vertex_indices.front()), 3, b1.begin());
48
49 // Compute min and max over vertices
50 for (std::int32_t local_vertex : vertex_indices)
51 {
52 for (std::size_t j = 0; j < 3; ++j)
53 {
54 b0[j] = std::min(b0[j], xg[3 * local_vertex + j]);
55 b1[j] = std::max(b1[j], xg[3 * local_vertex + j]);
56 }
57 }
58
59 return b;
60}
61//-----------------------------------------------------------------------------
62// Compute bounding box of bounding boxes. Each bounding box is defined as a
63// tuple (corners, entity_index). The corners of the bounding box is flattened
64// row-major as (lower left corner, top right corner).
65template <std::floating_point T>
66std::array<T, 6> compute_bbox_of_bboxes(
67 std::span<const std::pair<std::array<T, 6>, std::int32_t>> leaf_bboxes)
68{
69 // Compute min and max over remaining boxes
70 std::array<T, 6> b = leaf_bboxes.front().first;
71 for (auto [box, _] : leaf_bboxes)
72 {
73 std::transform(box.cbegin(), std::next(box.cbegin(), 3), b.cbegin(),
74 b.begin(), [](auto a, auto b) { return std::min(a, b); });
75 std::transform(std::next(box.cbegin(), 3), box.cend(),
76 std::next(b.cbegin(), 3), std::next(b.begin(), 3),
77 [](auto a, auto b) { return std::max(a, b); });
78 }
79
80 return b;
81}
82//------------------------------------------------------------------------------
83template <std::floating_point T>
84std::int32_t _build_from_leaf(
85 std::span<std::pair<std::array<T, 6>, std::int32_t>> leaf_bboxes,
86 std::vector<int>& bboxes, std::vector<T>& bbox_coordinates)
87{
88 if (leaf_bboxes.size() == 1)
89 {
90 // Reached leaf
91
92 // Get bounding box coordinates for leaf
93 const auto [b, entity_index] = leaf_bboxes.front();
94
95 // Store bounding box data
96 bboxes.push_back(entity_index);
97 bboxes.push_back(entity_index);
98 std::copy_n(b.begin(), 6, std::back_inserter(bbox_coordinates));
99 return bboxes.size() / 2 - 1;
100 }
101 else
102 {
103 // Compute bounding box of all bounding boxes
104 std::array b = compute_bbox_of_bboxes<T>(leaf_bboxes);
105
106 // Sort bounding boxes along longest axis
107 std::array<T, 3> b_diff;
108 std::transform(std::next(b.cbegin(), 3), b.cend(), b.cbegin(),
109 b_diff.begin(), std::minus<T>());
110 const std::size_t axis = std::distance(
111 b_diff.begin(), std::max_element(b_diff.begin(), b_diff.end()));
112
113 auto middle = std::next(leaf_bboxes.begin(), leaf_bboxes.size() / 2);
114 std::nth_element(leaf_bboxes.begin(), middle, leaf_bboxes.end(),
115 [axis](auto& p0, auto& p1) -> bool
116 {
117 auto x0 = p0.first[axis] + p0.first[3 + axis];
118 auto x1 = p1.first[axis] + p1.first[3 + axis];
119 return x0 < x1;
120 });
121
122 // Split bounding boxes into two groups and call recursively
123 assert(!leaf_bboxes.empty());
124 std::size_t part = leaf_bboxes.size() / 2;
125 std::int32_t bbox0
126 = _build_from_leaf(leaf_bboxes.first(part), bboxes, bbox_coordinates);
127 std::int32_t bbox1 = _build_from_leaf(
128 leaf_bboxes.last(leaf_bboxes.size() - part), bboxes, bbox_coordinates);
129
130 // Store bounding box data. Note that root box will be added last.
131 bboxes.push_back(bbox0);
132 bboxes.push_back(bbox1);
133 std::copy_n(b.begin(), 6, std::back_inserter(bbox_coordinates));
134 return bboxes.size() / 2 - 1;
135 }
136}
137//-----------------------------------------------------------------------------
138template <std::floating_point T>
139std::pair<std::vector<std::int32_t>, std::vector<T>> build_from_leaf(
140 std::vector<std::pair<std::array<T, 6>, std::int32_t>>& leaf_bboxes)
141{
142 std::vector<std::int32_t> bboxes;
143 std::vector<T> bbox_coordinates;
144 impl_bb::_build_from_leaf<T>(leaf_bboxes, bboxes, bbox_coordinates);
145 return {std::move(bboxes), std::move(bbox_coordinates)};
146}
147//-----------------------------------------------------------------------------
148template <std::floating_point T>
149std::int32_t
150_build_from_point(std::span<std::pair<std::array<T, 3>, std::int32_t>> points,
151 std::vector<std::int32_t>& bboxes,
152 std::vector<T>& bbox_coordinates)
153{
154 // Reached leaf
155 if (points.size() == 1)
156 {
157 // Store bounding box data
158
159 // Index of entity contained in leaf
160 const std::int32_t c1 = points[0].second;
161 bboxes.push_back(c1);
162 bboxes.push_back(c1);
163 bbox_coordinates.insert(bbox_coordinates.end(), points[0].first.begin(),
164 points[0].first.end());
165 bbox_coordinates.insert(bbox_coordinates.end(), points[0].first.begin(),
166 points[0].first.end());
167 return bboxes.size() / 2 - 1;
168 }
169
170 // Compute bounding box of all points
171 auto [min, max] = std::ranges::minmax_element(points);
172 std::array<T, 3> b0 = min->first;
173 std::array<T, 3> b1 = max->first;
174
175 // Sort bounding boxes along longest axis
176 std::array<T, 3> b_diff;
177 std::ranges::transform(b1, b0, b_diff.begin(), std::minus<T>());
178 const std::size_t axis
179 = std::distance(b_diff.begin(), std::ranges::max_element(b_diff));
180
181 auto middle = std::next(points.begin(), points.size() / 2);
182 std::nth_element(points.begin(), middle, points.end(),
183 [axis](auto& p0, auto&& p1) -> bool
184 { return p0.first[axis] < p1.first[axis]; });
185
186 // Split bounding boxes into two groups and call recursively
187 assert(!points.empty());
188 std::size_t part = points.size() / 2;
189 std::int32_t bbox0
190 = _build_from_point(points.first(part), bboxes, bbox_coordinates);
191 std::int32_t bbox1 = _build_from_point(points.last(points.size() - part),
192 bboxes, bbox_coordinates);
193
194 // Store bounding box data. Note that root box will be added last.
195 bboxes.push_back(bbox0);
196 bboxes.push_back(bbox1);
197 bbox_coordinates.insert(bbox_coordinates.end(), b0.begin(), b0.end());
198 bbox_coordinates.insert(bbox_coordinates.end(), b1.begin(), b1.end());
199 return bboxes.size() / 2 - 1;
200}
201//-----------------------------------------------------------------------------
202} // namespace impl_bb
203
206template <std::floating_point T>
208{
209private:
215 static std::vector<std::int32_t> range(mesh::Topology& topology, int tdim)
216 {
217 topology.create_entities(tdim);
218 auto map = topology.index_map(tdim);
219 assert(map);
220 const std::int32_t num_entities = map->size_local() + map->num_ghosts();
221 std::vector<std::int32_t> r(num_entities);
222 std::iota(r.begin(), r.end(), 0);
223 return r;
224 }
225
226public:
236 BoundingBoxTree(const mesh::Mesh<T>& mesh, int tdim, double padding,
237 std::optional<std::span<const std::int32_t>> entities
238 = std::nullopt)
239 : _tdim(tdim)
240 {
241 // Initialize entities of given dimension if they don't exist
242 mesh.topology_mutable()->create_entities(tdim);
243
244 // Get input entities. If not provided, get all local entities of the given
245 // dimension (including ghosts)
246 std::span<const std::int32_t> entities_span;
247 std::optional<std::vector<std::int32_t>> local_range(std::nullopt);
248 if (entities)
249 entities_span = entities.value();
250 else
251 {
252 local_range.emplace(range(*mesh.topology_mutable(), tdim));
253 entities_span = std::span<const std::int32_t>(local_range->data(),
254 local_range->size());
255 }
256
257 if (tdim < 0 or tdim > mesh.topology()->dim())
258 {
259 throw std::runtime_error(
260 "Dimension must be non-negative and less than or "
261 "equal to the topological dimension of the mesh");
262 }
263
264 mesh.topology_mutable()->create_connectivity(tdim, mesh.topology()->dim());
265
266 // Create bounding boxes for all mesh entities (leaves)
267 std::vector<std::pair<std::array<T, 6>, std::int32_t>> leaf_bboxes;
268 leaf_bboxes.reserve(entities_span.size());
269 for (std::int32_t e : entities_span)
270 {
271 std::array<T, 6> b = impl_bb::compute_bbox_of_entity(mesh, tdim, e);
272 std::transform(b.cbegin(), std::next(b.cbegin(), 3), b.begin(),
273 [padding](auto x) { return x - padding; });
274 std::transform(std::next(b.begin(), 3), b.end(), std::next(b.begin(), 3),
275 [padding](auto x) { return x + padding; });
276 leaf_bboxes.emplace_back(b, e);
277 }
278
279 // Recursively build the bounding box tree from the leaves
280 if (!leaf_bboxes.empty())
281 std::tie(_bboxes, _bbox_coordinates)
282 = impl_bb::build_from_leaf(leaf_bboxes);
283
284 spdlog::info("Computed bounding box tree with {} nodes for {} entities",
285 num_bboxes(), entities_span.size());
286 }
287
291 BoundingBoxTree(std::vector<std::pair<std::array<T, 3>, std::int32_t>> points)
292 : _tdim(0)
293 {
294 // Recursively build the bounding box tree from the leaves
295 if (!points.empty())
296 {
297 _bboxes.clear();
298 impl_bb::_build_from_point(std::span(points), _bboxes, _bbox_coordinates);
299 }
300
301 spdlog::info("Computed bounding box tree with {} nodes for {} points.",
302 num_bboxes(), points.size());
303 }
304
307
309 BoundingBoxTree(const BoundingBoxTree& tree) = delete;
310
313
315 BoundingBoxTree& operator=(const BoundingBoxTree& other) = default;
316
318 ~BoundingBoxTree() = default;
319
325 std::array<T, 6> get_bbox(std::size_t node) const
326 {
327 std::array<T, 6> x;
328 std::copy_n(_bbox_coordinates.data() + 6 * node, 6, x.begin());
329 return x;
330 }
331
338 {
339 // Build tree for each rank
340 const int mpi_size = dolfinx::MPI::size(comm);
341
342 // Send root node coordinates to all processes
343 // This is to counteract the fact that a process might have 0 bounding box
344 // causing false positives on process collisions around (0,0,0)
345 constexpr T max_val = std::numeric_limits<T>::max();
346 std::array<T, 6> send_bbox
347 = {max_val, max_val, max_val, max_val, max_val, max_val};
348 if (num_bboxes() > 0)
349 std::copy_n(std::prev(_bbox_coordinates.end(), 6), 6, send_bbox.begin());
350 std::vector<T> recv_bbox(mpi_size * 6);
351 MPI_Allgather(send_bbox.data(), 6, dolfinx::MPI::mpi_t<T>, recv_bbox.data(),
352 6, dolfinx::MPI::mpi_t<T>, comm);
353
354 std::vector<std::pair<std::array<T, 6>, std::int32_t>> _recv_bbox(mpi_size);
355 for (std::size_t i = 0; i < _recv_bbox.size(); ++i)
356 {
357 std::copy_n(std::next(recv_bbox.begin(), 6 * i), 6,
358 _recv_bbox[i].first.begin());
359 _recv_bbox[i].second = i;
360 }
361
362 auto [global_bboxes, global_coords] = impl_bb::build_from_leaf(_recv_bbox);
363 BoundingBoxTree global_tree(std::move(global_bboxes),
364 std::move(global_coords));
365
366 spdlog::info("Computed global bounding box tree with {} boxes.",
367 global_tree.num_bboxes());
368
369 return global_tree;
370 }
371
373 std::int32_t num_bboxes() const { return _bboxes.size() / 2; }
374
380 std::span<const T> bbox_coordinates() const { return _bbox_coordinates; }
381
387 std::span<T> bbox_coordinates() { return _bbox_coordinates; }
388
390 int tdim() const { return _tdim; }
391
393 std::string str() const
394 {
395 std::string s;
396 tree_print(s, _bboxes.size() / 2 - 1);
397 return s;
398 }
399
407 std::array<std::int32_t, 2> bbox(std::size_t node) const
408 {
409 assert(2 * node + 1 < _bboxes.size());
410 return {_bboxes[2 * node], _bboxes[2 * node + 1]};
411 }
412
413private:
414 // Constructor
415 BoundingBoxTree(std::vector<std::int32_t>&& bboxes,
416 std::vector<T>&& bbox_coords)
417 : _tdim(0), _bboxes(bboxes), _bbox_coordinates(bbox_coords)
418 {
419 // Do nothing
420 }
421
422 // Topological dimension of leaf entities
423 int _tdim;
424
425 // Print out recursively, for debugging
426 void tree_print(std::string& s, std::int32_t i) const
427 {
428 s += "[";
429 for (std::size_t j = 0; j < 2; ++j)
430 {
431 for (std::size_t k = 0; k < 3; ++k)
432 {
433 std::format_to(std::back_inserter(s), "{:.6} ",
434 _bbox_coordinates[6 * i + j * 3 + k]);
435 }
436 if (j == 0)
437 s += "]->[";
438 }
439 s += "]\n";
440
441 if (_bboxes[2 * i] == _bboxes[2 * i + 1])
442 {
443 std::format_to(std::back_inserter(s), "leaf containing entity ({})",
444 _bboxes[2 * i + 1]);
445 }
446 else
447 {
448 s += "{";
449 tree_print(s, _bboxes[2 * i]);
450 s += ", \n";
451 tree_print(s, _bboxes[2 * i + 1]);
452 s += "}\n";
453 }
454 }
455
456 // List of bounding boxes (parent-child-entity relations)
457 std::vector<std::int32_t> _bboxes;
458
459 // List of bounding box coordinates
460 std::vector<T> _bbox_coordinates;
461};
462} // namespace dolfinx::geometry
BoundingBoxTree(std::vector< std::pair< std::array< T, 3 >, std::int32_t > > points)
Definition BoundingBoxTree.h:291
std::span< T > bbox_coordinates()
Access coordinates of lower and upper corners of bounding boxes (non-const version).
Definition BoundingBoxTree.h:387
BoundingBoxTree & operator=(const BoundingBoxTree &other)=default
Copy assignment.
BoundingBoxTree & operator=(BoundingBoxTree &&other)=default
Move assignment.
BoundingBoxTree create_global_tree(MPI_Comm comm) const
Definition BoundingBoxTree.h:337
BoundingBoxTree(const mesh::Mesh< T > &mesh, int tdim, double padding, std::optional< std::span< const std::int32_t > > entities=std::nullopt)
Definition BoundingBoxTree.h:236
int tdim() const
Topological dimension of leaf entities.
Definition BoundingBoxTree.h:390
BoundingBoxTree(BoundingBoxTree &&tree)=default
Move constructor.
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
BoundingBoxTree(const BoundingBoxTree &tree)=delete
Copy constructor.
~BoundingBoxTree()=default
Destructor.
std::span< const T > bbox_coordinates() const
Access coordinates of lower and upper corners of bounding boxes (const version).
Definition BoundingBoxTree.h:380
std::string str() const
Print out for debugging.
Definition BoundingBoxTree.h:393
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
std::shared_ptr< const common::IndexMap > index_map(int dim) const
Get the IndexMap that described the parallel distribution of the mesh entities.
Definition Topology.cpp:873
bool create_entities(int dim, int num_threads=1)
Create entities of given topological dimension.
Definition Topology.cpp:956
Functions supporting mesh operations.
MPI_Datatype mpi_t
Retrieves the MPI data type associated to the provided type.
Definition MPI.h:257
int size(MPI_Comm comm)
Definition MPI.cpp:72
Geometry data structures and algorithms.
Definition BoundingBoxTree.h:24
Mesh data structures and algorithms on meshes.
Definition DofMap.h:32
std::pair< std::vector< std::int32_t >, std::array< std::size_t, 2 > > entities_to_geometry(const Mesh< T > &mesh, int dim, std::span< const std::int32_t > entities, bool permute=false)
Compute the geometry degrees of freedom associated with the closure of a given set of cell entities.
Definition utils.h:862