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