Reference documentation for deal.II version GIT relicensing-1062-gc06da148b8 2024-07-15 19:20:02+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
tria.cc
Go to the documentation of this file.
1// ------------------------------------------------------------------------
2//
3// SPDX-License-Identifier: LGPL-2.1-or-later
4// Copyright (C) 2010 - 2024 by the deal.II authors
5//
6// This file is part of the deal.II library.
7//
8// Part of the source code is dual licensed under Apache-2.0 WITH
9// LLVM-exception OR LGPL-2.1-or-later. Detailed license information
10// governing the source code and code contributions can be found in
11// LICENSE.md and CONTRIBUTING.md at the top level directory of deal.II.
12//
13// ------------------------------------------------------------------------
14
15
18#include <deal.II/base/point.h>
20
23
25#include <deal.II/grid/tria.h>
28
29#include <algorithm>
30#include <fstream>
31#include <iostream>
32#include <limits>
33#include <numeric>
34
35
37
38
39namespace internal
40{
41 namespace parallel
42 {
43 namespace distributed
44 {
45 namespace TriangulationImplementation
46 {
54 template <int dim, int spacedim>
55 void
58 {
59 auto pack =
61 &cell) -> std::uint8_t {
62 if (cell->refine_flag_set())
63 return 1;
64 if (cell->coarsen_flag_set())
65 return 2;
66 return 0;
67 };
68
69 auto unpack =
71 &cell,
72 const std::uint8_t &flag) -> void {
73 cell->clear_coarsen_flag();
74 cell->clear_refine_flag();
75 if (flag == 1)
76 cell->set_refine_flag();
77 else if (flag == 2)
78 cell->set_coarsen_flag();
79 };
80
81 GridTools::exchange_cell_data_to_ghosts<std::uint8_t>(tria,
82 pack,
83 unpack);
84 }
85 } // namespace TriangulationImplementation
86 } // namespace distributed
87 } // namespace parallel
88} // namespace internal
89
90
91
92#ifdef DEAL_II_WITH_P4EST
93
94namespace
95{
96 template <int dim, int spacedim>
97 void
98 get_vertex_to_cell_mappings(
100 std::vector<unsigned int> &vertex_touch_count,
101 std::vector<std::list<
103 unsigned int>>> &vertex_to_cell)
104 {
105 vertex_touch_count.resize(triangulation.n_vertices());
106 vertex_to_cell.resize(triangulation.n_vertices());
107
108 for (const auto &cell : triangulation.active_cell_iterators())
109 for (const unsigned int v : GeometryInfo<dim>::vertex_indices())
110 {
111 ++vertex_touch_count[cell->vertex_index(v)];
112 vertex_to_cell[cell->vertex_index(v)].emplace_back(cell, v);
113 }
114 }
115
116
117
118 template <int dim, int spacedim>
119 void
120 get_edge_to_cell_mappings(
122 std::vector<unsigned int> &edge_touch_count,
123 std::vector<std::list<
125 unsigned int>>> &edge_to_cell)
126 {
127 Assert(triangulation.n_levels() == 1, ExcInternalError());
128
129 edge_touch_count.resize(triangulation.n_active_lines());
130 edge_to_cell.resize(triangulation.n_active_lines());
131
132 for (const auto &cell : triangulation.active_cell_iterators())
133 for (unsigned int l = 0; l < GeometryInfo<dim>::lines_per_cell; ++l)
134 {
135 ++edge_touch_count[cell->line(l)->index()];
136 edge_to_cell[cell->line(l)->index()].emplace_back(cell, l);
137 }
138 }
139
140
141
146 template <int dim, int spacedim>
147 void
148 set_vertex_and_cell_info(
150 const std::vector<unsigned int> &vertex_touch_count,
151 const std::vector<std::list<
153 unsigned int>>> &vertex_to_cell,
154 const std::vector<types::global_dof_index>
155 &coarse_cell_to_p4est_tree_permutation,
156 const bool set_vertex_info,
157 typename internal::p4est::types<dim>::connectivity *connectivity)
158 {
159 // copy the vertices into the connectivity structure. the triangulation
160 // exports the array of vertices, but some of the entries are sometimes
161 // unused; this shouldn't be the case for a newly created triangulation,
162 // but make sure
163 //
164 // note that p4est stores coordinates as a triplet of values even in 2d
165 Assert(triangulation.get_used_vertices().size() ==
166 triangulation.get_vertices().size(),
168 Assert(std::find(triangulation.get_used_vertices().begin(),
169 triangulation.get_used_vertices().end(),
170 false) == triangulation.get_used_vertices().end(),
172 if (set_vertex_info == true)
173 for (unsigned int v = 0; v < triangulation.n_vertices(); ++v)
174 {
175 connectivity->vertices[3 * v] = triangulation.get_vertices()[v][0];
176 connectivity->vertices[3 * v + 1] =
177 triangulation.get_vertices()[v][1];
178 connectivity->vertices[3 * v + 2] =
179 (spacedim == 2 ? 0 : triangulation.get_vertices()[v][2]);
180 }
181
182 // next store the tree_to_vertex indices (each tree is here only a single
183 // cell in the coarse mesh). p4est requires vertex numbering in clockwise
184 // orientation
185 //
186 // while we're at it, also copy the neighborship information between cells
188 cell = triangulation.begin_active(),
189 endc = triangulation.end();
190 for (; cell != endc; ++cell)
191 {
192 const unsigned int index =
193 coarse_cell_to_p4est_tree_permutation[cell->index()];
194
195 for (const unsigned int v : GeometryInfo<dim>::vertex_indices())
196 {
197 if (set_vertex_info == true)
198 connectivity
200 v] = cell->vertex_index(v);
201 connectivity
203 v] = cell->vertex_index(v);
204 }
205
206 // neighborship information. if a cell is at a boundary, then enter
207 // the index of the cell itself here
208 for (auto f : GeometryInfo<dim>::face_indices())
209 if (cell->face(f)->at_boundary() == false)
210 connectivity
211 ->tree_to_tree[index * GeometryInfo<dim>::faces_per_cell + f] =
212 coarse_cell_to_p4est_tree_permutation[cell->neighbor(f)->index()];
213 else
214 connectivity
215 ->tree_to_tree[index * GeometryInfo<dim>::faces_per_cell + f] =
216 coarse_cell_to_p4est_tree_permutation[cell->index()];
217
218 // fill tree_to_face, which is essentially neighbor_to_neighbor;
219 // however, we have to remap the resulting face number as well
220 for (auto f : GeometryInfo<dim>::face_indices())
221 if (cell->face(f)->at_boundary() == false)
222 {
223 switch (dim)
224 {
225 case 2:
226 {
227 connectivity->tree_to_face
229 cell->neighbor_of_neighbor(f);
230 break;
231 }
232
233 case 3:
234 {
235 /*
236 * The values for tree_to_face are in 0..23 where ttf % 6
237 * gives the face number and ttf / 4 the face orientation
238 * code. The orientation is determined as follows. Let
239 * my_face and other_face be the two face numbers of the
240 * connecting trees in 0..5. Then the first face vertex
241 * of the lower of my_face and other_face connects to a
242 * face vertex numbered 0..3 in the higher of my_face and
243 * other_face. The face orientation is defined as this
244 * number. If my_face == other_face, treating either of
245 * both faces as the lower one leads to the same result.
246 */
247
248 connectivity->tree_to_face[index * 6 + f] =
249 cell->neighbor_of_neighbor(f);
250
251 unsigned int face_idx_list[2] = {
252 f, cell->neighbor_of_neighbor(f)};
254 cell_list[2] = {cell, cell->neighbor(f)};
255 unsigned int smaller_idx = 0;
256
257 if (f > cell->neighbor_of_neighbor(f))
258 smaller_idx = 1;
259
260 unsigned int larger_idx = (smaller_idx + 1) % 2;
261 // smaller = *_list[smaller_idx]
262 // larger = *_list[larger_idx]
263
264 unsigned int v = 0;
265
266 // global vertex index of vertex 0 on face of cell with
267 // smaller local face index
268 unsigned int g_idx = cell_list[smaller_idx]->vertex_index(
270 face_idx_list[smaller_idx],
271 0,
272 cell_list[smaller_idx]->face_orientation(
273 face_idx_list[smaller_idx]),
274 cell_list[smaller_idx]->face_flip(
275 face_idx_list[smaller_idx]),
276 cell_list[smaller_idx]->face_rotation(
277 face_idx_list[smaller_idx])));
278
279 // loop over vertices on face from other cell and compare
280 // global vertex numbers
281 for (unsigned int i = 0;
282 i < GeometryInfo<dim>::vertices_per_face;
283 ++i)
284 {
285 unsigned int idx =
286 cell_list[larger_idx]->vertex_index(
288 face_idx_list[larger_idx], i));
289
290 if (idx == g_idx)
291 {
292 v = i;
293 break;
294 }
295 }
296
297 connectivity->tree_to_face[index * 6 + f] += 6 * v;
298 break;
299 }
300
301 default:
303 }
304 }
305 else
306 connectivity
307 ->tree_to_face[index * GeometryInfo<dim>::faces_per_cell + f] = f;
308 }
309
310 // now fill the vertex information
311 connectivity->ctt_offset[0] = 0;
312 std::partial_sum(vertex_touch_count.begin(),
313 vertex_touch_count.end(),
314 &connectivity->ctt_offset[1]);
315
316 const typename internal::p4est::types<dim>::locidx num_vtt =
317 std::accumulate(vertex_touch_count.begin(), vertex_touch_count.end(), 0u);
318 (void)num_vtt;
319 Assert(connectivity->ctt_offset[triangulation.n_vertices()] == num_vtt,
321
322 for (unsigned int v = 0; v < triangulation.n_vertices(); ++v)
323 {
324 Assert(vertex_to_cell[v].size() == vertex_touch_count[v],
326
327 typename std::list<
328 std::pair<typename Triangulation<dim, spacedim>::active_cell_iterator,
329 unsigned int>>::const_iterator p =
330 vertex_to_cell[v].begin();
331 for (unsigned int c = 0; c < vertex_touch_count[v]; ++c, ++p)
332 {
333 connectivity->corner_to_tree[connectivity->ctt_offset[v] + c] =
334 coarse_cell_to_p4est_tree_permutation[p->first->index()];
335 connectivity->corner_to_corner[connectivity->ctt_offset[v] + c] =
336 p->second;
337 }
338 }
339 }
340
341
342
343 template <int dim, int spacedim>
344 bool
346 const typename internal::p4est::types<dim>::forest *parallel_forest,
347 const typename internal::p4est::types<dim>::topidx coarse_grid_cell)
348 {
349 Assert(coarse_grid_cell < parallel_forest->connectivity->num_trees,
351 return ((coarse_grid_cell >= parallel_forest->first_local_tree) &&
352 (coarse_grid_cell <= parallel_forest->last_local_tree));
353 }
354
355
356 template <int dim, int spacedim>
357 void
358 delete_all_children_and_self(
360 {
361 if (cell->has_children())
362 for (unsigned int c = 0; c < cell->n_children(); ++c)
363 delete_all_children_and_self<dim, spacedim>(cell->child(c));
364 else
365 cell->set_coarsen_flag();
366 }
367
368
369
370 template <int dim, int spacedim>
371 void
372 delete_all_children(
374 {
375 if (cell->has_children())
376 for (unsigned int c = 0; c < cell->n_children(); ++c)
377 delete_all_children_and_self<dim, spacedim>(cell->child(c));
378 }
379
380
381 template <int dim, int spacedim>
382 void
383 determine_level_subdomain_id_recursively(
384 const typename internal::p4est::types<dim>::tree &tree,
385 const typename internal::p4est::types<dim>::locidx &tree_index,
386 const typename Triangulation<dim, spacedim>::cell_iterator &dealii_cell,
387 const typename internal::p4est::types<dim>::quadrant &p4est_cell,
389 const types::subdomain_id my_subdomain,
390 const std::vector<std::vector<bool>> &marked_vertices)
391 {
392 if (dealii_cell->level_subdomain_id() == numbers::artificial_subdomain_id)
393 {
394 // important: only assign the level_subdomain_id if it is a ghost cell
395 // even though we could fill in all.
396 bool used = false;
397 for (const unsigned int v : GeometryInfo<dim>::vertex_indices())
398 {
399 if (marked_vertices[dealii_cell->level()]
400 [dealii_cell->vertex_index(v)])
401 {
402 used = true;
403 break;
404 }
405 }
406
407 // Special case: if this cell is active we might be a ghost neighbor
408 // to a locally owned cell across a vertex that is finer.
409 // Example (M= my, O=dealii_cell, owned by somebody else):
410 // *------*
411 // | |
412 // | O |
413 // | |
414 // *---*---*------*
415 // | M | M |
416 // *---*---*
417 // | | M |
418 // *---*---*
419 if (!used && dealii_cell->is_active() &&
420 dealii_cell->is_artificial() == false &&
421 dealii_cell->level() + 1 < static_cast<int>(marked_vertices.size()))
422 {
423 for (const unsigned int v : GeometryInfo<dim>::vertex_indices())
424 {
425 if (marked_vertices[dealii_cell->level() + 1]
426 [dealii_cell->vertex_index(v)])
427 {
428 used = true;
429 break;
430 }
431 }
432 }
433
434 // Like above, but now the other way around
435 if (!used && dealii_cell->is_active() &&
436 dealii_cell->is_artificial() == false && dealii_cell->level() > 0)
437 {
438 for (const unsigned int v : GeometryInfo<dim>::vertex_indices())
439 {
440 if (marked_vertices[dealii_cell->level() - 1]
441 [dealii_cell->vertex_index(v)])
442 {
443 used = true;
444 break;
445 }
446 }
447 }
448
449 if (used)
450 {
452 &forest, tree_index, &p4est_cell, my_subdomain);
453 Assert((owner != -2) && (owner != -1),
454 ExcMessage("p4est should know the owner."));
455 dealii_cell->set_level_subdomain_id(owner);
456 }
457 }
458
459 if (dealii_cell->has_children())
460 {
463 for (unsigned int c = 0; c < GeometryInfo<dim>::max_children_per_cell;
464 ++c)
465 switch (dim)
466 {
467 case 2:
468 P4EST_QUADRANT_INIT(&p4est_child[c]);
469 break;
470 case 3:
471 P8EST_QUADRANT_INIT(&p4est_child[c]);
472 break;
473 default:
475 }
476
477
479 p4est_child);
480
481 for (unsigned int c = 0; c < GeometryInfo<dim>::max_children_per_cell;
482 ++c)
483 {
484 determine_level_subdomain_id_recursively<dim, spacedim>(
485 tree,
486 tree_index,
487 dealii_cell->child(c),
488 p4est_child[c],
489 forest,
490 my_subdomain,
491 marked_vertices);
492 }
493 }
494 }
495
496
497 template <int dim, int spacedim>
498 void
499 match_tree_recursively(
500 const typename internal::p4est::types<dim>::tree &tree,
501 const typename Triangulation<dim, spacedim>::cell_iterator &dealii_cell,
502 const typename internal::p4est::types<dim>::quadrant &p4est_cell,
503 const typename internal::p4est::types<dim>::forest &forest,
504 const types::subdomain_id my_subdomain)
505 {
506 // check if this cell exists in the local p4est cell
507 if (sc_array_bsearch(const_cast<sc_array_t *>(&tree.quadrants),
508 &p4est_cell,
510 -1)
511 {
512 // yes, cell found in local part of p4est
513 delete_all_children<dim, spacedim>(dealii_cell);
514 if (dealii_cell->is_active())
515 dealii_cell->set_subdomain_id(my_subdomain);
516 }
517 else
518 {
519 // no, cell not found in local part of p4est. this means that the
520 // local part is more refined than the current cell. if this cell has
521 // no children of its own, we need to refine it, and if it does
522 // already have children then loop over all children and see if they
523 // are locally available as well
524 if (dealii_cell->is_active())
525 dealii_cell->set_refine_flag();
526 else
527 {
530 for (unsigned int c = 0;
531 c < GeometryInfo<dim>::max_children_per_cell;
532 ++c)
533 switch (dim)
534 {
535 case 2:
536 P4EST_QUADRANT_INIT(&p4est_child[c]);
537 break;
538 case 3:
539 P8EST_QUADRANT_INIT(&p4est_child[c]);
540 break;
541 default:
543 }
544
545
547 p4est_child);
548
549 for (unsigned int c = 0;
550 c < GeometryInfo<dim>::max_children_per_cell;
551 ++c)
553 const_cast<typename internal::p4est::types<dim>::tree *>(
554 &tree),
555 &p4est_child[c]) == false)
556 {
557 // no, this child is locally not available in the p4est.
558 // delete all its children but, because this may not be
559 // successful, make sure to mark all children recursively
560 // as not local.
561 delete_all_children<dim, spacedim>(dealii_cell->child(c));
562 dealii_cell->child(c)->recursively_set_subdomain_id(
564 }
565 else
566 {
567 // at least some part of the tree rooted in this child is
568 // locally available
569 match_tree_recursively<dim, spacedim>(tree,
570 dealii_cell->child(c),
571 p4est_child[c],
572 forest,
573 my_subdomain);
574 }
575 }
576 }
577 }
578
579
580 template <int dim, int spacedim>
581 void
582 match_quadrant(
583 const ::Triangulation<dim, spacedim> *tria,
584 unsigned int dealii_index,
585 const typename internal::p4est::types<dim>::quadrant &ghost_quadrant,
586 types::subdomain_id ghost_owner)
587 {
588 const int l = ghost_quadrant.level;
589
590 for (int i = 0; i < l; ++i)
591 {
593 i,
594 dealii_index);
595 if (cell->is_active())
596 {
597 cell->clear_coarsen_flag();
598 cell->set_refine_flag();
599 return;
600 }
601
602 const int child_id =
604 i + 1);
605 dealii_index = cell->child_index(child_id);
606 }
607
609 l,
610 dealii_index);
611 if (cell->has_children())
612 delete_all_children<dim, spacedim>(cell);
613 else
614 {
615 cell->clear_coarsen_flag();
616 cell->set_subdomain_id(ghost_owner);
617 }
618 }
619
620# ifdef P4EST_SEARCH_LOCAL
621 template <int dim>
622 class PartitionSearch
623 {
624 public:
625 PartitionSearch()
626 {
627 Assert(dim > 1, ExcNotImplemented());
628 }
629
630 PartitionSearch(const PartitionSearch<dim> &other) = delete;
631
632 PartitionSearch<dim> &
633 operator=(const PartitionSearch<dim> &other) = delete;
634
635 public:
645 static int
646 local_quadrant_fn(typename internal::p4est::types<dim>::forest *forest,
647 typename internal::p4est::types<dim>::topidx which_tree,
648 typename internal::p4est::types<dim>::quadrant *quadrant,
649 int rank_begin,
650 int rank_end,
651 void *point);
652
665 static int
666 local_point_fn(typename internal::p4est::types<dim>::forest *forest,
667 typename internal::p4est::types<dim>::topidx which_tree,
668 typename internal::p4est::types<dim>::quadrant *quadrant,
669 int rank_begin,
670 int rank_end,
671 void *point);
672
673 private:
678 class QuadrantData
679 {
680 public:
681 QuadrantData();
682
683 void
684 set_cell_vertices(
686 typename internal::p4est::types<dim>::topidx which_tree,
687 typename internal::p4est::types<dim>::quadrant *quadrant,
689 quad_length_on_level);
690
691 void
692 initialize_mapping();
693
695 map_real_to_unit_cell(const Point<dim> &p) const;
696
697 bool
698 is_in_this_quadrant(const Point<dim> &p) const;
699
700 private:
701 std::vector<Point<dim>> cell_vertices;
702
707 FullMatrix<double> quadrant_mapping_matrix;
708
709 bool are_vertices_initialized;
710
711 bool is_reference_mapping_initialized;
712 };
713
717 QuadrantData quadrant_data;
718 }; // class PartitionSearch
719
720
721
722 template <int dim>
723 int
724 PartitionSearch<dim>::local_quadrant_fn(
726 typename internal::p4est::types<dim>::topidx which_tree,
727 typename internal::p4est::types<dim>::quadrant *quadrant,
728 int /* rank_begin */,
729 int /* rank_end */,
730 void * /* this is always nullptr */ point)
731 {
732 // point must be nullptr here
733 (void)point;
734 Assert(point == nullptr, ::ExcInternalError());
735
736 // we need the user pointer
737 // note that this is not available since function is static
738 PartitionSearch<dim> *this_object =
739 reinterpret_cast<PartitionSearch<dim> *>(forest->user_pointer);
740
741 // Avoid p4est macros, instead do bitshifts manually with fixed size types
743 quad_length_on_level =
744 1 << (static_cast<typename internal::p4est::types<dim>::quadrant_coord>(
745 (dim == 2 ? P4EST_MAXLEVEL : P8EST_MAXLEVEL)) -
747 quadrant->level));
748
749 this_object->quadrant_data.set_cell_vertices(forest,
750 which_tree,
751 quadrant,
752 quad_length_on_level);
753
754 // from cell vertices we can initialize the mapping
755 this_object->quadrant_data.initialize_mapping();
756
757 // always return true since we must decide by point
758 return /* true */ 1;
759 }
760
761
762
763 template <int dim>
764 int
765 PartitionSearch<dim>::local_point_fn(
767 typename internal::p4est::types<dim>::topidx /* which_tree */,
768 typename internal::p4est::types<dim>::quadrant * /* quadrant */,
769 int rank_begin,
770 int rank_end,
771 void *point)
772 {
773 // point must NOT be be nullptr here
774 Assert(point != nullptr, ::ExcInternalError());
775
776 // we need the user pointer
777 // note that this is not available since function is static
778 PartitionSearch<dim> *this_object =
779 reinterpret_cast<PartitionSearch<dim> *>(forest->user_pointer);
780
781 // point with rank as double pointer
782 double *this_point_dptr = static_cast<double *>(point);
783
784 Point<dim> this_point =
785 (dim == 2 ? Point<dim>(this_point_dptr[0], this_point_dptr[1]) :
786 Point<dim>(this_point_dptr[0],
787 this_point_dptr[1],
788 this_point_dptr[2]));
789
790 // use reference mapping to decide whether this point is in this quadrant
791 const bool is_in_this_quadrant =
792 this_object->quadrant_data.is_in_this_quadrant(this_point);
793
794
795
796 if (!is_in_this_quadrant)
797 {
798 // no need to search further, stop recursion
799 return /* false */ 0;
800 }
801
802
803
804 // From here we have a candidate
805 if (rank_begin < rank_end)
806 {
807 // continue recursion
808 return /* true */ 1;
809 }
810
811 // Now, we know that the point is found (rank_begin==rank_end) and we have
812 // the MPI rank, so no need to search further.
813 this_point_dptr[dim] = static_cast<double>(rank_begin);
814
815 // stop recursion.
816 return /* false */ 0;
817 }
818
819
820
821 template <int dim>
822 bool
823 PartitionSearch<dim>::QuadrantData::is_in_this_quadrant(
824 const Point<dim> &p) const
825 {
826 const Point<dim> p_ref = map_real_to_unit_cell(p);
827
829 }
830
831
832
833 template <int dim>
835 PartitionSearch<dim>::QuadrantData::map_real_to_unit_cell(
836 const Point<dim> &p) const
837 {
838 Assert(is_reference_mapping_initialized,
840 "Cell vertices and mapping coefficients must be fully "
841 "initialized before transforming a point to the unit cell."));
842
843 Point<dim> p_out;
844
845 if (dim == 2)
846 {
847 for (unsigned int alpha = 0;
848 alpha < GeometryInfo<dim>::vertices_per_cell;
849 ++alpha)
850 {
851 const Point<dim> &p_ref =
853
854 p_out += (quadrant_mapping_matrix(alpha, 0) +
855 quadrant_mapping_matrix(alpha, 1) * p(0) +
856 quadrant_mapping_matrix(alpha, 2) * p(1) +
857 quadrant_mapping_matrix(alpha, 3) * p(0) * p(1)) *
858 p_ref;
859 }
860 }
861 else
862 {
863 for (unsigned int alpha = 0;
864 alpha < GeometryInfo<dim>::vertices_per_cell;
865 ++alpha)
866 {
867 const Point<dim> &p_ref =
869
870 p_out += (quadrant_mapping_matrix(alpha, 0) +
871 quadrant_mapping_matrix(alpha, 1) * p(0) +
872 quadrant_mapping_matrix(alpha, 2) * p(1) +
873 quadrant_mapping_matrix(alpha, 3) * p(2) +
874 quadrant_mapping_matrix(alpha, 4) * p(0) * p(1) +
875 quadrant_mapping_matrix(alpha, 5) * p(1) * p(2) +
876 quadrant_mapping_matrix(alpha, 6) * p(0) * p(2) +
877 quadrant_mapping_matrix(alpha, 7) * p(0) * p(1) * p(2)) *
878 p_ref;
879 }
880 }
881
882 return p_out;
883 }
884
885
886 template <int dim>
887 PartitionSearch<dim>::QuadrantData::QuadrantData()
888 : cell_vertices(GeometryInfo<dim>::vertices_per_cell)
889 , quadrant_mapping_matrix(GeometryInfo<dim>::vertices_per_cell,
890 GeometryInfo<dim>::vertices_per_cell)
891 , are_vertices_initialized(false)
892 , is_reference_mapping_initialized(false)
893 {}
894
895
896
897 template <int dim>
898 void
899 PartitionSearch<dim>::QuadrantData::initialize_mapping()
900 {
901 Assert(
902 are_vertices_initialized,
904 "Cell vertices must be initialized before the cell mapping can be filled."));
905
908
909 if (dim == 2)
910 {
911 for (unsigned int alpha = 0;
912 alpha < GeometryInfo<dim>::vertices_per_cell;
913 ++alpha)
914 {
915 // point matrix to be inverted
916 point_matrix(0, alpha) = 1;
917 point_matrix(1, alpha) = cell_vertices[alpha](0);
918 point_matrix(2, alpha) = cell_vertices[alpha](1);
919 point_matrix(3, alpha) =
920 cell_vertices[alpha](0) * cell_vertices[alpha](1);
921 }
922
923 /*
924 * Rows of quadrant_mapping_matrix are the coefficients of the basis
925 * on the physical cell
926 */
927 quadrant_mapping_matrix.invert(point_matrix);
928 }
929 else
930 {
931 for (unsigned int alpha = 0;
932 alpha < GeometryInfo<dim>::vertices_per_cell;
933 ++alpha)
934 {
935 // point matrix to be inverted
936 point_matrix(0, alpha) = 1;
937 point_matrix(1, alpha) = cell_vertices[alpha](0);
938 point_matrix(2, alpha) = cell_vertices[alpha](1);
939 point_matrix(3, alpha) = cell_vertices[alpha](2);
940 point_matrix(4, alpha) =
941 cell_vertices[alpha](0) * cell_vertices[alpha](1);
942 point_matrix(5, alpha) =
943 cell_vertices[alpha](1) * cell_vertices[alpha](2);
944 point_matrix(6, alpha) =
945 cell_vertices[alpha](0) * cell_vertices[alpha](2);
946 point_matrix(7, alpha) = cell_vertices[alpha](0) *
947 cell_vertices[alpha](1) *
948 cell_vertices[alpha](2);
949 }
950
951 /*
952 * Rows of quadrant_mapping_matrix are the coefficients of the basis
953 * on the physical cell
954 */
955 quadrant_mapping_matrix.invert(point_matrix);
956 }
957
958 is_reference_mapping_initialized = true;
959 }
960
961
962
963 template <>
964 void
965 PartitionSearch<2>::QuadrantData::set_cell_vertices(
966 typename internal::p4est::types<2>::forest *forest,
967 typename internal::p4est::types<2>::topidx which_tree,
968 typename internal::p4est::types<2>::quadrant *quadrant,
970 quad_length_on_level)
971 {
972 constexpr unsigned int dim = 2;
973
974 // p4est for some reason always needs double vxyz[3] as last argument to
975 // quadrant_coord_to_vertex
976 double corner_point[dim + 1] = {0};
977
978 // A lambda to avoid code duplication.
979 const auto copy_vertex = [&](unsigned int vertex_index) -> void {
980 // copy into local struct
981 for (unsigned int d = 0; d < dim; ++d)
982 {
983 cell_vertices[vertex_index](d) = corner_point[d];
984 // reset
985 corner_point[d] = 0;
986 }
987 };
988
989 // Fill points of QuadrantData in lexicographic order
990 /*
991 * Corner #0
992 */
993 unsigned int vertex_index = 0;
995 forest->connectivity, which_tree, quadrant->x, quadrant->y, corner_point);
996
997 // copy into local struct
998 copy_vertex(vertex_index);
999
1000 /*
1001 * Corner #1
1002 */
1003 vertex_index = 1;
1005 forest->connectivity,
1006 which_tree,
1007 quadrant->x + quad_length_on_level,
1008 quadrant->y,
1009 corner_point);
1010
1011 // copy into local struct
1012 copy_vertex(vertex_index);
1013
1014 /*
1015 * Corner #2
1016 */
1017 vertex_index = 2;
1019 forest->connectivity,
1020 which_tree,
1021 quadrant->x,
1022 quadrant->y + quad_length_on_level,
1023 corner_point);
1024
1025 // copy into local struct
1026 copy_vertex(vertex_index);
1027
1028 /*
1029 * Corner #3
1030 */
1031 vertex_index = 3;
1033 forest->connectivity,
1034 which_tree,
1035 quadrant->x + quad_length_on_level,
1036 quadrant->y + quad_length_on_level,
1037 corner_point);
1038
1039 // copy into local struct
1040 copy_vertex(vertex_index);
1041
1042 are_vertices_initialized = true;
1043 }
1044
1045
1046
1047 template <>
1048 void
1049 PartitionSearch<3>::QuadrantData::set_cell_vertices(
1050 typename internal::p4est::types<3>::forest *forest,
1051 typename internal::p4est::types<3>::topidx which_tree,
1052 typename internal::p4est::types<3>::quadrant *quadrant,
1054 quad_length_on_level)
1055 {
1056 constexpr unsigned int dim = 3;
1057
1058 double corner_point[dim] = {0};
1059
1060 // A lambda to avoid code duplication.
1061 auto copy_vertex = [&](unsigned int vertex_index) -> void {
1062 // copy into local struct
1063 for (unsigned int d = 0; d < dim; ++d)
1064 {
1065 cell_vertices[vertex_index](d) = corner_point[d];
1066 // reset
1067 corner_point[d] = 0;
1068 }
1069 };
1070
1071 // Fill points of QuadrantData in lexicographic order
1072 /*
1073 * Corner #0
1074 */
1075 unsigned int vertex_index = 0;
1077 forest->connectivity,
1078 which_tree,
1079 quadrant->x,
1080 quadrant->y,
1081 quadrant->z,
1082 corner_point);
1083
1084 // copy into local struct
1085 copy_vertex(vertex_index);
1086
1087
1088 /*
1089 * Corner #1
1090 */
1091 vertex_index = 1;
1093 forest->connectivity,
1094 which_tree,
1095 quadrant->x + quad_length_on_level,
1096 quadrant->y,
1097 quadrant->z,
1098 corner_point);
1099
1100 // copy into local struct
1101 copy_vertex(vertex_index);
1102
1103 /*
1104 * Corner #2
1105 */
1106 vertex_index = 2;
1108 forest->connectivity,
1109 which_tree,
1110 quadrant->x,
1111 quadrant->y + quad_length_on_level,
1112 quadrant->z,
1113 corner_point);
1114
1115 // copy into local struct
1116 copy_vertex(vertex_index);
1117
1118 /*
1119 * Corner #3
1120 */
1121 vertex_index = 3;
1123 forest->connectivity,
1124 which_tree,
1125 quadrant->x + quad_length_on_level,
1126 quadrant->y + quad_length_on_level,
1127 quadrant->z,
1128 corner_point);
1129
1130 // copy into local struct
1131 copy_vertex(vertex_index);
1132
1133 /*
1134 * Corner #4
1135 */
1136 vertex_index = 4;
1138 forest->connectivity,
1139 which_tree,
1140 quadrant->x,
1141 quadrant->y,
1142 quadrant->z + quad_length_on_level,
1143 corner_point);
1144
1145 // copy into local struct
1146 copy_vertex(vertex_index);
1147
1148 /*
1149 * Corner #5
1150 */
1151 vertex_index = 5;
1153 forest->connectivity,
1154 which_tree,
1155 quadrant->x + quad_length_on_level,
1156 quadrant->y,
1157 quadrant->z + quad_length_on_level,
1158 corner_point);
1159
1160 // copy into local struct
1161 copy_vertex(vertex_index);
1162
1163 /*
1164 * Corner #6
1165 */
1166 vertex_index = 6;
1168 forest->connectivity,
1169 which_tree,
1170 quadrant->x,
1171 quadrant->y + quad_length_on_level,
1172 quadrant->z + quad_length_on_level,
1173 corner_point);
1174
1175 // copy into local struct
1176 copy_vertex(vertex_index);
1177
1178 /*
1179 * Corner #7
1180 */
1181 vertex_index = 7;
1183 forest->connectivity,
1184 which_tree,
1185 quadrant->x + quad_length_on_level,
1186 quadrant->y + quad_length_on_level,
1187 quadrant->z + quad_length_on_level,
1188 corner_point);
1189
1190 // copy into local struct
1191 copy_vertex(vertex_index);
1192
1193
1194 are_vertices_initialized = true;
1195 }
1196# endif // P4EST_SEARCH_LOCAL defined
1197
1198
1204 template <int dim, int spacedim>
1205 class RefineAndCoarsenList
1206 {
1207 public:
1208 RefineAndCoarsenList(const Triangulation<dim, spacedim> &triangulation,
1209 const std::vector<types::global_dof_index>
1210 &p4est_tree_to_coarse_cell_permutation,
1211 const types::subdomain_id my_subdomain);
1212
1221 static int
1222 refine_callback(
1223 typename internal::p4est::types<dim>::forest *forest,
1224 typename internal::p4est::types<dim>::topidx coarse_cell_index,
1225 typename internal::p4est::types<dim>::quadrant *quadrant);
1226
1231 static int
1232 coarsen_callback(
1233 typename internal::p4est::types<dim>::forest *forest,
1234 typename internal::p4est::types<dim>::topidx coarse_cell_index,
1235 typename internal::p4est::types<dim>::quadrant *children[]);
1236
1237 bool
1238 pointers_are_at_end() const;
1239
1240 private:
1241 std::vector<typename internal::p4est::types<dim>::quadrant> refine_list;
1242 typename std::vector<typename internal::p4est::types<dim>::quadrant>::
1243 const_iterator current_refine_pointer;
1244
1245 std::vector<typename internal::p4est::types<dim>::quadrant> coarsen_list;
1246 typename std::vector<typename internal::p4est::types<dim>::quadrant>::
1247 const_iterator current_coarsen_pointer;
1248
1249 void
1250 build_lists(
1252 const typename internal::p4est::types<dim>::quadrant &p4est_cell,
1253 const types::subdomain_id myid);
1254 };
1255
1256
1257
1258 template <int dim, int spacedim>
1259 bool
1260 RefineAndCoarsenList<dim, spacedim>::pointers_are_at_end() const
1261 {
1262 return ((current_refine_pointer == refine_list.end()) &&
1263 (current_coarsen_pointer == coarsen_list.end()));
1264 }
1265
1266
1267
1268 template <int dim, int spacedim>
1269 RefineAndCoarsenList<dim, spacedim>::RefineAndCoarsenList(
1271 const std::vector<types::global_dof_index>
1272 &p4est_tree_to_coarse_cell_permutation,
1273 const types::subdomain_id my_subdomain)
1274 {
1275 // count how many flags are set and allocate that much memory
1276 unsigned int n_refine_flags = 0, n_coarsen_flags = 0;
1277 for (const auto &cell : triangulation.active_cell_iterators())
1278 {
1279 // skip cells that are not local
1280 if (cell->subdomain_id() != my_subdomain)
1281 continue;
1282
1283 if (cell->refine_flag_set())
1284 ++n_refine_flags;
1285 else if (cell->coarsen_flag_set())
1286 ++n_coarsen_flags;
1287 }
1288
1289 refine_list.reserve(n_refine_flags);
1290 coarsen_list.reserve(n_coarsen_flags);
1291
1292
1293 // now build the lists of cells that are flagged. note that p4est will
1294 // traverse its cells in the order in which trees appear in the
1295 // forest. this order is not the same as the order of coarse cells in the
1296 // deal.II Triangulation because we have translated everything by the
1297 // coarse_cell_to_p4est_tree_permutation permutation. in order to make
1298 // sure that the output array is already in the correct order, traverse
1299 // our coarse cells in the same order in which p4est will:
1300 for (unsigned int c = 0; c < triangulation.n_cells(0); ++c)
1301 {
1302 unsigned int coarse_cell_index =
1303 p4est_tree_to_coarse_cell_permutation[c];
1304
1306 &triangulation, 0, coarse_cell_index);
1307
1308 typename internal::p4est::types<dim>::quadrant p4est_cell;
1310 /*level=*/0,
1311 /*index=*/0);
1312 p4est_cell.p.which_tree = c;
1313 build_lists(cell, p4est_cell, my_subdomain);
1314 }
1315
1316
1317 Assert(refine_list.size() == n_refine_flags, ExcInternalError());
1318 Assert(coarsen_list.size() == n_coarsen_flags, ExcInternalError());
1319
1320 // make sure that our ordering in fact worked
1321 for (unsigned int i = 1; i < refine_list.size(); ++i)
1322 Assert(refine_list[i].p.which_tree >= refine_list[i - 1].p.which_tree,
1324 for (unsigned int i = 1; i < coarsen_list.size(); ++i)
1325 Assert(coarsen_list[i].p.which_tree >= coarsen_list[i - 1].p.which_tree,
1327
1328 current_refine_pointer = refine_list.begin();
1329 current_coarsen_pointer = coarsen_list.begin();
1330 }
1331
1332
1333
1334 template <int dim, int spacedim>
1335 void
1336 RefineAndCoarsenList<dim, spacedim>::build_lists(
1338 const typename internal::p4est::types<dim>::quadrant &p4est_cell,
1339 const types::subdomain_id my_subdomain)
1340 {
1341 if (cell->is_active())
1342 {
1343 if (cell->subdomain_id() == my_subdomain)
1344 {
1345 if (cell->refine_flag_set())
1346 refine_list.push_back(p4est_cell);
1347 else if (cell->coarsen_flag_set())
1348 coarsen_list.push_back(p4est_cell);
1349 }
1350 }
1351 else
1352 {
1355 for (unsigned int c = 0; c < GeometryInfo<dim>::max_children_per_cell;
1356 ++c)
1357 switch (dim)
1358 {
1359 case 2:
1360 P4EST_QUADRANT_INIT(&p4est_child[c]);
1361 break;
1362 case 3:
1363 P8EST_QUADRANT_INIT(&p4est_child[c]);
1364 break;
1365 default:
1367 }
1369 p4est_child);
1370 for (unsigned int c = 0; c < GeometryInfo<dim>::max_children_per_cell;
1371 ++c)
1372 {
1373 p4est_child[c].p.which_tree = p4est_cell.p.which_tree;
1374 build_lists(cell->child(c), p4est_child[c], my_subdomain);
1375 }
1376 }
1377 }
1378
1379
1380 template <int dim, int spacedim>
1381 int
1382 RefineAndCoarsenList<dim, spacedim>::refine_callback(
1383 typename internal::p4est::types<dim>::forest *forest,
1384 typename internal::p4est::types<dim>::topidx coarse_cell_index,
1385 typename internal::p4est::types<dim>::quadrant *quadrant)
1386 {
1387 RefineAndCoarsenList<dim, spacedim> *this_object =
1388 reinterpret_cast<RefineAndCoarsenList<dim, spacedim> *>(
1389 forest->user_pointer);
1390
1391 // if there are no more cells in our list the current cell can't be
1392 // flagged for refinement
1393 if (this_object->current_refine_pointer == this_object->refine_list.end())
1394 return 0;
1395
1396 Assert(coarse_cell_index <=
1397 this_object->current_refine_pointer->p.which_tree,
1399
1400 // if p4est hasn't yet reached the tree of the next flagged cell the
1401 // current cell can't be flagged for refinement
1402 if (coarse_cell_index < this_object->current_refine_pointer->p.which_tree)
1403 return 0;
1404
1405 // now we're in the right tree in the forest
1406 Assert(coarse_cell_index <=
1407 this_object->current_refine_pointer->p.which_tree,
1409
1410 // make sure that the p4est loop over cells hasn't gotten ahead of our own
1411 // pointer
1413 quadrant, &*this_object->current_refine_pointer) <= 0,
1415
1416 // now, if the p4est cell is one in the list, it is supposed to be refined
1418 quadrant, &*this_object->current_refine_pointer))
1419 {
1420 ++this_object->current_refine_pointer;
1421 return 1;
1422 }
1423
1424 // p4est cell is not in list
1425 return 0;
1426 }
1427
1428
1429
1430 template <int dim, int spacedim>
1431 int
1432 RefineAndCoarsenList<dim, spacedim>::coarsen_callback(
1433 typename internal::p4est::types<dim>::forest *forest,
1434 typename internal::p4est::types<dim>::topidx coarse_cell_index,
1435 typename internal::p4est::types<dim>::quadrant *children[])
1436 {
1437 RefineAndCoarsenList<dim, spacedim> *this_object =
1438 reinterpret_cast<RefineAndCoarsenList<dim, spacedim> *>(
1439 forest->user_pointer);
1440
1441 // if there are no more cells in our list the current cell can't be
1442 // flagged for coarsening
1443 if (this_object->current_coarsen_pointer == this_object->coarsen_list.end())
1444 return 0;
1445
1446 Assert(coarse_cell_index <=
1447 this_object->current_coarsen_pointer->p.which_tree,
1449
1450 // if p4est hasn't yet reached the tree of the next flagged cell the
1451 // current cell can't be flagged for coarsening
1452 if (coarse_cell_index < this_object->current_coarsen_pointer->p.which_tree)
1453 return 0;
1454
1455 // now we're in the right tree in the forest
1456 Assert(coarse_cell_index <=
1457 this_object->current_coarsen_pointer->p.which_tree,
1459
1460 // make sure that the p4est loop over cells hasn't gotten ahead of our own
1461 // pointer
1463 children[0], &*this_object->current_coarsen_pointer) <= 0,
1465
1466 // now, if the p4est cell is one in the list, it is supposed to be
1467 // coarsened
1469 children[0], &*this_object->current_coarsen_pointer))
1470 {
1471 // move current pointer one up
1472 ++this_object->current_coarsen_pointer;
1473
1474 // note that the next 3 cells in our list need to correspond to the
1475 // other siblings of the cell we have just found
1476 for (unsigned int c = 1; c < GeometryInfo<dim>::max_children_per_cell;
1477 ++c)
1478 {
1480 children[c], &*this_object->current_coarsen_pointer),
1482 ++this_object->current_coarsen_pointer;
1483 }
1484
1485 return 1;
1486 }
1487
1488 // p4est cell is not in list
1489 return 0;
1490 }
1491
1492
1493
1500 template <int dim, int spacedim>
1501 class PartitionWeights
1502 {
1503 public:
1509 explicit PartitionWeights(const std::vector<unsigned int> &cell_weights);
1510
1518 static int
1519 cell_weight(typename internal::p4est::types<dim>::forest *forest,
1520 typename internal::p4est::types<dim>::topidx coarse_cell_index,
1521 typename internal::p4est::types<dim>::quadrant *quadrant);
1522
1523 private:
1524 std::vector<unsigned int> cell_weights_list;
1525 std::vector<unsigned int>::const_iterator current_pointer;
1526 };
1527
1528
1529 template <int dim, int spacedim>
1530 PartitionWeights<dim, spacedim>::PartitionWeights(
1531 const std::vector<unsigned int> &cell_weights)
1532 : cell_weights_list(cell_weights)
1533 {
1534 // set the current pointer to the first element of the list, given that
1535 // we will walk through it sequentially
1536 current_pointer = cell_weights_list.begin();
1537 }
1538
1539
1540 template <int dim, int spacedim>
1541 int
1542 PartitionWeights<dim, spacedim>::cell_weight(
1543 typename internal::p4est::types<dim>::forest *forest,
1546 {
1547 // the function gets two additional arguments, but we don't need them
1548 // since we know in which order p4est will walk through the cells
1549 // and have already built our weight lists in this order
1550
1551 PartitionWeights<dim, spacedim> *this_object =
1552 reinterpret_cast<PartitionWeights<dim, spacedim> *>(forest->user_pointer);
1553
1554 Assert(this_object->current_pointer >=
1555 this_object->cell_weights_list.begin(),
1557 Assert(this_object->current_pointer < this_object->cell_weights_list.end(),
1559
1560 // Get the weight, increment the pointer, and return the weight. Also
1561 // make sure that we don't exceed the 'int' data type that p4est uses
1562 // to represent weights
1563 const unsigned int weight = *this_object->current_pointer;
1564 ++this_object->current_pointer;
1565
1566 Assert(weight < static_cast<unsigned int>(std::numeric_limits<int>::max()),
1567 ExcMessage("p4est uses 'signed int' to represent the partition "
1568 "weights for cells. The weight provided here exceeds "
1569 "the maximum value represented as a 'signed int'."));
1570 return static_cast<int>(weight);
1571 }
1572
1573 template <int dim, int spacedim>
1574 using cell_relation_t = typename std::pair<
1575 typename ::Triangulation<dim, spacedim>::cell_iterator,
1576 CellStatus>;
1577
1587 template <int dim, int spacedim>
1588 inline void
1589 add_single_cell_relation(
1590 std::vector<cell_relation_t<dim, spacedim>> &cell_rel,
1591 const typename ::internal::p4est::types<dim>::tree &tree,
1592 const unsigned int idx,
1593 const typename Triangulation<dim, spacedim>::cell_iterator &dealii_cell,
1594 const CellStatus status)
1595 {
1596 const unsigned int local_quadrant_index = tree.quadrants_offset + idx;
1597
1598 // check if we will be writing into valid memory
1599 Assert(local_quadrant_index < cell_rel.size(), ExcInternalError());
1600
1601 // store relation
1602 cell_rel[local_quadrant_index] = std::make_pair(dealii_cell, status);
1603 }
1604
1605
1606
1616 template <int dim, int spacedim>
1617 void
1618 update_cell_relations_recursively(
1619 std::vector<cell_relation_t<dim, spacedim>> &cell_rel,
1620 const typename ::internal::p4est::types<dim>::tree &tree,
1621 const typename Triangulation<dim, spacedim>::cell_iterator &dealii_cell,
1622 const typename ::internal::p4est::types<dim>::quadrant &p4est_cell)
1623 {
1624 // find index of p4est_cell in the quadrants array of the corresponding tree
1625 const int idx = sc_array_bsearch(
1626 const_cast<sc_array_t *>(&tree.quadrants),
1627 &p4est_cell,
1629 if (idx == -1 &&
1631 const_cast<typename ::internal::p4est::types<dim>::tree *>(
1632 &tree),
1633 &p4est_cell) == false))
1634 // this quadrant and none of its children belong to us.
1635 return;
1636
1637 // recurse further if both p4est and dealii still have children
1638 const bool p4est_has_children = (idx == -1);
1639 if (p4est_has_children && dealii_cell->has_children())
1640 {
1641 // recurse further
1642 typename ::internal::p4est::types<dim>::quadrant
1644
1645 for (unsigned int c = 0; c < GeometryInfo<dim>::max_children_per_cell;
1646 ++c)
1647 switch (dim)
1648 {
1649 case 2:
1650 P4EST_QUADRANT_INIT(&p4est_child[c]);
1651 break;
1652 case 3:
1653 P8EST_QUADRANT_INIT(&p4est_child[c]);
1654 break;
1655 default:
1657 }
1658
1660 &p4est_cell, p4est_child);
1661
1662 for (unsigned int c = 0; c < GeometryInfo<dim>::max_children_per_cell;
1663 ++c)
1664 {
1665 update_cell_relations_recursively<dim, spacedim>(
1666 cell_rel, tree, dealii_cell->child(c), p4est_child[c]);
1667 }
1668 }
1669 else if (!p4est_has_children && !dealii_cell->has_children())
1670 {
1671 // this active cell didn't change
1672 // save pair into corresponding position
1673 add_single_cell_relation<dim, spacedim>(
1674 cell_rel, tree, idx, dealii_cell, CellStatus::cell_will_persist);
1675 }
1676 else if (p4est_has_children) // based on the conditions above, we know that
1677 // dealii_cell has no children
1678 {
1679 // this cell got refined in p4est, but the dealii_cell has not yet been
1680 // refined
1681
1682 // this quadrant is not active
1683 // generate its children, and store information in those
1684 typename ::internal::p4est::types<dim>::quadrant
1686 for (unsigned int c = 0; c < GeometryInfo<dim>::max_children_per_cell;
1687 ++c)
1688 switch (dim)
1689 {
1690 case 2:
1691 P4EST_QUADRANT_INIT(&p4est_child[c]);
1692 break;
1693 case 3:
1694 P8EST_QUADRANT_INIT(&p4est_child[c]);
1695 break;
1696 default:
1698 }
1699
1701 &p4est_cell, p4est_child);
1702
1703 // mark first child with CellStatus::cell_will_be_refined and the
1704 // remaining children with CellStatus::cell_invalid, but associate them
1705 // all with the parent cell unpack algorithm will be called only on
1706 // CellStatus::cell_will_be_refined flagged quadrant
1707 int child_idx;
1708 CellStatus cell_status;
1709 for (unsigned int i = 0; i < GeometryInfo<dim>::max_children_per_cell;
1710 ++i)
1711 {
1712 child_idx = sc_array_bsearch(
1713 const_cast<sc_array_t *>(&tree.quadrants),
1714 &p4est_child[i],
1716
1717 cell_status = (i == 0) ? CellStatus::cell_will_be_refined :
1719
1720 add_single_cell_relation<dim, spacedim>(
1721 cell_rel, tree, child_idx, dealii_cell, cell_status);
1722 }
1723 }
1724 else // based on the conditions above, we know that p4est_cell has no
1725 // children, and the dealii_cell does
1726 {
1727 // its children got coarsened into this cell in p4est,
1728 // but the dealii_cell still has its children
1729 add_single_cell_relation<dim, spacedim>(
1730 cell_rel,
1731 tree,
1732 idx,
1733 dealii_cell,
1735 }
1736 }
1737} // namespace
1738
1739
1740
1741namespace parallel
1742{
1743 namespace distributed
1744 {
1745 /*----------------- class Triangulation<dim,spacedim> ---------------*/
1746 template <int dim, int spacedim>
1749 const MPI_Comm mpi_communicator,
1750 const typename ::Triangulation<dim, spacedim>::MeshSmoothing
1751 smooth_grid,
1752 const Settings settings)
1753 : // Do not check for distorted cells.
1754 // For multigrid, we need limit_level_difference_at_vertices
1755 // to make sure the transfer operators only need to consider two levels.
1756 ::parallel::DistributedTriangulationBase<dim, spacedim>(
1757 mpi_communicator,
1758 (settings & construct_multigrid_hierarchy) ?
1759 static_cast<
1760 typename ::Triangulation<dim, spacedim>::MeshSmoothing>(
1761 smooth_grid |
1762 Triangulation<dim, spacedim>::limit_level_difference_at_vertices) :
1763 smooth_grid,
1764 false)
1765 , settings(settings)
1766 , triangulation_has_content(false)
1767 , connectivity(nullptr)
1768 , parallel_forest(nullptr)
1769 {
1770 parallel_ghost = nullptr;
1771 }
1772
1773
1774
1775 template <int dim, int spacedim>
1777 Triangulation<dim, spacedim>::~Triangulation()
1778 {
1779 // virtual functions called in constructors and destructors never use the
1780 // override in a derived class
1781 // for clarity be explicit on which function is called
1782 try
1783 {
1785 }
1786 catch (...)
1787 {}
1788
1789 AssertNothrow(triangulation_has_content == false, ExcInternalError());
1790 AssertNothrow(connectivity == nullptr, ExcInternalError());
1791 AssertNothrow(parallel_forest == nullptr, ExcInternalError());
1792 }
1793
1794
1795
1796 template <int dim, int spacedim>
1798 void Triangulation<dim, spacedim>::create_triangulation(
1799 const std::vector<Point<spacedim>> &vertices,
1800 const std::vector<CellData<dim>> &cells,
1801 const SubCellData &subcelldata)
1802 {
1803 try
1804 {
1806 vertices, cells, subcelldata);
1807 }
1808 catch (
1809 const typename ::Triangulation<dim, spacedim>::DistortedCellList
1810 &)
1811 {
1812 // the underlying triangulation should not be checking for distorted
1813 // cells
1815 }
1816
1817 Assert(
1818 this->all_reference_cells_are_hyper_cube(),
1819 ExcMessage(
1820 "The class parallel::distributed::Triangulation only supports meshes "
1821 "consisting only of hypercube-like cells."));
1822
1823 // note that now we have some content in the p4est objects and call the
1824 // functions that do the actual work (which are dimension dependent, so
1825 // separate)
1826 triangulation_has_content = true;
1827
1828 setup_coarse_cell_to_p4est_tree_permutation();
1829
1830 copy_new_triangulation_to_p4est(std::integral_constant<int, dim>());
1831
1832 try
1833 {
1834 copy_local_forest_to_triangulation();
1835 }
1836 catch (const typename Triangulation<dim>::DistortedCellList &)
1837 {
1838 // the underlying triangulation should not be checking for distorted
1839 // cells
1841 }
1842
1843 this->update_periodic_face_map();
1844 this->update_number_cache();
1845 }
1846
1847
1848
1849 template <int dim, int spacedim>
1851 void Triangulation<dim, spacedim>::create_triangulation(
1852 const TriangulationDescription::Description<dim, spacedim>
1853 &construction_data)
1854 {
1855 (void)construction_data;
1856
1858 }
1859
1860
1861
1862 template <int dim, int spacedim>
1864 void Triangulation<dim, spacedim>::clear()
1865 {
1866 triangulation_has_content = false;
1867
1868 if (parallel_ghost != nullptr)
1869 {
1871 parallel_ghost);
1872 parallel_ghost = nullptr;
1873 }
1874
1875 if (parallel_forest != nullptr)
1876 {
1878 parallel_forest = nullptr;
1879 }
1880
1881 if (connectivity != nullptr)
1882 {
1884 connectivity);
1885 connectivity = nullptr;
1886 }
1887
1888 coarse_cell_to_p4est_tree_permutation.resize(0);
1889 p4est_tree_to_coarse_cell_permutation.resize(0);
1890
1892
1893 this->update_number_cache();
1894 }
1895
1896
1897
1898 template <int dim, int spacedim>
1900 bool Triangulation<dim, spacedim>::is_multilevel_hierarchy_constructed()
1901 const
1902 {
1903 return settings &
1905 }
1906
1907
1908
1909 template <int dim, int spacedim>
1911 bool Triangulation<dim, spacedim>::are_vertices_communicated_to_p4est()
1912 const
1913 {
1914 return settings &
1916 }
1917
1918
1919
1920 template <int dim, int spacedim>
1922 void Triangulation<dim, spacedim>::execute_transfer(
1923 const typename ::internal::p4est::types<dim>::forest
1924 *parallel_forest,
1925 const typename ::internal::p4est::types<dim>::gloidx
1926 *previous_global_first_quadrant)
1927 {
1928 Assert(this->data_serializer.sizes_fixed_cumulative.size() > 0,
1929 ExcMessage("No data has been packed!"));
1930
1931 // Resize memory according to the data that we will receive.
1932 this->data_serializer.dest_data_fixed.resize(
1933 parallel_forest->local_num_quadrants *
1934 this->data_serializer.sizes_fixed_cumulative.back());
1935
1936 // Execute non-blocking fixed size transfer.
1937 typename ::internal::p4est::types<dim>::transfer_context
1938 *tf_context;
1939 tf_context =
1941 parallel_forest->global_first_quadrant,
1942 previous_global_first_quadrant,
1943 parallel_forest->mpicomm,
1944 0,
1945 this->data_serializer.dest_data_fixed.data(),
1946 this->data_serializer.src_data_fixed.data(),
1947 this->data_serializer.sizes_fixed_cumulative.back());
1948
1949 if (this->data_serializer.variable_size_data_stored)
1950 {
1951 // Resize memory according to the data that we will receive.
1952 this->data_serializer.dest_sizes_variable.resize(
1953 parallel_forest->local_num_quadrants);
1954
1955 // Execute fixed size transfer of data sizes for variable size
1956 // transfer.
1958 parallel_forest->global_first_quadrant,
1959 previous_global_first_quadrant,
1960 parallel_forest->mpicomm,
1961 1,
1962 this->data_serializer.dest_sizes_variable.data(),
1963 this->data_serializer.src_sizes_variable.data(),
1964 sizeof(unsigned int));
1965 }
1966
1968
1969 // Release memory of previously packed data.
1970 this->data_serializer.src_data_fixed.clear();
1971 this->data_serializer.src_data_fixed.shrink_to_fit();
1972
1973 if (this->data_serializer.variable_size_data_stored)
1974 {
1975 // Resize memory according to the data that we will receive.
1976 this->data_serializer.dest_data_variable.resize(
1977 std::accumulate(this->data_serializer.dest_sizes_variable.begin(),
1978 this->data_serializer.dest_sizes_variable.end(),
1979 std::vector<int>::size_type(0)));
1980
1981# if DEAL_II_P4EST_VERSION_GTE(2, 0, 65, 0)
1982# else
1983 // ----- WORKAROUND -----
1984 // An assertion in p4est prevents us from sending/receiving no data
1985 // at all, which is mandatory if one of our processes does not own
1986 // any quadrant. This bypasses the assertion from being triggered.
1987 // - see: https://github.com/cburstedde/p4est/issues/48
1988 if (this->data_serializer.src_sizes_variable.empty())
1989 this->data_serializer.src_sizes_variable.resize(1);
1990 if (this->data_serializer.dest_sizes_variable.empty())
1991 this->data_serializer.dest_sizes_variable.resize(1);
1992# endif
1993
1994 // Execute variable size transfer.
1996 parallel_forest->global_first_quadrant,
1997 previous_global_first_quadrant,
1998 parallel_forest->mpicomm,
1999 1,
2000 this->data_serializer.dest_data_variable.data(),
2001 this->data_serializer.dest_sizes_variable.data(),
2002 this->data_serializer.src_data_variable.data(),
2003 this->data_serializer.src_sizes_variable.data());
2004
2005 // Release memory of previously packed data.
2006 this->data_serializer.src_sizes_variable.clear();
2007 this->data_serializer.src_sizes_variable.shrink_to_fit();
2008 this->data_serializer.src_data_variable.clear();
2009 this->data_serializer.src_data_variable.shrink_to_fit();
2010 }
2011 }
2012
2013
2014
2015 template <int dim, int spacedim>
2017 void Triangulation<dim,
2018 spacedim>::setup_coarse_cell_to_p4est_tree_permutation()
2019 {
2020 DynamicSparsityPattern cell_connectivity;
2022 cell_connectivity);
2023 coarse_cell_to_p4est_tree_permutation.resize(this->n_cells(0));
2025 cell_connectivity, coarse_cell_to_p4est_tree_permutation);
2026
2027 p4est_tree_to_coarse_cell_permutation =
2028 Utilities::invert_permutation(coarse_cell_to_p4est_tree_permutation);
2029 }
2030
2031
2032
2033 template <int dim, int spacedim>
2035 void Triangulation<dim, spacedim>::write_mesh_vtk(
2036 const std::string &file_basename) const
2037 {
2038 Assert(parallel_forest != nullptr,
2039 ExcMessage("Can't produce output when no forest is created yet."));
2040
2041 AssertThrow(are_vertices_communicated_to_p4est(),
2042 ExcMessage(
2043 "To use this function the triangulation's flag "
2044 "Settings::communicate_vertices_to_p4est must be set."));
2045
2047 parallel_forest, nullptr, file_basename.c_str());
2048 }
2049
2050
2051
2052 template <int dim, int spacedim>
2054 void Triangulation<dim, spacedim>::save(const std::string &filename) const
2055 {
2056 Assert(
2057 this->cell_attached_data.n_attached_deserialize == 0,
2058 ExcMessage(
2059 "Not all SolutionTransfer objects have been deserialized after the last call to load()."));
2060 Assert(this->n_cells() > 0,
2061 ExcMessage("Can not save() an empty Triangulation."));
2062
2063 const int myrank =
2064 Utilities::MPI::this_mpi_process(this->mpi_communicator);
2065
2066 // signal that serialization is going to happen
2067 this->signals.pre_distributed_save();
2068
2069 if (this->my_subdomain == 0)
2070 {
2071 std::string fname = std::string(filename) + ".info";
2072 std::ofstream f(fname);
2073 f << "version nproc n_attached_fixed_size_objs n_attached_variable_size_objs n_coarse_cells"
2074 << std::endl
2075 << 5 << " "
2076 << Utilities::MPI::n_mpi_processes(this->mpi_communicator) << " "
2077 << this->cell_attached_data.pack_callbacks_fixed.size() << " "
2078 << this->cell_attached_data.pack_callbacks_variable.size() << " "
2079 << this->n_cells(0) << std::endl;
2080 }
2081
2082 // each cell should have been flagged `CellStatus::cell_will_persist`
2083 for (const auto &cell_rel : this->local_cell_relations)
2084 {
2085 (void)cell_rel;
2086 Assert((cell_rel.second == // cell_status
2089 }
2090
2091 // Save cell attached data.
2092 this->save_attached_data(parallel_forest->global_first_quadrant[myrank],
2093 parallel_forest->global_num_quadrants,
2094 filename);
2095
2097 parallel_forest,
2098 false);
2099
2100 // signal that serialization has finished
2101 this->signals.post_distributed_save();
2102 }
2103
2104
2105
2106 template <int dim, int spacedim>
2108 void Triangulation<dim, spacedim>::load(const std::string &filename)
2109 {
2110 Assert(
2111 this->n_cells() > 0,
2112 ExcMessage(
2113 "load() only works if the Triangulation already contains a coarse mesh!"));
2114 Assert(
2115 this->n_levels() == 1,
2116 ExcMessage(
2117 "Triangulation may only contain coarse cells when calling load()."));
2118
2119 const int myrank =
2120 Utilities::MPI::this_mpi_process(this->mpi_communicator);
2121
2122 // signal that de-serialization is going to happen
2123 this->signals.pre_distributed_load();
2124
2125 if (parallel_ghost != nullptr)
2126 {
2128 parallel_ghost);
2129 parallel_ghost = nullptr;
2130 }
2132 parallel_forest = nullptr;
2134 connectivity);
2135 connectivity = nullptr;
2136
2137 unsigned int version, numcpus, attached_count_fixed,
2138 attached_count_variable, n_coarse_cells;
2139 {
2140 std::string fname = std::string(filename) + ".info";
2141 std::ifstream f(fname);
2142 AssertThrow(f.fail() == false, ExcIO());
2143 std::string firstline;
2144 getline(f, firstline); // skip first line
2145 f >> version >> numcpus >> attached_count_fixed >>
2146 attached_count_variable >> n_coarse_cells;
2147 }
2148
2149 AssertThrow(version == 5,
2150 ExcMessage("Incompatible version found in .info file."));
2151 Assert(this->n_cells(0) == n_coarse_cells,
2152 ExcMessage("Number of coarse cells differ!"));
2153
2154 // clear all of the callback data, as explained in the documentation of
2155 // register_data_attach()
2156 this->cell_attached_data.n_attached_data_sets = 0;
2157 this->cell_attached_data.n_attached_deserialize =
2158 attached_count_fixed + attached_count_variable;
2159
2161 filename.c_str(),
2162 this->mpi_communicator,
2163 0,
2164 0,
2165 1,
2166 0,
2167 this,
2168 &connectivity);
2169
2170 // We partition the p4est mesh that it conforms to the requirements of the
2171 // deal.II mesh, i.e., partition for coarsening.
2172 // This function call is optional.
2174 parallel_forest,
2175 /* prepare coarsening */ 1,
2176 /* weight_callback */ nullptr);
2177
2178 try
2179 {
2180 copy_local_forest_to_triangulation();
2181 }
2182 catch (const typename Triangulation<dim>::DistortedCellList &)
2183 {
2184 // the underlying triangulation should not be checking for distorted
2185 // cells
2187 }
2188
2189 // Load attached cell data, if any was stored.
2190 this->load_attached_data(parallel_forest->global_first_quadrant[myrank],
2191 parallel_forest->global_num_quadrants,
2192 parallel_forest->local_num_quadrants,
2193 filename,
2194 attached_count_fixed,
2195 attached_count_variable);
2196
2197 // signal that de-serialization is finished
2198 this->signals.post_distributed_load();
2199
2200 this->update_periodic_face_map();
2201 this->update_number_cache();
2202 }
2203
2204
2205
2206 template <int dim, int spacedim>
2208 void Triangulation<dim, spacedim>::load(const std::string &filename,
2209 const bool autopartition)
2210 {
2211 (void)autopartition;
2212 load(filename);
2213 }
2214
2215
2216
2217 template <int dim, int spacedim>
2219 void Triangulation<dim, spacedim>::load(
2220 const typename ::internal::p4est::types<dim>::forest *forest)
2221 {
2222 Assert(this->n_cells() > 0,
2223 ExcMessage(
2224 "load() only works if the Triangulation already contains "
2225 "a coarse mesh!"));
2226 Assert(this->n_cells() == forest->trees->elem_count,
2227 ExcMessage(
2228 "Coarse mesh of the Triangulation does not match the one "
2229 "of the provided forest!"));
2230
2231 // clear the old forest
2232 if (parallel_ghost != nullptr)
2233 {
2235 parallel_ghost);
2236 parallel_ghost = nullptr;
2237 }
2239 parallel_forest = nullptr;
2240
2241 // note: we can keep the connectivity, since the coarse grid does not
2242 // change
2243
2244 // create deep copy of the new forest
2245 typename ::internal::p4est::types<dim>::forest *temp =
2246 const_cast<typename ::internal::p4est::types<dim>::forest *>(
2247 forest);
2248 parallel_forest =
2250 parallel_forest->connectivity = connectivity;
2251 parallel_forest->user_pointer = this;
2252
2253 try
2254 {
2255 copy_local_forest_to_triangulation();
2256 }
2257 catch (const typename Triangulation<dim>::DistortedCellList &)
2258 {
2259 // the underlying triangulation should not be checking for distorted
2260 // cells
2262 }
2263
2264 this->update_periodic_face_map();
2265 this->update_number_cache();
2266 }
2267
2268
2269
2270 template <int dim, int spacedim>
2272 unsigned int Triangulation<dim, spacedim>::get_checksum() const
2273 {
2274 Assert(parallel_forest != nullptr,
2275 ExcMessage(
2276 "Can't produce a check sum when no forest is created yet."));
2277
2278 auto checksum =
2280
2281# if !DEAL_II_P4EST_VERSION_GTE(2, 8, 6, 0)
2282 /*
2283 * p4est prior to 2.8.6 returns the proper checksum only on rank 0
2284 * and simply "0" on all other ranks. This is not really what we
2285 * want, thus broadcast the correct value to all other ranks:
2286 */
2287 checksum = Utilities::MPI::broadcast(this->mpi_communicator,
2288 checksum,
2289 /*root_process*/ 0);
2290# endif
2291
2292 return checksum;
2293 }
2294
2295
2296
2297 template <int dim, int spacedim>
2299 const typename ::internal::p4est::types<dim>::forest
2301 {
2302 Assert(parallel_forest != nullptr,
2303 ExcMessage("The forest has not been allocated yet."));
2304 return parallel_forest;
2305 }
2306
2307
2308
2309 template <int dim, int spacedim>
2311 typename ::internal::p4est::types<dim>::tree
2313 const int dealii_coarse_cell_index) const
2314 {
2315 const unsigned int tree_index =
2316 coarse_cell_to_p4est_tree_permutation[dealii_coarse_cell_index];
2317 typename ::internal::p4est::types<dim>::tree *tree =
2318 static_cast<typename ::internal::p4est::types<dim>::tree *>(
2319 sc_array_index(parallel_forest->trees, tree_index));
2320
2321 return tree;
2322 }
2323
2324
2325
2326 // Note: this has been added here to prevent that these functions
2327 // appear in the Doxygen documentation of ::Triangulation
2328# ifndef DOXYGEN
2329
2330 template <>
2331 void
2333 std::integral_constant<int, 2>)
2334 {
2335 const unsigned int dim = 2, spacedim = 2;
2336 Assert(this->n_cells(0) > 0, ExcInternalError());
2337 Assert(this->n_levels() == 1, ExcInternalError());
2338
2339 // data structures that counts how many cells touch each vertex
2340 // (vertex_touch_count), and which cells touch a given vertex (together
2341 // with the local numbering of that vertex within the cells that touch
2342 // it)
2343 std::vector<unsigned int> vertex_touch_count;
2344 std::vector<
2345 std::list<std::pair<Triangulation<dim, spacedim>::active_cell_iterator,
2346 unsigned int>>>
2347 vertex_to_cell;
2348 get_vertex_to_cell_mappings(*this, vertex_touch_count, vertex_to_cell);
2349 const ::internal::p4est::types<2>::locidx num_vtt =
2350 std::accumulate(vertex_touch_count.begin(),
2351 vertex_touch_count.end(),
2352 0u);
2353
2354 // now create a connectivity object with the right sizes for all
2355 // arrays. set vertex information only in debug mode (saves a few bytes
2356 // in optimized mode)
2357 const bool set_vertex_info = this->are_vertices_communicated_to_p4est();
2358
2360 (set_vertex_info == true ? this->n_vertices() : 0),
2361 this->n_cells(0),
2362 this->n_vertices(),
2363 num_vtt);
2364
2365 set_vertex_and_cell_info(*this,
2366 vertex_touch_count,
2367 vertex_to_cell,
2368 coarse_cell_to_p4est_tree_permutation,
2369 set_vertex_info,
2370 connectivity);
2371
2372 Assert(p4est_connectivity_is_valid(connectivity) == 1,
2374
2375 // now create a forest out of the connectivity data structure
2377 this->mpi_communicator,
2378 connectivity,
2379 /* minimum initial number of quadrants per tree */ 0,
2380 /* minimum level of upfront refinement */ 0,
2381 /* use uniform upfront refinement */ 1,
2382 /* user_data_size = */ 0,
2383 /* user_data_constructor = */ nullptr,
2384 /* user_pointer */ this);
2385 }
2386
2387
2388
2389 // TODO: This is a verbatim copy of the 2,2 case. However, we can't just
2390 // specialize the dim template argument, but let spacedim open
2391 template <>
2392 void
2394 std::integral_constant<int, 2>)
2395 {
2396 const unsigned int dim = 2, spacedim = 3;
2397 Assert(this->n_cells(0) > 0, ExcInternalError());
2398 Assert(this->n_levels() == 1, ExcInternalError());
2399
2400 // data structures that counts how many cells touch each vertex
2401 // (vertex_touch_count), and which cells touch a given vertex (together
2402 // with the local numbering of that vertex within the cells that touch
2403 // it)
2404 std::vector<unsigned int> vertex_touch_count;
2405 std::vector<
2406 std::list<std::pair<Triangulation<dim, spacedim>::active_cell_iterator,
2407 unsigned int>>>
2408 vertex_to_cell;
2409 get_vertex_to_cell_mappings(*this, vertex_touch_count, vertex_to_cell);
2410 const ::internal::p4est::types<2>::locidx num_vtt =
2411 std::accumulate(vertex_touch_count.begin(),
2412 vertex_touch_count.end(),
2413 0u);
2414
2415 // now create a connectivity object with the right sizes for all
2416 // arrays. set vertex information only in debug mode (saves a few bytes
2417 // in optimized mode)
2418 const bool set_vertex_info = this->are_vertices_communicated_to_p4est();
2419
2421 (set_vertex_info == true ? this->n_vertices() : 0),
2422 this->n_cells(0),
2423 this->n_vertices(),
2424 num_vtt);
2425
2426 set_vertex_and_cell_info(*this,
2427 vertex_touch_count,
2428 vertex_to_cell,
2429 coarse_cell_to_p4est_tree_permutation,
2430 set_vertex_info,
2431 connectivity);
2432
2433 Assert(p4est_connectivity_is_valid(connectivity) == 1,
2435
2436 // now create a forest out of the connectivity data structure
2438 this->mpi_communicator,
2439 connectivity,
2440 /* minimum initial number of quadrants per tree */ 0,
2441 /* minimum level of upfront refinement */ 0,
2442 /* use uniform upfront refinement */ 1,
2443 /* user_data_size = */ 0,
2444 /* user_data_constructor = */ nullptr,
2445 /* user_pointer */ this);
2446 }
2447
2448
2449
2450 template <>
2451 void
2453 std::integral_constant<int, 3>)
2454 {
2455 const int dim = 3, spacedim = 3;
2456 Assert(this->n_cells(0) > 0, ExcInternalError());
2457 Assert(this->n_levels() == 1, ExcInternalError());
2458
2459 // data structures that counts how many cells touch each vertex
2460 // (vertex_touch_count), and which cells touch a given vertex (together
2461 // with the local numbering of that vertex within the cells that touch
2462 // it)
2463 std::vector<unsigned int> vertex_touch_count;
2464 std::vector<std::list<
2465 std::pair<Triangulation<3>::active_cell_iterator, unsigned int>>>
2466 vertex_to_cell;
2467 get_vertex_to_cell_mappings(*this, vertex_touch_count, vertex_to_cell);
2468 const ::internal::p4est::types<2>::locidx num_vtt =
2469 std::accumulate(vertex_touch_count.begin(),
2470 vertex_touch_count.end(),
2471 0u);
2472
2473 std::vector<unsigned int> edge_touch_count;
2474 std::vector<std::list<
2475 std::pair<Triangulation<3>::active_cell_iterator, unsigned int>>>
2476 edge_to_cell;
2477 get_edge_to_cell_mappings(*this, edge_touch_count, edge_to_cell);
2478 const ::internal::p4est::types<2>::locidx num_ett =
2479 std::accumulate(edge_touch_count.begin(), edge_touch_count.end(), 0u);
2480
2481 // now create a connectivity object with the right sizes for all arrays
2482 const bool set_vertex_info = this->are_vertices_communicated_to_p4est();
2483
2485 (set_vertex_info == true ? this->n_vertices() : 0),
2486 this->n_cells(0),
2487 this->n_active_lines(),
2488 num_ett,
2489 this->n_vertices(),
2490 num_vtt);
2491
2492 set_vertex_and_cell_info(*this,
2493 vertex_touch_count,
2494 vertex_to_cell,
2495 coarse_cell_to_p4est_tree_permutation,
2496 set_vertex_info,
2497 connectivity);
2498
2499 // next to tree-to-edge
2500 // data. note that in p4est lines
2501 // are ordered as follows
2502 // *---3---* *---3---*
2503 // /| | / /|
2504 // 6 | 11 6 7 11
2505 // / 10 | / / |
2506 // * | | *---2---* |
2507 // | *---1---* | | *
2508 // | / / | 9 /
2509 // 8 4 5 8 | 5
2510 // |/ / | |/
2511 // *---0---* *---0---*
2512 // whereas in deal.II they are like this:
2513 // *---7---* *---7---*
2514 // /| | / /|
2515 // 4 | 11 4 5 11
2516 // / 10 | / / |
2517 // * | | *---6---* |
2518 // | *---3---* | | *
2519 // | / / | 9 /
2520 // 8 0 1 8 | 1
2521 // |/ / | |/
2522 // *---2---* *---2---*
2523
2524 const unsigned int deal_to_p4est_line_index[12] = {
2525 4, 5, 0, 1, 6, 7, 2, 3, 8, 9, 10, 11};
2526
2528 this->begin_active();
2529 cell != this->end();
2530 ++cell)
2531 {
2532 const unsigned int index =
2533 coarse_cell_to_p4est_tree_permutation[cell->index()];
2534 for (unsigned int e = 0; e < GeometryInfo<3>::lines_per_cell; ++e)
2535 connectivity->tree_to_edge[index * GeometryInfo<3>::lines_per_cell +
2536 deal_to_p4est_line_index[e]] =
2537 cell->line(e)->index();
2538 }
2539
2540 // now also set edge-to-tree
2541 // information
2542 connectivity->ett_offset[0] = 0;
2543 std::partial_sum(edge_touch_count.begin(),
2544 edge_touch_count.end(),
2545 &connectivity->ett_offset[1]);
2546
2547 Assert(connectivity->ett_offset[this->n_active_lines()] == num_ett,
2549
2550 for (unsigned int v = 0; v < this->n_active_lines(); ++v)
2551 {
2552 Assert(edge_to_cell[v].size() == edge_touch_count[v],
2554
2555 std::list<
2556 std::pair<Triangulation<dim, spacedim>::active_cell_iterator,
2557 unsigned int>>::const_iterator p =
2558 edge_to_cell[v].begin();
2559 for (unsigned int c = 0; c < edge_touch_count[v]; ++c, ++p)
2560 {
2561 connectivity->edge_to_tree[connectivity->ett_offset[v] + c] =
2562 coarse_cell_to_p4est_tree_permutation[p->first->index()];
2563 connectivity->edge_to_edge[connectivity->ett_offset[v] + c] =
2564 deal_to_p4est_line_index[p->second];
2565 }
2566 }
2567
2568 Assert(p8est_connectivity_is_valid(connectivity) == 1,
2570
2571 // now create a forest out of the connectivity data structure
2573 this->mpi_communicator,
2574 connectivity,
2575 /* minimum initial number of quadrants per tree */ 0,
2576 /* minimum level of upfront refinement */ 0,
2577 /* use uniform upfront refinement */ 1,
2578 /* user_data_size = */ 0,
2579 /* user_data_constructor = */ nullptr,
2580 /* user_pointer */ this);
2581 }
2582# endif
2583
2584
2585
2586 namespace
2587 {
2588 // ensures the 2:1 mesh balance for periodic boundary conditions in the
2589 // artificial cell layer (the active cells are taken care of by p4est)
2590 template <int dim, int spacedim>
2591 bool
2592 enforce_mesh_balance_over_periodic_boundaries(
2594 {
2595 if (tria.get_periodic_face_map().empty())
2596 return false;
2597
2598 std::vector<bool> flags_before[2];
2599 tria.save_coarsen_flags(flags_before[0]);
2600 tria.save_refine_flags(flags_before[1]);
2601
2602 std::vector<unsigned int> topological_vertex_numbering(
2603 tria.n_vertices());
2604 for (unsigned int i = 0; i < topological_vertex_numbering.size(); ++i)
2605 topological_vertex_numbering[i] = i;
2606 // combine vertices that have different locations (and thus, different
2607 // vertex_index) but represent the same topological entity over
2608 // periodic boundaries. The vector topological_vertex_numbering
2609 // contains a linear map from 0 to n_vertices at input and at output
2610 // relates periodic vertices with only one vertex index. The output is
2611 // used to always identify the same vertex according to the
2612 // periodicity, e.g. when finding the maximum cell level around a
2613 // vertex.
2614 //
2615 // Example: On a 3d cell with vertices numbered from 0 to 7 and
2616 // periodic boundary conditions in x direction, the vector
2617 // topological_vertex_numbering will contain the numbers
2618 // {0,0,2,2,4,4,6,6} (because the vertex pairs {0,1}, {2,3}, {4,5},
2619 // {6,7} belong together, respectively). If periodicity is set in x
2620 // and z direction, the output is {0,0,2,2,0,0,2,2}, and if
2621 // periodicity is in all directions, the output is simply
2622 // {0,0,0,0,0,0,0,0}.
2623 using cell_iterator =
2625 typename std::map<std::pair<cell_iterator, unsigned int>,
2626 std::pair<std::pair<cell_iterator, unsigned int>,
2627 unsigned char>>::const_iterator it;
2628 for (it = tria.get_periodic_face_map().begin();
2629 it != tria.get_periodic_face_map().end();
2630 ++it)
2631 {
2632 const cell_iterator &cell_1 = it->first.first;
2633 const unsigned int face_no_1 = it->first.second;
2634 const cell_iterator &cell_2 = it->second.first.first;
2635 const unsigned int face_no_2 = it->second.first.second;
2636 const unsigned char combined_orientation = it->second.second;
2637 const auto [orientation, rotation, flip] =
2638 ::internal::split_face_orientation(combined_orientation);
2639
2640 if (cell_1->level() == cell_2->level())
2641 {
2642 for (unsigned int v = 0;
2643 v < GeometryInfo<dim - 1>::vertices_per_cell;
2644 ++v)
2645 {
2646 // take possible non-standard orientation of face on
2647 // cell[0] into account
2648 const unsigned int vface0 =
2650 v, orientation, flip, rotation);
2651 const unsigned int vi0 =
2652 topological_vertex_numbering[cell_1->face(face_no_1)
2653 ->vertex_index(vface0)];
2654 const unsigned int vi1 =
2655 topological_vertex_numbering[cell_2->face(face_no_2)
2656 ->vertex_index(v)];
2657 const unsigned int min_index = std::min(vi0, vi1);
2658 topological_vertex_numbering[cell_1->face(face_no_1)
2659 ->vertex_index(vface0)] =
2660 topological_vertex_numbering[cell_2->face(face_no_2)
2661 ->vertex_index(v)] =
2662 min_index;
2663 }
2664 }
2665 }
2666
2667 // There must not be any chains!
2668 for (unsigned int i = 0; i < topological_vertex_numbering.size(); ++i)
2669 {
2670 const unsigned int j = topological_vertex_numbering[i];
2671 if (j != i)
2672 Assert(topological_vertex_numbering[j] == j, ExcInternalError());
2673 }
2674
2675
2676 // this code is replicated from grid/tria.cc but using an indirection
2677 // for periodic boundary conditions
2678 bool continue_iterating = true;
2679 std::vector<int> vertex_level(tria.n_vertices());
2680 while (continue_iterating)
2681 {
2682 // store highest level one of the cells adjacent to a vertex
2683 // belongs to
2684 std::fill(vertex_level.begin(), vertex_level.end(), 0);
2686 cell = tria.begin_active(),
2687 endc = tria.end();
2688 for (; cell != endc; ++cell)
2689 {
2690 if (cell->refine_flag_set())
2691 for (const unsigned int vertex :
2693 vertex_level[topological_vertex_numbering
2694 [cell->vertex_index(vertex)]] =
2695 std::max(vertex_level[topological_vertex_numbering
2696 [cell->vertex_index(vertex)]],
2697 cell->level() + 1);
2698 else if (!cell->coarsen_flag_set())
2699 for (const unsigned int vertex :
2701 vertex_level[topological_vertex_numbering
2702 [cell->vertex_index(vertex)]] =
2703 std::max(vertex_level[topological_vertex_numbering
2704 [cell->vertex_index(vertex)]],
2705 cell->level());
2706 else
2707 {
2708 // if coarsen flag is set then tentatively assume
2709 // that the cell will be coarsened. this isn't
2710 // always true (the coarsen flag could be removed
2711 // again) and so we may make an error here. we try
2712 // to correct this by iterating over the entire
2713 // process until we are converged
2714 Assert(cell->coarsen_flag_set(), ExcInternalError());
2715 for (const unsigned int vertex :
2717 vertex_level[topological_vertex_numbering
2718 [cell->vertex_index(vertex)]] =
2719 std::max(vertex_level[topological_vertex_numbering
2720 [cell->vertex_index(vertex)]],
2721 cell->level() - 1);
2722 }
2723 }
2724
2725 continue_iterating = false;
2726
2727 // loop over all cells in reverse order. do so because we
2728 // can then update the vertex levels on the adjacent
2729 // vertices and maybe already flag additional cells in this
2730 // loop
2731 //
2732 // note that not only may we have to add additional
2733 // refinement flags, but we will also have to remove
2734 // coarsening flags on cells adjacent to vertices that will
2735 // see refinement
2736 for (cell = tria.last_active(); cell != endc; --cell)
2737 if (cell->refine_flag_set() == false)
2738 {
2739 for (const unsigned int vertex :
2741 if (vertex_level[topological_vertex_numbering
2742 [cell->vertex_index(vertex)]] >=
2743 cell->level() + 1)
2744 {
2745 // remove coarsen flag...
2746 cell->clear_coarsen_flag();
2747
2748 // ...and if necessary also refine the current
2749 // cell, at the same time updating the level
2750 // information about vertices
2751 if (vertex_level[topological_vertex_numbering
2752 [cell->vertex_index(vertex)]] >
2753 cell->level() + 1)
2754 {
2755 cell->set_refine_flag();
2756 continue_iterating = true;
2757
2758 for (const unsigned int v :
2760 vertex_level[topological_vertex_numbering
2761 [cell->vertex_index(v)]] =
2762 std::max(
2763 vertex_level[topological_vertex_numbering
2764 [cell->vertex_index(v)]],
2765 cell->level() + 1);
2766 }
2767
2768 // continue and see whether we may, for example,
2769 // go into the inner 'if' above based on a
2770 // different vertex
2771 }
2772 }
2773
2774 // clear coarsen flag if not all children were marked
2775 for (const auto &cell : tria.cell_iterators())
2776 {
2777 // nothing to do if we are already on the finest level
2778 if (cell->is_active())
2779 continue;
2780
2781 const unsigned int n_children = cell->n_children();
2782 unsigned int flagged_children = 0;
2783 for (unsigned int child = 0; child < n_children; ++child)
2784 if (cell->child(child)->is_active() &&
2785 cell->child(child)->coarsen_flag_set())
2786 ++flagged_children;
2787
2788 // if not all children were flagged for coarsening, remove
2789 // coarsen flags
2790 if (flagged_children < n_children)
2791 for (unsigned int child = 0; child < n_children; ++child)
2792 if (cell->child(child)->is_active())
2793 cell->child(child)->clear_coarsen_flag();
2794 }
2795 }
2796 std::vector<bool> flags_after[2];
2797 tria.save_coarsen_flags(flags_after[0]);
2798 tria.save_refine_flags(flags_after[1]);
2799 return ((flags_before[0] != flags_after[0]) ||
2800 (flags_before[1] != flags_after[1]));
2801 }
2802 } // namespace
2803
2804
2805
2806 template <int dim, int spacedim>
2808 bool Triangulation<dim, spacedim>::prepare_coarsening_and_refinement()
2809 {
2810 // First exchange coarsen/refinement flags on ghost cells. After this
2811 // collective communication call all flags on ghost cells match the
2812 // flags set by the user on the owning rank.
2815
2816 // Now we can call the sequential version to apply mesh smoothing and
2817 // other modifications:
2818 const bool any_changes = this->::Triangulation<dim, spacedim>::
2820 return any_changes;
2821 }
2822
2823
2824
2825 template <int dim, int spacedim>
2827 void Triangulation<dim, spacedim>::copy_local_forest_to_triangulation()
2828 {
2829 // Disable mesh smoothing for recreating the deal.II triangulation,
2830 // otherwise we might not be able to reproduce the p4est mesh
2831 // exactly. We restore the original smoothing at the end of this
2832 // function. Note that the smoothing flag is used in the normal
2833 // refinement process.
2834 typename Triangulation<dim, spacedim>::MeshSmoothing save_smooth =
2835 this->smooth_grid;
2836
2837 // We will refine manually to match the p4est further down, which
2838 // obeys a level difference of 2 at each vertex (see the balance call
2839 // to p4est). We can disable this here so we store fewer artificial
2840 // cells (in some cases).
2841 // For geometric multigrid it turns out that
2842 // we will miss level cells at shared vertices if we ignore this.
2843 // See tests/mpi/mg_06. In particular, the flag is still necessary
2844 // even though we force it for the original smooth_grid in the
2845 // constructor.
2846 if (settings & construct_multigrid_hierarchy)
2847 this->smooth_grid =
2848 ::Triangulation<dim,
2849 spacedim>::limit_level_difference_at_vertices;
2850 else
2851 this->smooth_grid = ::Triangulation<dim, spacedim>::none;
2852
2853 bool mesh_changed = false;
2854
2855 // Remove all deal.II refinements. Note that we could skip this and
2856 // start from our current state, because the algorithm later coarsens as
2857 // necessary. This has the advantage of being faster when large parts
2858 // of the local partition changes (likely) and gives a deterministic
2859 // ordering of the cells (useful for snapshot/resume).
2860 // TODO: is there a more efficient way to do this?
2861 if (settings & mesh_reconstruction_after_repartitioning)
2862 while (this->n_levels() > 1)
2863 {
2864 // Instead of marking all active cells, we slice off the finest
2865 // level, one level at a time. This takes the same number of
2866 // iterations but solves an issue where not all cells on a
2867 // periodic boundary are indeed coarsened and we run into an
2868 // irrelevant Assert() in update_periodic_face_map().
2869 for (const auto &cell :
2870 this->active_cell_iterators_on_level(this->n_levels() - 1))
2871 {
2872 cell->set_coarsen_flag();
2873 }
2874 try
2875 {
2878 }
2879 catch (
2881 {
2882 // the underlying triangulation should not be checking for
2883 // distorted cells
2885 }
2886 }
2887
2888
2889 // query p4est for the ghost cells
2890 if (parallel_ghost != nullptr)
2891 {
2893 parallel_ghost);
2894 parallel_ghost = nullptr;
2895 }
2897 parallel_forest,
2898 (dim == 2 ? typename ::internal::p4est::types<dim>::balance_type(
2899 P4EST_CONNECT_CORNER) :
2900 typename ::internal::p4est::types<dim>::balance_type(
2901 P8EST_CONNECT_CORNER)));
2902
2903 Assert(parallel_ghost, ExcInternalError());
2904
2905
2906 // set all cells to artificial. we will later set it to the correct
2907 // subdomain in match_tree_recursively
2908 for (const auto &cell : this->cell_iterators_on_level(0))
2909 cell->recursively_set_subdomain_id(numbers::artificial_subdomain_id);
2910
2911 do
2912 {
2913 for (const auto &cell : this->cell_iterators_on_level(0))
2914 {
2915 // if this processor stores no part of the forest that comes out
2916 // of this coarse grid cell, then we need to delete all children
2917 // of this cell (the coarse grid cell remains)
2918 if (tree_exists_locally<dim, spacedim>(
2919 parallel_forest,
2920 coarse_cell_to_p4est_tree_permutation[cell->index()]) ==
2921 false)
2922 {
2923 delete_all_children<dim, spacedim>(cell);
2924 if (cell->is_active())
2925 cell->set_subdomain_id(numbers::artificial_subdomain_id);
2926 }
2927
2928 else
2929 {
2930 // this processor stores at least a part of the tree that
2931 // comes out of this cell.
2932
2933 typename ::internal::p4est::types<dim>::quadrant
2934 p4est_coarse_cell;
2935 typename ::internal::p4est::types<dim>::tree *tree =
2936 init_tree(cell->index());
2937
2938 ::internal::p4est::init_coarse_quadrant<dim>(
2939 p4est_coarse_cell);
2940
2941 match_tree_recursively<dim, spacedim>(*tree,
2942 cell,
2943 p4est_coarse_cell,
2944 *parallel_forest,
2945 this->my_subdomain);
2946 }
2947 }
2948
2949 // check mesh for ghost cells, refine as necessary. iterate over
2950 // every ghostquadrant, find corresponding deal coarsecell and
2951 // recurse.
2952 typename ::internal::p4est::types<dim>::quadrant *quadr;
2953 types::subdomain_id ghost_owner = 0;
2954 typename ::internal::p4est::types<dim>::topidx ghost_tree = 0;
2955
2956 for (unsigned int g_idx = 0;
2957 g_idx < parallel_ghost->ghosts.elem_count;
2958 ++g_idx)
2959 {
2960 while (g_idx >= static_cast<unsigned int>(
2961 parallel_ghost->proc_offsets[ghost_owner + 1]))
2962 ++ghost_owner;
2963 while (g_idx >= static_cast<unsigned int>(
2964 parallel_ghost->tree_offsets[ghost_tree + 1]))
2965 ++ghost_tree;
2966
2967 quadr = static_cast<
2968 typename ::internal::p4est::types<dim>::quadrant *>(
2969 sc_array_index(&parallel_ghost->ghosts, g_idx));
2970
2971 unsigned int coarse_cell_index =
2972 p4est_tree_to_coarse_cell_permutation[ghost_tree];
2973
2974 match_quadrant<dim, spacedim>(this,
2975 coarse_cell_index,
2976 *quadr,
2977 ghost_owner);
2978 }
2979
2980 // Fix all the flags to make sure we have a consistent local
2981 // mesh. For some reason periodic boundaries involving artificial
2982 // cells are not obeying the 2:1 ratio that we require (and that is
2983 // enforced by p4est between active cells). So, here we will loop
2984 // refining across periodic boundaries until 2:1 is satisfied. Note
2985 // that we are using the base class (sequential) prepare and execute
2986 // calls here, not involving communication, because we are only
2987 // trying to recreate a local triangulation from the p4est data.
2988 {
2989 bool mesh_changed = true;
2990 unsigned int loop_counter = 0;
2991
2992 do
2993 {
2996
2997 this->update_periodic_face_map();
2998
2999 mesh_changed =
3000 enforce_mesh_balance_over_periodic_boundaries(*this);
3001
3002 // We can't be sure that we won't run into a situation where we
3003 // can not reconcile mesh smoothing and balancing of periodic
3004 // faces. As we don't know what else to do, at least abort with
3005 // an error message.
3006 ++loop_counter;
3007
3009 loop_counter < 32,
3010 ExcMessage(
3011 "Infinite loop in "
3012 "parallel::distributed::Triangulation::copy_local_forest_to_triangulation() "
3013 "for periodic boundaries detected. Aborting."));
3014 }
3015 while (mesh_changed);
3016 }
3017
3018 // see if any flags are still set
3019 mesh_changed =
3020 std::any_of(this->begin_active(),
3021 active_cell_iterator{this->end()},
3022 [](const CellAccessor<dim, spacedim> &cell) {
3023 return cell.refine_flag_set() ||
3024 cell.coarsen_flag_set();
3025 });
3026
3027 // actually do the refinement to change the local mesh by
3028 // calling the base class refinement function directly
3029 try
3030 {
3033 }
3034 catch (
3036 {
3037 // the underlying triangulation should not be checking for
3038 // distorted cells
3040 }
3041 }
3042 while (mesh_changed);
3043
3044# ifdef DEBUG
3045 // check if correct number of ghosts is created
3046 unsigned int num_ghosts = 0;
3047
3048 for (const auto &cell : this->active_cell_iterators())
3049 {
3050 if (cell->subdomain_id() != this->my_subdomain &&
3051 cell->subdomain_id() != numbers::artificial_subdomain_id)
3052 ++num_ghosts;
3053 }
3054
3055 Assert(num_ghosts == parallel_ghost->ghosts.elem_count,
3057# endif
3058
3059
3060
3061 // fill level_subdomain_ids for geometric multigrid
3062 // the level ownership of a cell is defined as the owner if the cell is
3063 // active or as the owner of child(0) we need this information for all
3064 // our ancestors and the same-level neighbors of our own cells (=level
3065 // ghosts)
3066 if (settings & construct_multigrid_hierarchy)
3067 {
3068 // step 1: We set our own ids all the way down and all the others to
3069 // -1. Note that we do not fill other cells we could figure out the
3070 // same way, because we might accidentally set an id for a cell that
3071 // is not a ghost cell.
3072 for (unsigned int lvl = this->n_levels(); lvl > 0;)
3073 {
3074 --lvl;
3075 for (const auto &cell : this->cell_iterators_on_level(lvl))
3076 {
3077 if ((cell->is_active() &&
3078 cell->subdomain_id() ==
3079 this->locally_owned_subdomain()) ||
3080 (cell->has_children() &&
3081 cell->child(0)->level_subdomain_id() ==
3082 this->locally_owned_subdomain()))
3083 cell->set_level_subdomain_id(
3084 this->locally_owned_subdomain());
3085 else
3086 {
3087 // not our cell
3088 cell->set_level_subdomain_id(
3090 }
3091 }
3092 }
3093
3094 // step 2: make sure all the neighbors to our level_cells exist.
3095 // Need to look up in p4est...
3096 std::vector<std::vector<bool>> marked_vertices(this->n_levels());
3097 for (unsigned int lvl = 0; lvl < this->n_levels(); ++lvl)
3098 marked_vertices[lvl] = mark_locally_active_vertices_on_level(lvl);
3099
3100 for (const auto &cell : this->cell_iterators_on_level(0))
3101 {
3102 typename ::internal::p4est::types<dim>::quadrant
3103 p4est_coarse_cell;
3104 const unsigned int tree_index =
3105 coarse_cell_to_p4est_tree_permutation[cell->index()];
3106 typename ::internal::p4est::types<dim>::tree *tree =
3107 init_tree(cell->index());
3108
3109 ::internal::p4est::init_coarse_quadrant<dim>(
3110 p4est_coarse_cell);
3111
3112 determine_level_subdomain_id_recursively<dim, spacedim>(
3113 *tree,
3114 tree_index,
3115 cell,
3116 p4est_coarse_cell,
3117 *parallel_forest,
3118 this->my_subdomain,
3119 marked_vertices);
3120 }
3121
3122 // step 3: make sure we have the parent of our level cells
3123 for (unsigned int lvl = this->n_levels(); lvl > 0;)
3124 {
3125 --lvl;
3126 for (const auto &cell : this->cell_iterators_on_level(lvl))
3127 {
3128 if (cell->has_children())
3129 for (unsigned int c = 0;
3130 c < GeometryInfo<dim>::max_children_per_cell;
3131 ++c)
3132 {
3133 if (cell->child(c)->level_subdomain_id() ==
3134 this->locally_owned_subdomain())
3135 {
3136 // at least one of the children belongs to us, so
3137 // make sure we set the level subdomain id
3138 const types::subdomain_id mark =
3139 cell->child(0)->level_subdomain_id();
3141 ExcInternalError()); // we should know the
3142 // child(0)
3143 cell->set_level_subdomain_id(mark);
3144 break;
3145 }
3146 }
3147 }
3148 }
3149 }
3150
3151
3152
3153 // check that our local copy has exactly as many cells as the p4est
3154 // original (at least if we are on only one processor); for parallel
3155 // computations, we want to check that we have at least as many as p4est
3156 // stores locally (in the future we should check that we have exactly as
3157 // many non-artificial cells as parallel_forest->local_num_quadrants)
3158 {
3159 const unsigned int total_local_cells = this->n_active_cells();
3160 (void)total_local_cells;
3161
3162 if (Utilities::MPI::n_mpi_processes(this->mpi_communicator) == 1)
3163 {
3164 Assert(static_cast<unsigned int>(
3165 parallel_forest->local_num_quadrants) == total_local_cells,
3167 }
3168 else
3169 {
3170 Assert(static_cast<unsigned int>(
3171 parallel_forest->local_num_quadrants) <= total_local_cells,
3173 }
3174
3175# ifdef DEBUG
3176 // count the number of owned, active cells and compare with p4est.
3177 unsigned int n_owned = 0;
3178 for (const auto &cell : this->active_cell_iterators())
3179 {
3180 if (cell->subdomain_id() == this->my_subdomain)
3181 ++n_owned;
3182 }
3183
3184 Assert(static_cast<unsigned int>(
3185 parallel_forest->local_num_quadrants) == n_owned,
3187# endif
3188 }
3189
3190 this->smooth_grid = save_smooth;
3191
3192 // finally, after syncing the parallel_forest with the triangulation,
3193 // also update the cell_relations, which will be used for
3194 // repartitioning, further refinement/coarsening, and unpacking
3195 // of stored or transferred data.
3196 update_cell_relations();
3197 }
3198
3199
3200
3201 template <int dim, int spacedim>
3205 {
3206 // Call the other function
3207 std::vector<Point<dim>> point{p};
3208 std::vector<types::subdomain_id> owner = find_point_owner_rank(point);
3209
3210 return owner[0];
3211 }
3212
3213
3214
3215 template <int dim, int spacedim>
3217 std::vector<types::subdomain_id> Triangulation<dim, spacedim>::
3218 find_point_owner_rank(const std::vector<Point<dim>> &points)
3219 {
3220# ifndef P4EST_SEARCH_LOCAL
3221 (void)points;
3223 false,
3224 ExcMessage(
3225 "This function is only available if p4est is version 2.2 and higher."));
3226 // Just return to satisfy compiler
3227 return std::vector<unsigned int>(1,
3229# else
3230 // We can only use this function if vertices are communicated to p4est
3231 AssertThrow(this->are_vertices_communicated_to_p4est(),
3232 ExcMessage(
3233 "Vertices need to be communicated to p4est to use this "
3234 "function. This must explicitly be turned on in the "
3235 "settings of the triangulation's constructor."));
3236
3237 // We can only use this function if all manifolds are flat
3238 for (const auto &manifold_id : this->get_manifold_ids())
3239 {
3241 manifold_id == numbers::flat_manifold_id,
3242 ExcMessage(
3243 "This function can only be used if the triangulation "
3244 "has no other manifold than a Cartesian (flat) manifold attached."));
3245 }
3246
3247 // Create object for callback
3248 PartitionSearch<dim> partition_search;
3249
3250 // Pointer should be this triangulation before we set it to something else
3251 Assert(parallel_forest->user_pointer == this, ExcInternalError());
3252
3253 // re-assign p4est's user pointer
3254 parallel_forest->user_pointer = &partition_search;
3255
3256 //
3257 // Copy points into p4est internal array data struct
3258 //
3259 // pointer to an array of points.
3260 sc_array_t *point_sc_array;
3261 // allocate memory for a number of dim-dimensional points including their
3262 // MPI rank, i.e., dim + 1 fields
3263 point_sc_array =
3264 sc_array_new_count(sizeof(double[dim + 1]), points.size());
3265
3266 // now assign the actual value
3267 for (size_t i = 0; i < points.size(); ++i)
3268 {
3269 // alias
3270 const Point<dim> &p = points[i];
3271 // get a non-const view of the array
3272 double *this_sc_point =
3273 static_cast<double *>(sc_array_index_ssize_t(point_sc_array, i));
3274 // fill this with the point data
3275 for (unsigned int d = 0; d < dim; ++d)
3276 {
3277 this_sc_point[d] = p(d);
3278 }
3279 this_sc_point[dim] = -1.0; // owner rank
3280 }
3281
3283 parallel_forest,
3284 /* execute quadrant function when leaving quadrant */
3285 static_cast<int>(false),
3286 &PartitionSearch<dim>::local_quadrant_fn,
3287 &PartitionSearch<dim>::local_point_fn,
3288 point_sc_array);
3289
3290 // copy the points found to an std::array
3291 std::vector<types::subdomain_id> owner_rank(
3292 points.size(), numbers::invalid_subdomain_id);
3293
3294 // fill the array
3295 for (size_t i = 0; i < points.size(); ++i)
3296 {
3297 // get a non-const view of the array
3298 double *this_sc_point =
3299 static_cast<double *>(sc_array_index_ssize_t(point_sc_array, i));
3300 Assert(this_sc_point[dim] >= 0. || this_sc_point[dim] == -1.,
3302 if (this_sc_point[dim] < 0.)
3303 owner_rank[i] = numbers::invalid_subdomain_id;
3304 else
3305 owner_rank[i] =
3306 static_cast<types::subdomain_id>(this_sc_point[dim]);
3307 }
3308
3309 // reset the internal pointer to this triangulation
3310 parallel_forest->user_pointer = this;
3311
3312 // release the memory (otherwise p4est will complain)
3313 sc_array_destroy_null(&point_sc_array);
3314
3315 return owner_rank;
3316# endif // P4EST_SEARCH_LOCAL defined
3317 }
3318
3319
3320
3321 template <int dim, int spacedim>
3323 void Triangulation<dim, spacedim>::execute_coarsening_and_refinement()
3324 {
3325 // do not allow anisotropic refinement
3326# ifdef DEBUG
3327 for (const auto &cell : this->active_cell_iterators())
3328 if (cell->is_locally_owned() && cell->refine_flag_set())
3329 Assert(cell->refine_flag_set() ==
3331 ExcMessage(
3332 "This class does not support anisotropic refinement"));
3333# endif
3334
3335
3336 // safety check: p4est has an upper limit on the level of a cell
3337 if (this->n_levels() ==
3339 {
3341 cell = this->begin_active(
3343 cell !=
3345 1);
3346 ++cell)
3347 {
3349 !(cell->refine_flag_set()),
3350 ExcMessage(
3351 "Fatal Error: maximum refinement level of p4est reached."));
3352 }
3353 }
3354
3355 this->prepare_coarsening_and_refinement();
3356
3357 // signal that refinement is going to happen
3358 this->signals.pre_distributed_refinement();
3359
3360 // now do the work we're supposed to do when we are in charge
3361 // make sure all flags are cleared on cells we don't own, since nothing
3362 // good can come of that if they are still around
3363 for (const auto &cell : this->active_cell_iterators())
3364 if (cell->is_ghost() || cell->is_artificial())
3365 {
3366 cell->clear_refine_flag();
3367 cell->clear_coarsen_flag();
3368 }
3369
3370
3371 // count how many cells will be refined and coarsened, and allocate that
3372 // much memory
3373 RefineAndCoarsenList<dim, spacedim> refine_and_coarsen_list(
3374 *this, p4est_tree_to_coarse_cell_permutation, this->my_subdomain);
3375
3376 // copy refine and coarsen flags into p4est and execute the refinement
3377 // and coarsening. this uses the refine_and_coarsen_list just built,
3378 // which is communicated to the callback functions through
3379 // p4est's user_pointer object
3380 Assert(parallel_forest->user_pointer == this, ExcInternalError());
3381 parallel_forest->user_pointer = &refine_and_coarsen_list;
3382
3383 if (parallel_ghost != nullptr)
3384 {
3386 parallel_ghost);
3387 parallel_ghost = nullptr;
3388 }
3390 parallel_forest,
3391 /* refine_recursive */ false,
3392 &RefineAndCoarsenList<dim, spacedim>::refine_callback,
3393 /*init_callback=*/nullptr);
3395 parallel_forest,
3396 /* coarsen_recursive */ false,
3397 &RefineAndCoarsenList<dim, spacedim>::coarsen_callback,
3398 /*init_callback=*/nullptr);
3399
3400 // make sure all cells in the lists have been consumed
3401 Assert(refine_and_coarsen_list.pointers_are_at_end(), ExcInternalError());
3402
3403 // reset the pointer
3404 parallel_forest->user_pointer = this;
3405
3406 // enforce 2:1 hanging node condition
3408 parallel_forest,
3409 /* face and corner balance */
3410 (dim == 2 ? typename ::internal::p4est::types<dim>::balance_type(
3411 P4EST_CONNECT_FULL) :
3412 typename ::internal::p4est::types<dim>::balance_type(
3413 P8EST_CONNECT_FULL)),
3414 /*init_callback=*/nullptr);
3415
3416 // since refinement and/or coarsening on the parallel forest
3417 // has happened, we need to update the quadrant cell relations
3418 update_cell_relations();
3419
3420 // signals that parallel_forest has been refined and cell relations have
3421 // been updated
3422 this->signals.post_p4est_refinement();
3423
3424 // before repartitioning the mesh, save a copy of the current positions
3425 // of quadrants only if data needs to be transferred later
3426 std::vector<typename ::internal::p4est::types<dim>::gloidx>
3427 previous_global_first_quadrant;
3428
3429 if (this->cell_attached_data.n_attached_data_sets > 0)
3430 {
3431 previous_global_first_quadrant.resize(parallel_forest->mpisize + 1);
3432 std::memcpy(previous_global_first_quadrant.data(),
3433 parallel_forest->global_first_quadrant,
3434 sizeof(
3435 typename ::internal::p4est::types<dim>::gloidx) *
3436 (parallel_forest->mpisize + 1));
3437 }
3438
3439 if (!(settings & no_automatic_repartitioning))
3440 {
3441 // partition the new mesh between all processors. If cell weights
3442 // have not been given balance the number of cells.
3443 if (this->signals.weight.empty())
3445 parallel_forest,
3446 /* prepare coarsening */ 1,
3447 /* weight_callback */ nullptr);
3448 else
3449 {
3450 // get cell weights for a weighted repartitioning.
3451 const std::vector<unsigned int> cell_weights = get_cell_weights();
3452
3453 // verify that the global sum of weights is larger than 0
3454 Assert(Utilities::MPI::sum(std::accumulate(cell_weights.begin(),
3455 cell_weights.end(),
3456 std::uint64_t(0)),
3457 this->mpi_communicator) > 0,
3458 ExcMessage(
3459 "The global sum of weights over all active cells "
3460 "is zero. Please verify how you generate weights."));
3461
3462 PartitionWeights<dim, spacedim> partition_weights(cell_weights);
3463
3464 // attach (temporarily) a pointer to the cell weights through
3465 // p4est's user_pointer object
3466 Assert(parallel_forest->user_pointer == this, ExcInternalError());
3467 parallel_forest->user_pointer = &partition_weights;
3468
3470 parallel_forest,
3471 /* prepare coarsening */ 1,
3472 /* weight_callback */
3473 &PartitionWeights<dim, spacedim>::cell_weight);
3474
3475 // release data
3477 parallel_forest, 0, nullptr, nullptr);
3478 // reset the user pointer to its previous state
3479 parallel_forest->user_pointer = this;
3480 }
3481 }
3482
3483 // pack data before triangulation gets updated
3484 if (this->cell_attached_data.n_attached_data_sets > 0)
3485 {
3486 this->data_serializer.pack_data(
3487 this->local_cell_relations,
3488 this->cell_attached_data.pack_callbacks_fixed,
3489 this->cell_attached_data.pack_callbacks_variable,
3490 this->get_communicator());
3491 }
3492
3493 // finally copy back from local part of tree to deal.II
3494 // triangulation. before doing so, make sure there are no refine or
3495 // coarsen flags pending
3496 for (const auto &cell : this->active_cell_iterators())
3497 {
3498 cell->clear_refine_flag();
3499 cell->clear_coarsen_flag();
3500 }
3501
3502 try
3503 {
3504 copy_local_forest_to_triangulation();
3505 }
3506 catch (const typename Triangulation<dim>::DistortedCellList &)
3507 {
3508 // the underlying triangulation should not be checking for distorted
3509 // cells
3511 }
3512
3513 // transfer data after triangulation got updated
3514 if (this->cell_attached_data.n_attached_data_sets > 0)
3515 {
3516 this->execute_transfer(parallel_forest,
3517 previous_global_first_quadrant.data());
3518
3519 // also update the CellStatus information on the new mesh
3520 this->data_serializer.unpack_cell_status(this->local_cell_relations);
3521 }
3522
3523# ifdef DEBUG
3524 // Check that we know the level subdomain ids of all our neighbors. This
3525 // also involves coarser cells that share a vertex if they are active.
3526 //
3527 // Example (M= my, O=other):
3528 // *------*
3529 // | |
3530 // | O |
3531 // | |
3532 // *---*---*------*
3533 // | M | M |
3534 // *---*---*
3535 // | | M |
3536 // *---*---*
3537 // ^- the parent can be owned by somebody else, so O is not a neighbor
3538 // one level coarser
3539 if (settings & construct_multigrid_hierarchy)
3540 {
3541 for (unsigned int lvl = 0; lvl < this->n_global_levels(); ++lvl)
3542 {
3543 std::vector<bool> active_verts =
3544 this->mark_locally_active_vertices_on_level(lvl);
3545
3546 const unsigned int maybe_coarser_lvl =
3547 (lvl > 0) ? (lvl - 1) : lvl;
3549 cell = this->begin(maybe_coarser_lvl),
3550 endc = this->end(lvl);
3551 for (; cell != endc; ++cell)
3552 if (cell->level() == static_cast<int>(lvl) || cell->is_active())
3553 {
3554 const bool is_level_artificial =
3555 (cell->level_subdomain_id() ==
3557 bool need_to_know = false;
3558 for (const unsigned int vertex :
3560 if (active_verts[cell->vertex_index(vertex)])
3561 {
3562 need_to_know = true;
3563 break;
3564 }
3565
3566 Assert(
3567 !need_to_know || !is_level_artificial,
3568 ExcMessage(
3569 "Internal error: the owner of cell" +
3570 cell->id().to_string() +
3571 " is unknown even though it is needed for geometric multigrid."));
3572 }
3573 }
3574 }
3575# endif
3576
3577 this->update_periodic_face_map();
3578 this->update_number_cache();
3579
3580 // signal that refinement is finished
3581 this->signals.post_distributed_refinement();
3582 }
3583
3584
3585
3586 template <int dim, int spacedim>
3588 void Triangulation<dim, spacedim>::repartition()
3589 {
3590# ifdef DEBUG
3591 for (const auto &cell : this->active_cell_iterators())
3592 if (cell->is_locally_owned())
3593 Assert(
3594 !cell->refine_flag_set() && !cell->coarsen_flag_set(),
3595 ExcMessage(
3596 "Error: There shouldn't be any cells flagged for coarsening/refinement when calling repartition()."));
3597# endif
3598
3599 // signal that repartitioning is going to happen
3600 this->signals.pre_distributed_repartition();
3601
3602 // before repartitioning the mesh, save a copy of the current positions
3603 // of quadrants only if data needs to be transferred later
3604 std::vector<typename ::internal::p4est::types<dim>::gloidx>
3605 previous_global_first_quadrant;
3606
3607 if (this->cell_attached_data.n_attached_data_sets > 0)
3608 {
3609 previous_global_first_quadrant.resize(parallel_forest->mpisize + 1);
3610 std::memcpy(previous_global_first_quadrant.data(),
3611 parallel_forest->global_first_quadrant,
3612 sizeof(
3613 typename ::internal::p4est::types<dim>::gloidx) *
3614 (parallel_forest->mpisize + 1));
3615 }
3616
3617 if (this->signals.weight.empty())
3618 {
3619 // no cell weights given -- call p4est's 'partition' without a
3620 // callback for cell weights
3622 parallel_forest,
3623 /* prepare coarsening */ 1,
3624 /* weight_callback */ nullptr);
3625 }
3626 else
3627 {
3628 // get cell weights for a weighted repartitioning.
3629 const std::vector<unsigned int> cell_weights = get_cell_weights();
3630
3631 // verify that the global sum of weights is larger than 0
3632 Assert(Utilities::MPI::sum(std::accumulate(cell_weights.begin(),
3633 cell_weights.end(),
3634 std::uint64_t(0)),
3635 this->mpi_communicator) > 0,
3636 ExcMessage(
3637 "The global sum of weights over all active cells "
3638 "is zero. Please verify how you generate weights."));
3639
3640 PartitionWeights<dim, spacedim> partition_weights(cell_weights);
3641
3642 // attach (temporarily) a pointer to the cell weights through
3643 // p4est's user_pointer object
3644 Assert(parallel_forest->user_pointer == this, ExcInternalError());
3645 parallel_forest->user_pointer = &partition_weights;
3646
3648 parallel_forest,
3649 /* prepare coarsening */ 1,
3650 /* weight_callback */
3651 &PartitionWeights<dim, spacedim>::cell_weight);
3652
3653 // reset the user pointer to its previous state
3654 parallel_forest->user_pointer = this;
3655 }
3656
3657 // pack data before triangulation gets updated
3658 if (this->cell_attached_data.n_attached_data_sets > 0)
3659 {
3660 this->data_serializer.pack_data(
3661 this->local_cell_relations,
3662 this->cell_attached_data.pack_callbacks_fixed,
3663 this->cell_attached_data.pack_callbacks_variable,
3664 this->get_communicator());
3665 }
3666
3667 try
3668 {
3669 copy_local_forest_to_triangulation();
3670 }
3671 catch (const typename Triangulation<dim>::DistortedCellList &)
3672 {
3673 // the underlying triangulation should not be checking for distorted
3674 // cells
3676 }
3677
3678 // transfer data after triangulation got updated
3679 if (this->cell_attached_data.n_attached_data_sets > 0)
3680 {
3681 this->execute_transfer(parallel_forest,
3682 previous_global_first_quadrant.data());
3683 }
3684
3685 this->update_periodic_face_map();
3686
3687 // update how many cells, edges, etc, we store locally
3688 this->update_number_cache();
3689
3690 // signal that repartitioning is finished
3691 this->signals.post_distributed_repartition();
3692 }
3693
3694
3695
3696 template <int dim, int spacedim>
3698 const std::vector<types::global_dof_index>
3700 const
3701 {
3702 return p4est_tree_to_coarse_cell_permutation;
3703 }
3704
3705
3706
3707 template <int dim, int spacedim>
3709 const std::vector<types::global_dof_index>
3711 const
3712 {
3713 return coarse_cell_to_p4est_tree_permutation;
3714 }
3715
3716
3717
3718 template <int dim, int spacedim>
3720 std::vector<bool> Triangulation<dim, spacedim>::
3721 mark_locally_active_vertices_on_level(const int level) const
3722 {
3723 Assert(dim > 1, ExcNotImplemented());
3724
3725 std::vector<bool> marked_vertices(this->n_vertices(), false);
3726 for (const auto &cell : this->cell_iterators_on_level(level))
3727 if (cell->level_subdomain_id() == this->locally_owned_subdomain())
3728 for (const unsigned int v : GeometryInfo<dim>::vertex_indices())
3729 marked_vertices[cell->vertex_index(v)] = true;
3730
3736 // When a connectivity in the code below is detected, the assignment
3737 // 'marked_vertices[v1] = marked_vertices[v2] = true' makes sure that
3738 // the information about the periodicity propagates back to vertices on
3739 // cells that are not owned locally. However, in the worst case we want
3740 // to connect to a vertex that is 'dim' hops away from the locally owned
3741 // cell. Depending on the order of the periodic face map, we might
3742 // connect to that point by chance or miss it. However, after looping
3743 // through all the periodic directions (which are at most as many as
3744 // the number of space dimensions) we can be sure that all connections
3745 // to vertices have been created.
3746 for (unsigned int repetition = 0; repetition < dim; ++repetition)
3747 for (const auto &it : this->get_periodic_face_map())
3748 {
3749 const cell_iterator &cell_1 = it.first.first;
3750 const unsigned int face_no_1 = it.first.second;
3751 const cell_iterator &cell_2 = it.second.first.first;
3752 const unsigned int face_no_2 = it.second.first.second;
3753 const unsigned char combined_orientation = it.second.second;
3754 const auto [orientation, rotation, flip] =
3755 ::internal::split_face_orientation(combined_orientation);
3756
3757 if (cell_1->level() == level && cell_2->level() == level)
3758 {
3759 for (unsigned int v = 0;
3760 v < GeometryInfo<dim - 1>::vertices_per_cell;
3761 ++v)
3762 {
3763 // take possible non-standard orientation of faces into
3764 // account
3765 const unsigned int vface0 =
3767 v, orientation, flip, rotation);
3768 if (marked_vertices[cell_1->face(face_no_1)->vertex_index(
3769 vface0)] ||
3770 marked_vertices[cell_2->face(face_no_2)->vertex_index(
3771 v)])
3772 marked_vertices[cell_1->face(face_no_1)->vertex_index(
3773 vface0)] =
3774 marked_vertices[cell_2->face(face_no_2)->vertex_index(
3775 v)] = true;
3776 }
3777 }
3778 }
3779
3780 return marked_vertices;
3781 }
3782
3783
3784
3785 template <int dim, int spacedim>
3787 unsigned int Triangulation<dim, spacedim>::
3788 coarse_cell_id_to_coarse_cell_index(
3789 const types::coarse_cell_id coarse_cell_id) const
3790 {
3791 return p4est_tree_to_coarse_cell_permutation[coarse_cell_id];
3792 }
3793
3794
3795
3796 template <int dim, int spacedim>
3800 const unsigned int coarse_cell_index) const
3801 {
3802 return coarse_cell_to_p4est_tree_permutation[coarse_cell_index];
3803 }
3804
3805
3806
3807 template <int dim, int spacedim>
3809 void Triangulation<dim, spacedim>::add_periodicity(
3810 const std::vector<::GridTools::PeriodicFacePair<cell_iterator>>
3811 &periodicity_vector)
3812 {
3813 Assert(triangulation_has_content == true,
3814 ExcMessage("The triangulation is empty!"));
3815 Assert(this->n_levels() == 1,
3816 ExcMessage("The triangulation is refined!"));
3817
3818 // call the base class for storing the periodicity information; we must
3819 // do this before going to p4est and rebuilding the triangulation to get
3820 // the level subdomain ids correct in the multigrid case
3822
3823 const auto reference_cell = ReferenceCells::get_hypercube<dim>();
3824 const auto face_reference_cell = ReferenceCells::get_hypercube<dim - 1>();
3825 for (const auto &face_pair : periodicity_vector)
3826 {
3827 const cell_iterator first_cell = face_pair.cell[0];
3828 const cell_iterator second_cell = face_pair.cell[1];
3829 const unsigned int face_left = face_pair.face_idx[0];
3830 const unsigned int face_right = face_pair.face_idx[1];
3831
3832 // respective cells of the matching faces in p4est
3833 const unsigned int tree_left =
3834 coarse_cell_to_p4est_tree_permutation[first_cell->index()];
3835 const unsigned int tree_right =
3836 coarse_cell_to_p4est_tree_permutation[second_cell->index()];
3837
3838 // p4est wants to know which corner the first corner on the face with
3839 // the lower id is mapped to on the face with with the higher id. For
3840 // d==2 there are only two possibilities: i.e., face_pair.orientation
3841 // must be 0 or 1. For d==3 we have to use a lookup table. The result
3842 // is given below.
3843
3844 unsigned int p4est_orientation = 0;
3845 if (dim == 2)
3846 {
3847 AssertIndexRange(face_pair.orientation, 2);
3848 p4est_orientation =
3849 face_pair.orientation ==
3851 0u :
3852 1u;
3853 }
3854 else
3855 {
3856 const unsigned int face_idx_list[] = {face_left, face_right};
3857 const cell_iterator cell_list[] = {first_cell, second_cell};
3858 unsigned int lower_idx, higher_idx;
3859 unsigned char orientation;
3860 if (face_left <= face_right)
3861 {
3862 higher_idx = 1;
3863 lower_idx = 0;
3864 orientation =
3865 face_reference_cell.get_inverse_combined_orientation(
3866 face_pair.orientation);
3867 }
3868 else
3869 {
3870 higher_idx = 0;
3871 lower_idx = 1;
3872 orientation = face_pair.orientation;
3873 }
3874
3875 // get the cell index of the first index on the face with the
3876 // lower id
3877 unsigned int first_p4est_idx_on_cell =
3878 p8est_face_corners[face_idx_list[lower_idx]][0];
3879 unsigned int first_dealii_idx_on_face =
3881 for (unsigned int i = 0; i < GeometryInfo<dim>::vertices_per_face;
3882 ++i)
3883 {
3884 const unsigned int first_dealii_idx_on_cell =
3886 face_idx_list[lower_idx],
3887 i,
3888 cell_list[lower_idx]->face_orientation(
3889 face_idx_list[lower_idx]),
3890 cell_list[lower_idx]->face_flip(face_idx_list[lower_idx]),
3891 cell_list[lower_idx]->face_rotation(
3892 face_idx_list[lower_idx]));
3893 if (first_p4est_idx_on_cell == first_dealii_idx_on_cell)
3894 {
3895 first_dealii_idx_on_face = i;
3896 break;
3897 }
3898 }
3899 Assert(first_dealii_idx_on_face != numbers::invalid_unsigned_int,
3901
3902 // Now map dealii_idx_on_face according to the orientation.
3903 const unsigned int second_dealii_idx_on_face =
3904 reference_cell.standard_to_real_face_vertex(
3905 first_dealii_idx_on_face,
3906 face_idx_list[lower_idx],
3907 orientation);
3908 const unsigned int second_dealii_idx_on_cell =
3909 reference_cell.face_to_cell_vertices(
3910 face_idx_list[higher_idx],
3911 second_dealii_idx_on_face,
3912 cell_list[higher_idx]->combined_face_orientation(
3913 face_idx_list[higher_idx]));
3914 // map back to p4est
3915 const unsigned int second_p4est_idx_on_face =
3916 p8est_corner_face_corners[second_dealii_idx_on_cell]
3917 [face_idx_list[higher_idx]];
3918 p4est_orientation = second_p4est_idx_on_face;
3919 }
3920
3922 connectivity,
3923 tree_left,
3924 tree_right,
3925 face_left,
3926 face_right,
3927 p4est_orientation);
3928 }
3929
3930
3932 connectivity) == 1,
3934
3935 // now create a forest out of the connectivity data structure
3938 this->mpi_communicator,
3939 connectivity,
3940 /* minimum initial number of quadrants per tree */ 0,
3941 /* minimum level of upfront refinement */ 0,
3942 /* use uniform upfront refinement */ 1,
3943 /* user_data_size = */ 0,
3944 /* user_data_constructor = */ nullptr,
3945 /* user_pointer */ this);
3946
3947 try
3948 {
3949 copy_local_forest_to_triangulation();
3950 }
3951 catch (const typename Triangulation<dim>::DistortedCellList &)
3952 {
3953 // the underlying triangulation should not be checking for distorted
3954 // cells
3956 }
3957
3958 // The range of ghost_owners might have changed so update that
3959 // information
3960 this->update_number_cache();
3961 }
3962
3963
3964
3965 template <int dim, int spacedim>
3967 std::size_t Triangulation<dim, spacedim>::memory_consumption() const
3968 {
3969 std::size_t mem =
3972 MemoryConsumption::memory_consumption(triangulation_has_content) +
3974 MemoryConsumption::memory_consumption(parallel_forest) +
3976 this->cell_attached_data.n_attached_data_sets) +
3977 // MemoryConsumption::memory_consumption(cell_attached_data.pack_callbacks_fixed)
3978 // +
3979 // MemoryConsumption::memory_consumption(cell_attached_data.pack_callbacks_variable)
3980 // +
3981 // TODO[TH]: how?
3983 coarse_cell_to_p4est_tree_permutation) +
3985 p4est_tree_to_coarse_cell_permutation) +
3986 memory_consumption_p4est();
3987
3988 return mem;
3989 }
3990
3991
3992
3993 template <int dim, int spacedim>
3995 std::size_t Triangulation<dim, spacedim>::memory_consumption_p4est() const
3996 {
3997 return ::internal::p4est::functions<dim>::forest_memory_used(
3998 parallel_forest) +
4000 connectivity);
4001 }
4002
4003
4004
4005 template <int dim, int spacedim>
4007 void Triangulation<dim, spacedim>::copy_triangulation(
4008 const ::Triangulation<dim, spacedim> &other_tria)
4009 {
4010 Assert(
4011 (dynamic_cast<
4012 const ::parallel::distributed::Triangulation<dim, spacedim> *>(
4013 &other_tria)) ||
4014 (other_tria.n_global_levels() == 1),
4016
4018
4019 try
4020 {
4022 copy_triangulation(other_tria);
4023 }
4024 catch (
4025 const typename ::Triangulation<dim, spacedim>::DistortedCellList
4026 &)
4027 {
4028 // the underlying triangulation should not be checking for distorted
4029 // cells
4031 }
4032
4033 if (const ::parallel::distributed::Triangulation<dim, spacedim>
4034 *other_distributed =
4035 dynamic_cast<const ::parallel::distributed::
4036 Triangulation<dim, spacedim> *>(&other_tria))
4037 {
4038 // copy parallel distributed specifics
4039 settings = other_distributed->settings;
4040 triangulation_has_content =
4041 other_distributed->triangulation_has_content;
4042 coarse_cell_to_p4est_tree_permutation =
4043 other_distributed->coarse_cell_to_p4est_tree_permutation;
4044 p4est_tree_to_coarse_cell_permutation =
4045 other_distributed->p4est_tree_to_coarse_cell_permutation;
4046
4047 // create deep copy of connectivity graph
4048 typename ::internal::p4est::types<dim>::connectivity
4049 *temp_connectivity = const_cast<
4050 typename ::internal::p4est::types<dim>::connectivity *>(
4051 other_distributed->connectivity);
4052 connectivity =
4053 ::internal::p4est::copy_connectivity<dim>(temp_connectivity);
4054
4055 // create deep copy of parallel forest
4056 typename ::internal::p4est::types<dim>::forest *temp_forest =
4057 const_cast<typename ::internal::p4est::types<dim>::forest *>(
4058 other_distributed->parallel_forest);
4059 parallel_forest =
4061 false);
4062 parallel_forest->connectivity = connectivity;
4063 parallel_forest->user_pointer = this;
4064 }
4065 else
4066 {
4067 triangulation_has_content = true;
4068 setup_coarse_cell_to_p4est_tree_permutation();
4069 copy_new_triangulation_to_p4est(std::integral_constant<int, dim>());
4070 }
4071
4072 try
4073 {
4074 copy_local_forest_to_triangulation();
4075 }
4076 catch (const typename Triangulation<dim>::DistortedCellList &)
4077 {
4078 // the underlying triangulation should not be checking for distorted
4079 // cells
4081 }
4082
4083 this->update_periodic_face_map();
4084 this->update_number_cache();
4085 }
4086
4087
4088
4089 template <int dim, int spacedim>
4091 void Triangulation<dim, spacedim>::update_cell_relations()
4092 {
4093 // reorganize memory for local_cell_relations
4094 this->local_cell_relations.resize(parallel_forest->local_num_quadrants);
4095 this->local_cell_relations.shrink_to_fit();
4096
4097 // recurse over p4est
4098 for (const auto &cell : this->cell_iterators_on_level(0))
4099 {
4100 // skip coarse cells that are not ours
4101 if (tree_exists_locally<dim, spacedim>(
4102 parallel_forest,
4103 coarse_cell_to_p4est_tree_permutation[cell->index()]) == false)
4104 continue;
4105
4106 // initialize auxiliary top level p4est quadrant
4107 typename ::internal::p4est::types<dim>::quadrant
4108 p4est_coarse_cell;
4109 ::internal::p4est::init_coarse_quadrant<dim>(p4est_coarse_cell);
4110
4111 // determine tree to start recursion on
4112 typename ::internal::p4est::types<dim>::tree *tree =
4113 init_tree(cell->index());
4114
4115 update_cell_relations_recursively<dim, spacedim>(
4116 this->local_cell_relations, *tree, cell, p4est_coarse_cell);
4117 }
4118 }
4119
4120
4121
4122 template <int dim, int spacedim>
4124 std::vector<unsigned int> Triangulation<dim, spacedim>::get_cell_weights()
4125 const
4126 {
4127 // check if local_cell_relations have been previously gathered
4128 // correctly
4129 Assert(this->local_cell_relations.size() ==
4130 static_cast<unsigned int>(parallel_forest->local_num_quadrants),
4132
4133 // Allocate the space for the weights. We reserve an integer for each
4134 // locally owned quadrant on the already refined p4est object.
4135 std::vector<unsigned int> weights;
4136 weights.reserve(this->local_cell_relations.size());
4137
4138 // Iterate over p4est and Triangulation relations
4139 // to find refined/coarsened/kept
4140 // cells. Then append weight.
4141 // Note that we need to follow the p4est ordering
4142 // instead of the deal.II ordering to get the weights
4143 // in the same order p4est will encounter them during repartitioning.
4144 for (const auto &cell_rel : this->local_cell_relations)
4145 {
4146 const auto &cell_it = cell_rel.first;
4147 const auto &cell_status = cell_rel.second;
4148
4149 weights.push_back(this->signals.weight(cell_it, cell_status));
4150 }
4151
4152 return weights;
4153 }
4154
4155
4156
4157 template <int spacedim>
4160 const MPI_Comm mpi_communicator,
4161 const typename ::Triangulation<1, spacedim>::MeshSmoothing
4162 smooth_grid,
4163 const Settings /*settings*/)
4164 : ::parallel::DistributedTriangulationBase<1, spacedim>(
4165 mpi_communicator,
4166 smooth_grid,
4167 false)
4168 {
4170 }
4171
4172
4173 template <int spacedim>
4176 {
4178 }
4179
4180
4181
4182 template <int spacedim>
4184 const std::vector<types::global_dof_index>
4186 const
4187 {
4188 static std::vector<types::global_dof_index> a;
4189 return a;
4190 }
4191
4192
4193
4194 template <int spacedim>
4196 std::map<unsigned int,
4197 std::set<::types::subdomain_id>> Triangulation<1, spacedim>::
4199 const unsigned int /*level*/) const
4200 {
4202
4203 return std::map<unsigned int, std::set<::types::subdomain_id>>();
4204 }
4205
4206
4207
4208 template <int spacedim>
4210 std::vector<bool> Triangulation<1, spacedim>::
4211 mark_locally_active_vertices_on_level(const unsigned int) const
4212 {
4214 return std::vector<bool>();
4215 }
4216
4217
4218
4219 template <int spacedim>
4221 unsigned int Triangulation<1, spacedim>::
4222 coarse_cell_id_to_coarse_cell_index(const types::coarse_cell_id) const
4223 {
4225 return 0;
4226 }
4227
4228
4229
4230 template <int spacedim>
4234 const unsigned int) const
4235 {
4237 return 0;
4238 }
4239
4240
4241
4242 template <int spacedim>
4244 void Triangulation<1, spacedim>::load(const std::string &)
4245 {
4247 }
4248
4249
4250
4251 template <int spacedim>
4253 void Triangulation<1, spacedim>::load(const std::string &, const bool)
4254 {
4256 }
4257
4258
4259
4260 template <int spacedim>
4262 void Triangulation<1, spacedim>::save(const std::string &) const
4263 {
4265 }
4266
4267
4268
4269 template <int spacedim>
4271 bool Triangulation<1, spacedim>::is_multilevel_hierarchy_constructed() const
4272 {
4274 return false;
4275 }
4276
4277
4278
4279 template <int spacedim>
4281 bool Triangulation<1, spacedim>::are_vertices_communicated_to_p4est() const
4282 {
4284 return false;
4285 }
4286
4287
4288
4289 template <int spacedim>
4291 void Triangulation<1, spacedim>::update_cell_relations()
4292 {
4294 }
4295
4296 } // namespace distributed
4297} // namespace parallel
4298
4299
4300#endif // DEAL_II_WITH_P4EST
4301
4302
4303
4304namespace parallel
4305{
4306 namespace distributed
4307 {
4308 template <int dim, int spacedim>
4311 : distributed_tria(
4312 dynamic_cast<
4313 ::parallel::distributed::Triangulation<dim, spacedim> *>(
4314 &tria))
4315 {
4316#ifdef DEAL_II_WITH_P4EST
4317 if (distributed_tria != nullptr)
4318 {
4319 // Save the current set of refinement flags, and adjust the
4320 // refinement flags to be consistent with the p4est oracle.
4321 distributed_tria->save_coarsen_flags(saved_coarsen_flags);
4322 distributed_tria->save_refine_flags(saved_refine_flags);
4323
4324 for (const auto &pair : distributed_tria->local_cell_relations)
4325 {
4326 const auto &cell = pair.first;
4327 const auto &status = pair.second;
4328
4329 switch (status)
4330 {
4332 // cell remains unchanged
4333 cell->clear_refine_flag();
4334 cell->clear_coarsen_flag();
4335 break;
4336
4338 // cell will be refined
4339 cell->clear_coarsen_flag();
4340 cell->set_refine_flag();
4341 break;
4342
4344 // children of this cell will be coarsened
4345 for (const auto &child : cell->child_iterators())
4346 {
4347 child->clear_refine_flag();
4348 child->set_coarsen_flag();
4349 }
4350 break;
4351
4353 // do nothing as cell does not exist yet
4354 break;
4355
4356 default:
4358 break;
4359 }
4360 }
4361 }
4362#endif
4363 }
4364
4365
4366
4367 template <int dim, int spacedim>
4369 {
4370#ifdef DEAL_II_WITH_P4EST
4371 if (distributed_tria)
4372 {
4373 // Undo the refinement flags modification.
4374 distributed_tria->load_coarsen_flags(saved_coarsen_flags);
4375 distributed_tria->load_refine_flags(saved_refine_flags);
4376 }
4377#else
4378 // pretend that this destructor does something to silence clang-tidy
4379 (void)distributed_tria;
4380#endif
4381 }
4382 } // namespace distributed
4383} // namespace parallel
4384
4385
4386
4387/*-------------- Explicit Instantiations -------------------------------*/
4388#include "tria.inst"
4389
4390
CellStatus
Definition cell_status.h:31
@ cell_will_be_refined
@ children_will_be_coarsened
Definition point.h:111
static constexpr unsigned char default_combined_face_orientation()
virtual void add_periodicity(const std::vector< GridTools::PeriodicFacePair< cell_iterator > > &)
virtual void clear()
const std::map< std::pair< cell_iterator, unsigned int >, std::pair< std::pair< cell_iterator, unsigned int >, unsigned char > > & get_periodic_face_map() const
active_cell_iterator last_active() const
virtual void create_triangulation(const std::vector< Point< spacedim > > &vertices, const std::vector< CellData< dim > > &cells, const SubCellData &subcelldata)
cell_iterator end() const
virtual types::coarse_cell_id coarse_cell_index_to_coarse_cell_id(const unsigned int coarse_cell_index) const
virtual void execute_coarsening_and_refinement()
virtual bool prepare_coarsening_and_refinement()
void save_refine_flags(std::ostream &out) const
unsigned int n_vertices() const
void save_coarsen_flags(std::ostream &out) const
active_cell_iterator begin_active(const unsigned int level=0) const
virtual std::size_t memory_consumption() const override
Definition tria_base.cc:92
virtual void clear() override
Definition tria_base.cc:687
virtual void copy_triangulation(const ::Triangulation< dim, spacedim > &old_tria) override
Definition tria_base.cc:67
const SmartPointer< ::parallel::distributed::Triangulation< dim, spacedim > > distributed_tria
Definition tria.h:1169
virtual void clear() override
Definition tria.cc:1864
#define DEAL_II_NAMESPACE_OPEN
Definition config.h:502
#define DEAL_II_CXX20_REQUIRES(condition)
Definition config.h:177
#define DEAL_II_NAMESPACE_CLOSE
Definition config.h:503
Point< 3 > vertices[4]
unsigned int level
Definition grid_out.cc:4626
unsigned int vertex_indices[2]
static ::ExceptionBase & ExcIO()
static ::ExceptionBase & ExcNotImplemented()
#define Assert(cond, exc)
#define AssertNothrow(cond, exc)
#define AssertIndexRange(index, range)
static ::ExceptionBase & ExcInternalError()
static ::ExceptionBase & ExcMessage(std::string arg1)
#define AssertThrow(cond, exc)
typename ::Triangulation< dim, spacedim >::cell_iterator cell_iterator
Definition tria.h:288
typename ::Triangulation< dim, spacedim >::active_cell_iterator active_cell_iterator
Definition tria.h:309
#define DEAL_II_ASSERT_UNREACHABLE()
#define DEAL_II_NOT_IMPLEMENTED()
void get_vertex_connectivity_of_cells(const Triangulation< dim, spacedim > &triangulation, DynamicSparsityPattern &connectivity)
std::enable_if_t< std::is_fundamental_v< T >, std::size_t > memory_consumption(const T &t)
Point< spacedim > point(const gp_Pnt &p, const double tolerance=1e-10)
Definition utilities.cc:191
SymmetricTensor< 2, dim, Number > e(const Tensor< 2, dim, Number > &F)
Tensor< 2, dim, Number > l(const Tensor< 2, dim, Number > &F, const Tensor< 2, dim, Number > &dF_dt)
SymmetricTensor< 2, dim, Number > d(const Tensor< 2, dim, Number > &F, const Tensor< 2, dim, Number > &dF_dt)
constexpr const ReferenceCell & get_hypercube()
void reorder_hierarchical(const DynamicSparsityPattern &sparsity, std::vector< DynamicSparsityPattern::size_type > &new_indices)
VectorType::value_type * end(VectorType &V)
std::enable_if_t< is_mpi_type< T >==false, T > broadcast(const MPI_Comm comm, const T &object_to_send, const unsigned int root_process=0)
T sum(const T &t, const MPI_Comm mpi_communicator)
unsigned int n_mpi_processes(const MPI_Comm mpi_communicator)
Definition mpi.cc:92
unsigned int this_mpi_process(const MPI_Comm mpi_communicator)
Definition mpi.cc:107
std::vector< Integer > invert_permutation(const std::vector< Integer > &permutation)
Definition utilities.h:1699
bool tree_exists_locally(const typename types< dim >::forest *parallel_forest, const typename types< dim >::topidx coarse_grid_cell)
void exchange_refinement_flags(::parallel::distributed::Triangulation< dim, spacedim > &tria)
Definition tria.cc:56
std::tuple< bool, bool, bool > split_face_orientation(const unsigned char combined_face_orientation)
const types::subdomain_id artificial_subdomain_id
Definition types.h:362
const types::subdomain_id invalid_subdomain_id
Definition types.h:341
static const unsigned int invalid_unsigned_int
Definition types.h:220
const types::manifold_id flat_manifold_id
Definition types.h:325
STL namespace.
::VectorizedArray< Number, width > min(const ::VectorizedArray< Number, width > &, const ::VectorizedArray< Number, width > &)
Definition types.h:32
const ::parallel::distributed::Triangulation< dim, spacedim > * triangulation
static unsigned int standard_to_real_face_vertex(const unsigned int vertex, const bool face_orientation=true, const bool face_flip=false, const bool face_rotation=false)
static unsigned int face_to_cell_vertices(const unsigned int face, const unsigned int vertex, const bool face_orientation=true, const bool face_flip=false, const bool face_rotation=false)
static std_cxx20::ranges::iota_view< unsigned int, unsigned int > vertex_indices()
static bool is_inside_unit_cell(const Point< dim > &p)
static Point< dim > unit_cell_vertex(const unsigned int vertex)