PolyDEAL
Loading...
Searching...
No Matches
poly_utils.h
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) XXXX - YYYY by the polyDEAL authors
5//
6// This file is part of the polyDEAL library.
7//
8// Detailed license information governing the source code
9// can be found in LICENSE.md at the top level directory.
10//
11// -----------------------------------------------------------------------------
12
13
14#ifndef poly_utils_h
15#define poly_utils_h
16
17
18#include <deal.II/base/config.h>
19
21#include <deal.II/base/point.h>
25
29
31
33
34#include <deal.II/fe/fe_dgq.h>
36
38
44
46
47#include <boost/geometry/algorithms/distance.hpp>
48#include <boost/geometry/index/detail/rtree/utilities/print.hpp>
49#include <boost/geometry/index/rtree.hpp>
50#include <boost/geometry/strategies/strategies.hpp>
51
53
54#ifdef DEAL_II_WITH_TRILINOS
55# include <EpetraExt_RowMatrixOut.h>
56#endif
57
58#ifdef DEAL_II_WITH_CGAL
59
60# include <CGAL/Constrained_Delaunay_triangulation_2.h>
61# include <CGAL/Constrained_triangulation_plus_2.h>
62# include <CGAL/Exact_predicates_exact_constructions_kernel.h>
63# include <CGAL/Exact_predicates_exact_constructions_kernel_with_sqrt.h>
64# include <CGAL/Polygon_2.h>
65# include <CGAL/Polygon_with_holes_2.h>
66# include <CGAL/Segment_Delaunay_graph_2.h>
67# include <CGAL/Segment_Delaunay_graph_traits_2.h>
68# include <CGAL/intersections.h>
69# include <CGAL/squared_distance_2.h>
70# include <CGAL/squared_distance_3.h>
71
72
73#endif
74
75#include <memory>
76
77
79{
84 get_index(const std::vector<types::global_cell_index> &v,
85 const types::global_cell_index index)
86 {
87 return std::distance(v.begin(), std::find(v.begin(), v.end(), index));
88 }
89
90
91
96 template <int dim, int spacedim>
97 void
100 &triangulation,
101 DynamicSparsityPattern &cell_connectivity,
102 const std::vector<types::global_cell_index> locally_owned_cells)
103 {
104 cell_connectivity.reinit(triangulation.n_locally_owned_active_cells(),
105 triangulation.n_locally_owned_active_cells());
106
107
108 // loop over all cells and their neighbors to build the sparsity
109 // pattern. note that it's a bit hard to enter all the connections when
110 // a neighbor has children since we would need to find out which of its
111 // children is adjacent to the current cell. this problem can be omitted
112 // if we only do something if the neighbor has no children -- in that
113 // case it is either on the same or a coarser level than we are. in
114 // return, we have to add entries in both directions for both cells
115 for (const auto &cell : triangulation.active_cell_iterators())
116 {
117 if (cell->is_locally_owned())
118 {
119 const unsigned int index = cell->active_cell_index();
120 cell_connectivity.add(get_index(locally_owned_cells, index),
121 get_index(locally_owned_cells, index));
122 for (auto f : cell->face_indices())
123 if ((cell->at_boundary(f) == false) &&
124 (cell->neighbor(f)->has_children() == false) &&
125 cell->neighbor(f)->is_locally_owned())
126 {
127 const unsigned int other_index =
128 cell->neighbor(f)->active_cell_index();
129
130 cell_connectivity.add(get_index(locally_owned_cells, index),
131 get_index(locally_owned_cells,
132 other_index));
133 cell_connectivity.add(get_index(locally_owned_cells,
134 other_index),
135 get_index(locally_owned_cells, index));
136 }
137 }
138 }
139 }
140} // namespace dealii::PolyUtils::internal
141
142
143namespace dealii::PolyUtils
144{
145 template <typename Value,
146 typename Options,
147 typename Translator,
148 typename Box,
149 typename Allocators>
150 struct Rtree_visitor : public boost::geometry::index::detail::rtree::visitor<
151 Value,
152 typename Options::parameters_type,
153 Box,
154 Allocators,
155 typename Options::node_tag,
156 true>::type
157 {
158 inline Rtree_visitor(
159 const Translator &translator,
160 unsigned int target_level,
161 std::vector<std::vector<typename Triangulation<
162 boost::geometry::dimension<Box>::value>::active_cell_iterator>> &boxes,
163 std::vector<std::vector<unsigned int>> &csr);
164
165
170 typename boost::geometry::index::detail::rtree::internal_node<
171 Value,
172 typename Options::parameters_type,
173 Box,
174 Allocators,
175 typename Options::node_tag>::type;
176
180 using Leaf = typename boost::geometry::index::detail::rtree::leaf<
181 Value,
182 typename Options::parameters_type,
183 Box,
184 Allocators,
185 typename Options::node_tag>::type;
186
191 inline void
192 operator()(const InternalNode &node);
193
197 inline void
198 operator()(const Leaf &);
199
203 const Translator &translator;
204
208 size_t level;
209
215
221 const size_t target_level;
222
228 std::vector<std::vector<typename Triangulation<
229 boost::geometry::dimension<Box>::value>::active_cell_iterator>>
231
232 std::vector<std::vector<unsigned int>> &row_ptr;
233 };
234
235
236
237 template <typename Value,
238 typename Options,
239 typename Translator,
240 typename Box,
241 typename Allocators>
243 const Translator &translator,
244 const unsigned int target_level,
245 std::vector<std::vector<typename Triangulation<
246 boost::geometry::dimension<Box>::value>::active_cell_iterator>>
247 &bb_in_boxes,
248 std::vector<std::vector<unsigned int>> &csr)
250 , level(0)
251 , node_counter(0)
254 , agglomerates(bb_in_boxes)
255 , row_ptr(csr)
256 {}
257
258
259
260 template <typename Value,
261 typename Options,
262 typename Translator,
263 typename Box,
264 typename Allocators>
265 void
267 const Rtree_visitor::InternalNode &node)
268 {
269 using elements_type =
270 typename boost::geometry::index::detail::rtree::elements_type<
271 InternalNode>::type; // pairs of bounding box and pointer to child node
272 const elements_type &elements =
273 boost::geometry::index::detail::rtree::elements(node);
274
275 if (level < target_level)
276 {
277 size_t level_backup = level;
278 ++level;
279
280 for (typename elements_type::const_iterator it = elements.begin();
281 it != elements.end();
282 ++it)
283 {
284 boost::geometry::index::detail::rtree::apply_visitor(*this,
285 *it->second);
286 }
287
288 level = level_backup;
289 }
290 else if (level == target_level)
291 {
292 // const unsigned int n_children = elements.size();
293 const auto offset = agglomerates.size();
294 agglomerates.resize(offset + 1);
295 row_ptr.resize(row_ptr.size() + 1);
297 row_ptr.back().push_back(
298 next_level_leafs_processed); // convention: row_ptr[0]=0
299 size_t level_backup = level;
300
301 ++level;
302 for (const auto &child : elements)
303 {
304 boost::geometry::index::detail::rtree::apply_visitor(*this,
305 *child.second);
306 }
307 // Done with node number 'node_counter'
308
309 ++node_counter; // visited all children of an internal node
310
311 level = level_backup;
312 }
313 else if (level > target_level)
314 {
315 // Keep visiting until you go to the leafs.
316 size_t level_backup = level;
317
318 ++level;
319
320 for (const auto &child : elements)
321 {
322 boost::geometry::index::detail::rtree::apply_visitor(*this,
323 *child.second);
324 }
325 level = level_backup;
327 }
328 }
329
330
331
332 template <typename Value,
333 typename Options,
334 typename Translator,
335 typename Box,
336 typename Allocators>
337 void
339 const Rtree_visitor::Leaf &leaf)
340 {
341 using elements_type =
342 typename boost::geometry::index::detail::rtree::elements_type<
343 Leaf>::type; // pairs of bounding box and pointer to child node
344 const elements_type &elements =
345 boost::geometry::index::detail::rtree::elements(leaf);
346
347
348 for (const auto &it : elements)
349 {
350 agglomerates[node_counter].push_back(it.second);
351 }
352 next_level_leafs_processed += elements.size();
353 }
354
355 template <typename Rtree>
356 inline std::pair<
357 std::vector<std::vector<unsigned int>>,
358 std::vector<std::vector<typename Triangulation<boost::geometry::dimension<
359 typename Rtree::indexable_type>::value>::active_cell_iterator>>>
360 extract_children_of_level(const Rtree &tree, const unsigned int level)
361 {
362 using RtreeView =
363 boost::geometry::index::detail::rtree::utilities::view<Rtree>;
364 RtreeView rtv(tree);
365
366 std::vector<std::vector<unsigned int>> csrs;
367 std::vector<std::vector<typename Triangulation<boost::geometry::dimension<
368 typename Rtree::indexable_type>::value>::active_cell_iterator>>
369 agglomerates;
370
371 if (rtv.depth() == 0)
372 {
373 // The below algorithm does not work for `rtv.depth()==0`, which might
374 // happen if the number entries in the tree is too small.
375 // In this case, simply return a single bounding box.
376 agglomerates.resize(1);
377 agglomerates[0].resize(1);
378 csrs.resize(1);
379 csrs[0].resize(1);
380 }
381 else
382 {
383 const unsigned int target_level =
384 std::min<unsigned int>(level, rtv.depth());
385
386 Rtree_visitor<typename RtreeView::value_type,
387 typename RtreeView::options_type,
388 typename RtreeView::translator_type,
389 typename RtreeView::box_type,
390 typename RtreeView::allocators_type>
391 node_visitor(rtv.translator(), target_level, agglomerates, csrs);
392 rtv.apply_visitor(node_visitor);
393 }
394 AssertDimension(agglomerates.size(), csrs.size());
395
396 return {csrs, agglomerates};
397 }
398
399
400 template <int dim, typename Number = double>
401 Number
403 const unsigned int face_index,
404 const std::vector<typename Triangulation<dim>::active_face_iterator>
405 &polygon_boundary,
406 const Tensor<1, dim> &deal_normal)
407 {
408#ifdef DEAL_II_WITH_CGAL
409
410 using Kernel = CGAL::Exact_predicates_exact_constructions_kernel;
411 std::vector<typename Kernel::FT> candidates;
412 candidates.reserve(polygon_boundary.size() - 1);
413
414 // Initialize the range of faces to be checked for intersection: they are
415 // {0,..,n_faces-1}\setminus the current face index face_index.
416 std::vector<unsigned int> face_indices(polygon_boundary.size());
417 std::iota(face_indices.begin(), face_indices.end(), 0); // fill the range
418 face_indices.erase(face_indices.cbegin() +
419 face_index); // remove current index
420
421 if constexpr (dim == 2)
422 {
423 typename Kernel::Segment_2 face_segm(
424 {polygon_boundary[face_index]->vertex(0)[0],
425 polygon_boundary[face_index]->vertex(0)[1]},
426 {polygon_boundary[face_index]->vertex(1)[0],
427 polygon_boundary[face_index]->vertex(1)[1]});
428
429 // Shoot a ray from the midpoint of the face in the orthogonal direction
430 // given by deal.II normals
431 const auto &midpoint = CGAL::midpoint(face_segm);
432 // deal.II normal is always outward, flip the direction
433 const typename Kernel::Vector_2 orthogonal_direction{-deal_normal[0],
434 -deal_normal[1]};
435 const typename Kernel::Ray_2 ray(midpoint, orthogonal_direction);
436 for (const auto f : face_indices)
437 {
438 typename Kernel::Segment_2 segm({polygon_boundary[f]->vertex(0)[0],
439 polygon_boundary[f]->vertex(0)[1]},
440 {polygon_boundary[f]->vertex(1)[0],
441 polygon_boundary[f]->vertex(
442 1)[1]});
443
444 if (CGAL::do_intersect(ray, segm))
445 candidates.push_back(CGAL::squared_distance(midpoint, segm));
446 }
447 return std::sqrt(CGAL::to_double(
448 *std::min_element(candidates.cbegin(), candidates.cend())));
449 }
450 else if constexpr (dim == 3)
451 {
452 const typename Kernel::Point_3 &center{
453 polygon_boundary[face_index]->center()[0],
454 polygon_boundary[face_index]->center()[1],
455 polygon_boundary[face_index]->center()[2]};
456 // deal.II normal is always outward, flip the direction
457 const typename Kernel::Vector_3 orthogonal_direction{-deal_normal[0],
458 -deal_normal[1],
459 -deal_normal[2]};
460 const typename Kernel::Ray_3 ray(center, orthogonal_direction);
461
462 for (const auto f : face_indices)
463 {
464 // split the face into 2 triangles and compute distances
465 typename Kernel::Triangle_3 first_triangle(
466 {polygon_boundary[f]->vertex(0)[0],
467 polygon_boundary[f]->vertex(0)[1],
468 polygon_boundary[f]->vertex(0)[2]},
469 {polygon_boundary[f]->vertex(1)[0],
470 polygon_boundary[f]->vertex(1)[1],
471 polygon_boundary[f]->vertex(1)[2]},
472 {polygon_boundary[f]->vertex(3)[0],
473 polygon_boundary[f]->vertex(3)[1],
474 polygon_boundary[f]->vertex(3)[2]});
475 typename Kernel::Triangle_3 second_triangle(
476 {polygon_boundary[f]->vertex(0)[0],
477 polygon_boundary[f]->vertex(0)[1],
478 polygon_boundary[f]->vertex(0)[2]},
479 {polygon_boundary[f]->vertex(3)[0],
480 polygon_boundary[f]->vertex(3)[1],
481 polygon_boundary[f]->vertex(3)[2]},
482 {polygon_boundary[f]->vertex(2)[0],
483 polygon_boundary[f]->vertex(2)[1],
484 polygon_boundary[f]->vertex(2)[2]});
485
486 // compute point-triangle distance only if the orthogonal ray
487 // hits the triangle
488 if (CGAL::do_intersect(ray, first_triangle))
489 candidates.push_back(
490 CGAL::squared_distance(center, first_triangle));
491 if (CGAL::do_intersect(ray, second_triangle))
492 candidates.push_back(
493 CGAL::squared_distance(center, second_triangle));
494 }
495
496 return std::sqrt(CGAL::to_double(
497 *std::min_element(candidates.cbegin(), candidates.cend())));
498 }
499 else
500 {
501 Assert(false, ExcImpossibleInDim(dim));
502 (void)face_index;
503 (void)polygon_boundary;
504 return {};
505 }
506
507#else
508
509 Assert(false, ExcNeedsCGAL());
510 (void)face_index;
511 (void)polygon_boundary;
512 return {};
513#endif
514 }
515
516
517
522 template <int dim, int spacedim = dim>
523 void
526 const std::vector<types::global_cell_index> &cell_idxs,
528 &cells_to_be_agglomerated)
529 {
530 Assert(cells_to_be_agglomerated.size() == 0,
531 ExcMessage(
532 "The vector of cells is supposed to be filled by this function."));
533 for (const auto &cell : tria.active_cell_iterators())
534 if (std::find(cell_idxs.begin(),
535 cell_idxs.end(),
536 cell->active_cell_index()) != cell_idxs.end())
537 {
538 cells_to_be_agglomerated.push_back(cell);
539 }
540 }
541
542
543
554 template <int dim, int spacedim>
555 void
556 partition_locally_owned_regions(const unsigned int n_partitions,
557 Triangulation<dim, spacedim> &triangulation,
558 const SparsityTools::Partitioner partitioner)
559 {
560 AssertDimension(dim, spacedim);
561 Assert(n_partitions > 0,
562 ExcMessage("Invalid number of partitions, you provided " +
563 std::to_string(n_partitions)));
564
565 auto parallel_triangulation =
567 &triangulation);
568 Assert(
569 (parallel_triangulation != nullptr),
570 ExcMessage(
571 "Only fully distributed triangulations are supported. If you are using"
572 "a parallel::distributed::triangulation, you must convert it to a fully"
573 "distributed as explained in the documentation."));
574
575 // check for an easy return
576 if (n_partitions == 1)
577 {
578 for (const auto &cell : parallel_triangulation->active_cell_iterators())
579 if (cell->is_locally_owned())
580 cell->set_material_id(0);
581 return;
582 }
583
584 // collect all locally owned cells
585 std::vector<types::global_cell_index> locally_owned_cells;
586 for (const auto &cell : triangulation.active_cell_iterators())
587 if (cell->is_locally_owned())
588 locally_owned_cells.push_back(cell->active_cell_index());
589
590 DynamicSparsityPattern cell_connectivity;
591 internal::get_face_connectivity_of_cells(*parallel_triangulation,
592 cell_connectivity,
593 locally_owned_cells);
594
595 SparsityPattern sp_cell_connectivity;
596 sp_cell_connectivity.copy_from(cell_connectivity);
597
598 // partition each locally owned connection graph and get
599 // back a vector of indices, one per degree
600 // of freedom (which is associated with a
601 // cell)
602 std::vector<unsigned int> partition_indices(
603 parallel_triangulation->n_locally_owned_active_cells());
604 SparsityTools::partition(sp_cell_connectivity,
605 n_partitions,
606 partition_indices,
607 partitioner);
608
609
610 // finally loop over all cells and set the material ids
611 for (const auto &cell : parallel_triangulation->active_cell_iterators())
612 if (cell->is_locally_owned())
613 cell->set_material_id(
614 partition_indices[internal::get_index(locally_owned_cells,
615 cell->active_cell_index())]);
616 }
617
618
619
630 template <int dim, int spacedim>
631 void
633 AgglomerationHandler<dim> &agglomeration_handler,
634 const unsigned int n_partitions,
635 Triangulation<dim, spacedim> &triangulation,
636 const SparsityTools::Partitioner partitioner)
637 {
638 AssertDimension(dim, spacedim);
639 Assert(
640 agglomeration_handler.n_agglomerates() == 0,
641 ExcMessage(
642 "The agglomerated grid must be empty upon calling this function."));
643 Assert(n_partitions > 0,
644 ExcMessage("Invalid number of partitions, you provided " +
645 std::to_string(n_partitions)));
646
647 auto parallel_triangulation =
649 &triangulation);
650 Assert(
651 (parallel_triangulation != nullptr),
652 ExcMessage(
653 "Only fully distributed triangulations are supported. If you are using"
654 "a parallel::distributed::triangulation, you must convert it to a"
655 "fully distributed as explained in the documentation."));
656
657 // check for an easy return
658 if (n_partitions == 1)
659 {
660 for (const auto &cell : parallel_triangulation->active_cell_iterators())
661 if (cell->is_locally_owned())
662 agglomeration_handler.define_agglomerate({cell});
663 return;
664 }
665
666 // collect all locally owned cells
667 std::vector<types::global_cell_index> locally_owned_cells;
668 for (const auto &cell : triangulation.active_cell_iterators())
669 if (cell->is_locally_owned())
670 locally_owned_cells.push_back(cell->active_cell_index());
671
672 DynamicSparsityPattern cell_connectivity;
673 internal::get_face_connectivity_of_cells(*parallel_triangulation,
674 cell_connectivity,
675 locally_owned_cells);
676
677 SparsityPattern sp_cell_connectivity;
678 sp_cell_connectivity.copy_from(cell_connectivity);
679
680 // partition each locally owned connection graph and get
681 // back a vector of indices, one per degree
682 // of freedom (which is associated with a
683 // cell)
684 std::vector<unsigned int> partition_indices(
685 parallel_triangulation->n_locally_owned_active_cells());
686 SparsityTools::partition(sp_cell_connectivity,
687 n_partitions,
688 partition_indices,
689 partitioner);
690
691 std::vector<std::vector<typename Triangulation<dim>::active_cell_iterator>>
692 cells_per_partion_id;
693 cells_per_partion_id.resize(n_partitions); // number of agglomerates
694
695 // finally loop over all cells and store the ones with same partition index
696 for (const auto &cell : parallel_triangulation->active_cell_iterators())
697 if (cell->is_locally_owned())
698 cells_per_partion_id[partition_indices[internal::get_index(
699 locally_owned_cells, cell->active_cell_index())]]
700 .push_back(cell);
701
702 // All the cells with the same partition index will be merged together.
703 for (unsigned int i = 0; i < n_partitions; ++i)
704 agglomeration_handler.define_agglomerate(cells_per_partion_id[i]);
705 }
706
707
708
709 template <int dim>
710 std::
711 tuple<std::vector<double>, std::vector<double>, std::vector<double>, double>
713 {
714 static_assert(dim == 2); // only 2D case is implemented.
715#ifdef DEAL_II_WITH_CGAL
716 using Kernel = CGAL::Exact_predicates_exact_constructions_kernel_with_sqrt;
717 using Polygon_with_holes = typename CGAL::Polygon_with_holes_2<Kernel>;
718 using Gt = typename CGAL::Segment_Delaunay_graph_traits_2<Kernel>;
719 using SDG2 = typename CGAL::Segment_Delaunay_graph_2<Gt>;
720 using CDT = typename CGAL::Constrained_Delaunay_triangulation_2<Kernel>;
721 using CDTP = typename CGAL::Constrained_triangulation_plus_2<CDT>;
722 using Point = typename CDTP::Point;
723 using Cid = typename CDTP::Constraint_id;
724 using Vertex_handle = typename CDTP::Vertex_handle;
725
726
727 const auto compute_radius_inscribed_circle =
728 [](const CGAL::Polygon_2<Kernel> &polygon) -> double {
729 SDG2 sdg;
730
731 sdg.insert_segments(polygon.edges_begin(), polygon.edges_end());
732
733 double sd = 0, sqdist = 0;
734 typename SDG2::Finite_faces_iterator fit = sdg.finite_faces_begin();
735 for (; fit != sdg.finite_faces_end(); ++fit)
736 {
737 typename Kernel::Point_2 pp = sdg.primal(fit);
738 for (int i = 0; i < 3; ++i)
739 {
740 assert(!sdg.is_infinite(fit->vertex(i)));
741 if (fit->vertex(i)->site().is_segment())
742 {
743 typename Kernel::Segment_2 s =
744 fit->vertex(i)->site().segment();
745 sqdist = CGAL::to_double(CGAL::squared_distance(pp, s));
746 }
747 else
748 {
749 typename Kernel::Point_2 p = fit->vertex(i)->site().point();
750 sqdist = CGAL::to_double(CGAL::squared_distance(pp, p));
751 }
752 }
753
754 if (polygon.bounded_side(pp) == CGAL::ON_BOUNDED_SIDE)
755 sd = std::max(sqdist, sd);
756 }
757
758 return std::sqrt(sd);
759 };
760
761 const auto mesh_size = [&ah]() -> double {
762 double hmax = 0.;
763 for (const auto &polytope : ah.polytope_iterators())
764 if (polytope->is_locally_owned())
765 {
766 const double diameter = polytope->diameter();
767 if (diameter > hmax)
768 hmax = diameter;
769 }
770 return hmax;
771 }();
772
773
774 // vectors holding quality metrics
775
776 // ration between radius of radius_inscribed_circle and circumscribed circle
777 std::vector<double> circle_ratios;
778 std::vector<double> unformity_factors; // diameter of element over mesh size
779 std::vector<double>
780 box_ratio; // ratio between measure of bbox and measure of element.
781
782 const std::vector<BoundingBox<dim>> &bboxes = ah.get_local_bboxes();
783 // Loop over all polytopes and compute metrics.
784 for (const auto &polytope : ah.polytope_iterators())
785 {
786 if (polytope->is_locally_owned())
787 {
788 const std::vector<typename Triangulation<dim>::active_face_iterator>
789 &boundary = polytope->polytope_boundary();
790
791 const double diameter = polytope->diameter();
792 const double radius_circumscribed_circle = .5 * diameter;
793
794 CDTP cdtp;
795 for (unsigned int f = 0; f < boundary.size(); f += 1)
796 {
797 // polyline
798 cdtp.insert_constraint(
799 {boundary[f]->vertex(0)[0], boundary[f]->vertex(0)[1]},
800 {boundary[f]->vertex(1)[0], boundary[f]->vertex(1)[1]});
801 }
802 cdtp.split_subconstraint_graph_into_constraints();
803
804 CGAL::Polygon_2<Kernel> outer_polygon;
805 auto it = outer_polygon.vertices_begin();
806 for (typename CDTP::Constraint_id cid : cdtp.constraints())
807 {
808 for (typename CDTP::Vertex_handle vh :
809 cdtp.vertices_in_constraint(cid))
810 {
811 it = outer_polygon.insert(outer_polygon.vertices_end(),
812 vh->point());
813 }
814 }
815 outer_polygon.erase(it); // remove duplicate final point
816
817 const double radius_inscribed_circle =
818 compute_radius_inscribed_circle(outer_polygon);
819
820 circle_ratios.push_back(radius_inscribed_circle /
821 radius_circumscribed_circle);
822 unformity_factors.push_back(diameter / mesh_size);
823
824 // box_ratio
825
826 const auto &agglo_values = ah.reinit(polytope);
827 const double measure_element =
828 std::accumulate(agglo_values.get_JxW_values().cbegin(),
829 agglo_values.get_JxW_values().cend(),
830 0.);
831 box_ratio.push_back(measure_element /
832 bboxes[polytope->index()].volume());
833 }
834 }
835
836
837
838 // Get all of the local bounding boxes
839 double covering_bboxes = 0.;
840 for (unsigned int i = 0; i < bboxes.size(); ++i)
841 covering_bboxes += bboxes[i].volume();
842
843 const double overlap_factor =
844 Utilities::MPI::sum(covering_bboxes,
846 GridTools::volume(ah.get_triangulation()); // assuming a linear mapping
847
848
849
850 return {unformity_factors, circle_ratios, box_ratio, overlap_factor};
851#else
852
853 (void)ah;
854 return {};
855#endif
856 }
857
858
862 template <int dim>
863 void
865 const AgglomerationHandler<dim> &agglomeration_handler,
866 const std::string &filename)
867 {
868 static_assert(dim == 2); // With 3D, Paraview is much better
869 std::ofstream myfile;
870 myfile.open(filename + ".csv");
871
872 for (const auto &polytope : agglomeration_handler.polytope_iterators())
873 if (polytope->is_locally_owned())
874 {
875 const std::vector<typename Triangulation<dim>::active_face_iterator>
876 &boundary = polytope->polytope_boundary();
877 for (unsigned int f = 0; f < boundary.size(); ++f)
878 {
879 myfile << boundary[f]->vertex(0)[0];
880 myfile << ",";
881 myfile << boundary[f]->vertex(0)[1];
882 myfile << ",";
883 myfile << boundary[f]->vertex(1)[0];
884 myfile << ",";
885 myfile << boundary[f]->vertex(1)[1];
886 myfile << "\n";
887 }
888 }
889
890
891 myfile.close();
892 }
893
894
895 template <typename T>
896 inline constexpr T
897 constexpr_pow(T num, unsigned int pow)
898 {
899 return (pow >= sizeof(unsigned int) * 8) ? 0 :
900 pow == 0 ? 1 :
901 num * constexpr_pow(num, pow - 1);
902 }
903
904
905
906 void
907 write_to_matrix_market_format(const std::string &filename,
908 const std::string &matrix_name,
909 const TrilinosWrappers::SparseMatrix &matrix)
910 {
911#ifdef DEAL_II_WITH_TRILINOS
912 const Epetra_CrsMatrix &trilinos_matrix = matrix.trilinos_matrix();
913
914 const int ierr =
915 EpetraExt::RowMatrixToMatrixMarketFile(filename.c_str(),
916 trilinos_matrix,
917 matrix_name.c_str(),
918 0 /*description field empty*/,
919 true /*write header*/);
920 AssertThrow(ierr == 0, ExcTrilinosError(ierr));
921#else
922 (void)filename;
923 (void)matrix_name;
924 (void)matrix;
925#endif
926 }
927
928
929
930 namespace internal
931 {
937 template <int dim, int spacedim, typename VectorType>
938 void
940 const AgglomerationHandler<dim, spacedim> &agglomeration_handler,
941 VectorType &dst,
942 const VectorType &src)
943 {
944 Assert((dim == spacedim), ExcNotImplemented());
945 Assert(
946 dst.size() == 0,
947 ExcMessage(
948 "The destination vector must the empt upon calling this function."));
949
950 using NumberType = typename VectorType::value_type;
951 constexpr bool is_trilinos_vector =
952 std::is_same_v<VectorType, TrilinosWrappers::MPI::Vector>;
953 using MatrixType = std::conditional_t<is_trilinos_vector,
956
957 MatrixType interpolation_matrix;
958
959 [[maybe_unused]]
960 typename std::conditional_t<!is_trilinos_vector, SparsityPattern, void *>
961 sp;
962
963 // Get some info from the handler
964 const DoFHandler<dim, spacedim> &agglo_dh =
965 agglomeration_handler.agglo_dh;
966
967 DoFHandler<dim, spacedim> *output_dh =
968 const_cast<DoFHandler<dim, spacedim> *>(
969 &agglomeration_handler.output_dh);
970 const FiniteElement<dim, spacedim> &fe = agglomeration_handler.get_fe();
971 const Mapping<dim> &mapping = agglomeration_handler.get_mapping();
972 const Triangulation<dim, spacedim> &tria =
973 agglomeration_handler.get_triangulation();
974 const auto &bboxes = agglomeration_handler.get_local_bboxes();
975
976 std::unique_ptr<FiniteElement<dim>> output_fe;
978 output_fe = std::make_unique<FE_DGQ<dim>>(fe.degree);
979 else if (tria.all_reference_cells_are_simplex())
980 output_fe = std::make_unique<FE_SimplexDGP<dim>>(fe.degree);
981 else
982 AssertThrow(false, ExcNotImplemented());
983
984 // Setup an auxiliary DoFHandler for output purposes
985 output_dh->reinit(tria);
986 output_dh->distribute_dofs(*output_fe);
987
988 const IndexSet &locally_owned_dofs = output_dh->locally_owned_dofs();
989 const IndexSet locally_relevant_dofs =
991
992 const IndexSet &locally_owned_dofs_agglo = agglo_dh.locally_owned_dofs();
993
994
995 DynamicSparsityPattern dsp(output_dh->n_dofs(),
996 agglo_dh.n_dofs(),
997 locally_relevant_dofs);
998
999 std::vector<types::global_dof_index> agglo_dof_indices(fe.dofs_per_cell);
1000 std::vector<types::global_dof_index> standard_dof_indices(
1001 fe.dofs_per_cell);
1002 std::vector<types::global_dof_index> output_dof_indices(
1003 output_fe->dofs_per_cell);
1004
1005 Quadrature<dim> quad(output_fe->get_unit_support_points());
1006 FEValues<dim, spacedim> output_fe_values(mapping,
1007 *output_fe,
1008 quad,
1010
1011 for (const auto &cell : agglo_dh.active_cell_iterators())
1012 if (cell->is_locally_owned())
1013 {
1014 if (agglomeration_handler.is_master_cell(cell))
1015 {
1016 auto slaves = agglomeration_handler.get_slaves_of_idx(
1017 cell->active_cell_index());
1018 slaves.emplace_back(cell);
1019
1020 cell->get_dof_indices(agglo_dof_indices);
1021
1022 for (const auto &slave : slaves)
1023 {
1024 // addd master-slave relationship
1025 const auto slave_output =
1026 slave->as_dof_handler_iterator(*output_dh);
1027 slave_output->get_dof_indices(output_dof_indices);
1028 for (const auto row : output_dof_indices)
1029 dsp.add_entries(row,
1030 agglo_dof_indices.begin(),
1031 agglo_dof_indices.end());
1032 }
1033 }
1034 }
1035
1036
1037 const auto assemble_interpolation_matrix = [&]() {
1038 FullMatrix<NumberType> local_matrix(fe.dofs_per_cell, fe.dofs_per_cell);
1039 std::vector<Point<dim>> reference_q_points(fe.dofs_per_cell);
1040
1041 // Dummy AffineConstraints, only needed for loc2glb
1043 c.close();
1044
1045 for (const auto &cell : agglo_dh.active_cell_iterators())
1046 if (cell->is_locally_owned())
1047 {
1048 if (agglomeration_handler.is_master_cell(cell))
1049 {
1050 auto slaves = agglomeration_handler.get_slaves_of_idx(
1051 cell->active_cell_index());
1052 slaves.emplace_back(cell);
1053
1054 cell->get_dof_indices(agglo_dof_indices);
1055
1056 const types::global_cell_index polytope_index =
1057 agglomeration_handler.cell_to_polytope_index(cell);
1058
1059 // Get the box of this agglomerate.
1060 const BoundingBox<dim> &box = bboxes[polytope_index];
1061
1062 for (const auto &slave : slaves)
1063 {
1064 // add master-slave relationship
1065 const auto slave_output =
1066 slave->as_dof_handler_iterator(*output_dh);
1067
1068 slave_output->get_dof_indices(output_dof_indices);
1069 output_fe_values.reinit(slave_output);
1070
1071 local_matrix = 0.;
1072
1073 const auto &q_points =
1074 output_fe_values.get_quadrature_points();
1075 for (const auto i : output_fe_values.dof_indices())
1076 {
1077 const auto &p = box.real_to_unit(q_points[i]);
1078 for (const auto j : output_fe_values.dof_indices())
1079 {
1080 local_matrix(i, j) = fe.shape_value(j, p);
1081 }
1082 }
1083 c.distribute_local_to_global(local_matrix,
1084 output_dof_indices,
1085 agglo_dof_indices,
1086 interpolation_matrix);
1087 }
1088 }
1089 }
1090 };
1091
1092
1093 if constexpr (std::is_same_v<MatrixType, TrilinosWrappers::SparseMatrix>)
1094 {
1095 const MPI_Comm &communicator = tria.get_mpi_communicator();
1097 locally_owned_dofs,
1098 communicator,
1099 locally_relevant_dofs);
1100
1101 interpolation_matrix.reinit(locally_owned_dofs,
1102 locally_owned_dofs_agglo,
1103 dsp,
1104 communicator);
1105 dst.reinit(locally_owned_dofs);
1106 assemble_interpolation_matrix();
1107 }
1108 else if constexpr (std::is_same_v<MatrixType, SparseMatrix<NumberType>>)
1109 {
1110 sp.copy_from(dsp);
1111 interpolation_matrix.reinit(sp);
1112 dst.reinit(output_dh->n_dofs());
1113 assemble_interpolation_matrix();
1114 }
1115 else
1116 {
1117 // PETSc, LA::d::v options not implemented.
1118 (void)agglomeration_handler;
1119 (void)dst;
1120 (void)src;
1121 AssertThrow(false, ExcNotImplemented());
1122 }
1123
1124 // If tria is distributed
1125 if (dynamic_cast<const parallel::TriangulationBase<dim, spacedim> *>(
1126 &tria) != nullptr)
1127 interpolation_matrix.compress(VectorOperation::add);
1128
1129 // Finally, perform the interpolation.
1130 interpolation_matrix.vmult(dst, src);
1131 }
1132 } // namespace internal
1133
1134
1135
1146 template <int dim, int spacedim, typename VectorType>
1147 void
1149 const AgglomerationHandler<dim, spacedim> &agglomeration_handler,
1150 VectorType &dst,
1151 const VectorType &src,
1152 const bool on_the_fly = true)
1153 {
1154 Assert((dim == spacedim), ExcNotImplemented());
1155 Assert(
1156 dst.size() == 0,
1157 ExcMessage(
1158 "The destination vector must the empt upon calling this function."));
1159
1160 using NumberType = typename VectorType::value_type;
1161 static constexpr bool is_trilinos_vector =
1162 std::is_same_v<VectorType, TrilinosWrappers::MPI::Vector>;
1163
1164 static constexpr bool is_supported_vector =
1165 std::is_same_v<VectorType, Vector<NumberType>> || is_trilinos_vector;
1166 static_assert(is_supported_vector);
1167
1168 // First, check for an easy return
1169 if (on_the_fly == false)
1170 {
1171 return internal::interpolate_to_fine_grid(agglomeration_handler,
1172 dst,
1173 src);
1174 }
1175 else
1176 {
1177 // otherwise, do not create any matrix
1178 if (!agglomeration_handler.used_fe_collection())
1179 {
1180 // Original version: handle case without hp::FECollection
1181 const Triangulation<dim, spacedim> &tria =
1182 agglomeration_handler.get_triangulation();
1183 const Mapping<dim> &mapping = agglomeration_handler.get_mapping();
1184 const FiniteElement<dim, spacedim> &original_fe =
1185 agglomeration_handler.get_fe();
1186
1187 // We use DGQ (on tensor-product meshes) or DGP (on simplex meshes)
1188 // nodal elements of the same degree as the ones in the
1189 // agglomeration handler to interpolate the solution onto the finer
1190 // grid.
1191 std::unique_ptr<FiniteElement<dim>> output_fe;
1193 output_fe = std::make_unique<FE_DGQ<dim>>(original_fe.degree);
1194 else if (tria.all_reference_cells_are_simplex())
1195 output_fe =
1196 std::make_unique<FE_SimplexDGP<dim>>(original_fe.degree);
1197 else
1198 AssertThrow(false, ExcNotImplemented());
1199
1200 DoFHandler<dim> &output_dh =
1201 const_cast<DoFHandler<dim> &>(agglomeration_handler.output_dh);
1202 output_dh.reinit(tria);
1203 output_dh.distribute_dofs(*output_fe);
1204
1205 if constexpr (std::is_same_v<VectorType,
1207 {
1208 const IndexSet &locally_owned_dofs =
1209 output_dh.locally_owned_dofs();
1210 dst.reinit(locally_owned_dofs);
1211 }
1212 else if constexpr (std::is_same_v<VectorType, Vector<NumberType>>)
1213 {
1214 dst.reinit(output_dh.n_dofs());
1215 }
1216 else
1217 {
1218 // PETSc, LA::d::v options not implemented.
1219 (void)agglomeration_handler;
1220 (void)dst;
1221 (void)src;
1222 AssertThrow(false, ExcNotImplemented());
1223 }
1224
1225
1226
1227 const unsigned int dofs_per_cell =
1228 agglomeration_handler.n_dofs_per_cell();
1229 const unsigned int output_dofs_per_cell =
1230 output_fe->n_dofs_per_cell();
1231 Quadrature<dim> quad(output_fe->get_unit_support_points());
1232 FEValues<dim> output_fe_values(mapping,
1233 *output_fe,
1234 quad,
1236
1237 std::vector<types::global_dof_index> local_dof_indices(
1238 dofs_per_cell);
1239 std::vector<types::global_dof_index> local_dof_indices_output(
1240 output_dofs_per_cell);
1241
1242 const auto &bboxes = agglomeration_handler.get_local_bboxes();
1243 for (const auto &polytope :
1244 agglomeration_handler.polytope_iterators())
1245 {
1246 if (polytope->is_locally_owned())
1247 {
1248 polytope->get_dof_indices(local_dof_indices);
1249 const BoundingBox<dim> &box = bboxes[polytope->index()];
1250
1251 const auto &deal_cells =
1252 polytope->get_agglomerate(); // fine deal.II cells
1253 for (const auto &cell : deal_cells)
1254 {
1255 const auto slave_output = cell->as_dof_handler_iterator(
1256 agglomeration_handler.output_dh);
1257 slave_output->get_dof_indices(local_dof_indices_output);
1258 output_fe_values.reinit(slave_output);
1259
1260 const auto &qpoints =
1261 output_fe_values.get_quadrature_points();
1262
1263 for (unsigned int j = 0; j < output_dofs_per_cell; ++j)
1264 {
1265 const auto &ref_qpoint =
1266 box.real_to_unit(qpoints[j]);
1267 for (unsigned int i = 0; i < dofs_per_cell; ++i)
1268 dst(local_dof_indices_output[j]) +=
1269 src(local_dof_indices[i]) *
1270 original_fe.shape_value(i, ref_qpoint);
1271 }
1272 }
1273 }
1274 }
1275 }
1276 else
1277 {
1278 // Handle the hp::FECollection case
1279 const Triangulation<dim, spacedim> &tria =
1280 agglomeration_handler.get_triangulation();
1281 const Mapping<dim> &mapping = agglomeration_handler.get_mapping();
1282 const hp::FECollection<dim, spacedim> &original_fe_collection =
1283 agglomeration_handler.get_fe_collection();
1284
1285 // We use DGQ (on tensor-product meshes) or DGP (on simplex meshes)
1286 // nodal elements of the same degree as the ones in the
1287 // agglomeration handler to interpolate the solution onto the finer
1288 // grid.
1289 hp::FECollection<dim, spacedim> output_fe_collection;
1290
1291 Assert(original_fe_collection[0].n_components() >= 1,
1292 ExcMessage("Invalid FE: must have at least one component."));
1293 if (original_fe_collection[0].n_components() == 1)
1294 {
1295 // Scalar case
1296 for (unsigned int i = 0; i < original_fe_collection.size(); ++i)
1297 {
1298 std::unique_ptr<FiniteElement<dim>> output_fe;
1300 output_fe = std::make_unique<FE_DGQ<dim>>(
1301 original_fe_collection[i].degree);
1302 else if (tria.all_reference_cells_are_simplex())
1303 output_fe = std::make_unique<FE_SimplexDGP<dim>>(
1304 original_fe_collection[i].degree);
1305 else
1306 AssertThrow(false, ExcNotImplemented());
1307 output_fe_collection.push_back(*output_fe);
1308 }
1309 }
1310 else if (original_fe_collection[0].n_components() > 1)
1311 {
1312 // System case
1313 for (unsigned int i = 0; i < original_fe_collection.size(); ++i)
1314 {
1315 std::vector<const FiniteElement<dim, spacedim> *>
1316 base_elements;
1317 std::vector<unsigned int> multiplicities;
1318 for (unsigned int b = 0;
1319 b < original_fe_collection[i].n_base_elements();
1320 ++b)
1321 {
1322 if (dynamic_cast<const FE_Nothing<dim> *>(
1323 &original_fe_collection[i].base_element(b)))
1324 base_elements.push_back(
1326 else
1327 {
1329 base_elements.push_back(new FE_DGQ<dim, spacedim>(
1330 original_fe_collection[i]
1331 .base_element(b)
1332 .degree));
1333 else if (tria.all_reference_cells_are_simplex())
1334 base_elements.push_back(
1336 original_fe_collection[i]
1337 .base_element(b)
1338 .degree));
1339 else
1340 AssertThrow(false, ExcNotImplemented());
1341 }
1342 multiplicities.push_back(
1343 original_fe_collection[i].element_multiplicity(b));
1344 }
1345
1346 FESystem<dim, spacedim> output_fe_system(base_elements,
1347 multiplicities);
1348 for (const auto *ptr : base_elements)
1349 delete ptr;
1350 output_fe_collection.push_back(output_fe_system);
1351 }
1352 }
1353
1354
1355 DoFHandler<dim> &output_dh =
1356 const_cast<DoFHandler<dim> &>(agglomeration_handler.output_dh);
1357 output_dh.reinit(tria);
1358 for (const auto &polytope :
1359 agglomeration_handler.polytope_iterators())
1360 {
1361 if (polytope->is_locally_owned())
1362 {
1363 const auto &deal_cells =
1364 polytope->get_agglomerate(); // fine deal.II cells
1365 const unsigned int active_fe_idx =
1366 polytope->active_fe_index();
1367
1368 for (const auto &cell : deal_cells)
1369 {
1371 slave_cell_dh_iterator =
1372 cell->as_dof_handler_iterator(output_dh);
1373 slave_cell_dh_iterator->set_active_fe_index(
1374 active_fe_idx);
1375 }
1376 }
1377 }
1378 output_dh.distribute_dofs(output_fe_collection);
1379
1380 if constexpr (std::is_same_v<VectorType,
1382 {
1383 const IndexSet &locally_owned_dofs =
1384 output_dh.locally_owned_dofs();
1385 dst.reinit(locally_owned_dofs);
1386 }
1387 else if constexpr (std::is_same_v<VectorType, Vector<NumberType>>)
1388 {
1389 dst.reinit(output_dh.n_dofs());
1390 }
1391 else
1392 {
1393 // PETSc, LA::d::v options not implemented.
1394 (void)agglomeration_handler;
1395 (void)dst;
1396 (void)src;
1397 AssertThrow(false, ExcNotImplemented());
1398 }
1399
1400 const auto &bboxes = agglomeration_handler.get_local_bboxes();
1401 for (const auto &polytope :
1402 agglomeration_handler.polytope_iterators())
1403 {
1404 if (polytope->is_locally_owned())
1405 {
1406 const unsigned int active_fe_idx =
1407 polytope->active_fe_index();
1408 const unsigned int dofs_per_cell =
1409 polytope->get_fe().dofs_per_cell;
1410 const unsigned int output_dofs_per_cell =
1411 output_fe_collection[active_fe_idx].n_dofs_per_cell();
1412 Quadrature<dim> quad(output_fe_collection[active_fe_idx]
1413 .get_unit_support_points());
1414 FEValues<dim> output_fe_values(
1415 mapping,
1416 output_fe_collection[active_fe_idx],
1417 quad,
1419 std::vector<types::global_dof_index> local_dof_indices(
1420 dofs_per_cell);
1421 std::vector<types::global_dof_index>
1422 local_dof_indices_output(output_dofs_per_cell);
1423
1424 polytope->get_dof_indices(local_dof_indices);
1425 const BoundingBox<dim> &box = bboxes[polytope->index()];
1426
1427 const auto &deal_cells =
1428 polytope->get_agglomerate(); // fine deal.II cells
1429 for (const auto &cell : deal_cells)
1430 {
1431 const auto slave_output = cell->as_dof_handler_iterator(
1432 agglomeration_handler.output_dh);
1433 slave_output->get_dof_indices(local_dof_indices_output);
1434 output_fe_values.reinit(slave_output);
1435
1436 const auto &qpoints =
1437 output_fe_values.get_quadrature_points();
1438
1439 for (unsigned int j = 0; j < output_dofs_per_cell; ++j)
1440 {
1441 const unsigned int component_idx_of_this_dof =
1442 slave_output->get_fe()
1443 .system_to_component_index(j)
1444 .first;
1445 const auto &ref_qpoint =
1446 box.real_to_unit(qpoints[j]);
1447 for (unsigned int i = 0; i < dofs_per_cell; ++i)
1448 dst(local_dof_indices_output[j]) +=
1449 src(local_dof_indices[i]) *
1450 original_fe_collection[active_fe_idx]
1451 .shape_value_component(
1452 i, ref_qpoint, component_idx_of_this_dof);
1453 }
1454 }
1455 }
1456 }
1457 }
1458 }
1459 }
1460
1461
1462
1470 template <int dim, int spacedim, typename MatrixType>
1471 void
1473 const AgglomerationHandler<dim, spacedim> &agglomeration_handler,
1474 MatrixType &interpolation_matrix)
1475 {
1476 Assert((dim == spacedim), ExcNotImplemented());
1477
1478 using NumberType = typename MatrixType::value_type;
1479 constexpr bool is_trilinos_matrix =
1480 std::is_same_v<MatrixType, TrilinosWrappers::MPI::Vector>;
1481
1482 [[maybe_unused]]
1483 typename std::conditional_t<!is_trilinos_matrix, SparsityPattern, void *>
1484 sp;
1485
1486 // Get some info from the handler
1487 const DoFHandler<dim, spacedim> &agglo_dh = agglomeration_handler.agglo_dh;
1488
1489 DoFHandler<dim, spacedim> *output_dh =
1490 const_cast<DoFHandler<dim, spacedim> *>(&agglomeration_handler.output_dh);
1491 const Mapping<dim, spacedim> &mapping = agglomeration_handler.get_mapping();
1492 const FiniteElement<dim, spacedim> &fe = agglomeration_handler.get_fe();
1493 const Triangulation<dim, spacedim> &tria =
1494 agglomeration_handler.get_triangulation();
1495 const auto &bboxes = agglomeration_handler.get_local_bboxes();
1496
1497 // Setup an auxiliary DoFHandler for output purposes
1498 output_dh->reinit(tria);
1499 output_dh->distribute_dofs(fe);
1500
1501 const IndexSet &locally_owned_dofs = output_dh->locally_owned_dofs();
1502 const IndexSet locally_relevant_dofs =
1504
1505 const IndexSet &locally_owned_dofs_agglo = agglo_dh.locally_owned_dofs();
1506
1507
1508 DynamicSparsityPattern dsp(output_dh->n_dofs(),
1509 agglo_dh.n_dofs(),
1510 locally_relevant_dofs);
1511
1512 std::vector<types::global_dof_index> agglo_dof_indices(fe.dofs_per_cell);
1513 std::vector<types::global_dof_index> standard_dof_indices(fe.dofs_per_cell);
1514 std::vector<types::global_dof_index> output_dof_indices(fe.dofs_per_cell);
1515
1517 FEValues<dim, spacedim> output_fe_values(mapping,
1518 fe,
1519 quad,
1521
1522 for (const auto &cell : agglo_dh.active_cell_iterators())
1523 if (cell->is_locally_owned())
1524 {
1525 if (agglomeration_handler.is_master_cell(cell))
1526 {
1527 auto slaves = agglomeration_handler.get_slaves_of_idx(
1528 cell->active_cell_index());
1529 slaves.emplace_back(cell);
1530
1531 cell->get_dof_indices(agglo_dof_indices);
1532
1533 for (const auto &slave : slaves)
1534 {
1535 // addd master-slave relationship
1536 const auto slave_output =
1537 slave->as_dof_handler_iterator(*output_dh);
1538 slave_output->get_dof_indices(output_dof_indices);
1539 for (const auto row : output_dof_indices)
1540 dsp.add_entries(row,
1541 agglo_dof_indices.begin(),
1542 agglo_dof_indices.end());
1543 }
1544 }
1545 }
1546
1547
1548 const auto assemble_interpolation_matrix = [&]() {
1550 std::vector<Point<dim>> reference_q_points(fe.dofs_per_cell);
1551
1552 // Dummy AffineConstraints, only needed for loc2glb
1554 c.close();
1555
1556 for (const auto &cell : agglo_dh.active_cell_iterators())
1557 if (cell->is_locally_owned())
1558 {
1559 if (agglomeration_handler.is_master_cell(cell))
1560 {
1561 auto slaves = agglomeration_handler.get_slaves_of_idx(
1562 cell->active_cell_index());
1563 slaves.emplace_back(cell);
1564
1565 cell->get_dof_indices(agglo_dof_indices);
1566
1567 const types::global_cell_index polytope_index =
1568 agglomeration_handler.cell_to_polytope_index(cell);
1569
1570 // Get the box of this agglomerate.
1571 const BoundingBox<dim> &box = bboxes[polytope_index];
1572
1573 for (const auto &slave : slaves)
1574 {
1575 // add master-slave relationship
1576 const auto slave_output =
1577 slave->as_dof_handler_iterator(*output_dh);
1578
1579 slave_output->get_dof_indices(output_dof_indices);
1580 output_fe_values.reinit(slave_output);
1581
1582 local_matrix = 0.;
1583
1584 const auto &q_points =
1585 output_fe_values.get_quadrature_points();
1586 for (const auto i : output_fe_values.dof_indices())
1587 {
1588 const auto &p = box.real_to_unit(q_points[i]);
1589 for (const auto j : output_fe_values.dof_indices())
1590 {
1591 local_matrix(i, j) = fe.shape_value(j, p);
1592 }
1593 }
1594 c.distribute_local_to_global(local_matrix,
1595 output_dof_indices,
1596 agglo_dof_indices,
1597 interpolation_matrix);
1598 }
1599 }
1600 }
1601 };
1602
1603
1604 if constexpr (std::is_same_v<MatrixType, TrilinosWrappers::SparseMatrix>)
1605 {
1606 const MPI_Comm &communicator = tria.get_mpi_communicator();
1608 locally_owned_dofs,
1609 communicator,
1610 locally_relevant_dofs);
1611
1612 interpolation_matrix.reinit(locally_owned_dofs,
1613 locally_owned_dofs_agglo,
1614 dsp,
1615 communicator);
1616 assemble_interpolation_matrix();
1617 }
1618 else if constexpr (std::is_same_v<MatrixType, SparseMatrix<NumberType>>)
1619 {
1620 sp.copy_from(dsp);
1621 interpolation_matrix.reinit(sp);
1622 assemble_interpolation_matrix();
1623 }
1624 else
1625 {
1626 // PETSc, LA::d::v options not implemented.
1627 (void)agglomeration_handler;
1628 AssertThrow(false, ExcNotImplemented());
1629 }
1630
1631 // If tria is distributed
1632 if (dynamic_cast<const parallel::TriangulationBase<dim, spacedim> *>(
1633 &tria) != nullptr)
1634 interpolation_matrix.compress(VectorOperation::add);
1635 }
1636
1637
1638
1648 template <int dim, typename Number, typename VectorType>
1649 void
1651 const VectorType &solution,
1652 const Function<dim, Number> &exact_solution,
1653 const std::vector<VectorTools::NormType> &norms,
1654 std::vector<double> &global_errors)
1655 {
1656 Assert(solution.size() > 0,
1657 ExcNotImplemented(
1658 "Solution vector must be non-empty upon calling this function."));
1659 Assert(std::any_of(norms.cbegin(),
1660 norms.cend(),
1661 [](VectorTools::NormType norm_type) {
1662 return (norm_type ==
1663 VectorTools::NormType::H1_seminorm ||
1664 norm_type == VectorTools::NormType::L2_norm);
1665 }),
1666 ExcMessage("Norm type not supported"));
1667 global_errors.resize(norms.size());
1668 std::fill(global_errors.begin(), global_errors.end(), 0.);
1669
1670 // Vector storing errors local to the current processor.
1671 std::vector<double> local_errors(norms.size());
1672 std::fill(local_errors.begin(), local_errors.end(), 0.);
1673
1674 // Get some info from the handler
1675 const unsigned int dofs_per_cell = agglomeration_handler.n_dofs_per_cell();
1676
1677 const bool compute_semi_H1 =
1678 std::any_of(norms.cbegin(),
1679 norms.cend(),
1680 [](VectorTools::NormType norm_type) {
1681 return norm_type == VectorTools::NormType::H1_seminorm;
1682 });
1683
1684 std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);
1685 for (const auto &polytope : agglomeration_handler.polytope_iterators())
1686 {
1687 if (polytope->is_locally_owned())
1688 {
1689 const auto &agglo_values = agglomeration_handler.reinit(polytope);
1690 polytope->get_dof_indices(local_dof_indices);
1691
1692 const auto &q_points = agglo_values.get_quadrature_points();
1693 const unsigned int n_qpoints = q_points.size();
1694 std::vector<double> analyical_sol_at_qpoints(n_qpoints);
1695 exact_solution.value_list(q_points, analyical_sol_at_qpoints);
1696 std::vector<Tensor<1, dim>> grad_analyical_sol_at_qpoints(
1697 n_qpoints);
1698
1699 if (compute_semi_H1)
1700 exact_solution.gradient_list(q_points,
1701 grad_analyical_sol_at_qpoints);
1702
1703 for (unsigned int q_index : agglo_values.quadrature_point_indices())
1704 {
1705 double solution_at_qpoint = 0.;
1706 Tensor<1, dim> grad_solution_at_qpoint;
1707 for (unsigned int i = 0; i < dofs_per_cell; ++i)
1708 {
1709 solution_at_qpoint += solution(local_dof_indices[i]) *
1710 agglo_values.shape_value(i, q_index);
1711
1712 if (compute_semi_H1)
1713 grad_solution_at_qpoint +=
1714 solution(local_dof_indices[i]) *
1715 agglo_values.shape_grad(i, q_index);
1716 }
1717 // L2
1718 local_errors[0] += std::pow((analyical_sol_at_qpoints[q_index] -
1719 solution_at_qpoint),
1720 2) *
1721 agglo_values.JxW(q_index);
1722
1723 // H1 seminorm
1724 if (compute_semi_H1)
1725 for (unsigned int d = 0; d < dim; ++d)
1726 local_errors[1] +=
1727 std::pow((grad_analyical_sol_at_qpoints[q_index][d] -
1728 grad_solution_at_qpoint[d]),
1729 2) *
1730 agglo_values.JxW(q_index);
1731 }
1732 }
1733 }
1734
1735 // Perform reduction and take sqrt of each error
1736 global_errors[0] = Utilities::MPI::reduce<double>(
1737 local_errors[0],
1738 agglomeration_handler.get_triangulation().get_mpi_communicator(),
1739 [](const double a, const double b) { return a + b; });
1740
1741 global_errors[0] = std::sqrt(global_errors[0]);
1742
1743 if (compute_semi_H1)
1744 {
1745 global_errors[1] = Utilities::MPI::reduce<double>(
1746 local_errors[1],
1747 agglomeration_handler.get_triangulation().get_mpi_communicator(),
1748 [](const double a, const double b) { return a + b; });
1749 global_errors[1] = std::sqrt(global_errors[1]);
1750 }
1751 }
1752
1753
1754
1762 template <int dim>
1763 unsigned int
1765 const Triangulation<dim> &tria,
1766 std::vector<std::unique_ptr<AgglomerationHandler<dim>>>
1767 &agglomeration_handlers,
1768 const FE_DGQ<dim> &fe_dg,
1769 const Mapping<dim> &mapping,
1770 const unsigned int starting_tree_level)
1771 {
1772 const auto parallel_tria =
1773 dynamic_cast<const parallel::TriangulationBase<dim> *>(&tria);
1774
1775 GridTools::Cache<dim> cached_tria(tria);
1776 Assert(parallel_tria->n_active_cells() > 0, ExcInternalError());
1777
1778 const MPI_Comm comm = parallel_tria->get_mpi_communicator();
1779 ConditionalOStream pcout(std::cout,
1781
1782 // Start building R-tree
1783 namespace bgi = boost::geometry::index;
1784 static constexpr unsigned int max_elem_per_node =
1785 constexpr_pow(2, dim); // 2^dim
1786 std::vector<std::pair<BoundingBox<dim>,
1788 boxes(parallel_tria->n_locally_owned_active_cells());
1789 unsigned int i = 0;
1790 for (const auto &cell : parallel_tria->active_cell_iterators())
1791 if (cell->is_locally_owned())
1792 boxes[i++] = std::make_pair(mapping.get_bounding_box(cell), cell);
1793
1794 auto tree = pack_rtree<bgi::rstar<max_elem_per_node>>(boxes);
1795 Assert(n_levels(tree) >= 2, ExcMessage("At least two levels are needed."));
1796 pcout << "Total number of available levels: " << n_levels(tree)
1797 << std::endl;
1798
1799 pcout << "Starting level: " << starting_tree_level << std::endl;
1800 const unsigned int total_tree_levels =
1801 n_levels(tree) - starting_tree_level + 1;
1802
1803
1804 // Resize the agglomeration handlers to the right size
1805
1806 agglomeration_handlers.resize(total_tree_levels);
1807 // Loop through the available levels and set AgglomerationHandlers up.
1808 for (unsigned int extraction_level = starting_tree_level;
1809 extraction_level <= n_levels(tree);
1810 ++extraction_level)
1811 {
1812 agglomeration_handlers[extraction_level - starting_tree_level] =
1813 std::make_unique<AgglomerationHandler<dim>>(cached_tria);
1814 CellsAgglomerator<dim, decltype(tree)> agglomerator{tree,
1815 extraction_level};
1816 const auto agglomerates = agglomerator.extract_agglomerates();
1817 agglomeration_handlers[extraction_level - starting_tree_level]
1818 ->connect_hierarchy(agglomerator);
1819
1820 // Flag elements for agglomeration
1821 unsigned int agglo_index = 0;
1822 for (unsigned int i = 0; i < agglomerates.size(); ++i)
1823 {
1824 const auto &agglo = agglomerates[i]; // i-th agglomerate
1825 for (const auto &el : agglo)
1826 {
1827 el->set_material_id(agglo_index);
1828 }
1829 ++agglo_index;
1830 }
1831
1832 const unsigned int n_local_agglomerates = agglo_index;
1833 unsigned int total_agglomerates =
1834 Utilities::MPI::sum(n_local_agglomerates, comm);
1835 pcout << "Total agglomerates per (tree) level: " << extraction_level
1836 << ": " << total_agglomerates << std::endl;
1837
1838
1839 // Now, perform agglomeration within each locally owned partition
1840 std::vector<
1841 std::vector<typename Triangulation<dim>::active_cell_iterator>>
1842 cells_per_subdomain(n_local_agglomerates);
1843 for (const auto &cell : parallel_tria->active_cell_iterators())
1844 if (cell->is_locally_owned())
1845 cells_per_subdomain[cell->material_id()].push_back(cell);
1846
1847 // For every subdomain, agglomerate elements together
1848 for (std::size_t i = 0; i < cells_per_subdomain.size(); ++i)
1849 agglomeration_handlers[extraction_level - starting_tree_level]
1850 ->define_agglomerate(cells_per_subdomain[i]);
1851
1852 agglomeration_handlers[extraction_level - starting_tree_level]
1853 ->initialize_fe_values(QGauss<dim>(fe_dg.degree + 1),
1856 QGauss<dim - 1>(fe_dg.degree + 1),
1858 agglomeration_handlers[extraction_level - starting_tree_level]
1859 ->distribute_agglomerated_dofs(fe_dg);
1860 }
1861
1862 return total_tree_levels;
1863 }
1864
1865
1866
1871 template <int dim>
1872 void
1874 FullMatrix<double> &M12,
1875 FullMatrix<double> &M21,
1876 FullMatrix<double> &M22,
1877 const FEValuesBase<dim> &fe_faces0,
1878 const FEValuesBase<dim> &fe_faces1,
1879 const double penalty_constant,
1880 const double h_f)
1881 {
1882 const std::vector<Tensor<1, dim>> &normals = fe_faces0.get_normal_vectors();
1883 const unsigned int dofs_per_cell =
1884 M11.m(); // size of local matrices equals the #DoFs
1885 for (unsigned int q_index : fe_faces0.quadrature_point_indices())
1886 {
1887 const Tensor<1, dim> &normal = normals[q_index];
1888 for (unsigned int i = 0; i < dofs_per_cell; ++i)
1889 {
1890 for (unsigned int j = 0; j < dofs_per_cell; ++j)
1891 {
1892 M11(i, j) += (-0.5 * fe_faces0.shape_grad(i, q_index) * normal *
1893 fe_faces0.shape_value(j, q_index) -
1894 0.5 * fe_faces0.shape_grad(j, q_index) * normal *
1895 fe_faces0.shape_value(i, q_index) +
1896 (penalty_constant / h_f) *
1897 fe_faces0.shape_value(i, q_index) *
1898 fe_faces0.shape_value(j, q_index)) *
1899 fe_faces0.JxW(q_index);
1900 M12(i, j) += (0.5 * fe_faces0.shape_grad(i, q_index) * normal *
1901 fe_faces1.shape_value(j, q_index) -
1902 0.5 * fe_faces1.shape_grad(j, q_index) * normal *
1903 fe_faces0.shape_value(i, q_index) -
1904 (penalty_constant / h_f) *
1905 fe_faces0.shape_value(i, q_index) *
1906 fe_faces1.shape_value(j, q_index)) *
1907 fe_faces1.JxW(q_index);
1908 M21(i, j) += (-0.5 * fe_faces1.shape_grad(i, q_index) * normal *
1909 fe_faces0.shape_value(j, q_index) +
1910 0.5 * fe_faces0.shape_grad(j, q_index) * normal *
1911 fe_faces1.shape_value(i, q_index) -
1912 (penalty_constant / h_f) *
1913 fe_faces1.shape_value(i, q_index) *
1914 fe_faces0.shape_value(j, q_index)) *
1915 fe_faces1.JxW(q_index);
1916 M22(i, j) += (0.5 * fe_faces1.shape_grad(i, q_index) * normal *
1917 fe_faces1.shape_value(j, q_index) +
1918 0.5 * fe_faces1.shape_grad(j, q_index) * normal *
1919 fe_faces1.shape_value(i, q_index) +
1920 (penalty_constant / h_f) *
1921 fe_faces1.shape_value(i, q_index) *
1922 fe_faces1.shape_value(j, q_index)) *
1923 fe_faces1.JxW(q_index);
1924 }
1925 }
1926 }
1927 }
1928
1931 template <int dim>
1932 void
1934 FullMatrix<double> &M11,
1935 FullMatrix<double> &M12,
1936 FullMatrix<double> &M21,
1937 FullMatrix<double> &M22,
1938 const FEValuesBase<dim> &fe_faces0,
1939 const std::vector<std::vector<double>> &recv_values,
1940 const std::vector<std::vector<Tensor<1, dim>>> &recv_gradients,
1941 const std::vector<double> &recv_jxws,
1942 const double penalty_constant,
1943 const double h_f)
1944 {
1945 Assert(
1946 (recv_values.size() > 0 && recv_gradients.size() && recv_jxws.size()),
1947 ExcMessage(
1948 "Not possible to assemble jumps and averages at a ghosted interface."));
1949 const unsigned int dofs_per_cell = M11.m();
1950 const std::vector<Tensor<1, dim>> &normals = fe_faces0.get_normal_vectors();
1951 for (unsigned int q_index : fe_faces0.quadrature_point_indices())
1952 {
1953 const Tensor<1, dim> &normal = normals[q_index];
1954 for (unsigned int i = 0; i < dofs_per_cell; ++i)
1955 {
1956 for (unsigned int j = 0; j < dofs_per_cell; ++j)
1957 {
1958 M11(i, j) += (-0.5 * fe_faces0.shape_grad(i, q_index) * normal *
1959 fe_faces0.shape_value(j, q_index) -
1960 0.5 * fe_faces0.shape_grad(j, q_index) * normal *
1961 fe_faces0.shape_value(i, q_index) +
1962 (penalty_constant / h_f) *
1963 fe_faces0.shape_value(i, q_index) *
1964 fe_faces0.shape_value(j, q_index)) *
1965 fe_faces0.JxW(q_index);
1966 M12(i, j) += (0.5 * fe_faces0.shape_grad(i, q_index) * normal *
1967 recv_values[j][q_index] -
1968 0.5 * recv_gradients[j][q_index] * normal *
1969 fe_faces0.shape_value(i, q_index) -
1970 (penalty_constant / h_f) *
1971 fe_faces0.shape_value(i, q_index) *
1972 recv_values[j][q_index]) *
1973 recv_jxws[q_index];
1974 M21(i, j) +=
1975 (-0.5 * recv_gradients[i][q_index] * normal *
1976 fe_faces0.shape_value(j, q_index) +
1977 0.5 * fe_faces0.shape_grad(j, q_index) * normal *
1978 recv_values[i][q_index] -
1979 (penalty_constant / h_f) * recv_values[i][q_index] *
1980 fe_faces0.shape_value(j, q_index)) *
1981 recv_jxws[q_index];
1982 M22(i, j) +=
1983 (0.5 * recv_gradients[i][q_index] * normal *
1984 recv_values[j][q_index] +
1985 0.5 * recv_gradients[j][q_index] * normal *
1986 recv_values[i][q_index] +
1987 (penalty_constant / h_f) * recv_values[i][q_index] *
1988 recv_values[j][q_index]) *
1989 recv_jxws[q_index];
1990 }
1991 }
1992 }
1993 }
1994
1995
2001 template <int dim, typename MatrixType>
2002 void
2003 assemble_dg_matrix(MatrixType &system_matrix,
2004 const FiniteElement<dim> &fe_dg,
2005 const AgglomerationHandler<dim> &ah)
2006 {
2007 static_assert(
2008 (std::is_same_v<MatrixType, TrilinosWrappers::SparseMatrix> ||
2009 std::is_same_v<MatrixType,
2011
2012 Assert((dynamic_cast<const FE_DGQ<dim> *>(&fe_dg) ||
2013 dynamic_cast<const FE_DGP<dim> *>(&fe_dg) ||
2014 dynamic_cast<const FE_SimplexDGP<dim> *>(&fe_dg)),
2015 ExcMessage("FE type not supported."));
2016
2017 AffineConstraints constraints;
2018 constraints.close();
2019 const double penalty_constant =
2020 10 * (fe_dg.degree + dim) * (fe_dg.degree + 1);
2022 const_cast<AgglomerationHandler<dim> &>(ah)
2023 .create_agglomeration_sparsity_pattern(dsp);
2024 system_matrix.reinit(dsp);
2025 const unsigned int dofs_per_cell = fe_dg.n_dofs_per_cell();
2026 FullMatrix<double> cell_matrix(dofs_per_cell, dofs_per_cell);
2027 FullMatrix<double> M11(dofs_per_cell, dofs_per_cell);
2028 FullMatrix<double> M12(dofs_per_cell, dofs_per_cell);
2029 FullMatrix<double> M21(dofs_per_cell, dofs_per_cell);
2030 FullMatrix<double> M22(dofs_per_cell, dofs_per_cell);
2031 std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);
2032 std::vector<types::global_dof_index> local_dof_indices_neighbor(
2033 dofs_per_cell);
2034
2035 for (const auto &polytope : ah.polytope_iterators())
2036 {
2037 if (polytope->is_locally_owned())
2038 {
2039 cell_matrix = 0.;
2040 const auto &agglo_values = ah.reinit(polytope);
2041 for (unsigned int q_index : agglo_values.quadrature_point_indices())
2042 {
2043 for (unsigned int i = 0; i < dofs_per_cell; ++i)
2044 {
2045 for (unsigned int j = 0; j < dofs_per_cell; ++j)
2046 {
2047 cell_matrix(i, j) +=
2048 agglo_values.shape_grad(i, q_index) *
2049 agglo_values.shape_grad(j, q_index) *
2050 agglo_values.JxW(q_index);
2051 }
2052 }
2053 }
2054 // get volumetric DoFs
2055 polytope->get_dof_indices(local_dof_indices);
2056 // Assemble face terms
2057 unsigned int n_faces = polytope->n_faces();
2058 const double h_f = polytope->diameter();
2059 for (unsigned int f = 0; f < n_faces; ++f)
2060 {
2061 if (polytope->at_boundary(f))
2062 {
2063 // Get normal vectors seen from each agglomeration.
2064 const auto &fe_face = ah.reinit(polytope, f);
2065 const auto &normals = fe_face.get_normal_vectors();
2066 for (unsigned int q_index :
2067 fe_face.quadrature_point_indices())
2068 {
2069 const Tensor<1, dim> &normal = normals[q_index];
2070 for (unsigned int i = 0; i < dofs_per_cell; ++i)
2071 {
2072 for (unsigned int j = 0; j < dofs_per_cell; ++j)
2073 {
2074 cell_matrix(i, j) +=
2075 (-fe_face.shape_value(i, q_index) *
2076 fe_face.shape_grad(j, q_index) * normal -
2077 fe_face.shape_grad(i, q_index) * normal *
2078 fe_face.shape_value(j, q_index) +
2079 (penalty_constant / h_f) *
2080 fe_face.shape_value(i, q_index) *
2081 fe_face.shape_value(j, q_index)) *
2082 fe_face.JxW(q_index);
2083 }
2084 }
2085 }
2086 }
2087 else
2088 {
2089 const auto &neigh_polytope = polytope->neighbor(f);
2090 if (polytope->id() < neigh_polytope->id())
2091 {
2092 unsigned int nofn =
2093 polytope->neighbor_of_agglomerated_neighbor(f);
2094 Assert(neigh_polytope->neighbor(nofn)->id() ==
2095 polytope->id(),
2096 ExcMessage("Mismatch."));
2097 const auto &fe_faces = ah.reinit_interface(
2098 polytope, neigh_polytope, f, nofn);
2099 const auto &fe_faces0 = fe_faces.first;
2100 if (neigh_polytope->is_locally_owned())
2101 {
2102 // use both fevalues
2103 const auto &fe_faces1 = fe_faces.second;
2104 M11 = 0.;
2105 M12 = 0.;
2106 M21 = 0.;
2107 M22 = 0.;
2109 M12,
2110 M21,
2111 M22,
2112 fe_faces0,
2113 fe_faces1,
2114 penalty_constant,
2115 h_f);
2116 // distribute DoFs accordingly
2117 // fluxes
2118 neigh_polytope->get_dof_indices(
2119 local_dof_indices_neighbor);
2120 constraints.distribute_local_to_global(
2121 M11, local_dof_indices, system_matrix);
2122 constraints.distribute_local_to_global(
2123 M12,
2124 local_dof_indices,
2125 local_dof_indices_neighbor,
2126 system_matrix);
2127 constraints.distribute_local_to_global(
2128 M21,
2129 local_dof_indices_neighbor,
2130 local_dof_indices,
2131 system_matrix);
2132 constraints.distribute_local_to_global(
2133 M22, local_dof_indices_neighbor, system_matrix);
2134 }
2135 else
2136 {
2137 // neigh polytope is ghosted, so retrieve necessary
2138 // metadata.
2139 types::subdomain_id neigh_rank =
2140 neigh_polytope->subdomain_id();
2141 const auto &recv_jxws =
2142 ah.recv_jxws.at(neigh_rank)
2143 .at({neigh_polytope->id(), nofn});
2144 const auto &recv_values =
2145 ah.recv_values.at(neigh_rank)
2146 .at({neigh_polytope->id(), nofn});
2147 const auto &recv_gradients =
2148 ah.recv_gradients.at(neigh_rank)
2149 .at({neigh_polytope->id(), nofn});
2150 M11 = 0.;
2151 M12 = 0.;
2152 M21 = 0.;
2153 M22 = 0.;
2154 // there's no FEFaceValues on the other side (it's
2155 // ghosted), so we just pass the actual data we have
2156 // recevied from the neighboring ghosted polytope
2158 M11,
2159 M12,
2160 M21,
2161 M22,
2162 fe_faces0,
2163 recv_values,
2164 recv_gradients,
2165 recv_jxws,
2166 penalty_constant,
2167 h_f);
2168 // distribute DoFs accordingly
2169 // fluxes
2170 neigh_polytope->get_dof_indices(
2171 local_dof_indices_neighbor);
2172 constraints.distribute_local_to_global(
2173 M11, local_dof_indices, system_matrix);
2174 constraints.distribute_local_to_global(
2175 M12,
2176 local_dof_indices,
2177 local_dof_indices_neighbor,
2178 system_matrix);
2179 constraints.distribute_local_to_global(
2180 M21,
2181 local_dof_indices_neighbor,
2182 local_dof_indices,
2183 system_matrix);
2184 constraints.distribute_local_to_global(
2185 M22, local_dof_indices_neighbor, system_matrix);
2186 } // ghosted polytope case
2187 } // only once
2188 } // internal face
2189 } // face loop
2190 constraints.distribute_local_to_global(cell_matrix,
2191 local_dof_indices,
2192 system_matrix);
2193 } // locally owned polytopes
2194 }
2195 system_matrix.compress(VectorOperation::add);
2196 }
2197
2198
2199
2205 template <int dim, typename MatrixType, typename VectorType>
2206 void
2207 assemble_dg_matrix_on_standard_mesh(MatrixType &system_matrix,
2208 VectorType &system_rhs,
2209 const Mapping<dim> &mapping,
2210 const FiniteElement<dim> &fe_dg,
2211 const DoFHandler<dim> &dof_handler)
2212 {
2213 static_assert(
2214 (std::is_same_v<MatrixType, TrilinosWrappers::SparseMatrix> ||
2215 std::is_same_v<MatrixType,
2217
2218 Assert((dynamic_cast<const FE_SimplexDGP<dim> *>(&fe_dg) != nullptr),
2219 ExcNotImplemented(
2220 "Implemented only for simplex meshes for the time being."));
2221
2223 ExcNotImplemented());
2224
2225 const double penalty_constant = .5 * fe_dg.degree * (fe_dg.degree + 1);
2227 constraints.close();
2228
2229 const IndexSet &locally_owned_dofs = dof_handler.locally_owned_dofs();
2230 const IndexSet locally_relevant_dofs =
2232
2233 DynamicSparsityPattern dsp(locally_relevant_dofs);
2234 DoFTools::make_flux_sparsity_pattern(dof_handler, dsp);
2236 dsp,
2237 dof_handler.locally_owned_dofs(),
2238 dof_handler.get_mpi_communicator(),
2239 locally_relevant_dofs);
2240
2241 system_matrix.reinit(locally_owned_dofs,
2242 locally_owned_dofs,
2243 dsp,
2244 dof_handler.get_mpi_communicator());
2245
2246 system_rhs.reinit(locally_owned_dofs, dof_handler.get_mpi_communicator());
2247
2248 const unsigned int quadrature_degree = fe_dg.degree + 1;
2249 FEFaceValues<dim> fe_faces0(mapping,
2250 fe_dg,
2251 QGaussSimplex<dim - 1>(quadrature_degree),
2255
2256
2257 FEValues<dim> fe_values(mapping,
2258 fe_dg,
2259 QGaussSimplex<dim>(quadrature_degree),
2262
2263 FEFaceValues<dim> fe_faces1(mapping,
2264 fe_dg,
2265 QGaussSimplex<dim - 1>(quadrature_degree),
2269 const unsigned int dofs_per_cell = fe_dg.n_dofs_per_cell();
2270
2271 FullMatrix<double> cell_matrix(dofs_per_cell, dofs_per_cell);
2272 Vector<double> cell_rhs(dofs_per_cell);
2273
2274 FullMatrix<double> M11(dofs_per_cell, dofs_per_cell);
2275 FullMatrix<double> M12(dofs_per_cell, dofs_per_cell);
2276 FullMatrix<double> M21(dofs_per_cell, dofs_per_cell);
2277 FullMatrix<double> M22(dofs_per_cell, dofs_per_cell);
2278
2279 std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);
2280
2281 // Loop over standard deal.II cells
2282 for (const auto &cell : dof_handler.active_cell_iterators())
2283 {
2284 if (cell->is_locally_owned())
2285 {
2286 cell_matrix = 0.;
2287 cell_rhs = 0.;
2288
2289 fe_values.reinit(cell);
2290
2291 // const auto &q_points = fe_values.get_quadrature_points();
2292 // const unsigned int n_qpoints = q_points.size();
2293
2294 for (unsigned int q_index : fe_values.quadrature_point_indices())
2295 {
2296 for (unsigned int i = 0; i < dofs_per_cell; ++i)
2297 {
2298 for (unsigned int j = 0; j < dofs_per_cell; ++j)
2299 {
2300 cell_matrix(i, j) += fe_values.shape_grad(i, q_index) *
2301 fe_values.shape_grad(j, q_index) *
2302 fe_values.JxW(q_index);
2303 }
2304 cell_rhs(i) +=
2305 fe_values.shape_value(i, q_index) * 1. *
2306 fe_values.JxW(q_index); // TODO: pass functional
2307 }
2308 }
2309
2310 // distribute volumetric DoFs
2311 cell->get_dof_indices(local_dof_indices);
2312 double hf = 0.;
2313 for (const auto f : cell->face_indices())
2314 {
2315 const double extent1 =
2316 cell->measure() / cell->face(f)->measure();
2317
2318 if (cell->face(f)->at_boundary())
2319 {
2320 hf = (1. / extent1 + 1. / extent1);
2321 fe_faces0.reinit(cell, f);
2322
2323 const auto &normals = fe_faces0.get_normal_vectors();
2324 for (unsigned int q_index :
2325 fe_faces0.quadrature_point_indices())
2326 {
2327 for (unsigned int i = 0; i < dofs_per_cell; ++i)
2328 {
2329 for (unsigned int j = 0; j < dofs_per_cell; ++j)
2330 {
2331 cell_matrix(i, j) +=
2332 (-fe_faces0.shape_value(i, q_index) *
2333 fe_faces0.shape_grad(j, q_index) *
2334 normals[q_index] -
2335 fe_faces0.shape_grad(i, q_index) *
2336 normals[q_index] *
2337 fe_faces0.shape_value(j, q_index) +
2338 (penalty_constant * hf) *
2339 fe_faces0.shape_value(i, q_index) *
2340 fe_faces0.shape_value(j, q_index)) *
2341 fe_faces0.JxW(q_index);
2342 }
2343 cell_rhs(i) +=
2344 0.; // TODO: add bdary conditions functional
2345 }
2346 }
2347 }
2348 else
2349 {
2350 const auto &neigh_cell = cell->neighbor(f);
2351 if (cell->global_active_cell_index() <
2352 neigh_cell->global_active_cell_index())
2353 {
2354 const double extent2 =
2355 neigh_cell->measure() /
2356 neigh_cell->face(cell->neighbor_of_neighbor(f))
2357 ->measure();
2358 hf = (1. / extent1 + 1. / extent2);
2359 fe_faces0.reinit(cell, f);
2360 fe_faces1.reinit(neigh_cell,
2361 cell->neighbor_of_neighbor(f));
2362
2363 std::vector<types::global_dof_index>
2364 local_dof_indices_neighbor(dofs_per_cell);
2365
2366 M11 = 0.;
2367 M12 = 0.;
2368 M21 = 0.;
2369 M22 = 0.;
2370
2371 const auto &normals = fe_faces0.get_normal_vectors();
2372 // M11
2373 for (unsigned int q_index :
2374 fe_faces0.quadrature_point_indices())
2375 {
2376 for (unsigned int i = 0; i < dofs_per_cell; ++i)
2377 {
2378 for (unsigned int j = 0; j < dofs_per_cell; ++j)
2379 {
2380 M11(i, j) +=
2381 (-0.5 * fe_faces0.shape_grad(i, q_index) *
2382 normals[q_index] *
2383 fe_faces0.shape_value(j, q_index) -
2384 0.5 * fe_faces0.shape_grad(j, q_index) *
2385 normals[q_index] *
2386 fe_faces0.shape_value(i, q_index) +
2387 (penalty_constant * hf) *
2388 fe_faces0.shape_value(i, q_index) *
2389 fe_faces0.shape_value(j, q_index)) *
2390 fe_faces0.JxW(q_index);
2391
2392 M12(i, j) +=
2393 (0.5 * fe_faces0.shape_grad(i, q_index) *
2394 normals[q_index] *
2395 fe_faces1.shape_value(j, q_index) -
2396 0.5 * fe_faces1.shape_grad(j, q_index) *
2397 normals[q_index] *
2398 fe_faces0.shape_value(i, q_index) -
2399 (penalty_constant * hf) *
2400 fe_faces0.shape_value(i, q_index) *
2401 fe_faces1.shape_value(j, q_index)) *
2402 fe_faces1.JxW(q_index);
2403
2404 // A10
2405 M21(i, j) +=
2406 (-0.5 * fe_faces1.shape_grad(i, q_index) *
2407 normals[q_index] *
2408 fe_faces0.shape_value(j, q_index) +
2409 0.5 * fe_faces0.shape_grad(j, q_index) *
2410 normals[q_index] *
2411 fe_faces1.shape_value(i, q_index) -
2412 (penalty_constant * hf) *
2413 fe_faces1.shape_value(i, q_index) *
2414 fe_faces0.shape_value(j, q_index)) *
2415 fe_faces1.JxW(q_index);
2416
2417 // A11
2418 M22(i, j) +=
2419 (0.5 * fe_faces1.shape_grad(i, q_index) *
2420 normals[q_index] *
2421 fe_faces1.shape_value(j, q_index) +
2422 0.5 * fe_faces1.shape_grad(j, q_index) *
2423 normals[q_index] *
2424 fe_faces1.shape_value(i, q_index) +
2425 (penalty_constant * hf) *
2426 fe_faces1.shape_value(i, q_index) *
2427 fe_faces1.shape_value(j, q_index)) *
2428 fe_faces1.JxW(q_index);
2429 }
2430 }
2431 }
2432
2433 // distribute DoFs accordingly
2434
2435 neigh_cell->get_dof_indices(local_dof_indices_neighbor);
2436
2437 constraints.distribute_local_to_global(
2438 M11, local_dof_indices, system_matrix);
2439 constraints.distribute_local_to_global(
2440 M12,
2441 local_dof_indices,
2442 local_dof_indices_neighbor,
2443 system_matrix);
2444 constraints.distribute_local_to_global(
2445 M21,
2446 local_dof_indices_neighbor,
2447 local_dof_indices,
2448 system_matrix);
2449 constraints.distribute_local_to_global(
2450 M22, local_dof_indices_neighbor, system_matrix);
2451
2452 } // check idx neighbors
2453 } // over faces
2454 }
2455 constraints.distribute_local_to_global(cell_matrix,
2456 cell_rhs,
2457 local_dof_indices,
2458 system_matrix,
2459 system_rhs);
2460 }
2461 }
2462 system_matrix.compress(VectorOperation::add);
2463 system_rhs.compress(VectorOperation::add);
2464 }
2465
2466
2467} // namespace dealii::PolyUtils
2468
2469#endif
void distribute_local_to_global(const InVector &local_vector, const std::vector< size_type > &local_dof_indices, OutVector &global_vector) const
Point< spacedim, Number > real_to_unit(const Point< spacedim, Number > &point) const
void distribute_dofs(const FiniteElement< dim, spacedim > &fe)
const Triangulation< dim, spacedim > & get_triangulation() const
const IndexSet & locally_owned_dofs() const
void reinit(const Triangulation< dim, spacedim > &tria)
types::global_dof_index n_dofs() const
MPI_Comm get_mpi_communicator() const
void add_entries(const size_type row, ForwardIterator begin, ForwardIterator end, const bool indices_are_unique_and_sorted=false)
void reinit(const size_type m, const size_type n, const IndexSet &rowset=IndexSet())
void add(const size_type i, const size_type j)
void reinit(const TriaIterator< DoFCellAccessor< dim, spacedim, level_dof_access > > &cell, const unsigned int face_no)
const std::vector< Point< spacedim > > & get_quadrature_points() const
const std::vector< Tensor< 1, spacedim > > & get_normal_vectors() const
std_cxx20::ranges::iota_view< unsigned int, unsigned int > dof_indices() const
std_cxx20::ranges::iota_view< unsigned int, unsigned int > quadrature_point_indices() const
const Tensor< 1, spacedim > & shape_grad(const unsigned int i, const unsigned int q_point) const
double JxW(const unsigned int q_point) const
const double & shape_value(const unsigned int i, const unsigned int q_point) const
void reinit(const TriaIterator< DoFCellAccessor< dim, spacedim, level_dof_access > > &cell)
const unsigned int degree
unsigned int n_dofs_per_cell() const
const unsigned int dofs_per_cell
const std::vector< Point< dim > > & get_unit_support_points() const
virtual double shape_value(const unsigned int i, const Point< dim > &p) const
size_type m() const
virtual void gradient_list(const std::vector< Point< dim > > &points, std::vector< Tensor< 1, dim, RangeNumberType > > &gradients, const unsigned int component=0) const
virtual void value_list(const std::vector< Point< dim > > &points, std::vector< RangeNumberType > &values, const unsigned int component=0) const
virtual BoundingBox< spacedim > get_bounding_box(const typename Triangulation< dim, spacedim >::cell_iterator &cell) const
void copy_from(const size_type n_rows, const size_type n_cols, const ForwardIterator begin, const ForwardIterator end)
bool all_reference_cells_are_hyper_cube() const
virtual MPI_Comm get_mpi_communicator() const
bool all_reference_cells_are_simplex() const
unsigned int n_dofs_per_cell() const noexcept
types::global_cell_index cell_to_polytope_index(const typename Triangulation< dim, spacedim >::active_cell_iterator &cell) const
const DoFHandler< dim, spacedim > & get_dof_handler() const
const std::vector< typename Triangulation< dim, spacedim >::active_cell_iterator > & get_slaves_of_idx(types::global_cell_index idx) const
const FEValues< dim, spacedim > & reinit(const AgglomerationIterator< dim, spacedim > &polytope) const
std::map< types::subdomain_id, std::map< std::pair< CellId, unsigned int >, std::vector< double > > > recv_jxws
DoFHandler< dim, spacedim > output_dh
std::pair< const FEValuesBase< dim, spacedim > &, const FEValuesBase< dim, spacedim > & > reinit_interface(const AgglomerationIterator< dim, spacedim > &polytope_in, const AgglomerationIterator< dim, spacedim > &neigh_polytope, const unsigned int local_in, const unsigned int local_outside) const
std::map< types::subdomain_id, std::map< std::pair< CellId, unsigned int >, std::vector< std::vector< Tensor< 1, spacedim > > > > > recv_gradients
const Triangulation< dim, spacedim > & get_triangulation() const
const Mapping< dim > & get_mapping() const
unsigned int n_agglomerates() const
const std::vector< BoundingBox< dim > > & get_local_bboxes() const
const FiniteElement< dim, spacedim > & get_fe() const
std::map< types::subdomain_id, std::map< std::pair< CellId, unsigned int >, std::vector< std::vector< double > > > > recv_values
bool is_master_cell(const CellIterator &cell) const
IteratorRange< agglomeration_iterator > polytope_iterators() const
agglomeration_iterator define_agglomerate(const AgglomerationContainer &cells)
DoFHandler< dim, spacedim > agglo_dh
const hp::FECollection< dim, spacedim > & get_fe_collection() const
const std::vector< std::vector< typename Triangulation< dim >::active_cell_iterator > > & extract_agglomerates()
unsigned int size() const
void push_back(const FiniteElement< dim, spacedim > &new_fe)
unsigned int n_locally_owned_active_cells() const
unsigned int level
IteratorRange< active_cell_iterator > active_cell_iterators() const
IteratorRange< active_cell_iterator > active_cell_iterators() const
#define Assert(cond, exc)
#define AssertDimension(dim1, dim2)
#define AssertThrow(cond, exc)
TriaActiveIterator< CellAccessor< dim, spacedim > > active_cell_iterator
typename ActiveSelector::active_cell_iterator active_cell_iterator
TriaActiveIterator< TriaAccessor< dim - 1, dim, spacedim > > active_face_iterator
void make_flux_sparsity_pattern(const DoFHandler< dim, spacedim > &dof_handler, SparsityPatternBase &sparsity_pattern)
update_values
update_normal_vectors
update_JxW_values
update_gradients
update_quadrature_points
Expression pow(const Expression &base, const Expression &exponent)
IndexSet extract_locally_relevant_dofs(const DoFHandler< dim, spacedim > &dof_handler)
double volume(const Triangulation< dim, spacedim > &tria)
double diameter(const Triangulation< dim, spacedim > &tria)
SymmetricTensor< 2, dim, Number > b(const Tensor< 2, dim, Number > &F)
SymmetricTensor< 2, dim, Number > d(const Tensor< 2, dim, Number > &F, const Tensor< 2, dim, Number > &dF_dt)
void partition(const SparsityPattern &sparsity_pattern, const unsigned int n_partitions, std::vector< unsigned int > &partition_indices, const Partitioner partitioner=Partitioner::metis)
void distribute_sparsity_pattern(DynamicSparsityPattern &dsp, const IndexSet &locally_owned_rows, const MPI_Comm mpi_comm, const IndexSet &locally_relevant_rows)
T sum(const T &t, const MPI_Comm mpi_communicator)
unsigned int this_mpi_process(const MPI_Comm mpi_communicator)
T reduce(const T &local_value, const MPI_Comm comm, const std::function< T(const T &, const T &)> &combiner, const unsigned int root_process=0)
void get_face_connectivity_of_cells(const parallel::fullydistributed::Triangulation< dim, spacedim > &triangulation, DynamicSparsityPattern &cell_connectivity, const std::vector< types::global_cell_index > locally_owned_cells)
Definition poly_utils.h:98
void interpolate_to_fine_grid(const AgglomerationHandler< dim, spacedim > &agglomeration_handler, VectorType &dst, const VectorType &src)
Definition poly_utils.h:939
types::global_cell_index get_index(const std::vector< types::global_cell_index > &v, const types::global_cell_index index)
Definition poly_utils.h:84
void partition_locally_owned_regions(const unsigned int n_partitions, Triangulation< dim, spacedim > &triangulation, const SparsityTools::Partitioner partitioner)
Definition poly_utils.h:556
void fill_interpolation_matrix(const AgglomerationHandler< dim, spacedim > &agglomeration_handler, MatrixType &interpolation_matrix)
void assemble_local_jumps_and_averages(FullMatrix< double > &M11, FullMatrix< double > &M12, FullMatrix< double > &M21, FullMatrix< double > &M22, const FEValuesBase< dim > &fe_faces0, const FEValuesBase< dim > &fe_faces1, const double penalty_constant, const double h_f)
std::pair< std::vector< std::vector< unsigned int > >, std::vector< std::vector< typename Triangulation< boost::geometry::dimension< typename Rtree::indexable_type >::value >::active_cell_iterator > > > extract_children_of_level(const Rtree &tree, const unsigned int level)
Definition poly_utils.h:360
void interpolate_to_fine_grid(const AgglomerationHandler< dim, spacedim > &agglomeration_handler, VectorType &dst, const VectorType &src, const bool on_the_fly=true)
void compute_global_error(const AgglomerationHandler< dim > &agglomeration_handler, const VectorType &solution, const Function< dim, Number > &exact_solution, const std::vector< VectorTools::NormType > &norms, std::vector< double > &global_errors)
Number compute_h_orthogonal(const unsigned int face_index, const std::vector< typename Triangulation< dim >::active_face_iterator > &polygon_boundary, const Tensor< 1, dim > &deal_normal)
Definition poly_utils.h:402
unsigned int construct_agglomerated_levels(const Triangulation< dim > &tria, std::vector< std::unique_ptr< AgglomerationHandler< dim > > > &agglomeration_handlers, const FE_DGQ< dim > &fe_dg, const Mapping< dim > &mapping, const unsigned int starting_tree_level)
constexpr T constexpr_pow(T num, unsigned int pow)
Definition poly_utils.h:897
void assemble_dg_matrix(MatrixType &system_matrix, const FiniteElement< dim > &fe_dg, const AgglomerationHandler< dim > &ah)
void collect_cells_for_agglomeration(const Triangulation< dim, spacedim > &tria, const std::vector< types::global_cell_index > &cell_idxs, std::vector< typename Triangulation< dim, spacedim >::active_cell_iterator > &cells_to_be_agglomerated)
Definition poly_utils.h:524
void assemble_local_jumps_and_averages_ghost(FullMatrix< double > &M11, FullMatrix< double > &M12, FullMatrix< double > &M21, FullMatrix< double > &M22, const FEValuesBase< dim > &fe_faces0, const std::vector< std::vector< double > > &recv_values, const std::vector< std::vector< Tensor< 1, dim > > > &recv_gradients, const std::vector< double > &recv_jxws, const double penalty_constant, const double h_f)
void assemble_dg_matrix_on_standard_mesh(MatrixType &system_matrix, VectorType &system_rhs, const Mapping< dim > &mapping, const FiniteElement< dim > &fe_dg, const DoFHandler< dim > &dof_handler)
void write_to_matrix_market_format(const std::string &filename, const std::string &matrix_name, const TrilinosWrappers::SparseMatrix &matrix)
Definition poly_utils.h:907
void export_polygon_to_csv_file(const AgglomerationHandler< dim > &agglomeration_handler, const std::string &filename)
Definition poly_utils.h:864
std::tuple< std::vector< double >, std::vector< double >, std::vector< double >, double > compute_quality_metrics(const AgglomerationHandler< dim > &ah)
Definition poly_utils.h:712
::VectorizedArray< Number, width > min(const ::VectorizedArray< Number, width > &, const ::VectorizedArray< Number, width > &)
::VectorizedArray< Number, width > max(const ::VectorizedArray< Number, width > &, const ::VectorizedArray< Number, width > &)
::VectorizedArray< Number, width > sqrt(const ::VectorizedArray< Number, width > &)
::VectorizedArray< Number, width > pow(const ::VectorizedArray< Number, width > &, const Number p)
unsigned int subdomain_id
unsigned int global_cell_index
*braid_SplitCommworld & comm
RTree< typename LeafTypeIterator::value_type, IndexType, IndexableGetter > pack_rtree(const LeafTypeIterator &begin, const LeafTypeIterator &end)
const Translator & translator
Definition poly_utils.h:203
void operator()(const InternalNode &node)
Definition poly_utils.h:266
std::vector< std::vector< typename Triangulation< boost::geometry::dimension< Box >::value >::active_cell_iterator > > & agglomerates
Definition poly_utils.h:230
Rtree_visitor(const Translator &translator, unsigned int target_level, std::vector< std::vector< typename Triangulation< boost::geometry::dimension< Box >::value >::active_cell_iterator > > &boxes, std::vector< std::vector< unsigned int > > &csr)
Definition poly_utils.h:242
typename boost::geometry::index::detail::rtree::leaf< Value, typename Options::parameters_type, Box, Allocators, typename Options::node_tag >::type Leaf
Definition poly_utils.h:180
std::vector< std::vector< unsigned int > > & row_ptr
Definition poly_utils.h:232
typename boost::geometry::index::detail::rtree::internal_node< Value, typename Options::parameters_type, Box, Allocators, typename Options::node_tag >::type InternalNode
Definition poly_utils.h:169