deal.II version GIT relicensing-6834-g5b78e6bcdf 2026-10-01 11:20:01+00:00
\(\newcommand{\dealvcentcolon}{\mathrel{\mathop{:}}}\) \(\newcommand{\dealcoloneq}{\dealvcentcolon\mathrel{\mkern-1.2mu}=}\) \(\newcommand{\jump}[1]{\left[\!\left[ #1 \right]\!\right]}\) \(\newcommand{\average}[1]{\left\{\!\left\{ #1 \right\}\!\right\}}\)
Loading...
Searching...
No Matches
grid_tools_dof_handlers.cc
Go to the documentation of this file.
1// -----------------------------------------------------------------------------
2//
3// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception OR LGPL-2.1-or-later
4// Copyright (C) 2018 - 2025 by the deal.II authors
5//
6// This file is part of the deal.II library.
7//
8// Detailed license information governing the source code and contributions
9// can be found in LICENSE.md and CONTRIBUTING.md at the top level directory.
10//
11// -----------------------------------------------------------------------------
12
14#include <deal.II/base/point.h>
15#include <deal.II/base/tensor.h>
16#include <deal.II/base/types.h>
17
21
24
26
29#include <deal.II/grid/tria.h>
32
34
36
37#include <algorithm>
38#include <array>
39#include <cmath>
40#include <limits>
41#include <list>
42#include <map>
43#include <numeric>
44#include <optional>
45#include <set>
46#include <vector>
47
48
50
51namespace GridTools
52{
53 template <int dim, template <int, int> class MeshType, int spacedim>
55 (concepts::is_triangulation_or_dof_handler<MeshType<dim, spacedim>>))
56 unsigned int find_closest_vertex(const MeshType<dim, spacedim> &mesh,
57 const Point<spacedim> &p,
58 const std::vector<bool> &marked_vertices)
59 {
60 // first get the underlying
61 // triangulation from the
62 // mesh and determine vertices
63 // and used vertices
65
66 const std::vector<Point<spacedim>> &vertices = tria.get_vertices();
67
68 Assert(tria.get_vertices().size() == marked_vertices.size() ||
69 marked_vertices.empty(),
71 marked_vertices.size()));
72
73 // If p is an element of marked_vertices,
74 // and q is that of used_Vertices,
75 // the vector marked_vertices does NOT
76 // contain unused vertices if p implies q.
77 // I.e., if p is true q must be true
78 // (if p is false, q could be false or true).
79 // p implies q logic is encapsulated in ~p|q.
80 Assert(
81 marked_vertices.empty() ||
82 std::equal(marked_vertices.begin(),
83 marked_vertices.end(),
84 tria.get_used_vertices().begin(),
85 [](bool p, bool q) { return !p || q; }),
87 "marked_vertices should be a subset of used vertices in the triangulation "
88 "but marked_vertices contains one or more vertices that are not used vertices!"));
89
90 // In addition, if a vector bools
91 // is specified (marked_vertices)
92 // marking all the vertices which
93 // could be the potentially closest
94 // vertex to the point, use it instead
95 // of used vertices
96 const std::vector<bool> &used =
97 (marked_vertices.empty()) ? tria.get_used_vertices() : marked_vertices;
98
99 // At the beginning, the first
100 // used vertex is the closest one
101 std::vector<bool>::const_iterator first =
102 std::find(used.begin(), used.end(), true);
103
104 // Assert that at least one vertex
105 // is actually used
106 Assert(first != used.end(), ExcInternalError());
107
108 unsigned int best_vertex = std::distance(used.begin(), first);
109 double best_dist = (p - vertices[best_vertex]).norm_square();
110
111 // For all remaining vertices, test
112 // whether they are any closer
113 for (unsigned int j = best_vertex + 1; j < vertices.size(); ++j)
114 if (used[j])
115 {
116 double dist = (p - vertices[j]).norm_square();
117 if (dist < best_dist)
118 {
119 best_vertex = j;
120 best_dist = dist;
121 }
122 }
123
124 return best_vertex;
125 }
126
127
128
129 template <int dim, template <int, int> class MeshType, int spacedim>
131 (concepts::is_triangulation_or_dof_handler<MeshType<dim, spacedim>>))
132 unsigned int find_closest_vertex(const Mapping<dim, spacedim> &mapping,
133 const MeshType<dim, spacedim> &mesh,
134 const Point<spacedim> &p,
135 const std::vector<bool> &marked_vertices)
136 {
137 // Take a shortcut in the simple case.
138 if (mapping.preserves_vertex_locations() == true)
139 return find_closest_vertex(mesh, p, marked_vertices);
140
141 // first get the underlying
142 // triangulation from the
143 // mesh and determine vertices
144 // and used vertices
146
147 auto vertices = extract_used_vertices(tria, mapping);
148
149 Assert(tria.get_vertices().size() == marked_vertices.size() ||
150 marked_vertices.empty(),
152 marked_vertices.size()));
153
154 // If p is an element of marked_vertices,
155 // and q is that of used_Vertices,
156 // the vector marked_vertices does NOT
157 // contain unused vertices if p implies q.
158 // I.e., if p is true q must be true
159 // (if p is false, q could be false or true).
160 // p implies q logic is encapsulated in ~p|q.
161 Assert(
162 marked_vertices.empty() ||
163 std::equal(marked_vertices.begin(),
164 marked_vertices.end(),
165 tria.get_used_vertices().begin(),
166 [](bool p, bool q) { return !p || q; }),
168 "marked_vertices should be a subset of used vertices in the triangulation "
169 "but marked_vertices contains one or more vertices that are not used vertices!"));
170
171 // Remove from the map unwanted elements.
172 if (marked_vertices.size())
173 for (auto it = vertices.begin(); it != vertices.end();)
174 {
175 if (marked_vertices[it->first] == false)
176 {
177 vertices.erase(it++);
178 }
179 else
180 {
181 ++it;
182 }
183 }
184
185 return find_closest_vertex(vertices, p);
186 }
187
188
189
190 template <typename MeshType>
192#ifndef _MSC_VER
193 std::vector<typename MeshType::active_cell_iterator>
194#else
195 std::vector<
196 typename ::internal::ActiveCellIterator<MeshType::dimension,
197 MeshType::space_dimension,
198 MeshType>::type>
199#endif
200 find_cells_adjacent_to_vertex(const MeshType &mesh,
201 const unsigned int vertex)
202 {
203 const int dim = MeshType::dimension;
204 const int spacedim = MeshType::space_dimension;
205
206 // make sure that the given vertex is
207 // an active vertex of the underlying
208 // triangulation
209 AssertIndexRange(vertex, mesh.get_triangulation().n_vertices());
210 Assert(mesh.get_triangulation().get_used_vertices()[vertex],
211 ExcVertexNotUsed(vertex));
212
213 // use a set instead of a vector
214 // to ensure that cells are inserted only
215 // once
216 std::set<typename ::internal::
217 ActiveCellIterator<dim, spacedim, MeshType>::type>
219
220 typename ::internal::ActiveCellIterator<dim, spacedim, MeshType>::type
221 cell = mesh.begin_active(),
222 endc = mesh.end();
223
224 // go through all active cells and look if the vertex is part of that cell
225 //
226 // in 1d, this is all we need to care about. in 2d/3d we also need to worry
227 // that the vertex might be a hanging node on a face or edge of a cell; in
228 // this case, we would want to add those cells as well on whose faces the
229 // vertex is located but for which it is not a vertex itself.
230 //
231 // getting this right is a lot simpler in 2d than in 3d. in 2d, a hanging
232 // node can only be in the middle of a face and we can query the neighboring
233 // cell from the current cell. on the other hand, in 3d a hanging node
234 // vertex can also be on an edge but there can be many other cells on
235 // this edge and we can not access them from the cell we are currently
236 // on.
237 //
238 // so, in the 3d case, if we run the algorithm as in 2d, we catch all
239 // those cells for which the vertex we seek is on a *subface*, but we
240 // miss the case of cells for which the vertex we seek is on a
241 // sub-edge for which there is no corresponding sub-face (because the
242 // immediate neighbor behind this face is not refined), see for example
243 // the bits/find_cells_adjacent_to_vertex_6 testcase. thus, if we
244 // haven't yet found the vertex for the current cell we also need to
245 // look at the mid-points of edges
246 //
247 // as a final note, deciding whether a neighbor is actually coarser is
248 // simple in the case of isotropic refinement (we just need to look at
249 // the level of the current and the neighboring cell). however, this
250 // isn't so simple if we have used anisotropic refinement since then
251 // the level of a cell is not indicative of whether it is coarser or
252 // not than the current cell. ultimately, we want to add all cells on
253 // which the vertex is, independent of whether they are coarser or
254 // finer and so in the 2d case below we simply add *any* *active* neighbor.
255 // in the worst case, we add cells multiple times to the adjacent_cells
256 // list, but std::set throws out those cells already entered
257 for (; cell != endc; ++cell)
258 {
259 for (const unsigned int v : cell->vertex_indices())
260 if (cell->vertex_index(v) == vertex)
261 {
262 // OK, we found a cell that contains
263 // the given vertex. We add it
264 // to the list.
265 adjacent_cells.insert(cell);
266
267 // as explained above, in 2+d we need to check whether
268 // this vertex is on a face behind which there is a
269 // (possibly) coarser neighbor. if this is the case,
270 // then we need to also add this neighbor
271 if (dim >= 2)
272 {
273 const auto reference_cell = cell->reference_cell();
274 for (const auto face :
275 reference_cell.faces_for_given_vertex(v))
276 if (!cell->at_boundary(face) &&
277 cell->neighbor(face)->is_active())
278 {
279 // there is a (possibly) coarser cell behind a
280 // face to which the vertex belongs. the
281 // vertex we are looking at is then either a
282 // vertex of that coarser neighbor, or it is a
283 // hanging node on one of the faces of that
284 // cell. in either case, it is adjacent to the
285 // vertex, so add it to the list as well (if
286 // the cell was already in the list then the
287 // std::set makes sure that we get it only
288 // once)
289 adjacent_cells.insert(cell->neighbor(face));
290 }
291 }
292
293 // in any case, we have found a cell, so go to the next cell
294 goto next_cell;
295 }
296
297 // in 3d also loop over the edges
298 if (dim >= 3)
299 {
300 for (unsigned int e = 0; e < cell->n_lines(); ++e)
301 if (cell->line(e)->has_children())
302 // the only place where this vertex could have been
303 // hiding is on the mid-edge point of the edge we
304 // are looking at
305 if (cell->line(e)->child(0)->vertex_index(1) == vertex)
306 {
307 adjacent_cells.insert(cell);
308
309 // jump out of this tangle of nested loops
310 goto next_cell;
311 }
312 }
313
314 // in more than 3d we would probably have to do the same as
315 // above also for even lower-dimensional objects
316 Assert(dim <= 3, ExcNotImplemented());
317
318 // move on to the next cell if we have found the
319 // vertex on the current one
320 next_cell:;
321 }
322
323 // if this was an active vertex then there needs to have been
324 // at least one cell to which it is adjacent!
326
327 // return the result as a vector, rather than the set we built above
328 return std::vector<typename ::internal::
329 ActiveCellIterator<dim, spacedim, MeshType>::type>(
330 adjacent_cells.begin(), adjacent_cells.end());
331 }
332
333
334
335 namespace
336 {
337 template <int dim, template <int, int> class MeshType, int spacedim>
339 (concepts::is_triangulation_or_dof_handler<MeshType<dim, spacedim>>))
340 void find_active_cell_around_point_internal(
341 const MeshType<dim, spacedim> &mesh,
342#ifndef _MSC_VER
343 std::set<typename MeshType<dim, spacedim>::active_cell_iterator>
344 &searched_cells,
345 std::set<typename MeshType<dim, spacedim>::active_cell_iterator>
347#else
348 std::set<
349 typename ::internal::
350 ActiveCellIterator<dim, spacedim, MeshType<dim, spacedim>>::type>
351 &searched_cells,
352 std::set<
353 typename ::internal::
354 ActiveCellIterator<dim, spacedim, MeshType<dim, spacedim>>::type>
356#endif
357 {
358#ifndef _MSC_VER
359 using cell_iterator =
360 typename MeshType<dim, spacedim>::active_cell_iterator;
361#else
362 using cell_iterator = typename ::internal::
363 ActiveCellIterator<dim, spacedim, MeshType<dim, spacedim>>::type;
364#endif
365
366 // update the searched cells
367 searched_cells.insert(adjacent_cells.begin(), adjacent_cells.end());
368 // now we to collect all neighbors
369 // of the cells in adjacent_cells we
370 // have not yet searched.
371 std::set<cell_iterator> adjacent_cells_new;
372
373 for (const auto &cell : adjacent_cells)
374 {
375 std::vector<cell_iterator> active_neighbors;
376 get_active_neighbors<MeshType<dim, spacedim>>(cell, active_neighbors);
377 for (unsigned int i = 0; i < active_neighbors.size(); ++i)
378 if (searched_cells.find(active_neighbors[i]) ==
379 searched_cells.end())
380 adjacent_cells_new.insert(active_neighbors[i]);
381 }
382 adjacent_cells.clear();
383 adjacent_cells.insert(adjacent_cells_new.begin(),
384 adjacent_cells_new.end());
385 if (adjacent_cells.empty())
386 {
387 // we haven't found any other cell that would be a
388 // neighbor of a previously found cell, but we know
389 // that we haven't checked all cells yet. that means
390 // that the domain is disconnected. in that case,
391 // choose the first previously untouched cell we
392 // can find
393 cell_iterator it = mesh.begin_active();
394 for (; it != mesh.end(); ++it)
395 if (searched_cells.find(it) == searched_cells.end())
396 {
397 adjacent_cells.insert(it);
398 break;
399 }
400 }
401 }
402 } // namespace
403
404
405
406 template <int dim, template <int, int> class MeshType, int spacedim>
408 (concepts::is_triangulation_or_dof_handler<MeshType<dim, spacedim>>))
409#ifndef _MSC_VER
410 typename MeshType<dim, spacedim>::active_cell_iterator
411#else
412 typename ::internal::
413 ActiveCellIterator<dim, spacedim, MeshType<dim, spacedim>>::type
414#endif
415 find_active_cell_around_point(const MeshType<dim, spacedim> &mesh,
416 const Point<spacedim> &p,
417 const std::vector<bool> &marked_vertices,
418 const double tolerance)
419 {
420 return find_active_cell_around_point<dim, MeshType, spacedim>(
421 get_default_linear_mapping(mesh.get_triangulation()),
422 mesh,
423 p,
424 marked_vertices,
425 tolerance)
426 .first;
427 }
428
429
430
431 template <int dim, template <int, int> class MeshType, int spacedim>
433 (concepts::is_triangulation_or_dof_handler<MeshType<dim, spacedim>>))
434#ifndef _MSC_VER
435 std::pair<typename MeshType<dim, spacedim>::active_cell_iterator, Point<dim>>
436#else
437 std::pair<typename ::internal::
438 ActiveCellIterator<dim, spacedim, MeshType<dim, spacedim>>::type,
440#endif
442 const MeshType<dim, spacedim> &mesh,
443 const Point<spacedim> &p,
444 const std::vector<bool> &marked_vertices,
445 const double tolerance)
446 {
447 using active_cell_iterator = typename ::internal::
448 ActiveCellIterator<dim, spacedim, MeshType<dim, spacedim>>::type;
449
450 // The best distance is set to the
451 // maximum allowable distance from
452 // the unit cell; we assume a
453 // max. deviation of the given tolerance
454 double best_distance = tolerance;
455 int best_level = -1;
456 std::pair<active_cell_iterator, Point<dim>> best_cell;
457
458 // Initialize best_cell.first to the end iterator
459 best_cell.first = mesh.end();
460
461 // Find closest vertex and determine
462 // all adjacent cells
463 std::vector<active_cell_iterator> adjacent_cells_tmp =
465 mesh, find_closest_vertex(mapping, mesh, p, marked_vertices));
466
467 // Make sure that we have found
468 // at least one cell adjacent to vertex.
469 Assert(adjacent_cells_tmp.size() > 0, ExcInternalError());
470
471 // Copy all the cells into a std::set
472 std::set<active_cell_iterator> adjacent_cells(adjacent_cells_tmp.begin(),
473 adjacent_cells_tmp.end());
474 std::set<active_cell_iterator> searched_cells;
475
476 // Determine the maximal number of cells
477 // in the grid.
478 // As long as we have not found
479 // the cell and have not searched
480 // every cell in the triangulation,
481 // we keep on looking.
482 const auto n_active_cells = mesh.get_triangulation().n_active_cells();
483 bool found = false;
484 unsigned int cells_searched = 0;
485 while (!found && cells_searched < n_active_cells)
486 {
487 for (const auto &cell : adjacent_cells)
488 {
489 if (cell->is_artificial() == false)
490 {
491 // marked_vertices are used to filter cell candidates
492 if (marked_vertices.size() > 0)
493 {
494 bool any_vertex_marked = false;
495 for (const auto &v : cell->vertex_indices())
496 {
497 if (marked_vertices[cell->vertex_index(v)])
498 {
499 any_vertex_marked = true;
500 break;
501 }
502 }
503 if (!any_vertex_marked)
504 continue;
505 }
506
507 try
508 {
509 const Point<dim> p_cell =
510 mapping.transform_real_to_unit_cell(cell, p);
511
512 // calculate the Euclidean norm of
513 // the distance vector to the unit cell.
514 const double dist =
515 cell->reference_cell().closest_point(p_cell).distance(
516 p_cell);
517
518 // We compare if the point is inside the
519 // unit cell (or at least not too far
520 // outside). If it is, it is also checked
521 // that the cell has a more refined state
522 if ((dist < best_distance) ||
523 ((dist == best_distance) &&
524 (cell->level() > best_level)))
525 {
526 found = true;
527 best_distance = dist;
528 best_level = cell->level();
529 best_cell = std::make_pair(cell, p_cell);
530 }
531 }
532 catch (
534 {
535 // ok, the transformation
536 // failed presumably
537 // because the point we
538 // are looking for lies
539 // outside the current
540 // cell. this means that
541 // the current cell can't
542 // be the cell around the
543 // point, so just ignore
544 // this cell and move on
545 // to the next
546 }
547 }
548 }
549
550 // update the number of cells searched
551 cells_searched += adjacent_cells.size();
552
553 // if we have not found the cell in
554 // question and have not yet searched every
555 // cell, we expand our search to
556 // all the not already searched neighbors of
557 // the cells in adjacent_cells. This is
558 // what find_active_cell_around_point_internal
559 // is for.
560 if (!found && cells_searched < n_active_cells)
561 {
562 find_active_cell_around_point_internal<dim, MeshType, spacedim>(
563 mesh, searched_cells, adjacent_cells);
564 }
565 }
566
567 return best_cell;
568 }
569
570
571
572 template <int dim, template <int, int> class MeshType, int spacedim>
574 (concepts::is_triangulation_or_dof_handler<MeshType<dim, spacedim>>))
575#ifndef _MSC_VER
576 std::vector<std::pair<typename MeshType<dim, spacedim>::active_cell_iterator,
577 Point<dim>>>
578#else
579 std::vector<std::pair<
580 typename ::internal::
581 ActiveCellIterator<dim, spacedim, MeshType<dim, spacedim>>::type,
582 Point<dim>>>
583#endif
585 const MeshType<dim, spacedim> &mesh,
586 const Point<spacedim> &p,
587 const double tolerance,
588 const std::vector<bool> &marked_vertices)
589 {
590 const auto cell_and_point = find_active_cell_around_point(
591 mapping, mesh, p, marked_vertices, tolerance);
592
593 if (cell_and_point.first == mesh.end())
594 return {};
595
597 mapping, mesh, p, tolerance, cell_and_point);
598 }
599
600
601
602 template <int dim, template <int, int> class MeshType, int spacedim>
604 (concepts::is_triangulation_or_dof_handler<MeshType<dim, spacedim>>))
605#ifndef _MSC_VER
606 std::vector<std::pair<typename MeshType<dim, spacedim>::active_cell_iterator,
607 Point<dim>>>
608#else
609 std::vector<std::pair<
610 typename ::internal::
611 ActiveCellIterator<dim, spacedim, MeshType<dim, spacedim>>::type,
612 Point<dim>>>
613#endif
615 const Mapping<dim, spacedim> &mapping,
616 const MeshType<dim, spacedim> &mesh,
617 const Point<spacedim> &p,
618 const double tolerance,
619 const std::pair<typename MeshType<dim, spacedim>::active_cell_iterator,
620 Point<dim>> &first_cell,
621 const std::vector<
622 std::set<typename MeshType<dim, spacedim>::active_cell_iterator>>
623 *vertex_to_cells)
624 {
625 std::vector<
626 std::pair<typename MeshType<dim, spacedim>::active_cell_iterator,
627 Point<dim>>>
628 cells_and_points;
629
630 // insert the fist cell and point into the vector
631 cells_and_points.push_back(first_cell);
632
633 const Point<dim> unit_point = cells_and_points.front().second;
634 const auto my_cell = cells_and_points.front().first;
635
636 std::vector<typename MeshType<dim, spacedim>::active_cell_iterator>
637 cells_to_add;
638
639 if (my_cell->reference_cell().is_hyper_cube())
640 {
641 // check if the given point is on the surface of the unit cell. If yes,
642 // need to find all neighbors
643
644 Tensor<1, dim> distance_to_center;
645 unsigned int n_dirs_at_threshold = 0;
646 unsigned int last_point_at_threshold = numbers::invalid_unsigned_int;
647 for (unsigned int d = 0; d < dim; ++d)
648 {
649 distance_to_center[d] = std::abs(unit_point[d] - 0.5);
650 if (distance_to_center[d] > 0.5 - tolerance)
651 {
652 ++n_dirs_at_threshold;
653 last_point_at_threshold = d;
654 }
655 }
656
657 // point is within face -> only need neighbor
658 if (n_dirs_at_threshold == 1)
659 {
660 unsigned int neighbor_index =
661 2 * last_point_at_threshold +
662 (unit_point[last_point_at_threshold] > 0.5 ? 1 : 0);
663 if (!my_cell->at_boundary(neighbor_index))
664 {
665 const auto neighbor_cell = my_cell->neighbor(neighbor_index);
666
667 if (neighbor_cell->is_active())
668 cells_to_add.push_back(neighbor_cell);
669 else
670 for (const auto &child_cell :
671 neighbor_cell->child_iterators())
672 {
673 if (child_cell->is_active())
674 cells_to_add.push_back(child_cell);
675 }
676 }
677 }
678 // corner point -> use all neighbors
679 else if (n_dirs_at_threshold == dim)
680 {
681 unsigned int local_vertex_index = 0;
682 for (unsigned int d = 0; d < dim; ++d)
683 local_vertex_index += (unit_point[d] > 0.5 ? 1 : 0) << d;
684
685 const auto fu = [&](const auto &tentative_cells) {
686 for (const auto &cell : tentative_cells)
687 if (cell != my_cell)
688 cells_to_add.push_back(cell);
689 };
690
691 const auto vertex_index = my_cell->vertex_index(local_vertex_index);
692
693 if (vertex_to_cells != nullptr)
694 fu((*vertex_to_cells)[vertex_index]);
695 else
696 fu(find_cells_adjacent_to_vertex(mesh, vertex_index));
697 }
698 // point on line in 3d: We cannot simply take the intersection between
699 // the two vertices of cells because of hanging nodes. So instead we
700 // list the vertices around both points and then select the
701 // appropriate cells according to the result of read_to_unit_cell
702 // below.
703 else if (n_dirs_at_threshold == 2)
704 {
705 std::pair<unsigned int, unsigned int> vertex_indices[3];
706 unsigned int count_vertex_indices = 0;
707 unsigned int free_direction = numbers::invalid_unsigned_int;
708 for (unsigned int d = 0; d < dim; ++d)
709 {
710 if (distance_to_center[d] > 0.5 - tolerance)
711 {
712 vertex_indices[count_vertex_indices].first = d;
713 vertex_indices[count_vertex_indices].second =
714 unit_point[d] > 0.5 ? 1 : 0;
715 ++count_vertex_indices;
716 }
717 else
718 free_direction = d;
719 }
720
721 AssertDimension(count_vertex_indices, 2);
722 Assert(free_direction != numbers::invalid_unsigned_int,
724
725 const unsigned int first_vertex =
726 (vertex_indices[0].second << vertex_indices[0].first) +
728 for (unsigned int d = 0; d < 2; ++d)
729 {
730 const auto fu = [&](const auto &tentative_cells) {
731 for (const auto &cell : tentative_cells)
732 {
733 bool cell_not_yet_present = true;
734 for (const auto &other_cell : cells_to_add)
735 if (cell == other_cell)
736 {
737 cell_not_yet_present = false;
738 break;
739 }
740 if (cell_not_yet_present)
741 cells_to_add.push_back(cell);
742 }
743 };
744
745 const auto vertex_index =
746 my_cell->vertex_index(first_vertex + (d << free_direction));
747
748 if (vertex_to_cells != nullptr)
749 fu((*vertex_to_cells)[vertex_index]);
750 else
751 fu(find_cells_adjacent_to_vertex(mesh, vertex_index));
752 }
753 }
754 }
755 else
756 {
757 // Note: The non-hypercube path takes a very naive approach and
758 // checks all possible neighbors. This can be made faster by 1)
759 // checking if the point is in the inner cell and 2) identifying
760 // the right lines/vertices so that the number of potential
761 // neighbors is reduced.
762
763 for (const auto v : my_cell->vertex_indices())
764 {
765 const auto fu = [&](const auto &tentative_cells) {
766 for (const auto &cell : tentative_cells)
767 {
768 bool cell_not_yet_present = true;
769 for (const auto &other_cell : cells_to_add)
770 if (cell == other_cell)
771 {
772 cell_not_yet_present = false;
773 break;
774 }
775 if (cell_not_yet_present)
776 cells_to_add.push_back(cell);
777 }
778 };
779
780 const auto vertex_index = my_cell->vertex_index(v);
781
782 if (vertex_to_cells != nullptr)
783 fu((*vertex_to_cells)[vertex_index]);
784 else
785 fu(find_cells_adjacent_to_vertex(mesh, vertex_index));
786 }
787 }
788
789 for (const auto &cell : cells_to_add)
790 {
791 if (cell != my_cell)
792 try
793 {
794 const Point<dim> p_unit =
795 mapping.transform_real_to_unit_cell(cell, p);
796 if (cell->reference_cell().contains_point(p_unit, tolerance))
797 cells_and_points.emplace_back(cell, p_unit);
798 }
800 {}
801 }
802
803 std::sort(
804 cells_and_points.begin(),
805 cells_and_points.end(),
806 [](const std::pair<typename MeshType<dim, spacedim>::active_cell_iterator,
807 Point<dim>> &a,
808 const std::pair<typename MeshType<dim, spacedim>::active_cell_iterator,
809 Point<dim>> &b) { return a.first < b.first; });
810
811 return cells_and_points;
812 }
813
814
815
816 template <typename MeshType>
818 std::
819 vector<typename MeshType::active_cell_iterator> compute_active_cell_halo_layer(
820 const MeshType &mesh,
821 const std::function<bool(const typename MeshType::active_cell_iterator &)>
822 &predicate)
823 {
824 std::vector<typename MeshType::active_cell_iterator> active_halo_layer;
825 std::vector<bool> locally_active_vertices_on_subdomain(
826 mesh.get_triangulation().n_vertices(), false);
827
828 std::map<unsigned int, std::vector<unsigned int>> coinciding_vertex_groups;
829 std::map<unsigned int, unsigned int> vertex_to_coinciding_vertex_group;
830 GridTools::collect_coinciding_vertices(mesh.get_triangulation(),
831 coinciding_vertex_groups,
832 vertex_to_coinciding_vertex_group);
833
834 // Find the cells for which the predicate is true
835 // These are the cells around which we wish to construct
836 // the halo layer
837 for (const auto &cell : mesh.active_cell_iterators())
838 if (predicate(cell)) // True predicate --> Part of subdomain
839 for (const auto v : cell->vertex_indices())
840 {
841 locally_active_vertices_on_subdomain[cell->vertex_index(v)] = true;
842 for (const auto vv : coinciding_vertex_groups
843 [vertex_to_coinciding_vertex_group[cell->vertex_index(v)]])
844 locally_active_vertices_on_subdomain[vv] = true;
845 }
846
847 // Find the cells that do not conform to the predicate
848 // but share a vertex with the selected subdomain
849 // These comprise the halo layer
850 for (const auto &cell : mesh.active_cell_iterators())
851 if (!predicate(cell)) // False predicate --> Potential halo cell
852 for (const auto v : cell->vertex_indices())
853 if (locally_active_vertices_on_subdomain[cell->vertex_index(v)] ==
854 true)
855 {
856 active_halo_layer.push_back(cell);
857 break;
858 }
859
860 return active_halo_layer;
861 }
862
863
864
865 template <typename MeshType>
867 std::
868 vector<typename MeshType::cell_iterator> compute_cell_halo_layer_on_level(
869 const MeshType &mesh,
870 const std::function<bool(const typename MeshType::cell_iterator &)>
871 &predicate,
872 const unsigned int level)
873 {
874 std::vector<typename MeshType::cell_iterator> level_halo_layer;
875 std::vector<bool> locally_active_vertices_on_level_subdomain(
876 mesh.get_triangulation().n_vertices(), false);
877
878 // Find the cells for which the predicate is true
879 // These are the cells around which we wish to construct
880 // the halo layer
881 for (typename MeshType::cell_iterator cell = mesh.begin(level);
882 cell != mesh.end(level);
883 ++cell)
884 if (predicate(cell)) // True predicate --> Part of subdomain
885 for (const unsigned int v : cell->vertex_indices())
886 locally_active_vertices_on_level_subdomain[cell->vertex_index(v)] =
887 true;
888
889 // Find the cells that do not conform to the predicate
890 // but share a vertex with the selected subdomain on that level
891 // These comprise the halo layer
892 for (typename MeshType::cell_iterator cell = mesh.begin(level);
893 cell != mesh.end(level);
894 ++cell)
895 if (!predicate(cell)) // False predicate --> Potential halo cell
896 for (const unsigned int v : cell->vertex_indices())
897 if (locally_active_vertices_on_level_subdomain[cell->vertex_index(
898 v)] == true)
899 {
900 level_halo_layer.push_back(cell);
901 break;
902 }
903
904 return level_halo_layer;
905 }
906
907
908 namespace
909 {
910 template <typename MeshType>
912 bool contains_locally_owned_cells(
913 const std::vector<typename MeshType::active_cell_iterator> &cells)
914 {
915 for (typename std::vector<
916 typename MeshType::active_cell_iterator>::const_iterator it =
917 cells.begin();
918 it != cells.end();
919 ++it)
920 {
921 if ((*it)->is_locally_owned())
922 return true;
923 }
924 return false;
925 }
926
927 template <typename MeshType>
929 bool contains_artificial_cells(
930 const std::vector<typename MeshType::active_cell_iterator> &cells)
931 {
932 for (typename std::vector<
933 typename MeshType::active_cell_iterator>::const_iterator it =
934 cells.begin();
935 it != cells.end();
936 ++it)
937 {
938 if ((*it)->is_artificial())
939 return true;
940 }
941 return false;
942 }
943 } // namespace
944
945
946
947 template <typename MeshType>
949 std::vector<
950 typename MeshType::
951 active_cell_iterator> compute_ghost_cell_halo_layer(const MeshType &mesh)
952 {
953 std::function<bool(const typename MeshType::active_cell_iterator &)>
955
956 const std::vector<typename MeshType::active_cell_iterator>
957 active_halo_layer = compute_active_cell_halo_layer(mesh, predicate);
958
959 // Check that we never return locally owned or artificial cells
960 // What is left should only be the ghost cells
961 Assert(contains_locally_owned_cells<MeshType>(active_halo_layer) == false,
962 ExcMessage("Halo layer contains locally owned cells"));
963 Assert(contains_artificial_cells<MeshType>(active_halo_layer) == false,
964 ExcMessage("Halo layer contains artificial cells"));
965
966 return active_halo_layer;
967 }
968
969
970
971 template <typename MeshType>
973 std::
974 vector<typename MeshType::active_cell_iterator> compute_active_cell_layer_within_distance(
975 const MeshType &mesh,
976 const std::function<bool(const typename MeshType::active_cell_iterator &)>
977 &predicate,
978 const double layer_thickness)
979 {
980 std::vector<typename MeshType::active_cell_iterator>
981 subdomain_boundary_cells, active_cell_layer_within_distance;
982 std::vector<bool> vertices_outside_subdomain(
983 mesh.get_triangulation().n_vertices(), false);
984
985 const unsigned int spacedim = MeshType::space_dimension;
986
987 unsigned int n_non_predicate_cells = 0; // Number of non predicate cells
988
989 // Find the layer of cells for which predicate is true and that
990 // are on the boundary with other cells. These are
991 // subdomain boundary cells.
992
993 // Find the cells for which the predicate is false
994 // These are the cells which are around the predicate subdomain
995 for (const auto &cell : mesh.active_cell_iterators())
996 if (!predicate(cell)) // Negation of predicate --> Not Part of subdomain
997 {
998 for (const unsigned int v : cell->vertex_indices())
999 vertices_outside_subdomain[cell->vertex_index(v)] = true;
1000 ++n_non_predicate_cells;
1001 }
1002
1003 // If all the active cells conform to the predicate
1004 // or if none of the active cells conform to the predicate
1005 // there is no active cell layer around the predicate
1006 // subdomain (within any distance)
1007 if (n_non_predicate_cells == 0 ||
1008 n_non_predicate_cells == mesh.get_triangulation().n_active_cells())
1009 return std::vector<typename MeshType::active_cell_iterator>();
1010
1011 // Find the cells that conform to the predicate
1012 // but share a vertex with the cell not in the predicate subdomain
1013 for (const auto &cell : mesh.active_cell_iterators())
1014 if (predicate(cell)) // True predicate --> Potential boundary cell of the
1015 // subdomain
1016 for (const unsigned int v : cell->vertex_indices())
1017 if (vertices_outside_subdomain[cell->vertex_index(v)] == true)
1018 {
1019 subdomain_boundary_cells.push_back(cell);
1020 break; // No need to go through remaining vertices
1021 }
1022
1023 // To cheaply filter out some cells located far away from the predicate
1024 // subdomain, get the bounding box of the predicate subdomain.
1025 std::pair<Point<spacedim>, Point<spacedim>> bounding_box =
1026 compute_bounding_box(mesh, predicate);
1027
1028 // DOUBLE_EPSILON to compare really close double values
1029 const double DOUBLE_EPSILON = 100. * std::numeric_limits<double>::epsilon();
1030
1031 // Add layer_thickness to the bounding box
1032 for (unsigned int d = 0; d < spacedim; ++d)
1033 {
1034 bounding_box.first[d] -= (layer_thickness + DOUBLE_EPSILON); // minp
1035 bounding_box.second[d] += (layer_thickness + DOUBLE_EPSILON); // maxp
1036 }
1037
1038 std::vector<Point<spacedim>>
1039 subdomain_boundary_cells_centers; // cache all the subdomain boundary
1040 // cells centers here
1041 std::vector<double>
1042 subdomain_boundary_cells_radii; // cache all the subdomain boundary cells
1043 // radii
1044 subdomain_boundary_cells_centers.reserve(subdomain_boundary_cells.size());
1045 subdomain_boundary_cells_radii.reserve(subdomain_boundary_cells.size());
1046 // compute cell radius for each boundary cell of the predicate subdomain
1047 for (typename std::vector<typename MeshType::active_cell_iterator>::
1048 const_iterator subdomain_boundary_cell_iterator =
1049 subdomain_boundary_cells.begin();
1050 subdomain_boundary_cell_iterator != subdomain_boundary_cells.end();
1051 ++subdomain_boundary_cell_iterator)
1052 {
1053 const std::pair<Point<spacedim>, double>
1054 &subdomain_boundary_cell_enclosing_ball =
1055 (*subdomain_boundary_cell_iterator)->enclosing_ball();
1056
1057 subdomain_boundary_cells_centers.push_back(
1058 subdomain_boundary_cell_enclosing_ball.first);
1059 subdomain_boundary_cells_radii.push_back(
1060 subdomain_boundary_cell_enclosing_ball.second);
1061 }
1062 AssertThrow(subdomain_boundary_cells_radii.size() ==
1063 subdomain_boundary_cells_centers.size(),
1065
1066 // Find the cells that are within layer_thickness of predicate subdomain
1067 // boundary distance but are inside the extended bounding box. Most cells
1068 // might be outside the extended bounding box, so we could skip them. Those
1069 // cells that are inside the extended bounding box but are not part of the
1070 // predicate subdomain are possible candidates to be within the distance to
1071 // the boundary cells of the predicate subdomain.
1072 for (const auto &cell : mesh.active_cell_iterators())
1073 {
1074 // Ignore all the cells that are in the predicate subdomain
1075 if (predicate(cell))
1076 continue;
1077
1078 const std::pair<Point<spacedim>, double> &cell_enclosing_ball =
1079 cell->enclosing_ball();
1080
1081 const Point<spacedim> cell_enclosing_ball_center =
1082 cell_enclosing_ball.first;
1083 const double cell_enclosing_ball_radius = cell_enclosing_ball.second;
1084
1085 bool cell_inside = true; // reset for each cell
1086
1087 for (unsigned int d = 0; d < spacedim; ++d)
1088 cell_inside &=
1089 (cell_enclosing_ball_center[d] + cell_enclosing_ball_radius >
1090 bounding_box.first[d]) &&
1091 (cell_enclosing_ball_center[d] - cell_enclosing_ball_radius <
1092 bounding_box.second[d]);
1093 // cell_inside is true if its enclosing ball intersects the extended
1094 // bounding box
1095
1096 // Ignore all the cells that are outside the extended bounding box
1097 if (cell_inside)
1098 for (unsigned int i = 0; i < subdomain_boundary_cells_radii.size();
1099 ++i)
1100 if (cell_enclosing_ball_center.distance_square(
1101 subdomain_boundary_cells_centers[i]) <
1102 Utilities::fixed_power<2>(cell_enclosing_ball_radius +
1103 subdomain_boundary_cells_radii[i] +
1104 layer_thickness + DOUBLE_EPSILON))
1105 {
1106 active_cell_layer_within_distance.push_back(cell);
1107 break; // Exit the loop checking all the remaining subdomain
1108 // boundary cells
1109 }
1110 }
1111 return active_cell_layer_within_distance;
1112 }
1113
1114
1115
1116 template <typename MeshType>
1118 std::vector<
1119 typename MeshType::
1120 active_cell_iterator> compute_ghost_cell_layer_within_distance(const MeshType
1121 &mesh,
1122 const double
1123 layer_thickness)
1124 {
1125 IteratorFilters::LocallyOwnedCell locally_owned_cell_predicate;
1126 std::function<bool(const typename MeshType::active_cell_iterator &)>
1127 predicate(locally_owned_cell_predicate);
1128
1129 const std::vector<typename MeshType::active_cell_iterator>
1130 ghost_cell_layer_within_distance =
1132 predicate,
1133 layer_thickness);
1134
1135 // Check that we never return locally owned or artificial cells
1136 // What is left should only be the ghost cells
1137 Assert(
1138 contains_locally_owned_cells<MeshType>(
1139 ghost_cell_layer_within_distance) == false,
1140 ExcMessage(
1141 "Ghost cells within layer_thickness contains locally owned cells."));
1142 Assert(
1143 contains_artificial_cells<MeshType>(ghost_cell_layer_within_distance) ==
1144 false,
1145 ExcMessage(
1146 "Ghost cells within layer_thickness contains artificial cells. "
1147 "The function compute_ghost_cell_layer_within_distance "
1148 "is probably called while using parallel::distributed::Triangulation. "
1149 "In such case please refer to the description of this function."));
1150
1151 return ghost_cell_layer_within_distance;
1152 }
1153
1154
1155
1156 template <typename MeshType>
1158 std::pair<
1160 Point<MeshType::
1161 space_dimension>> compute_bounding_box(const MeshType &mesh,
1162 const std::function<bool(
1163 const typename MeshType::
1164 active_cell_iterator &)>
1165 &predicate)
1166 {
1167 std::vector<bool> locally_active_vertices_on_subdomain(
1168 mesh.get_triangulation().n_vertices(), false);
1169
1170 const unsigned int spacedim = MeshType::space_dimension;
1171
1172 // Two extreme points can define the bounding box
1173 // around the active cells that conform to the given predicate.
1175
1176 // initialize minp and maxp with the first predicate cell center
1177 for (const auto &cell : mesh.active_cell_iterators())
1178 if (predicate(cell))
1179 {
1180 minp = cell->center();
1181 maxp = cell->center();
1182 break;
1183 }
1184
1185 // Run through all the cells to check if it belongs to predicate domain,
1186 // if it belongs to the predicate domain, extend the bounding box.
1187 for (const auto &cell : mesh.active_cell_iterators())
1188 if (predicate(cell)) // True predicate --> Part of subdomain
1189 for (const unsigned int v : cell->vertex_indices())
1190 if (locally_active_vertices_on_subdomain[cell->vertex_index(v)] ==
1191 false)
1192 {
1193 locally_active_vertices_on_subdomain[cell->vertex_index(v)] =
1194 true;
1195 for (unsigned int d = 0; d < spacedim; ++d)
1196 {
1197 minp[d] = std::min(minp[d], cell->vertex(v)[d]);
1198 maxp[d] = std::max(maxp[d], cell->vertex(v)[d]);
1199 }
1200 }
1201
1202 return std::make_pair(minp, maxp);
1203 }
1204
1205
1206
1207 template <typename MeshType>
1209 std::list<std::pair<
1210 typename MeshType::cell_iterator,
1211 typename MeshType::cell_iterator>> get_finest_common_cells(const MeshType
1212 &mesh_1,
1213 const MeshType
1214 &mesh_2)
1215 {
1216 Assert(have_same_coarse_mesh(mesh_1, mesh_2),
1217 ExcMessage("The two meshes must be represent triangulations that "
1218 "have the same coarse meshes"));
1219 // We will allow the output to contain ghost cells when we have shared
1220 // Triangulations (i.e., so that each processor will get exactly the same
1221 // list of cell pairs), but not when we have two distributed
1222 // Triangulations (so that all active cells are partitioned by processor).
1223 // Non-parallel Triangulations have no ghost or artificial cells, so they
1224 // work the same way as shared Triangulations here.
1225 bool remove_ghost_cells = false;
1226#ifdef DEAL_II_WITH_MPI
1227 {
1228 constexpr int dim = MeshType::dimension;
1229 constexpr int spacedim = MeshType::space_dimension;
1231 *>(&mesh_1.get_triangulation()) != nullptr ||
1233 *>(&mesh_2.get_triangulation()) != nullptr)
1234 {
1235 Assert(&mesh_1.get_triangulation() == &mesh_2.get_triangulation(),
1236 ExcMessage("This function can only be used with meshes "
1237 "corresponding to distributed Triangulations when "
1238 "both Triangulations are equal."));
1239 remove_ghost_cells = true;
1240 }
1241 }
1242#endif
1243
1244 // the algorithm goes as follows: first, we fill a list with pairs of
1245 // iterators common to the two meshes on the coarsest level. then we
1246 // traverse the list; each time, we find a pair of iterators for which
1247 // both correspond to non-active cells, we delete this item and push the
1248 // pairs of iterators to their children to the back. if these again both
1249 // correspond to non-active cells, we will get to the later on for further
1250 // consideration
1251 using CellList = std::list<std::pair<typename MeshType::cell_iterator,
1252 typename MeshType::cell_iterator>>;
1253 CellList cell_list;
1254
1255 // first push the coarse level cells
1256 typename MeshType::cell_iterator cell_1 = mesh_1.begin(0),
1257 cell_2 = mesh_2.begin(0);
1258 for (; cell_1 != mesh_1.end(0); ++cell_1, ++cell_2)
1259 cell_list.emplace_back(cell_1, cell_2);
1260
1261 // then traverse list as described above
1262 typename CellList::iterator cell_pair = cell_list.begin();
1263 while (cell_pair != cell_list.end())
1264 {
1265 // if both cells in this pair have children, then erase this element
1266 // and push their children instead
1267 if (cell_pair->first->has_children() &&
1268 cell_pair->second->has_children())
1269 {
1270 Assert(cell_pair->first->refinement_case() ==
1271 cell_pair->second->refinement_case(),
1273 for (unsigned int c = 0; c < cell_pair->first->n_children(); ++c)
1274 cell_list.emplace_back(cell_pair->first->child(c),
1275 cell_pair->second->child(c));
1276
1277 // erasing an iterator keeps other iterators valid, so already
1278 // advance the present iterator by one and then delete the element
1279 // we've visited before
1280 const auto previous_cell_pair = cell_pair;
1281 ++cell_pair;
1282 cell_list.erase(previous_cell_pair);
1283 }
1284 else
1285 {
1286 // at least one cell is active
1287 if (remove_ghost_cells &&
1288 ((cell_pair->first->is_active() &&
1289 !cell_pair->first->is_locally_owned()) ||
1290 (cell_pair->second->is_active() &&
1291 !cell_pair->second->is_locally_owned())))
1292 {
1293 // we only exclude ghost cells for distributed Triangulations
1294 const auto previous_cell_pair = cell_pair;
1295 ++cell_pair;
1296 cell_list.erase(previous_cell_pair);
1297 }
1298 else
1299 ++cell_pair;
1300 }
1301 }
1302
1303 // just to make sure everything is ok, validate that all pairs have at
1304 // least one active iterator or have different refinement_cases
1305 for (cell_pair = cell_list.begin(); cell_pair != cell_list.end();
1306 ++cell_pair)
1307 Assert(cell_pair->first->is_active() || cell_pair->second->is_active() ||
1308 (cell_pair->first->refinement_case() !=
1309 cell_pair->second->refinement_case()),
1311
1312 return cell_list;
1313 }
1314
1315
1316
1317 template <int dim, int spacedim>
1318 bool
1320 const Triangulation<dim, spacedim> &mesh_2)
1321 {
1322 // make sure the two meshes have
1323 // the same number of coarse cells
1324 if (mesh_1.n_cells(0) != mesh_2.n_cells(0))
1325 return false;
1326
1327 // if so, also make sure they have
1328 // the same vertices on the cells
1329 // of the coarse mesh
1331 mesh_1.begin(0),
1332 cell_2 =
1333 mesh_2.begin(0),
1334 endc = mesh_1.end(0);
1335 for (; cell_1 != endc; ++cell_1, ++cell_2)
1336 {
1337 if (cell_1->n_vertices() != cell_2->n_vertices())
1338 return false;
1339 for (const unsigned int v : cell_1->vertex_indices())
1340 if (cell_1->vertex(v) != cell_2->vertex(v))
1341 return false;
1342 }
1343
1344 // if we've gotten through all
1345 // this, then the meshes really
1346 // seem to have a common coarse
1347 // mesh
1348 return true;
1349 }
1350
1351
1352
1353 template <typename MeshType>
1355 bool have_same_coarse_mesh(const MeshType &mesh_1, const MeshType &mesh_2)
1356 {
1357 return have_same_coarse_mesh(mesh_1.get_triangulation(),
1358 mesh_2.get_triangulation());
1359 }
1360
1361
1362
1363 template <int dim, int spacedim>
1364 std::pair<typename DoFHandler<dim, spacedim>::active_cell_iterator,
1365 Point<dim>>
1368 const DoFHandler<dim, spacedim> &mesh,
1369 const Point<spacedim> &p,
1370 const double tolerance)
1371 {
1372 Assert((mapping.size() == 1) ||
1373 (mapping.size() == mesh.get_fe_collection().size()),
1374 ExcMessage("Mapping collection needs to have either size 1 "
1375 "or size equal to the number of elements in "
1376 "the FECollection."));
1377
1378 using cell_iterator =
1380
1381 std::pair<cell_iterator, Point<dim>> best_cell;
1382 // If we have only one element in the MappingCollection,
1383 // we use find_active_cell_around_point using only one
1384 // mapping.
1385 if (mapping.size() == 1)
1386 {
1387 const std::vector<bool> marked_vertices = {};
1389 mapping[0], mesh, p, marked_vertices, tolerance);
1390 }
1391 else
1392 {
1393 // The best distance is set to the
1394 // maximum allowable distance from
1395 // the unit cell
1396 double best_distance = tolerance;
1397 int best_level = -1;
1398
1399
1400 // Find closest vertex and determine
1401 // all adjacent cells
1402 unsigned int vertex = find_closest_vertex(mesh, p);
1403
1404 std::vector<cell_iterator> adjacent_cells_tmp =
1405 find_cells_adjacent_to_vertex(mesh, vertex);
1406
1407 // Make sure that we have found
1408 // at least one cell adjacent to vertex.
1409 Assert(adjacent_cells_tmp.size() > 0, ExcInternalError());
1410
1411 // Copy all the cells into a std::set
1412 std::set<cell_iterator> adjacent_cells(adjacent_cells_tmp.begin(),
1413 adjacent_cells_tmp.end());
1414 std::set<cell_iterator> searched_cells;
1415
1416 // Determine the maximal number of cells
1417 // in the grid.
1418 // As long as we have not found
1419 // the cell and have not searched
1420 // every cell in the triangulation,
1421 // we keep on looking.
1422 const auto n_cells = mesh.get_triangulation().n_cells();
1423 bool found = false;
1424 unsigned int cells_searched = 0;
1425 while (!found && cells_searched < n_cells)
1426 {
1427 for (const auto &cell : adjacent_cells)
1428 {
1429 try
1430 {
1431 const Point<dim> p_cell =
1432 mapping[cell->active_fe_index()]
1433 .transform_real_to_unit_cell(cell, p);
1434
1435
1436 // calculate the Euclidean norm of
1437 // the distance vector to the unit cell.
1438 const double dist =
1439 cell->reference_cell().closest_point(p_cell).distance(
1440 p_cell);
1441
1442 // We compare if the point is inside the
1443 // unit cell (or at least not too far
1444 // outside). If it is, it is also checked
1445 // that the cell has a more refined state
1446 if (dist < best_distance ||
1447 (dist == best_distance && cell->level() > best_level))
1448 {
1449 found = true;
1450 best_distance = dist;
1451 best_level = cell->level();
1452 best_cell = std::make_pair(cell, p_cell);
1453 }
1454 }
1455 catch (
1457 {
1458 // ok, the transformation
1459 // failed presumably
1460 // because the point we
1461 // are looking for lies
1462 // outside the current
1463 // cell. this means that
1464 // the current cell can't
1465 // be the cell around the
1466 // point, so just ignore
1467 // this cell and move on
1468 // to the next
1469 }
1470 }
1471 // update the number of cells searched
1472 cells_searched += adjacent_cells.size();
1473 // if we have not found the cell in
1474 // question and have not yet searched every
1475 // cell, we expand our search to
1476 // all the not already searched neighbors of
1477 // the cells in adjacent_cells.
1478 if (!found && cells_searched < n_cells)
1479 {
1480 find_active_cell_around_point_internal<dim,
1481 DoFHandler,
1482 spacedim>(
1483 mesh, searched_cells, adjacent_cells);
1484 }
1485 }
1486 }
1487
1488 return best_cell;
1489 }
1490
1491
1492 template <typename MeshType>
1494 std::vector<typename MeshType::active_cell_iterator> get_patch_around_cell(
1495 const typename MeshType::active_cell_iterator &cell)
1496 {
1497 Assert(cell->is_locally_owned(),
1498 ExcMessage("This function only makes sense if the cell for "
1499 "which you are asking for a patch, is locally "
1500 "owned."));
1501
1502 std::vector<typename MeshType::active_cell_iterator> patch;
1503 patch.push_back(cell);
1504 for (const unsigned int face_number : cell->face_indices())
1505 if (cell->face(face_number)->at_boundary() == false)
1506 {
1507 if (cell->neighbor(face_number)->has_children() == false)
1508 patch.push_back(cell->neighbor(face_number));
1509 else
1510 // the neighbor is refined. in 2d/3d, we can simply ask for the
1511 // children of the neighbor because they can not be further refined
1512 // and, consequently, the children is active
1513 if (MeshType::dimension > 1)
1514 {
1515 for (unsigned int subface = 0;
1516 subface < cell->face(face_number)->n_children();
1517 ++subface)
1518 patch.push_back(
1519 cell->neighbor_child_on_subface(face_number, subface));
1520 }
1521 else
1522 {
1523 // in 1d, we need to work a bit harder: iterate until we find
1524 // the child by going from cell to child to child etc
1525 typename MeshType::cell_iterator neighbor =
1526 cell->neighbor(face_number);
1527 while (neighbor->has_children())
1528 neighbor = neighbor->child(1 - face_number);
1529
1530 Assert(neighbor->neighbor(1 - face_number) == cell,
1532 patch.push_back(neighbor);
1533 }
1534 }
1535 return patch;
1536 }
1537
1538
1539
1540 template <class Container>
1541 std::vector<typename Container::cell_iterator>
1543 const std::vector<typename Container::active_cell_iterator> &patch)
1544 {
1545 Assert(patch.size() > 0,
1546 ExcMessage(
1547 "Vector containing patch cells should not be an empty vector!"));
1548 // In order to extract the set of cells with the coarsest common level from
1549 // the give vector of cells: First it finds the number associated with the
1550 // minimum level of refinement, namely "min_level"
1551 int min_level = patch[0]->level();
1552
1553 for (unsigned int i = 0; i < patch.size(); ++i)
1554 min_level = std::min(min_level, patch[i]->level());
1555 std::set<typename Container::cell_iterator> uniform_cells;
1556 typename std::vector<
1557 typename Container::active_cell_iterator>::const_iterator patch_cell;
1558 // it loops through all cells of the input vector
1559 for (patch_cell = patch.begin(); patch_cell != patch.end(); ++patch_cell)
1560 {
1561 // If the refinement level of each cell i the loop be equal to the
1562 // min_level, so that that cell inserted into the set of uniform_cells,
1563 // as the set of cells with the coarsest common refinement level
1564 if ((*patch_cell)->level() == min_level)
1565 uniform_cells.insert(*patch_cell);
1566 else
1567 // If not, it asks for the parent of the cell, until it finds the
1568 // parent cell with the refinement level equal to the min_level and
1569 // inserts that parent cell into the set of uniform_cells, as the
1570 // set of cells with the coarsest common refinement level.
1571 {
1572 typename Container::cell_iterator parent = *patch_cell;
1573
1574 while (parent->level() > min_level)
1575 parent = parent->parent();
1576 uniform_cells.insert(parent);
1577 }
1578 }
1579
1580 return std::vector<typename Container::cell_iterator>(uniform_cells.begin(),
1581 uniform_cells.end());
1582 }
1583
1584
1585
1586 template <class Container>
1587 void
1589 const std::vector<typename Container::active_cell_iterator> &patch,
1591 &local_triangulation,
1592 std::map<
1593 typename Triangulation<Container::dimension,
1594 Container::space_dimension>::active_cell_iterator,
1595 typename Container::active_cell_iterator> &patch_to_global_tria_map)
1596
1597 {
1598 const std::vector<typename Container::cell_iterator> uniform_cells =
1599 get_cells_at_coarsest_common_level<Container>(patch);
1600 // First it creates triangulation from the vector of "uniform_cells"
1601 local_triangulation.clear();
1602 std::vector<Point<Container::space_dimension>> vertices;
1603 const unsigned int n_uniform_cells = uniform_cells.size();
1604 std::vector<CellData<Container::dimension>> cells(n_uniform_cells);
1605 unsigned int k = 0; // for enumerating cells
1606 unsigned int i = 0; // for enumerating vertices
1607 typename std::vector<typename Container::cell_iterator>::const_iterator
1608 uniform_cell;
1609 for (uniform_cell = uniform_cells.begin();
1610 uniform_cell != uniform_cells.end();
1611 ++uniform_cell)
1612 {
1613 for (const unsigned int v : (*uniform_cell)->vertex_indices())
1614 {
1616 (*uniform_cell)->vertex(v);
1617 bool repeat_vertex = false;
1618
1619 for (unsigned int m = 0; m < i; ++m)
1620 {
1621 if (position == vertices[m])
1622 {
1623 repeat_vertex = true;
1624 cells[k].vertices[v] = m;
1625 break;
1626 }
1627 }
1628 if (repeat_vertex == false)
1629 {
1630 vertices.push_back(position);
1631 cells[k].vertices[v] = i;
1632 i = i + 1;
1633 }
1634
1635 } // for vertices_per_cell
1636 k = k + 1;
1637 }
1638 local_triangulation.create_triangulation(vertices, cells, SubCellData());
1639 Assert(local_triangulation.n_active_cells() == uniform_cells.size(),
1641 local_triangulation.clear_user_flags();
1642 unsigned int index = 0;
1643 // Create a map between cells of class DoFHandler into class Triangulation
1644 std::map<typename Triangulation<Container::dimension,
1645 Container::space_dimension>::cell_iterator,
1646 typename Container::cell_iterator>
1647 patch_to_global_tria_map_tmp;
1648 for (typename Triangulation<Container::dimension,
1649 Container::space_dimension>::cell_iterator
1650 coarse_cell = local_triangulation.begin();
1651 coarse_cell != local_triangulation.end();
1652 ++coarse_cell, ++index)
1653 {
1654 patch_to_global_tria_map_tmp.insert(
1655 std::make_pair(coarse_cell, uniform_cells[index]));
1656 // To ensure that the cells with the same coordinates (here, we compare
1657 // their centers) are mapped into each other.
1658
1659 Assert(coarse_cell->center().distance(uniform_cells[index]->center()) <=
1660 1e-15 * coarse_cell->diameter(),
1662 }
1663 bool refinement_necessary;
1664 // In this loop we start to do refinement on the above coarse triangulation
1665 // to reach to the same level of refinement as the patch cells are really on
1666 do
1667 {
1668 refinement_necessary = false;
1669 for (const auto &active_tria_cell :
1670 local_triangulation.active_cell_iterators())
1671 {
1672 if (patch_to_global_tria_map_tmp[active_tria_cell]->has_children())
1673 {
1674 active_tria_cell->set_refine_flag();
1675 refinement_necessary = true;
1676 }
1677 else
1678 for (unsigned int i = 0; i < patch.size(); ++i)
1679 {
1680 // Even though vertices may not be exactly the same, the
1681 // appropriate cells will match since == for TriAccessors
1682 // checks only cell level and index.
1683 if (patch_to_global_tria_map_tmp[active_tria_cell] ==
1684 patch[i])
1685 {
1686 // adjust the cell vertices of the local_triangulation to
1687 // match cell vertices of the global triangulation
1688 for (const unsigned int v :
1689 active_tria_cell->vertex_indices())
1690 active_tria_cell->vertex(v) = patch[i]->vertex(v);
1691
1692 Assert(active_tria_cell->center().distance(
1693 patch_to_global_tria_map_tmp[active_tria_cell]
1694 ->center()) <=
1695 1e-15 * active_tria_cell->diameter(),
1697
1698 active_tria_cell->set_user_flag();
1699 break;
1700 }
1701 }
1702 }
1703
1704 if (refinement_necessary)
1705 {
1706 local_triangulation.execute_coarsening_and_refinement();
1707
1708 for (typename Triangulation<
1709 Container::dimension,
1710 Container::space_dimension>::cell_iterator cell =
1711 local_triangulation.begin();
1712 cell != local_triangulation.end();
1713 ++cell)
1714 {
1715 if (patch_to_global_tria_map_tmp.find(cell) !=
1716 patch_to_global_tria_map_tmp.end())
1717 {
1718 if (cell->has_children())
1719 {
1720 // Note: Since the cell got children, then it should not
1721 // be in the map anymore children may be added into the
1722 // map, instead
1723
1724 // these children may not yet be in the map
1725 for (unsigned int c = 0; c < cell->n_children(); ++c)
1726 {
1727 if (patch_to_global_tria_map_tmp.find(cell->child(
1728 c)) == patch_to_global_tria_map_tmp.end())
1729 {
1730 patch_to_global_tria_map_tmp.insert(
1731 std::make_pair(
1732 cell->child(c),
1733 patch_to_global_tria_map_tmp[cell]->child(
1734 c)));
1735
1736 // One might be tempted to assert that the cell
1737 // being added here has the same center as the
1738 // equivalent cell in the global triangulation,
1739 // but it may not be the case. For
1740 // triangulations that have been perturbed or
1741 // smoothed, the cell indices and levels may be
1742 // the same, but the vertex locations may not.
1743 // We adjust the vertices of the cells that have
1744 // no children (ie the active cells) to be
1745 // consistent with the global triangulation
1746 // later on and add assertions at that time
1747 // to guarantee the cells in the
1748 // local_triangulation are physically at the
1749 // same locations of the cells in the patch of
1750 // the global triangulation.
1751 }
1752 }
1753 // The parent cell whose children were added
1754 // into the map should be deleted from the map
1755 patch_to_global_tria_map_tmp.erase(cell);
1756 }
1757 }
1758 }
1759 }
1760 }
1761 while (refinement_necessary);
1762
1763
1764 // Last assertion check to make sure we have the right cells and centers
1765 // in the map, and hence the correct vertices of the triangulation
1766 for (typename Triangulation<Container::dimension,
1767 Container::space_dimension>::cell_iterator
1768 cell = local_triangulation.begin();
1769 cell != local_triangulation.end();
1770 ++cell)
1771 {
1772 if (cell->user_flag_set())
1773 {
1774 Assert(patch_to_global_tria_map_tmp.find(cell) !=
1775 patch_to_global_tria_map_tmp.end(),
1777
1778 Assert(cell->center().distance(
1779 patch_to_global_tria_map_tmp[cell]->center()) <=
1780 1e-15 * cell->diameter(),
1782 }
1783 }
1784
1785
1786 typename std::map<
1787 typename Triangulation<Container::dimension,
1788 Container::space_dimension>::cell_iterator,
1789 typename Container::cell_iterator>::iterator
1790 map_tmp_it = patch_to_global_tria_map_tmp.begin(),
1791 map_tmp_end = patch_to_global_tria_map_tmp.end();
1792 // Now we just need to take the temporary map of pairs of type cell_iterator
1793 // "patch_to_global_tria_map_tmp" making pair of active_cell_iterators so
1794 // that filling out the final map "patch_to_global_tria_map"
1795 for (; map_tmp_it != map_tmp_end; ++map_tmp_it)
1796 patch_to_global_tria_map[map_tmp_it->first] = map_tmp_it->second;
1797 }
1798
1799
1800
1801 template <int dim, int spacedim>
1802 std::map<
1804 std::vector<typename DoFHandler<dim, spacedim>::active_cell_iterator>>
1806 {
1807 // This is the map from global_dof_index to
1808 // a set of cells on patch. We first map into
1809 // a set because it is very likely that we
1810 // will attempt to add a cell more than once
1811 // to a particular patch and we want to preserve
1812 // uniqueness of cell iterators. std::set does this
1813 // automatically for us. Later after it is all
1814 // constructed, we will copy to a map of vectors
1815 // since that is the preferred output for other
1816 // functions.
1817 std::map<types::global_dof_index,
1818 std::set<typename DoFHandler<dim, spacedim>::active_cell_iterator>>
1819 dof_to_set_of_cells_map;
1820
1821 std::vector<types::global_dof_index> local_dof_indices;
1822 std::vector<types::global_dof_index> local_face_dof_indices;
1823 std::vector<types::global_dof_index> local_line_dof_indices;
1824
1825 // a place to save the dof_handler user flags and restore them later
1826 // to maintain const of dof_handler.
1827 std::vector<bool> user_flags;
1828
1829
1830 // in 3d, we need pointers from active lines to the
1831 // active parent lines, so we construct it as needed.
1832 std::map<typename DoFHandler<dim, spacedim>::active_line_iterator,
1834 lines_to_parent_lines_map;
1835 if (dim == 3)
1836 {
1837 // save user flags as they will be modified and then later restored
1838 dof_handler.get_triangulation().save_user_flags(user_flags);
1839 const_cast<::Triangulation<dim, spacedim> &>(
1840 dof_handler.get_triangulation())
1841 .clear_user_flags();
1842
1843
1845 cell = dof_handler.begin_active(),
1846 endc = dof_handler.end();
1847 for (; cell != endc; ++cell)
1848 {
1849 // We only want lines that are locally_relevant
1850 // although it doesn't hurt to have lines that
1851 // are children of ghost cells since there are
1852 // few and we don't have to use them.
1853 if (cell->is_artificial() == false)
1854 {
1855 for (unsigned int l = 0; l < cell->n_lines(); ++l)
1856 if (cell->line(l)->has_children())
1857 for (unsigned int c = 0; c < cell->line(l)->n_children();
1858 ++c)
1859 {
1860 lines_to_parent_lines_map[cell->line(l)->child(c)] =
1861 cell->line(l);
1862 // set flags to know that child
1863 // line has an active parent.
1864 cell->line(l)->child(c)->set_user_flag();
1865 }
1866 }
1867 }
1868 }
1869
1870
1871 // We loop through all cells and add cell to the
1872 // map for the dofs that it immediately touches
1873 // and then account for all the other dofs of
1874 // which it is a part, mainly the ones that must
1875 // be added on account of adaptivity hanging node
1876 // constraints.
1878 cell = dof_handler.begin_active(),
1879 endc = dof_handler.end();
1880 for (; cell != endc; ++cell)
1881 {
1882 // Need to loop through all cells that could
1883 // be in the patch of dofs on locally_owned
1884 // cells including ghost cells
1885 if (cell->is_artificial() == false)
1886 {
1887 const unsigned int n_dofs_per_cell =
1888 cell->get_fe().n_dofs_per_cell();
1889 local_dof_indices.resize(n_dofs_per_cell);
1890
1891 // Take care of adding cell pointer to each
1892 // dofs that exists on cell.
1893 cell->get_dof_indices(local_dof_indices);
1894 for (unsigned int i = 0; i < n_dofs_per_cell; ++i)
1895 dof_to_set_of_cells_map[local_dof_indices[i]].insert(cell);
1896
1897 // In the case of the adjacent cell (over
1898 // faces or edges) being more refined, we
1899 // want to add all of the children to the
1900 // patch since the support function at that
1901 // dof could be non-zero along that entire
1902 // face (or line).
1903
1904 // Take care of dofs on neighbor faces
1905 for (const unsigned int f : cell->face_indices())
1906 {
1907 if (cell->face(f)->has_children())
1908 {
1909 for (unsigned int c = 0; c < cell->face(f)->n_children();
1910 ++c)
1911 {
1912 // Add cell to dofs of all subfaces
1913 //
1914 // *-------------------*----------*---------*
1915 // | | add cell | |
1916 // | |<- to dofs| |
1917 // | |of subface| |
1918 // | cell *----------*---------*
1919 // | | add cell | |
1920 // | |<- to dofs| |
1921 // | |of subface| |
1922 // *-------------------*----------*---------*
1923 //
1924 Assert(cell->face(f)->child(c)->has_children() == false,
1926
1927 const unsigned int n_dofs_per_face =
1928 cell->get_fe().n_dofs_per_face(f, c);
1929 local_face_dof_indices.resize(n_dofs_per_face);
1930
1931 cell->face(f)->child(c)->get_dof_indices(
1932 local_face_dof_indices);
1933 for (unsigned int i = 0; i < n_dofs_per_face; ++i)
1934 dof_to_set_of_cells_map[local_face_dof_indices[i]]
1935 .insert(cell);
1936 }
1937 }
1938 else if ((cell->face(f)->at_boundary() == false) &&
1939 (cell->neighbor_is_coarser(f)))
1940 {
1941 // Add cell to dofs of parent face and all
1942 // child faces of parent face
1943 //
1944 // *-------------------*----------*---------*
1945 // | | | |
1946 // | | cell | |
1947 // | add cell | | |
1948 // | to dofs -> *----------*---------*
1949 // | of parent | add cell | |
1950 // | face |<- to dofs| |
1951 // | |of subface| |
1952 // *-------------------*----------*---------*
1953 //
1954
1955 // Add cell to all dofs of parent face
1956 auto [face_no, subface] =
1957 cell->neighbor_of_coarser_neighbor(f);
1958
1959
1960 const unsigned int n_dofs_per_face =
1961 cell->get_fe().n_dofs_per_face(face_no);
1962 local_face_dof_indices.resize(n_dofs_per_face);
1963
1964 cell->neighbor(f)->face(face_no)->get_dof_indices(
1965 local_face_dof_indices);
1966 for (unsigned int i = 0; i < n_dofs_per_face; ++i)
1967 dof_to_set_of_cells_map[local_face_dof_indices[i]].insert(
1968 cell);
1969
1970 // Add cell to all dofs of children of
1971 // parent face
1972 for (unsigned int c = 0;
1973 c < cell->neighbor(f)->face(face_no)->n_children();
1974 ++c)
1975 {
1976 if (c != subface) // don't repeat work on dofs of
1977 // original cell
1978 {
1979 const unsigned int n_dofs_per_face =
1980 cell->get_fe().n_dofs_per_face(face_no, c);
1981 local_face_dof_indices.resize(n_dofs_per_face);
1982
1983 Assert(cell->neighbor(f)
1984 ->face(face_no)
1985 ->child(c)
1986 ->has_children() == false,
1988 cell->neighbor(f)
1989 ->face(face_no)
1990 ->child(c)
1991 ->get_dof_indices(local_face_dof_indices);
1992 for (unsigned int i = 0; i < n_dofs_per_face; ++i)
1993 dof_to_set_of_cells_map[local_face_dof_indices[i]]
1994 .insert(cell);
1995 }
1996 }
1997 }
1998 }
1999
2000
2001 // If 3d, take care of dofs on lines in the
2002 // same pattern as faces above. That is, if
2003 // a cell's line has children, distribute
2004 // cell to dofs of children of line, and
2005 // if cell's line has an active parent, then
2006 // distribute cell to dofs on parent line
2007 // and dofs on all children of parent line.
2008 if (dim == 3)
2009 {
2010 for (unsigned int l = 0; l < cell->n_lines(); ++l)
2011 {
2012 if (cell->line(l)->has_children())
2013 {
2014 for (unsigned int c = 0;
2015 c < cell->line(l)->n_children();
2016 ++c)
2017 {
2018 Assert(cell->line(l)->child(c)->has_children() ==
2019 false,
2021
2022 // dofs_per_line returns number of dofs
2023 // on line not including the vertices of the line.
2024 const unsigned int n_dofs_per_line =
2025 2 * cell->get_fe().n_dofs_per_vertex() +
2026 cell->get_fe().n_dofs_per_line();
2027 local_line_dof_indices.resize(n_dofs_per_line);
2028
2029 cell->line(l)->child(c)->get_dof_indices(
2030 local_line_dof_indices);
2031 for (unsigned int i = 0; i < n_dofs_per_line; ++i)
2032 dof_to_set_of_cells_map[local_line_dof_indices[i]]
2033 .insert(cell);
2034 }
2035 }
2036 // user flag was set above to denote that
2037 // an active parent line exists so add
2038 // cell to dofs of parent and all it's
2039 // children
2040 else if (cell->line(l)->user_flag_set() == true)
2041 {
2043 parent_line =
2044 lines_to_parent_lines_map[cell->line(l)];
2045 Assert(parent_line->has_children(), ExcInternalError());
2046
2047 // dofs_per_line returns number of dofs
2048 // on line not including the vertices of the line.
2049 const unsigned int n_dofs_per_line =
2050 2 * cell->get_fe().n_dofs_per_vertex() +
2051 cell->get_fe().n_dofs_per_line();
2052 local_line_dof_indices.resize(n_dofs_per_line);
2053
2054 parent_line->get_dof_indices(local_line_dof_indices);
2055 for (unsigned int i = 0; i < n_dofs_per_line; ++i)
2056 dof_to_set_of_cells_map[local_line_dof_indices[i]]
2057 .insert(cell);
2058
2059 for (unsigned int c = 0; c < parent_line->n_children();
2060 ++c)
2061 {
2062 Assert(parent_line->child(c)->has_children() ==
2063 false,
2065
2066 const unsigned int n_dofs_per_line =
2067 2 * cell->get_fe().n_dofs_per_vertex() +
2068 cell->get_fe().n_dofs_per_line();
2069 local_line_dof_indices.resize(n_dofs_per_line);
2070
2071 parent_line->child(c)->get_dof_indices(
2072 local_line_dof_indices);
2073 for (unsigned int i = 0; i < n_dofs_per_line; ++i)
2074 dof_to_set_of_cells_map[local_line_dof_indices[i]]
2075 .insert(cell);
2076 }
2077 }
2078 } // for lines l
2079 } // if dim == 3
2080 } // if cell->is_locally_owned()
2081 } // for cells
2082
2083
2084 if (dim == 3)
2085 {
2086 // finally, restore user flags that were changed above
2087 // to when we constructed the pointers to parent of lines
2088 // Since dof_handler is const, we must leave it unchanged.
2089 const_cast<::Triangulation<dim, spacedim> &>(
2090 dof_handler.get_triangulation())
2091 .load_user_flags(user_flags);
2092 }
2093
2094 // Finally, we copy map of sets to
2095 // map of vectors using the std::vector::assign() function
2096 std::map<
2098 std::vector<typename DoFHandler<dim, spacedim>::active_cell_iterator>>
2099 dof_to_cell_patches;
2100
2101 typename std::map<
2103 std::set<typename DoFHandler<dim, spacedim>::active_cell_iterator>>::
2104 iterator it = dof_to_set_of_cells_map.begin(),
2105 it_end = dof_to_set_of_cells_map.end();
2106 for (; it != it_end; ++it)
2107 dof_to_cell_patches[it->first].assign(it->second.begin(),
2108 it->second.end());
2109
2110 return dof_to_cell_patches;
2111 }
2112
2113 /*
2114 * Internally used in collect_periodic_faces
2115 */
2116 template <typename CellIterator>
2117 void
2119 std::set<std::pair<CellIterator, unsigned int>> &pairs1,
2120 std::set<std::pair<std_cxx20::type_identity_t<CellIterator>, unsigned int>>
2121 &pairs2,
2122 const unsigned int direction,
2123 std::vector<PeriodicFacePair<CellIterator>> &matched_pairs,
2124 const ::Tensor<1, CellIterator::AccessorType::space_dimension>
2125 &offset,
2126 const FullMatrix<double> &matrix,
2127 const double abs_tol = 1e-10)
2128 {
2129 static const int space_dim = CellIterator::AccessorType::space_dimension;
2130 AssertIndexRange(direction, space_dim);
2131
2132 if constexpr (running_in_debug_mode())
2133 {
2134 {
2135 constexpr int dim = CellIterator::AccessorType::dimension;
2136 constexpr int spacedim = CellIterator::AccessorType::space_dimension;
2137 // For parallel::fullydistributed::Triangulation there might be
2138 // unmatched faces on periodic boundaries on the coarse grid. As a
2139 // result this assert is not fulfilled (which is not a bug!). See also
2140 // the discussion in the method collect_periodic_faces.
2141 if (!(((pairs1.size() > 0) &&
2142 (dynamic_cast<const parallel::fullydistributed::
2143 Triangulation<dim, spacedim> *>(
2144 &pairs1.begin()->first->get_triangulation()) != nullptr)) ||
2145 ((pairs2.size() > 0) &&
2146 (dynamic_cast<const parallel::fullydistributed::
2147 Triangulation<dim, spacedim> *>(
2148 &pairs2.begin()->first->get_triangulation()) != nullptr))))
2149 Assert(pairs1.size() == pairs2.size(),
2150 ExcMessage("Unmatched faces on periodic boundaries"));
2151 }
2152 }
2153
2154 unsigned int n_matches = 0;
2155
2156 // Match with a complexity of O(n^2). This could be improved...
2157 using PairIterator =
2158 typename std::set<std::pair<CellIterator, unsigned int>>::const_iterator;
2159 for (PairIterator it1 = pairs1.begin(); it1 != pairs1.end(); ++it1)
2160 {
2161 for (PairIterator it2 = pairs2.begin(); it2 != pairs2.end(); ++it2)
2162 {
2163 const CellIterator cell1 = it1->first;
2164 const CellIterator cell2 = it2->first;
2165 const unsigned int face_idx1 = it1->second;
2166 const unsigned int face_idx2 = it2->second;
2167 if (const std::optional<types::geometric_orientation> orientation =
2168 GridTools::orthogonal_equality(cell1->face(face_idx1),
2169 cell2->face(face_idx2),
2170 direction,
2171 offset,
2172 matrix,
2173 abs_tol))
2174 {
2175 // We have a match, so insert the matching pairs and
2176 // remove the matched cell in pairs2 to speed up the
2177 // matching:
2178 const PeriodicFacePair<CellIterator> matched_face = {
2179 {cell1, cell2},
2180 {face_idx1, face_idx2},
2181 orientation.value(),
2182 matrix};
2183 matched_pairs.push_back(matched_face);
2184 pairs2.erase(it2);
2185 ++n_matches;
2186 break;
2187 }
2188 }
2189 }
2190
2191 // Assure that all faces are matched if
2192 // parallel::fullydistributed::Triangulation is not used. This is related to
2193 // the fact that the faces might not be successfully matched on the coarse
2194 // grid (not a bug!). See also the comment above and in the method
2195 // collect_periodic_faces.
2196 {
2197 constexpr int dim = CellIterator::AccessorType::dimension;
2198 constexpr int spacedim = CellIterator::AccessorType::space_dimension;
2199 if (!(((pairs1.size() > 0) &&
2200 (dynamic_cast<const parallel::fullydistributed::
2201 Triangulation<dim, spacedim> *>(
2202 &pairs1.begin()->first->get_triangulation()) != nullptr)) ||
2203 ((pairs2.size() > 0) &&
2204 (dynamic_cast<
2206 *>(&pairs2.begin()->first->get_triangulation()) != nullptr))))
2207 AssertThrow(n_matches == pairs1.size() && pairs2.empty(),
2208 ExcMessage("Unmatched faces on periodic boundaries"));
2209 }
2210 }
2211
2212
2213
2214 template <typename MeshType>
2217 const MeshType &mesh,
2218 const types::boundary_id b_id,
2219 const unsigned int direction,
2220 std::vector<PeriodicFacePair<typename MeshType::cell_iterator>>
2221 &matched_pairs,
2222 const Tensor<1, MeshType::space_dimension> &offset,
2223 const FullMatrix<double> &matrix,
2224 const double abs_tol)
2225 {
2226 static const int dim = MeshType::dimension;
2227 static const int space_dim = MeshType::space_dimension;
2228 AssertIndexRange(direction, space_dim);
2229 Assert(dim == space_dim, ExcNotImplemented());
2230
2231 // Loop over all cells on the highest level and collect all boundary
2232 // faces 2*direction and 2*direction*1:
2233
2234 std::set<std::pair<typename MeshType::cell_iterator, unsigned int>> pairs1;
2235 std::set<std::pair<typename MeshType::cell_iterator, unsigned int>> pairs2;
2236
2237 for (typename MeshType::cell_iterator cell = mesh.begin(0);
2238 cell != mesh.end(0);
2239 ++cell)
2240 {
2241 const typename MeshType::face_iterator face_1 =
2242 cell->face(2 * direction);
2243 const typename MeshType::face_iterator face_2 =
2244 cell->face(2 * direction + 1);
2245
2246 if (face_1->at_boundary() && face_1->boundary_id() == b_id)
2247 {
2248 const std::pair<typename MeshType::cell_iterator, unsigned int>
2249 pair1 = std::make_pair(cell, 2 * direction);
2250 pairs1.insert(pair1);
2251 }
2252
2253 if (face_2->at_boundary() && face_2->boundary_id() == b_id)
2254 {
2255 const std::pair<typename MeshType::cell_iterator, unsigned int>
2256 pair2 = std::make_pair(cell, 2 * direction + 1);
2257 pairs2.insert(pair2);
2258 }
2259 }
2260
2261 Assert(pairs1.size() == pairs2.size(),
2262 ExcMessage("Unmatched faces on periodic boundaries"));
2263
2264 Assert(pairs1.size() > 0,
2265 ExcMessage("No new periodic face pairs have been found. "
2266 "Are you sure that you've selected the correct boundary "
2267 "id's and that the coarsest level mesh is colorized?"));
2268
2269 [[maybe_unused]] const unsigned int size_old = matched_pairs.size();
2270
2271 // and call match_periodic_face_pairs that does the actual matching:
2273 pairs1, pairs2, direction, matched_pairs, offset, matrix, abs_tol);
2274
2275 if constexpr (running_in_debug_mode())
2276 {
2277 // check for standard orientation
2278 const unsigned int size_new = matched_pairs.size();
2279 for (unsigned int i = size_old; i < size_new; ++i)
2280 {
2281 Assert(matched_pairs[i].orientation ==
2283 ExcMessage(
2284 "Found a face match with non standard orientation. "
2285 "This function is only suitable for meshes with cells "
2286 "in default orientation"));
2287 }
2288 }
2289 }
2290
2291
2292
2293 template <typename MeshType>
2296 const MeshType &mesh,
2297 const types::boundary_id b_id1,
2298 const types::boundary_id b_id2,
2299 const unsigned int direction,
2300 std::vector<PeriodicFacePair<typename MeshType::cell_iterator>>
2301 &matched_pairs,
2302 const Tensor<1, MeshType::space_dimension> &offset,
2303 const FullMatrix<double> &matrix,
2304 const double abs_tol)
2305 {
2306 static const int dim = MeshType::dimension;
2307 static const int space_dim = MeshType::space_dimension;
2308 AssertIndexRange(direction, space_dim);
2309
2310 // Loop over all cells on the highest level and collect all boundary
2311 // faces belonging to b_id1 and b_id2:
2312
2313 std::set<std::pair<typename MeshType::cell_iterator, unsigned int>> pairs1;
2314 std::set<std::pair<typename MeshType::cell_iterator, unsigned int>> pairs2;
2315
2316 for (typename MeshType::cell_iterator cell = mesh.begin(0);
2317 cell != mesh.end(0);
2318 ++cell)
2319 {
2320 for (const unsigned int i : cell->face_indices())
2321 {
2322 const typename MeshType::face_iterator face = cell->face(i);
2323 if (face->at_boundary() && face->boundary_id() == b_id1)
2324 {
2325 const std::pair<typename MeshType::cell_iterator, unsigned int>
2326 pair1 = std::make_pair(cell, i);
2327 pairs1.insert(pair1);
2328 }
2329
2330 if (face->at_boundary() && face->boundary_id() == b_id2)
2331 {
2332 const std::pair<typename MeshType::cell_iterator, unsigned int>
2333 pair2 = std::make_pair(cell, i);
2334 pairs2.insert(pair2);
2335 }
2336 }
2337 }
2338
2339 // Assure that all faces are matched on the coarse grid. This requirement
2340 // can only fulfilled if a process owns the complete coarse grid. This is
2341 // not the case for a parallel::fullydistributed::Triangulation, i.e., this
2342 // requirement has not to be met (consider faces on the outside of a
2343 // ghost cell that are periodic but for which the ghost neighbor doesn't
2344 // exist).
2345 if (!(((pairs1.size() > 0) &&
2346 (dynamic_cast<
2348 *>(&pairs1.begin()->first->get_triangulation()) != nullptr)) ||
2349 ((pairs2.size() > 0) &&
2350 (dynamic_cast<
2352 *>(&pairs2.begin()->first->get_triangulation()) != nullptr))))
2353 Assert(pairs1.size() == pairs2.size(),
2354 ExcMessage("Unmatched faces on periodic boundaries"));
2355
2356 Assert(
2357 (pairs1.size() > 0 ||
2358 (dynamic_cast<
2360 &mesh.begin()->get_triangulation()) != nullptr)),
2361 ExcMessage("No new periodic face pairs have been found. "
2362 "Are you sure that you've selected the correct boundary "
2363 "id's and that the coarsest level mesh is colorized?"));
2364
2365 // and call match_periodic_face_pairs that does the actual matching:
2367 pairs1, pairs2, direction, matched_pairs, offset, matrix, abs_tol);
2368 }
2369
2370
2371
2372 /*
2373 * Internally used in orthogonal_equality
2374 *
2375 * An orthogonal equality test for points:
2376 *
2377 * point1 and point2 are considered equal, if
2378 * matrix.point1 + offset - point2
2379 * is parallel to the unit vector in <direction>
2380 */
2381 template <int spacedim>
2382 bool
2384 const Point<spacedim> &point2,
2385 const unsigned int direction,
2386 const Tensor<1, spacedim> &offset,
2387 const FullMatrix<double> &matrix,
2388 const double abs_tol = 1e-10)
2389 {
2390 AssertIndexRange(direction, spacedim);
2391
2392 Assert(matrix.m() == matrix.n(), ExcInternalError());
2393
2394 Point<spacedim> distance;
2395
2396 if (matrix.m() == spacedim)
2397 for (unsigned int i = 0; i < spacedim; ++i)
2398 for (unsigned int j = 0; j < spacedim; ++j)
2399 distance[i] += matrix(i, j) * point1[j];
2400 else
2401 distance = point1;
2402
2403 distance += offset - point2;
2404
2405 for (unsigned int i = 0; i < spacedim; ++i)
2406 {
2407 // Only compare coordinate-components != direction:
2408 if (i == direction)
2409 continue;
2410
2411 if (std::abs(distance[i]) > abs_tol)
2412 return false;
2413 }
2414
2415 return true;
2416 }
2417
2418
2419
2420 template <typename FaceIterator>
2421 std::optional<types::geometric_orientation>
2423 const FaceIterator &face1,
2424 const FaceIterator &face2,
2425 const unsigned int direction,
2427 const FullMatrix<double> &matrix,
2428 const double abs_tol)
2429 {
2430 Assert(matrix.m() == matrix.n(),
2431 ExcMessage("The supplied matrix must be a square matrix"));
2432 Assert(face1->reference_cell() == face2->reference_cell(),
2433 ExcMessage(
2434 "The faces to be matched must have the same reference cell."));
2435
2436 // Do a full matching of the face vertices:
2437 AssertDimension(face1->n_vertices(), face2->n_vertices());
2438
2439 std::vector<unsigned int> face1_vertices(face1->n_vertices(),
2441 face2_vertices(face2->n_vertices(), numbers::invalid_unsigned_int);
2442
2443 std::set<unsigned int> face2_vertices_set;
2444 for (unsigned int i = 0; i < face1->n_vertices(); ++i)
2445 face2_vertices_set.insert(i);
2446
2447 for (unsigned int i = 0; i < face1->n_vertices(); ++i)
2448 {
2449 for (auto it = face2_vertices_set.begin();
2450 it != face2_vertices_set.end();
2451 ++it)
2452 {
2453 if (orthogonal_equality(face1->vertex(i),
2454 face2->vertex(*it),
2455 direction,
2456 offset,
2457 matrix,
2458 abs_tol))
2459 {
2460 face1_vertices[i] = *it;
2461 face2_vertices[i] = i;
2462 face2_vertices_set.erase(it);
2463 break; // jump out of the innermost loop
2464 }
2465 }
2466 }
2467
2468 if (face2_vertices_set.empty())
2469 {
2470 // Just to be sure, did we fill both arrays with sensible data?
2471 Assert(face1_vertices.end() ==
2472 std::find(face1_vertices.begin(),
2473 face1_vertices.begin() + face1->n_vertices(),
2476 Assert(face2_vertices.end() ==
2477 std::find(face2_vertices.begin(),
2478 face2_vertices.begin() + face1->n_vertices(),
2481
2482 const auto reference_cell = face1->reference_cell();
2483 // We want the relative orientation of face1 with respect to face2 so
2484 // the order is flipped here:
2485 return std::make_optional(reference_cell.get_combined_orientation(
2486 make_array_view(face2_vertices.cbegin(),
2487 face2_vertices.cbegin() + face2->n_vertices()),
2488 make_array_view(face1_vertices.cbegin(),
2489 face1_vertices.cbegin() + face1->n_vertices())));
2490 }
2491 else
2492 return std::nullopt;
2493 }
2494} // namespace GridTools
2495
2496
2497#include "grid/grid_tools_dof_handlers.inst"
2498
2499
*  x_component_mask set(0, true)
*  *  const_iterator()=default
ArrayView< std::remove_reference_t< typename std::iterator_traits< Iterator >::reference >, MemorySpaceType > make_array_view(const Iterator begin, const Iterator end)
cell_iterator end() const
const hp::FECollection< dim, spacedim > & get_fe_collection() const
const FiniteElement< dim, spacedim > & get_fe(const types::fe_index index=0) const
const Triangulation< dim, spacedim > & get_triangulation() const
active_cell_iterator begin_active(const unsigned int level=0) const
unsigned int n_dofs_per_vertex() const
unsigned int n_dofs_per_cell() const
unsigned int n_dofs_per_line() const
unsigned int n_dofs_per_face(unsigned int face_no=0, unsigned int child=0) const
Abstract base class for mapping classes.
Definition mapping.h:318
virtual Point< dim > transform_real_to_unit_cell(const typename Triangulation< dim, spacedim >::cell_iterator &cell, const Point< spacedim > &p) const =0
Definition point.h:111
constexpr numbers::NumberTraits< Number >::real_type distance_square(const Point< dim, Number > &p) const
virtual void clear()
cell_iterator begin(const unsigned int level=0) const
virtual void create_triangulation(const std::vector< Point< spacedim > > &vertices, const std::vector< CellData< dim > > &cells, const SubCellData &subcelldata)
unsigned int n_active_cells() const
void save_user_flags(std::ostream &out) const
const std::vector< Point< spacedim > > & get_vertices() const
cell_iterator end() const
void clear_user_flags()
virtual void execute_coarsening_and_refinement()
unsigned int n_cells() const
const std::vector< bool > & get_used_vertices() const
Triangulation< dim, spacedim > & get_triangulation()
unsigned int size() const
Definition collection.h:314
#define DEAL_II_NAMESPACE_OPEN
Definition config.h:38
constexpr bool running_in_debug_mode()
Definition config.h:76
#define DEAL_II_CXX20_REQUIRES(condition)
Definition config.h:249
#define DEAL_II_NAMESPACE_CLOSE
Definition config.h:39
Point< 2 > second
Definition grid_out.cc:4640
Point< 2 > first
Definition grid_out.cc:4639
unsigned int level
Definition grid_out.cc:4642
AdjacentCell adjacent_cells[2]
unsigned int vertex_indices[2]
IteratorRange< active_cell_iterator > active_cell_iterators() const
static ::ExceptionBase & ExcNotImplemented()
#define Assert(cond, exc)
static ::ExceptionBase & ExcVertexNotUsed(unsigned int arg1)
#define AssertDimension(dim1, dim2)
#define AssertIndexRange(index, range)
static ::ExceptionBase & ExcInternalError()
static ::ExceptionBase & ExcDimensionMismatch(std::size_t arg1, std::size_t arg2)
static ::ExceptionBase & ExcMessage(std::string arg1)
#define AssertThrow(cond, exc)
typename ActiveSelector::line_iterator line_iterator
typename ActiveSelector::active_cell_iterator active_cell_iterator
const Mapping< dim, spacedim > & get_default_linear_mapping(const Triangulation< dim, spacedim > &triangulation)
Definition mapping.cc:314
std::vector< typename Container::cell_iterator > get_cells_at_coarsest_common_level(const std::vector< typename Container::active_cell_iterator > &patch_cells)
void collect_periodic_faces(const MeshType &mesh, const types::boundary_id b_id1, const types::boundary_id b_id2, const unsigned int direction, std::vector< PeriodicFacePair< typename MeshType::cell_iterator > > &matched_pairs, const Tensor< 1, MeshType::space_dimension > &offset=::Tensor< 1, MeshType::space_dimension >(), const FullMatrix< double > &matrix=FullMatrix< double >(), const double abs_tol=1e-10)
unsigned int find_closest_vertex(const std::map< unsigned int, Point< spacedim > > &vertices, const Point< spacedim > &p)
std::pair< typename MeshType< dim, spacedim >::active_cell_iterator, Point< dim > > find_active_cell_around_point(const Mapping< dim, spacedim > &mapping, const MeshType< dim, spacedim > &mesh, const Point< spacedim > &p, const std::vector< bool > &marked_vertices={}, const double tolerance=1.e-10)
std::list< std::pair< typename MeshType::cell_iterator, typename MeshType::cell_iterator > > get_finest_common_cells(const MeshType &mesh_1, const MeshType &mesh_2)
std::vector< typename MeshType::active_cell_iterator > find_cells_adjacent_to_vertex(const MeshType &container, const unsigned int vertex_index)
std::vector< typename MeshType::active_cell_iterator > compute_active_cell_halo_layer(const MeshType &mesh, const std::function< bool(const typename MeshType::active_cell_iterator &)> &predicate)
std::vector< typename MeshType::active_cell_iterator > compute_active_cell_layer_within_distance(const MeshType &mesh, const std::function< bool(const typename MeshType::active_cell_iterator &)> &predicate, const double layer_thickness)
std::vector< typename MeshType::active_cell_iterator > compute_ghost_cell_halo_layer(const MeshType &mesh)
void collect_coinciding_vertices(const Triangulation< dim, spacedim > &tria, std::map< unsigned int, std::vector< unsigned int > > &coinciding_vertex_groups, std::map< unsigned int, unsigned int > &vertex_to_coinciding_vertex_group)
void match_periodic_face_pairs(std::set< std::pair< CellIterator, unsigned int > > &pairs1, std::set< std::pair< std_cxx20::type_identity_t< CellIterator >, unsigned int > > &pairs2, const unsigned int direction, std::vector< PeriodicFacePair< CellIterator > > &matched_pairs, const ::Tensor< 1, CellIterator::AccessorType::space_dimension > &offset, const FullMatrix< double > &matrix, const double abs_tol=1e-10)
std::map< types::global_dof_index, std::vector< typename DoFHandler< dim, spacedim >::active_cell_iterator > > get_dof_to_support_patch_map(DoFHandler< dim, spacedim > &dof_handler)
std::vector< typename MeshType::cell_iterator > compute_cell_halo_layer_on_level(const MeshType &mesh, const std::function< bool(const typename MeshType::cell_iterator &)> &predicate, const unsigned int level)
std::vector< typename MeshType::active_cell_iterator > compute_ghost_cell_layer_within_distance(const MeshType &mesh, const double layer_thickness)
bool have_same_coarse_mesh(const Triangulation< dim, spacedim > &mesh_1, const Triangulation< dim, spacedim > &mesh_2)
std::vector< typename MeshType::active_cell_iterator > get_patch_around_cell(const typename MeshType::active_cell_iterator &cell)
std::vector< std::pair< typename MeshType< dim, spacedim >::active_cell_iterator, Point< dim > > > find_all_active_cells_around_point(const Mapping< dim, spacedim > &mapping, const MeshType< dim, spacedim > &mesh, const Point< spacedim > &p, const double tolerance, const std::pair< typename MeshType< dim, spacedim >::active_cell_iterator, Point< dim > > &first_cell, const std::vector< std::set< typename MeshType< dim, spacedim >::active_cell_iterator > > *vertex_to_cells=nullptr)
void build_triangulation_from_patch(const std::vector< typename Container::active_cell_iterator > &patch, Triangulation< Container::dimension, Container::space_dimension > &local_triangulation, std::map< typename Triangulation< Container::dimension, Container::space_dimension >::active_cell_iterator, typename Container::active_cell_iterator > &patch_to_global_tria_map)
std::optional< types::geometric_orientation > orthogonal_equality(const FaceIterator &face1, const FaceIterator &face2, const unsigned int direction, const Tensor< 1, FaceIterator::AccessorType::space_dimension > &offset=Tensor< 1, FaceIterator::AccessorType::space_dimension >(), const FullMatrix< double > &matrix=FullMatrix< double >(), const double abs_tol=1e-10)
BoundingBox< spacedim > compute_bounding_box(const Triangulation< dim, spacedim > &triangulation)
std::map< unsigned int, Point< spacedim > > extract_used_vertices(const Triangulation< dim, spacedim > &container, const Mapping< dim, spacedim > &mapping=(ReferenceCells::get_hypercube< dim >() .template get_default_linear_mapping< spacedim >()))
constexpr unsigned int invalid_unsigned_int
Definition types.h:228
constexpr types::geometric_orientation default_geometric_orientation
Definition types.h:342
typename type_identity< T >::type type_identity_t
Definition type_traits.h:93
STL namespace.
::VectorizedArray< Number, width > min(const ::VectorizedArray< Number, width > &, const ::VectorizedArray< Number, width > &)
::VectorizedArray< Number, width > max(const ::VectorizedArray< Number, width > &, const ::VectorizedArray< Number, width > &)
::VectorizedArray< Number, width > abs(const ::VectorizedArray< Number, width > &)
Definition types.h:30
unsigned int global_dof_index
Definition types.h:92