LCOV - code coverage report
Current view: top level - src/mesh - unstructured_mesh.C (source / functions) Hit Total Coverage
Test: libMesh/libmesh: #4640 (c5f9f0) with base a68dd6 Lines: 824 1024 80.5 %
Date: 2026-11-02 23:02:27 Functions: 37 48 77.1 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : // The libMesh Finite Element Library.
       2             : // Copyright (C) 2002-2026 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
       3             : 
       4             : // This library is free software; you can redistribute it and/or
       5             : // modify it under the terms of the GNU Lesser General Public
       6             : // License as published by the Free Software Foundation; either
       7             : // version 2.1 of the License, or (at your option) any later version.
       8             : 
       9             : // This library is distributed in the hope that it will be useful,
      10             : // but WITHOUT ANY WARRANTY; without even the implied warranty of
      11             : // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
      12             : // Lesser General Public License for more details.
      13             : 
      14             : // You should have received a copy of the GNU Lesser General Public
      15             : // License along with this library; if not, write to the Free Software
      16             : // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
      17             : 
      18             : 
      19             : 
      20             : // Local includes
      21             : #include "libmesh/boundary_info.h"
      22             : #include "libmesh/ghosting_functor.h"
      23             : #include "libmesh/ghost_point_neighbors.h"
      24             : #include "libmesh/unstructured_mesh.h"
      25             : #include "libmesh/libmesh_logging.h"
      26             : #include "libmesh/elem.h"
      27             : #include "libmesh/elem_range.h"
      28             : #include "libmesh/face_polygon.h"
      29             : #include "libmesh/mesh_tools.h" // For n_levels
      30             : #include "libmesh/parallel.h"
      31             : #include "libmesh/remote_elem.h"
      32             : #include "libmesh/namebased_io.h"
      33             : #include "libmesh/partitioner.h"
      34             : #include "libmesh/enum_order.h"
      35             : #include "libmesh/mesh_communication.h"
      36             : #include "libmesh/enum_to_string.h"
      37             : #include "libmesh/mesh_serializer.h"
      38             : #include "libmesh/utility.h"
      39             : 
      40             : #ifdef LIBMESH_HAVE_NANOFLANN
      41             : #include "libmesh/nanoflann.hpp"
      42             : #endif
      43             : 
      44             : // C++ includes
      45             : #include <algorithm> // std::all_of
      46             : #include <atomic>
      47             : #include <fstream>
      48             : #include <iomanip>
      49             : #include <map>
      50             : #include <sstream>
      51             : #include <unordered_map>
      52             : 
      53             : // for disjoint neighbors
      54             : #include "libmesh/periodic_boundaries.h"
      55             : #include "libmesh/periodic_boundary.h"
      56             : 
      57             : namespace {
      58             : 
      59             : using namespace libMesh;
      60             : 
      61             : // Helper functions for all_second_order, all_complete_order
      62             : 
      63             : std::map<std::vector<dof_id_type>, Node *>::iterator
      64    38580372 : map_hi_order_node(unsigned int hon,
      65             :                   const Elem & hi_elem,
      66             :                   std::map<std::vector<dof_id_type>, Node *> & adj_vertices_to_ho_nodes)
      67             : {
      68             :   /*
      69             :    * form a vector that will hold the node id's of
      70             :    * the vertices that are adjacent to the nth
      71             :    * higher-order node.
      72             :    */
      73             :   const unsigned int n_adjacent_vertices =
      74    38580372 :     hi_elem.n_second_order_adjacent_vertices(hon);
      75             : 
      76    38580372 :   std::vector<dof_id_type> adjacent_vertices_ids(n_adjacent_vertices);
      77             : 
      78   129401857 :   for (unsigned int v=0; v<n_adjacent_vertices; v++)
      79    93251043 :     adjacent_vertices_ids[v] =
      80    90821485 :       hi_elem.node_id( hi_elem.second_order_adjacent_vertex(hon,v) );
      81             : 
      82             :   /*
      83             :    * \p adjacent_vertices_ids is now in order of the current
      84             :    * side.  sort it, so that comparisons  with the
      85             :    * \p adjacent_vertices_ids created through other elements'
      86             :    * sides can match
      87             :    */
      88    38580372 :   std::sort(adjacent_vertices_ids.begin(),
      89             :             adjacent_vertices_ids.end());
      90             : 
      91             :   // Does this set of vertices already have a mid-node added?  If not
      92             :   // we'll want to add it.
      93    40627404 :   return adj_vertices_to_ho_nodes.try_emplace(adjacent_vertices_ids, nullptr).first;
      94             : }
      95             : 
      96     4140989 : void transfer_elem(Elem & lo_elem,
      97             :                    std::unique_ptr<Elem> hi_elem,
      98             : #ifdef LIBMESH_ENABLE_UNIQUE_ID
      99             :                    unique_id_type max_unique_id,
     100             :                    unique_id_type max_new_nodes_per_elem,
     101             : #endif
     102             :                    UnstructuredMesh & mesh,
     103             :                    std::map<std::vector<dof_id_type>, Node *> & adj_vertices_to_ho_nodes,
     104             :                    std::unordered_map<Elem *, std::vector<Elem *>> & exterior_children_of)
     105             : {
     106      108650 :   libmesh_assert_equal_to (lo_elem.n_vertices(), hi_elem->n_vertices());
     107             : 
     108      217300 :   const processor_id_type my_pid = mesh.processor_id();
     109     4140989 :   const processor_id_type lo_pid = lo_elem.processor_id();
     110             : 
     111             :   /*
     112             :    * Now handle the additional higher-order nodes.  This
     113             :    * is simply handled through a map that remembers
     114             :    * the already-added nodes.  This map maps the global
     115             :    * ids of the vertices (that uniquely define this
     116             :    * higher-order node) to the new node.
     117             :    * Notation: hon = high-order node
     118             :    */
     119     4140989 :   const unsigned int hon_begin = lo_elem.n_nodes();
     120     4140989 :   const unsigned int hon_end   = hi_elem->n_nodes();
     121             : 
     122      108650 :   libmesh_assert_less (hon_begin, hon_end);
     123             : #ifdef LIBMESH_ENABLE_UNIQUE_ID
     124      108650 :   libmesh_assert_less_equal
     125             :     (hon_end-hon_begin, max_new_nodes_per_elem);
     126             : #endif
     127             : 
     128    42435798 :   for (unsigned int hon=hon_begin; hon<hon_end; hon++)
     129             :     {
     130    38294809 :       auto pos = map_hi_order_node(hon, *hi_elem, adj_vertices_to_ho_nodes);
     131             : 
     132             :       // no, not added yet
     133    38294809 :       if (!pos->second)
     134             :         {
     135      366424 :           const auto & adjacent_vertices_ids = pos->first;
     136             : 
     137             :           /*
     138             :            * for this set of vertices, there is no
     139             :            * second_order node yet.  Add it.
     140             :            *
     141             :            * compute the location of the new node as
     142             :            * the average over the adjacent vertices.
     143             :            */
     144      366424 :           Point new_location = 0;
     145    49053494 :           for (dof_id_type vertex_id : adjacent_vertices_ids)
     146    35255422 :             new_location += mesh.point(vertex_id);
     147             : 
     148    14164496 :           new_location /= static_cast<Real>(adjacent_vertices_ids.size());
     149             : 
     150             :           /* Add the new point to the mesh.
     151             :            *
     152             :            * If we are on a serialized mesh, then we're doing this
     153             :            * all in sync, and the node processor_id will be
     154             :            * consistent between processors.
     155             :            *
     156             :            * If we are on a distributed mesh, we can fix
     157             :            * inconsistent processor ids later, but only if every
     158             :            * processor gives new nodes a *locally* consistent
     159             :            * processor id, so we'll give the new node the
     160             :            * processor id of an adjacent element for now and then
     161             :            * we'll update that later if appropriate.
     162             :            */
     163             :           Node * hi_node = mesh.add_point
     164    13798072 :             (new_location, DofObject::invalid_id, lo_pid);
     165             : 
     166             :           /* Come up with a unique unique_id for a potentially new
     167             :            * node.  On a distributed mesh we don't yet know what
     168             :            * processor_id will definitely own it, so we can't let
     169             :            * the pid determine the unique_id.  But we're not
     170             :            * adding unpartitioned nodes in sync, so we can't let
     171             :            * the mesh autodetermine a unique_id for a new
     172             :            * unpartitioned node either.  So we have to pick unique
     173             :            * unique_id values manually.
     174             :            *
     175             :            * We don't have to pick the *same* unique_id value as
     176             :            * will be picked on other processors, though; we'll
     177             :            * sync up each node later.  We just need to make sure
     178             :            * we don't duplicate any unique_id that might be chosen
     179             :            * by the same process elsewhere.
     180             :            */
     181             : #ifdef LIBMESH_ENABLE_UNIQUE_ID
     182    13798072 :           unique_id_type new_unique_id = max_unique_id +
     183    14164496 :             max_new_nodes_per_elem * lo_elem.id() +
     184    13798072 :             hon - hon_begin;
     185             : 
     186      366424 :           hi_node->set_unique_id(new_unique_id);
     187             : #endif
     188             : 
     189             :           /*
     190             :            * insert the new node with its defining vertex
     191             :            * set into the map, and relocate pos to this
     192             :            * new entry, so that the hi_elem can use
     193             :            * \p pos for inserting the node
     194             :            */
     195    13798072 :           pos->second = hi_node;
     196             : 
     197    13798072 :           hi_elem->set_node(hon, hi_node);
     198             :         }
     199             :       // yes, already added.
     200             :       else
     201             :         {
     202      643330 :           Node * hi_node = pos->second;
     203      643330 :           libmesh_assert(hi_node);
     204      643330 :           libmesh_assert_equal_to(mesh.node_ptr(hi_node->id()), hi_node);
     205             : 
     206    24496737 :           hi_elem->set_node(hon, hi_node);
     207             : 
     208             :           // We need to ensure that the processor who should own a
     209             :           // node *knows* they own the node.  And because
     210             :           // Node::choose_processor_id() may depend on Node id,
     211             :           // which may not yet be authoritative, we still have to
     212             :           // use a dumb-but-id-independent partitioning heuristic.
     213             :           processor_id_type chosen_pid =
     214    24496737 :             std::min (hi_node->processor_id(), lo_pid);
     215             : 
     216             :           // Plus, if we just discovered that we own this node,
     217             :           // then on a distributed mesh we need to make sure to
     218             :           // give it a valid id, not just a placeholder id!
     219    24496737 :           if (!mesh.is_replicated() &&
     220    24496737 :               hi_node->processor_id() != my_pid &&
     221             :               chosen_pid == my_pid)
     222        4130 :             mesh.own_node(*hi_node);
     223             : 
     224    24496737 :           hi_node->processor_id() = chosen_pid;
     225             :         }
     226             :     }
     227             : 
     228             :   /*
     229             :    * find_neighbors relies on remote_elem neighbor links being
     230             :    * properly maintained.  Our own code here relies on ordinary
     231             :    * neighbor links being properly maintained, so let's just keep
     232             :    * everything up to date.
     233             :    */
     234    21222786 :   for (auto s : lo_elem.side_index_range())
     235             :     {
     236    17081797 :       Elem * neigh = lo_elem.neighbor_ptr(s);
     237    17081797 :       if (!neigh)
     238    16130172 :         continue;
     239             : 
     240      528687 :       if (neigh != remote_elem)
     241             :         {
     242             :           // We don't support AMR even outside our own range yet.
     243       30394 :           libmesh_assert_equal_to (neigh->level(), 0);
     244             : 
     245      494790 :           const unsigned int ns = neigh->which_neighbor_am_i(&lo_elem);
     246       30394 :           libmesh_assert_not_equal_to(ns, libMesh::invalid_uint);
     247             : 
     248       60788 :           neigh->set_neighbor(ns, hi_elem.get());
     249             :         }
     250             : 
     251       61108 :       hi_elem->set_neighbor(s, neigh);
     252             :     }
     253             : 
     254             :   /**
     255             :    * If the old element has an interior_parent(), transfer it to the
     256             :    * new element ... and if the interior_parent itself might be
     257             :    * getting upgraded, make sure we later consider the new element to
     258             :    * be its exterior child, not the old element.
     259             :    */
     260     4140989 :   Elem * interior_p = lo_elem.interior_parent();
     261     4140989 :   if (interior_p)
     262           0 :     hi_elem->set_interior_parent(interior_p);
     263             : 
     264     4140989 :   if (auto parent_exterior_it = exterior_children_of.find(interior_p);
     265      108650 :       parent_exterior_it != exterior_children_of.end())
     266             :     {
     267           0 :       auto & exteriors = parent_exterior_it->second;
     268           0 :       for (std::size_t i : index_range(exteriors))
     269           0 :         if (exteriors[i] == &lo_elem)
     270             :           {
     271           0 :             exteriors[i] = hi_elem.get();
     272           0 :             break;
     273             :           }
     274             :     }
     275             : 
     276             :   /**
     277             :    * If we had interior_parent() links to the old element, transfer
     278             :    * them to the new element.
     279             :    */
     280     4249639 :   if (auto exterior_it = exterior_children_of.find(&lo_elem);
     281      108650 :       exterior_it != exterior_children_of.end())
     282             :     {
     283     4140989 :       for (Elem * exterior_elem : exterior_it->second)
     284             :         {
     285           0 :           libmesh_assert(exterior_elem->interior_parent() == &lo_elem);
     286           0 :           exterior_elem->set_interior_parent(hi_elem.get());
     287             :         }
     288             :     }
     289             : 
     290             :   /**
     291             :    * If the old element had any boundary conditions they
     292             :    * should be transferred to the second-order element.  The old
     293             :    * boundary conditions will be removed from the BoundaryInfo
     294             :    * data structure by insert_elem.
     295             :    *
     296             :    * Also, prepare_for_use() will reconstruct most of our neighbor
     297             :    * links, but if we have any remote_elem links in a distributed
     298             :    * mesh, they need to be preserved.  We do that in the same loop
     299             :    * here.
     300             :    */
     301      108650 :   mesh.get_boundary_info().copy_boundary_ids
     302     4140989 :     (mesh.get_boundary_info(), &lo_elem, hi_elem.get());
     303             : 
     304             :   /*
     305             :    * The new second-order element is ready.
     306             :    * Inserting it into the mesh will replace and delete
     307             :    * the first-order element.
     308             :    */
     309      217300 :   hi_elem->set_id(lo_elem.id());
     310             : #ifdef LIBMESH_ENABLE_UNIQUE_ID
     311      217300 :   hi_elem->set_unique_id(lo_elem.unique_id());
     312             : #endif
     313             : 
     314     4140989 :   const unsigned int nei = lo_elem.n_extra_integers();
     315     4140989 :   hi_elem->add_extra_integers(nei);
     316     4141308 :   for (unsigned int i=0; i != nei; ++i)
     317         319 :     hi_elem->set_extra_integer(i, lo_elem.get_extra_integer(i));
     318             : 
     319     4032339 :   hi_elem->inherit_data_from(lo_elem);
     320             : 
     321     4249639 :   mesh.insert_elem(std::move(hi_elem));
     322     4140989 : }
     323             : 
     324             : 
     325             : template <typename ElemTypeConverter>
     326             : void
     327       53713 : all_increased_order_range (UnstructuredMesh & mesh,
     328             :                            const SimpleRange<MeshBase::element_iterator> & range,
     329             :                            const unsigned int max_new_nodes_per_elem,
     330             :                            const ElemTypeConverter & elem_type_converter)
     331             : {
     332             :   // This function must be run on all processors at once
     333        1528 :   timpi_parallel_only(mesh.comm());
     334             : 
     335             :   /*
     336             :    * The maximum number of new higher-order nodes we might be adding,
     337             :    * for use when picking unique unique_id values later. This variable
     338             :    * is not used unless unique ids are enabled, so libmesh_ignore() it
     339             :    * to avoid warnings in that case.
     340             :    */
     341        1528 :   libmesh_ignore(max_new_nodes_per_elem);
     342             : 
     343             :   /*
     344             :    * The mesh should at least be consistent enough for us to add new
     345             :    * nodes consistently.
     346             :    */
     347       53713 :   mesh.update_parallel_id_counts();
     348             : 
     349             :   /*
     350             :    * If the mesh is empty then we have nothing to do
     351             :    */
     352       53713 :   if (!mesh.n_elem())
     353        3984 :     return;
     354             : 
     355             :   // If every element in the range _on every proc_ is already of the
     356             :   // requested higher order then we have nothing to do. However, if
     357             :   // any proc has some lower-order elements in the range, then _all_
     358             :   // processors need to continue this function because it is
     359             :   // parallel_only().
     360             :   //
     361             :   // Note: std::all_of() returns true for an empty range, which can
     362             :   // happen for example in the DistributedMesh case when there are
     363             :   // more processors than elements. In the case of an empty range we
     364             :   // therefore set already_second_order to true on that proc.
     365      131406 :   auto is_higher_order = [&elem_type_converter](const Elem * elem) {
     366       51744 :     ElemType old_type = elem->type();
     367        2554 :     ElemType new_type = elem_type_converter(old_type);
     368       51744 :     return old_type == new_type;
     369             :   };
     370             : 
     371       53713 :   bool already_higher_order =
     372      105898 :     std::all_of(range.begin(), range.end(), is_higher_order);
     373             : 
     374             :   // Check with other processors and possibly return early
     375       53713 :   mesh.comm().min(already_higher_order);
     376       53713 :   if (already_higher_order)
     377         116 :     return;
     378             : 
     379             :   /*
     380             :    * this map helps in identifying higher order
     381             :    * nodes.  Namely, a higher-order node:
     382             :    * - edge node
     383             :    * - face node
     384             :    * - bubble node
     385             :    * is uniquely defined through a set of adjacent
     386             :    * vertices.  This set of adjacent vertices is
     387             :    * used to identify already added higher-order
     388             :    * nodes.  We are safe to use node id's since we
     389             :    * make sure that these are correctly numbered.
     390             :    *
     391             :    * We lazily use an ordered map here to avoid having to implement a
     392             :    * good hash for vector<dof_id_type>
     393             :    */
     394        2824 :   std::map<std::vector<dof_id_type>, Node *> adj_vertices_to_ho_nodes;
     395             : 
     396             :   /*
     397             :    * This map helps us reset any interior_parent() values from the
     398             :    * lower order element to its higher order replacement.  Unlike with
     399             :    * neighbor pointers, we don't have backlinks here, so we have to
     400             :    * iterate over the mesh to track forward links.
     401             :    */
     402        2824 :   std::unordered_map<Elem *, std::vector<Elem *>> exterior_children_of;
     403             : 
     404             :   /*
     405             :    * max_new_nodes_per_elem is the maximum number of new higher order
     406             :    * nodes we might be adding, for use when picking unique unique_id
     407             :    * values later. This variable is not used unless unique ids are
     408             :    * enabled.
     409             :    */
     410             : #ifdef LIBMESH_ENABLE_UNIQUE_ID
     411       49729 :   unique_id_type max_unique_id = mesh.parallel_max_unique_id();
     412             : #endif
     413             : 
     414             :   /**
     415             :    * On distributed meshes we currently only support unpartitioned
     416             :    * meshes (where we'll add every node in sync) or
     417             :    * completely-partitioned meshes (where we'll sync nodes later);
     418             :    * let's keep track to make sure we're not in any in-between state.
     419             :    */
     420        1412 :   dof_id_type n_unpartitioned_elem = 0;
     421             : 
     422             :   /**
     423             :    * Loop over the elements in the given range.  If any are
     424             :    * already at higher than first-order, track their higher-order
     425             :    * nodes in case we need them for neighboring elements later.
     426             :    *
     427             :    * In this way we can use this method to "fix up" a mesh which has
     428             :    * otherwise inconsistent neighbor pairs of lower and higher order
     429             :    * geometric elements.
     430             :    *
     431             :    * If any elements are not at the desired order yet, we need to
     432             :    * check their neighbors and even their edge neighbors for higher
     433             :    * order; we may need to share elements with a neighbor not in the
     434             :    * range.
     435             :    */
     436     8277179 :   auto track_if_necessary = [&adj_vertices_to_ho_nodes,
     437             :                              &exterior_children_of,
     438      221164 :                              &elem_type_converter](Elem * elem) {
     439     4178342 :     if (elem && elem != remote_elem)
     440             :       {
     441     4178342 :         if (elem->default_order() != FIRST)
     442      305187 :           for (unsigned int hon : make_range(elem->n_vertices(), elem->n_nodes()))
     443             :             {
     444      285563 :               auto pos = map_hi_order_node(hon, *elem, adj_vertices_to_ho_nodes);
     445      299325 :               pos->second = elem->node_ptr(hon);
     446             :             }
     447             : 
     448     4178342 :         const ElemType old_type = elem->type();
     449      151222 :         const ElemType new_type = elem_type_converter(old_type);
     450     4178342 :         if (old_type != new_type)
     451     4158718 :           exterior_children_of.emplace(elem, std::vector<Elem *>());
     452             :       }
     453             :   };
     454             : 
     455             :   // If we're in the common case then just track everything; otherwise
     456             :   // find point neighbors to track
     457      150375 :   if (range.begin() == mesh.elements_begin() &&
     458      185546 :       range.end() == mesh.elements_end())
     459             :     {
     460     8100823 :       for (auto & elem : range)
     461     4135981 :         track_if_necessary(elem);
     462             :     }
     463             :   else
     464             :     {
     465         240 :       GhostingFunctor::map_type point_neighbor_elements;
     466             : 
     467         240 :       GhostPointNeighbors point_neighbor_finder(mesh);
     468       11880 :       point_neighbor_finder(range.begin(), range.end(),
     469             :                             mesh.n_processors(),
     470             :                             point_neighbor_elements);
     471             : 
     472       46401 :       for (auto & [elem, coupling_map] : point_neighbor_elements)
     473             :         {
     474        2168 :           libmesh_ignore(coupling_map);
     475       42361 :           track_if_necessary(const_cast<Elem *>(elem));
     476             :         }
     477             :     }
     478             : 
     479             :   /**
     480             :    * Loop over all mesh elements to look for interior_parent links we
     481             :    * need to upgrade later.
     482             :    */
     483     8376981 :   for (auto & elem : mesh.element_ptr_range())
     484     4341415 :     if (auto exterior_map_it = exterior_children_of.find(elem->interior_parent());
     485      112700 :         exterior_map_it != exterior_children_of.end())
     486           0 :       exterior_map_it->second.push_back(elem);
     487             : 
     488             :   /**
     489             :    * Loop over the low-ordered elements in the _elements vector.
     490             :    * First make sure they _are_ indeed low-order, and then replace
     491             :    * them with an equivalent second-order element.  Don't
     492             :    * forget to delete the low-order element, or else it will leak!
     493             :    */
     494     8115345 :   for (auto & lo_elem : range)
     495             :     {
     496             :       // Now we can skip the elements in the range that are already
     497             :       // higher-order.
     498     4141480 :       const ElemType old_type = lo_elem->type();
     499      148850 :       const ElemType new_type = elem_type_converter(old_type);
     500             : 
     501     4141480 :       if (old_type == new_type)
     502         491 :         continue;
     503             : 
     504             :       // this does _not_ work for refined elements
     505      108650 :       libmesh_assert_equal_to (lo_elem->level(), 0);
     506             : 
     507     4140989 :       if (lo_elem->processor_id() == DofObject::invalid_processor_id)
     508     4037519 :         ++n_unpartitioned_elem;
     509             : 
     510             :       /*
     511             :        * Build the higher-order equivalent; add to
     512             :        * the new_elements list.
     513             :        */
     514     4140989 :       auto ho_elem = Elem::build (new_type);
     515             : 
     516      108650 :       libmesh_assert_equal_to (lo_elem->n_vertices(), ho_elem->n_vertices());
     517             : 
     518             :       /*
     519             :        * By definition the initial nodes of the lower and higher order
     520             :        * element are identically numbered.  Transfer these.
     521             :        */
     522    21382998 :       for (unsigned int v=0, lnn=lo_elem->n_nodes(); v < lnn; v++)
     523    17704673 :         ho_elem->set_node(v, lo_elem->node_ptr(v));
     524             : 
     525     4358289 :       transfer_elem(*lo_elem, std::move(ho_elem),
     526             : #ifdef LIBMESH_ENABLE_UNIQUE_ID
     527             :                     max_unique_id, max_new_nodes_per_elem,
     528             : #endif
     529             :                     mesh, adj_vertices_to_ho_nodes,
     530             :                     exterior_children_of);
     531             :     } // end for (auto & lo_elem : range)
     532             : 
     533             :   // we can clear the map at this point.
     534        1412 :   adj_vertices_to_ho_nodes.clear();
     535             : 
     536             : #ifdef LIBMESH_ENABLE_UNIQUE_ID
     537       49729 :   const unique_id_type new_max_unique_id = max_unique_id +
     538       49729 :     max_new_nodes_per_elem * mesh.n_elem();
     539       49729 :   mesh.set_next_unique_id(new_max_unique_id);
     540             : #endif
     541             : 
     542             :   // On a DistributedMesh our ghost node processor ids may be bad,
     543             :   // the ids of nodes touching remote elements may be inconsistent,
     544             :   // unique_ids of newly added non-local nodes remain unset, and our
     545             :   // partitioning of new nodes may not be well balanced.
     546             :   //
     547             :   // make_nodes_parallel_consistent() will fix all this.
     548       49729 :   if (!mesh.is_replicated())
     549             :     {
     550       43362 :       dof_id_type max_unpartitioned_elem = n_unpartitioned_elem;
     551       43362 :       mesh.comm().max(max_unpartitioned_elem);
     552       43362 :       if (max_unpartitioned_elem)
     553             :         {
     554             :           // We'd better be effectively serialized here.  In theory we
     555             :           // could support more complicated cases but for now we
     556             :           // only support "completely partitioned" and/or "serialized"
     557       35725 :           if (mesh.is_serial())
     558          22 :             libmesh_assert(mesh.comm().verify(n_unpartitioned_elem));
     559             :           else
     560           0 :             libmesh_not_implemented();
     561             :         }
     562             :       else
     563             :         {
     564        7637 :           MeshCommunication().make_nodes_parallel_consistent (mesh);
     565             :         }
     566             :     }
     567             : 
     568             :   // renumber nodes, repartition nodes, etc.  We may no longer need a
     569             :   // find_neighbors() here since we're keeping neighbor links intact
     570             :   // ourselves, *except* that if we're not already prepared we may
     571             :   // have user code that was expecting this call to prepare neighbors.
     572        2824 :   const bool old_find_neighbors = mesh.allow_find_neighbors();
     573       49729 :   if (mesh.is_prepared())
     574         272 :     mesh.allow_find_neighbors(false);
     575       49729 :   mesh.prepare_for_use();
     576        1412 :   mesh.allow_find_neighbors(old_find_neighbors);
     577             : }
     578             : 
     579             : 
     580             : } // anonymous namespace
     581             : 
     582             : 
     583             : namespace libMesh
     584             : {
     585             : 
     586             : // This class adapts a vector of Nodes (represented by a pair of a Point and a dof_id_type)
     587             : // for use in a nanoflann KD-Tree
     588             : 
     589           0 : class VectorOfNodesAdaptor
     590             : {
     591             : private:
     592             :   const std::vector<std::pair<Point, dof_id_type>> _nodes;
     593             : 
     594             : public:
     595           0 :   VectorOfNodesAdaptor(const std::vector<std::pair<Point, dof_id_type>> & nodes) :
     596           0 :     _nodes(nodes)
     597           0 :   {}
     598             : 
     599             :   /**
     600             :    * Must return the number of data points
     601             :    */
     602           0 :   inline size_t kdtree_get_point_count() const { return _nodes.size(); }
     603             : 
     604             :   /**
     605             :    * \returns The dim'th component of the idx'th point in the class:
     606             :    * Since this is inlined and the "dim" argument is typically an immediate value, the
     607             :    *  "if's" are actually solved at compile time.
     608             :    */
     609           0 :   inline Real kdtree_get_pt(const size_t idx, int dim) const
     610             :     {
     611           0 :       libmesh_assert_less (idx, _nodes.size());
     612           0 :       libmesh_assert_less (dim, 3);
     613             : 
     614           0 :       const Point & p(_nodes[idx].first);
     615             : 
     616           0 :       if (dim==0) return p(0);
     617           0 :       if (dim==1) return p(1);
     618           0 :       return p(2);
     619             :     }
     620             : 
     621             :   /*
     622             :    * Optional bounding-box computation
     623             :    */
     624             :   template <class BBOX>
     625           0 :   bool kdtree_get_bbox(BBOX & /* bb */) const { return false; }
     626             : };
     627             : 
     628             : 
     629             : // ------------------------------------------------------------
     630             : // UnstructuredMesh class member functions
     631      477303 : UnstructuredMesh::UnstructuredMesh (const Parallel::Communicator & comm_in,
     632      477303 :                                     unsigned char d) :
     633      477303 :   MeshBase (comm_in,d)
     634             : {
     635       13833 :   libmesh_assert (libMesh::initialized());
     636      477303 : }
     637             : 
     638             : 
     639             : 
     640       24543 : UnstructuredMesh::UnstructuredMesh (const MeshBase & other_mesh) :
     641       24543 :   MeshBase (other_mesh)
     642             : {
     643         816 :   libmesh_assert (libMesh::initialized());
     644       24543 : }
     645             : 
     646             : 
     647             : 
     648       26318 : void UnstructuredMesh::copy_nodes_and_elements(const MeshBase & other_mesh,
     649             :                                                const bool skip_find_neighbors,
     650             :                                                dof_id_type element_id_offset,
     651             :                                                dof_id_type node_id_offset,
     652             :                                                unique_id_type
     653             : #ifdef LIBMESH_ENABLE_UNIQUE_ID
     654             :                                                  unique_id_offset
     655             : #endif
     656             :                                                ,
     657             :                                                std::unordered_map<subdomain_id_type, subdomain_id_type> *
     658             :                                                  id_remapping,
     659             :                                                const bool skip_preparation)
     660             : {
     661        2574 :   LOG_SCOPE("copy_nodes_and_elements()", "UnstructuredMesh");
     662             : 
     663             :   // If we're asked to skip all preparation, we should be skipping
     664             :   // find_neighbors specifically.
     665         866 :   libmesh_assert(!skip_preparation || skip_find_neighbors);
     666             : 
     667             :   std::pair<std::vector<unsigned int>, std::vector<unsigned int>>
     668       28026 :     extra_int_maps = this->merge_extra_integer_names(other_mesh);
     669             : 
     670       26318 :   const unsigned int n_old_node_ints = extra_int_maps.second.size(),
     671       26318 :                      n_new_node_ints = _node_integer_names.size(),
     672       26318 :                      n_old_elem_ints = extra_int_maps.first.size(),
     673       26318 :                      n_new_elem_ints = _elem_integer_names.size();
     674             : 
     675             :   // If we are partitioned into fewer parts than the incoming mesh has
     676             :   // processors to handle, then we need to "wrap" the other Mesh's
     677             :   // processor ids to fit within our range. This can happen, for
     678             :   // example, while stitching meshes with small numbers of elements in
     679             :   // parallel...
     680        1708 :   bool wrap_proc_ids = (this->n_processors() <
     681        1708 :                         other_mesh.n_partitions());
     682             : 
     683             :   // We're assuming the other mesh has proper element number ordering,
     684             :   // so that we add parents before their children, and that the other
     685             :   // mesh is consistently partitioned.  We're not assuming that node
     686             :   // proc ids are topologically consistent, so we don't just
     687             :   // libmesh_assert_valid_procids.
     688             : #ifdef DEBUG
     689         866 :   MeshTools::libmesh_assert_valid_amr_elem_ids(other_mesh);
     690         866 :   MeshTools::libmesh_assert_parallel_consistent_procids<Node>(other_mesh);
     691             : #endif
     692             : 
     693             :   //Copy in Nodes
     694             :   {
     695             :     //Preallocate Memory if necessary
     696       26318 :     this->reserve_nodes(other_mesh.n_nodes());
     697             : 
     698     7427928 :     for (const auto & oldn : other_mesh.node_ptr_range())
     699             :       {
     700             :         processor_id_type added_pid = cast_int<processor_id_type>
     701     3869053 :           (wrap_proc_ids ? oldn->processor_id() % this->n_processors() : oldn->processor_id());
     702             : 
     703             :         // Add new nodes in old node Point locations
     704             :         Node * newn =
     705     4415359 :           this->add_point(*oldn,
     706     3869053 :                           oldn->id() + node_id_offset,
     707      361948 :                           added_pid);
     708             : 
     709     3869053 :         newn->add_extra_integers(n_new_node_ints);
     710     4093901 :         for (unsigned int i = 0; i != n_old_node_ints; ++i)
     711      236796 :           newn->set_extra_integer(extra_int_maps.second[i],
     712      224848 :                                   oldn->get_extra_integer(i));
     713             : 
     714             : #ifdef LIBMESH_ENABLE_UNIQUE_ID
     715     3869053 :         newn->set_unique_id(oldn->unique_id() + unique_id_offset);
     716             : #endif
     717       24610 :       }
     718             :   }
     719             : 
     720             :   //Copy in Elements
     721             :   {
     722             :     //Preallocate Memory if necessary
     723       26318 :     this->reserve_elem(other_mesh.n_elem());
     724             : 
     725             :     // Declare a map linking old and new elements, needed to copy the neighbor lists
     726             :     typedef std::unordered_map<const Elem *, Elem *> map_type;
     727        1732 :     map_type old_elems_to_new_elems, ip_map;
     728             : 
     729             :     // Loop over the elements
     730    18434452 :     for (const auto & old : other_mesh.element_ptr_range())
     731             :       {
     732             :         // Build a new element
     733     9788145 :         Elem * newparent = old->parent() ?
     734      240605 :           this->elem_ptr(old->parent()->id() + element_id_offset) :
     735      306568 :           nullptr;
     736     9799033 :         auto el = old->disconnected_clone();
     737      602248 :         el->set_parent(newparent);
     738             : 
     739     9492465 :         subdomain_id_type sbd_id = old->subdomain_id();
     740     9492465 :         if (id_remapping)
     741             :           {
     742         538 :             auto remapping_it = id_remapping->find(sbd_id);
     743       19099 :             if (remapping_it != id_remapping->end())
     744         568 :               sbd_id = remapping_it->second;
     745             :           }
     746     9492465 :         el->subdomain_id() = sbd_id;
     747             : 
     748             :         // Hold off on trying to set the interior parent because we may actually
     749             :         // add lower dimensional elements before their interior parents
     750     9492465 :         if (old->interior_parent())
     751         688 :           ip_map[old] = el.get();
     752             : 
     753             : #ifdef LIBMESH_ENABLE_AMR
     754     9492465 :         if (old->has_children())
     755      392477 :           for (unsigned int c = 0, nc = old->n_children(); c != nc; ++c)
     756      332580 :             if (old->child_ptr(c) == remote_elem)
     757       67551 :               el->add_child(const_cast<RemoteElem *>(remote_elem), c);
     758             : 
     759             :         //Create the parent's child pointers if necessary
     760     9492465 :         if (newparent)
     761             :           {
     762      265009 :             unsigned int oldc = old->parent()->which_child_am_i(old);
     763      240605 :             newparent->add_child(el.get(), oldc);
     764             :           }
     765             : 
     766             :         // Copy the refinement flags
     767     9492465 :         el->set_refinement_flag(old->refinement_flag());
     768             : 
     769             :         // Use hack_p_level since we may not have sibling elements
     770             :         // added yet
     771      602248 :         el->hack_p_level(old->p_level());
     772             : 
     773      602248 :         el->set_p_refinement_flag(old->p_refinement_flag());
     774             : #endif // #ifdef LIBMESH_ENABLE_AMR
     775             : 
     776             :         //Assign all the nodes
     777    50103157 :         for (auto i : el->node_index_range())
     778    42007536 :           el->set_node(i,
     779    40610692 :             this->node_ptr(old->node_id(i) + node_id_offset));
     780             : 
     781             :         // And start it off with the same processor id (mod _n_parts).
     782     9492465 :         el->processor_id() = cast_int<processor_id_type>
     783     9492465 :           (wrap_proc_ids ? old->processor_id() % this->n_processors() : old->processor_id());
     784             : 
     785             :         // Give it the same element and unique ids
     786     9492465 :         el->set_id(old->id() + element_id_offset);
     787             : 
     788     9492465 :         el->add_extra_integers(n_new_elem_ints);
     789     9509718 :         for (unsigned int i = 0; i != n_old_elem_ints; ++i)
     790       18225 :           el->set_extra_integer(extra_int_maps.first[i],
     791       17253 :                                 old->get_extra_integer(i));
     792             : 
     793             : #ifdef LIBMESH_ENABLE_UNIQUE_ID
     794     9492465 :         el->set_unique_id(old->unique_id() + unique_id_offset);
     795             : #endif
     796             : 
     797             :         //Hold onto it
     798     9492465 :         if (!skip_find_neighbors)
     799             :           {
     800      220630 :             for (auto s : old->side_index_range())
     801      182136 :               if (old->neighbor_ptr(s) == remote_elem)
     802         256 :                 el->set_neighbor(s, const_cast<RemoteElem *>(remote_elem));
     803       46942 :             this->add_elem(std::move(el));
     804             :           }
     805             :         else
     806             :           {
     807     9742611 :             Elem * new_el = this->add_elem(std::move(el));
     808     9448339 :             old_elems_to_new_elems[old] = new_el;
     809             :           }
     810     8914827 :       }
     811             : 
     812             :     // If the other_mesh had some interior parents, we may need to
     813             :     // copy those pointers (if they're to elements in a third mesh),
     814             :     // or create new equivalent pointers (if they're to elements we
     815             :     // just copied), or scream and die (if the other mesh had interior
     816             :     // parents from a third mesh but we already have interior parents
     817             :     // that aren't to that same third mesh.
     818       26318 :     if (!ip_map.empty())
     819             :       {
     820         156 :         std::atomic<bool> existing_interior_parents{false};
     821             : 
     822             :         Threads::parallel_for
     823         156 :           (this->element_stored_range(),
     824         468 :            [&existing_interior_parents](const ElemRange & range)
     825             :            {
     826        2750 :              for (Elem * elem : range)
     827        2594 :                if (elem->interior_parent())
     828             :                  {
     829           0 :                    existing_interior_parents = true;
     830           0 :                    break;
     831             :                  }
     832         156 :            });
     833             : 
     834             :         MeshBase * other_interior_mesh =
     835           0 :           const_cast<MeshBase *>(&other_mesh.interior_mesh());
     836             : 
     837             :         // If we don't already have interior parents, then we can just
     838             :         // use whatever interior_mesh we need for the incoming
     839             :         // elements.
     840         156 :         if (!existing_interior_parents)
     841             :           {
     842         156 :             if (other_interior_mesh == &other_mesh)
     843           0 :               this->set_interior_mesh(*this);
     844             :             else
     845           0 :               this->set_interior_mesh(*other_interior_mesh);
     846             :           }
     847             : 
     848         156 :         if (other_interior_mesh == &other_mesh &&
     849         156 :             _interior_mesh == this)
     850         844 :           for (auto & elem_pair : ip_map)
     851         688 :             elem_pair.second->set_interior_parent(
     852         688 :               this->elem_ptr(elem_pair.first->interior_parent()->id() + element_id_offset));
     853           0 :         else if (other_interior_mesh == _interior_mesh)
     854           0 :           for (auto & elem_pair : ip_map)
     855             :             {
     856           0 :               Elem * ip = const_cast<Elem *>(elem_pair.first->interior_parent());
     857           0 :               libmesh_assert(ip == remote_elem ||
     858             :                              ip == other_interior_mesh->elem_ptr(ip->id()));
     859           0 :               elem_pair.second->set_interior_parent(ip);
     860             :             }
     861             :         else
     862           0 :           libmesh_error_msg("Cannot copy boundary elements between meshes with different interior meshes");
     863             :       }
     864             : 
     865             :     // Loop (again) over the elements to fill in the neighbors
     866       26318 :     if (skip_find_neighbors)
     867             :       {
     868       26034 :         old_elems_to_new_elems[remote_elem] = const_cast<RemoteElem*>(remote_elem);
     869             : 
     870    18348456 :         for (const auto & old_elem : other_mesh.element_ptr_range())
     871             :           {
     872     9448339 :             Elem * new_elem = old_elems_to_new_elems[old_elem];
     873    47411104 :             for (auto s : old_elem->side_index_range())
     874             :               {
     875    38836965 :                 const Elem * old_neighbor = old_elem->neighbor_ptr(s);
     876    37668493 :                 Elem * new_neighbor = old_elems_to_new_elems[old_neighbor];
     877     2380374 :                 new_elem->set_neighbor(s, new_neighbor);
     878             :               }
     879       24342 :           }
     880             :       }
     881             :   }
     882             : 
     883             : #ifdef LIBMESH_ENABLE_UNIQUE_ID
     884             :   // We set the unique ids of nodes after adding them to the mesh such that our value of
     885             :   // _next_unique_id may be wrong. So we amend that here
     886       26318 :   this->set_next_unique_id(other_mesh.parallel_max_unique_id() + unique_id_offset + 1);
     887             : #endif
     888             : 
     889             :   // Finally, partially prepare the new Mesh for use, if that isn't
     890             :   // being skipped.
     891             :   // Even the default behavior here is for backwards compatibility,
     892             :   // and we don't want to prepare everything.
     893             : 
     894       26318 :   if (!skip_preparation)
     895             :     {
     896             :       // Keep the same numbering and partitioning and distribution
     897             :       // status for now, but save our original policies to restore
     898             :       // later.
     899         100 :       const bool allowed_renumbering = this->allow_renumbering();
     900         100 :       const bool allowed_find_neighbors = this->allow_find_neighbors();
     901         100 :       const bool allowed_elem_removal = this->allow_remote_element_removal();
     902         100 :       const bool allowed_detect_detect_interior_parents = this->allow_detect_interior_parents();
     903          50 :       this->allow_renumbering(false);
     904          50 :       this->allow_remote_element_removal(false);
     905          50 :       this->allow_find_neighbors(!skip_find_neighbors);
     906         100 :       this->allow_detect_interior_parents(other_mesh.allow_detect_interior_parents());
     907             : 
     908             :       // We should generally be able to skip *all* partitioning here
     909             :       // because we're only adding one already-consistent mesh to
     910             :       // another.
     911         100 :       const bool skipped_partitioning = this->skip_partitioning();
     912          50 :       this->skip_partitioning(true);
     913             : 
     914        1775 :       const bool was_prepared = this->is_prepared();
     915        1775 :       this->prepare_for_use();
     916             : 
     917             :       //But in the long term, don't change our policies.
     918          50 :       this->allow_find_neighbors(allowed_find_neighbors);
     919          50 :       this->allow_renumbering(allowed_renumbering);
     920          50 :       this->allow_remote_element_removal(allowed_elem_removal);
     921          50 :       this->skip_partitioning(skipped_partitioning);
     922          50 :       this->allow_detect_interior_parents(allowed_detect_detect_interior_parents);
     923             : 
     924             :       // That prepare_for_use() call marked us as prepared, but we
     925             :       // specifically avoided some important preparation, so we might not
     926             :       // actually be prepared now.
     927        1783 :       if (skip_find_neighbors ||
     928        1775 :           !was_prepared || !other_mesh.is_prepared())
     929        1491 :         this->unset_is_prepared();
     930             :     }
     931             : 
     932             :   // In general we've just invalidated just about everything, and we'd
     933             :   // like to unset_is_prepared(), but specific use cases might know a
     934             :   // priori that they're still partitioned well, or that they've
     935             :   // copied in a disjoint mesh component and don't need new neighbor
     936             :   // pointers, or that they're not adding anything that would change
     937             :   // cached subdomain/element/boundary sets, etc., so we'll rely on
     938             :   // users of the "advanced" skip_preparation option to also set what
     939             :   // preparation they still need.
     940             : 
     941             :   // else
     942             :     // this->unset_is_prepared();
     943       26318 : }
     944             : 
     945             : 
     946             : 
     947      501846 : UnstructuredMesh::~UnstructuredMesh ()
     948             : {
     949             :   //  this->clear ();  // Nothing to clear at this level
     950             : 
     951       14649 :   libmesh_exceptionless_assert (!libMesh::closed());
     952      501846 : }
     953             : 
     954             : 
     955             : 
     956             : namespace {
     957             : /**
     958             :  * \returns \p true if element sides \p a and \p b are the same elem,
     959             :  * for the purpose of linking them as neighbors in find_neighbors().
     960             :  *
     961             :  * This is normally just Elem::operator==, which compares (sorted) node
     962             :  * ids.  But operator== first requires the two sides to have the same
     963             :  * element type, so it never matches a Polyhedron's polygonal side
     964             :  * against the TRI3/QUAD4 side of an adjacent standard element (tet,
     965             :  * hex, ...) even when they are geometrically the same face.  At such a
     966             :  * mixed interface -- exactly one side is a polygon -- we fall back to
     967             :  * comparing the vertex node ids, which is what low_order_key() already
     968             :  * keys on.  Purely standard/standard and polygon/polygon pairs are left
     969             :  * entirely to operator==.
     970             :  */
     971   131215834 : bool sides_are_the_same_elem(const Elem & a, const Elem & b)
     972             : {
     973   131215834 :   if (a == b)
     974     2682626 :     return true;
     975             : 
     976             :   // The check above would have been sufficient if they were both
     977             :   // polygons or both not. If just one is a polygon, we need to check the nodes
     978         142 :   if (!a.runtime_topology() && !b.runtime_topology())
     979           0 :     return false;
     980             : 
     981         142 :   const unsigned int nv = a.n_vertices();
     982         142 :   if (nv != b.n_vertices())
     983           0 :     return false;
     984             : 
     985         150 :   std::vector<dof_id_type> a_ids(nv), b_ids(nv);
     986         568 :   for (unsigned int v = 0; v != nv; ++v)
     987             :     {
     988         438 :       a_ids[v] = a.node_id(v);
     989         450 :       b_ids[v] = b.node_id(v);
     990             :     }
     991         142 :   std::sort(a_ids.begin(), a_ids.end());
     992         142 :   std::sort(b_ids.begin(), b_ids.end());
     993         142 :   return a_ids == b_ids;
     994             : }
     995             : }
     996             : 
     997             : 
     998             : 
     999      781732 : void UnstructuredMesh::find_neighbors (const bool reset_remote_elements,
    1000             :                                        const bool reset_current_list,
    1001             :                                        const bool assert_valid,
    1002             :                                        const bool check_non_remote)
    1003             : {
    1004             :   // We might actually want to run this on an empty mesh
    1005             :   // (e.g. the boundary mesh for a nonexistent bcid!)
    1006             :   // libmesh_assert_not_equal_to (this->n_nodes(), 0);
    1007             :   // libmesh_assert_not_equal_to (this->n_elem(), 0);
    1008             : 
    1009             :   // This function must be run on all processors at once
    1010       17966 :   parallel_object_only();
    1011             : 
    1012       35908 :   LOG_SCOPE("find_neighbors()", "Mesh");
    1013             : 
    1014             :   //TODO:[BSK] This should be removed later?!
    1015      781732 :   if (reset_current_list)
    1016             :     Threads::parallel_for_each
    1017      702916 :       (this->element_stored_range(),
    1018    71681977 :        [reset_remote_elements](Elem * e)
    1019             :        {
    1020   355750278 :          for (auto s : e->side_index_range())
    1021   290598832 :            if (e->neighbor_ptr(s) != remote_elem || reset_remote_elements)
    1022     5900039 :              e->set_neighbor(s, nullptr);
    1023    71011364 :        });
    1024             : 
    1025             :   // Find neighboring elements by first finding elements
    1026             :   // with identical side keys and then check to see if they
    1027             :   // are neighbors
    1028             :   {
    1029             :     // data structures -- Use the hash_multimap if available
    1030             :     typedef dof_id_type                     key_type;
    1031             :     typedef std::pair<Elem *, unsigned char> val_type;
    1032             :     typedef std::unordered_multimap<key_type, val_type> map_type;
    1033             : 
    1034             :     // A map from side keys to corresponding elements & side numbers
    1035       35932 :     map_type side_to_elem_map;
    1036             : 
    1037             :     // Pull objects out of the loop to reduce heap operations
    1038      781732 :     std::unique_ptr<Elem> my_side, their_side;
    1039             : 
    1040   153118754 :     for (const auto & element : this->element_ptr_range())
    1041             :       {
    1042   390250933 :         for (auto ms : element->side_index_range())
    1043             :           {
    1044   442528666 :           next_side:
    1045             :             // If we haven't yet found a neighbor on this side, try.
    1046             :             // Even if we think our neighbor is remote, that
    1047             :             // information may be out of date.
    1048             :             //
    1049             :             // If we're only checking remote neighbors, after a
    1050             :             // redistribution, then we'll skip the non-remote ones
    1051   453852419 :             if ((element->neighbor_ptr(ms) == nullptr && check_non_remote) ||
    1052   160016975 :                 element->neighbor_ptr(ms) == remote_elem)
    1053             :               {
    1054             :                 // Get the key for the side of this element.  Use the
    1055             :                 // low_order_key so we can find neighbors in
    1056             :                 // mixed-order meshes if necessary.
    1057   286585128 :                 const dof_id_type key = element->low_order_key(ms);
    1058             : 
    1059             :                 // Look for elements that have an identical side key
    1060     5911042 :                 auto bounds = side_to_elem_map.equal_range(key);
    1061             : 
    1062             :                 // May be multiple keys, check all the possible
    1063             :                 // elements which _might_ be neighbors.
    1064   286585128 :                 if (bounds.first != bounds.second)
    1065             :                   {
    1066             :                     // Get the side for this element
    1067   131099059 :                     element->side_ptr(my_side, ms);
    1068             : 
    1069             :                     // Look at all the entries with an equivalent key
    1070   131304186 :                     while (bounds.first != bounds.second)
    1071             :                       {
    1072             :                         // Get the potential element
    1073   131215834 :                         Elem * neighbor = bounds.first->second.first;
    1074             : 
    1075             :                         // Get the side for the neighboring element
    1076   131215834 :                         const unsigned int ns = bounds.first->second.second;
    1077   131215834 :                         neighbor->side_ptr(their_side, ns);
    1078             :                         //libmesh_assert(my_side.get());
    1079             :                         //libmesh_assert(their_side.get());
    1080             : 
    1081             :                         // If found a match with my side
    1082             :                         //
    1083             :                         // In 1D, since parents and children have an
    1084             :                         // equal side (i.e. a node) we need to check
    1085             :                         // for matching level() to avoid setting our
    1086             :                         // neighbor pointer to any of our neighbor's
    1087             :                         // descendants.
    1088   262431668 :                         if (sides_are_the_same_elem(*my_side, *their_side) &&
    1089   131215834 :                             (element->level() == neighbor->level()))
    1090             :                           {
    1091             :                             // So share a side.  Is this a mixed pair
    1092             :                             // of subactive and active/ancestor
    1093             :                             // elements?
    1094             :                             // If not, then we're neighbors.
    1095             :                             // If so, then the subactive's neighbor is
    1096             : 
    1097   133669063 :                             if (element->subactive() ==
    1098   131010707 :                                 neighbor->subactive())
    1099             :                               {
    1100             :                                 // an element is only subactive if it has
    1101             :                                 // been coarsened but not deleted
    1102     5323586 :                                 element->set_neighbor (ms,neighbor);
    1103   130840862 :                                 neighbor->set_neighbor(ns,element);
    1104             :                               }
    1105      169845 :                             else if (element->subactive())
    1106             :                               {
    1107        5072 :                                 element->set_neighbor(ms,neighbor);
    1108             :                               }
    1109       93609 :                             else if (neighbor->subactive())
    1110             :                               {
    1111        9368 :                                 neighbor->set_neighbor(ns,element);
    1112             :                               }
    1113     2679670 :                             side_to_elem_map.erase (bounds.first);
    1114             : 
    1115             :                             // get out of this nested crap
    1116   131010707 :                             goto next_side;
    1117             :                           }
    1118             : 
    1119        2960 :                         ++bounds.first;
    1120             :                       }
    1121             :                   }
    1122             : 
    1123             :                 // didn't find a match...
    1124             :                 // Build the map entry for this element
    1125             :                 side_to_elem_map.emplace
    1126   155574421 :                   (key, std::make_pair(element, cast_int<unsigned char>(ms)));
    1127             :               }
    1128             :           }
    1129      745824 :       }
    1130      745824 :   }
    1131             : 
    1132             : #ifdef LIBMESH_ENABLE_PERIODIC
    1133             :   // Get the disjoint neighbor boundary pairs object (from periodic BCs)
    1134      781732 :   auto * db = this->get_disjoint_neighbor_boundary_pairs();
    1135             : 
    1136      781732 :   if (db)
    1137             :     {
    1138             :       // Obtain a point locator
    1139        1589 :       std::unique_ptr<PointLocatorBase> point_locator = this->sub_point_locator();
    1140             : 
    1141        9522 :       for (const auto & element : this->element_ptr_range())
    1142             :         {
    1143       16478 :           for (auto ms : element->side_index_range())
    1144             :             {
    1145             :               // Skip if this side already has a valid neighbor (including remote neighbors)
    1146       13452 :               if (element->neighbor_ptr(ms) != nullptr &&
    1147        2371 :                   element->neighbor_ptr(ms) != remote_elem)
    1148        2319 :                 continue;
    1149             : 
    1150       39239 :               for (const auto & [id, boundary_ptr] : *db)
    1151             :                 {
    1152       28482 :                   if (!this->get_boundary_info().has_boundary_id(element, ms, id))
    1153       26735 :                     continue;
    1154             : 
    1155             :                   unsigned int neigh_side;
    1156             :                   const Elem * neigh =
    1157        1783 :                     db->neighbor(id, *point_locator, element, ms, &neigh_side);
    1158             : 
    1159        1747 :                   if (neigh && neigh != remote_elem && neigh != element)
    1160             :                     {
    1161        1747 :                       auto neigh_changeable = this->elem_ptr(neigh->id());
    1162        1747 :                       element->set_neighbor(ms, neigh_changeable);
    1163        1747 :                       neigh_changeable->set_neighbor(neigh_side, element);
    1164             :                     }
    1165             :                 }
    1166             :             }
    1167        1505 :         }
    1168        1505 :     }
    1169             : #endif // LIBMESH_ENABLE_PERIODIC
    1170             : 
    1171             : #ifdef LIBMESH_ENABLE_AMR
    1172             : 
    1173             :   /**
    1174             :    * Here we look at all of the child elements which
    1175             :    * don't already have valid neighbors.
    1176             :    *
    1177             :    * If a child element has a nullptr neighbor it is
    1178             :    * either because it is on the boundary or because
    1179             :    * its neighbor is at a different level.  In the
    1180             :    * latter case we must get the neighbor from the
    1181             :    * parent.
    1182             :    *
    1183             :    * If a child element has a remote_elem neighbor
    1184             :    * on a boundary it shares with its parent, that
    1185             :    * info may have become out-dated through coarsening
    1186             :    * of the neighbor's parent.  In this case, if the
    1187             :    * parent's neighbor is active then the child should
    1188             :    * share it.
    1189             :    *
    1190             :    * Furthermore, that neighbor better be active,
    1191             :    * otherwise we missed a child somewhere.
    1192             :    *
    1193             :    *
    1194             :    * We also need to look through children ordered by increasing
    1195             :    * refinement level in order to add new interior_parent() links in
    1196             :    * boundary elements which have just been generated by refinement,
    1197             :    * and fix links in boundary elements whose previous
    1198             :    * interior_parent() has just been coarsened away.
    1199             :    */
    1200      781732 :   const unsigned int n_levels = MeshTools::n_levels(*this);
    1201     1057401 :   for (unsigned int level = 1; level < n_levels; ++level)
    1202             :     {
    1203     1377960 :       for (auto & current_elem : as_range(level_elements_begin(level),
    1204   100048716 :                                           level_elements_end(level)))
    1205             :         {
    1206      831178 :           libmesh_assert(current_elem);
    1207    49893165 :           Elem * parent = current_elem->parent();
    1208      831178 :           libmesh_assert(parent);
    1209    49893165 :           const unsigned int my_child_num = parent->which_child_am_i(current_elem);
    1210             : 
    1211   248594901 :           for (auto s : current_elem->side_index_range())
    1212             :             {
    1213   204165832 :               if (current_elem->neighbor_ptr(s) == nullptr ||
    1214   190486441 :                   (current_elem->neighbor_ptr(s) == remote_elem &&
    1215     1883271 :                    parent->is_child_on_side(my_child_num, s)))
    1216             :                 {
    1217      468792 :                   Elem * neigh = parent->neighbor_ptr(s);
    1218             : 
    1219             :                   // If neigh was refined and had non-subactive children
    1220             :                   // made remote earlier, then our current elem should
    1221             :                   // actually have one of those remote children as a
    1222             :                   // neighbor
    1223    14696657 :                   if (neigh &&
    1224     4329111 :                       (neigh->ancestor() ||
    1225             :                        // If neigh has subactive children which should have
    1226             :                        // matched as neighbors of the current element but
    1227             :                        // did not, then those likewise must be remote
    1228             :                        // children.
    1229     4141289 :                        (current_elem->subactive() && neigh->has_children() &&
    1230         189 :                         (neigh->level()+1) == current_elem->level())))
    1231             :                     {
    1232             : #ifdef DEBUG
    1233             :                       // Let's make sure that "had children made remote"
    1234             :                       // situation is actually the case
    1235           0 :                       libmesh_assert(neigh->has_children());
    1236           0 :                       bool neigh_has_remote_children = false;
    1237           0 :                       for (auto & child : neigh->child_ref_range())
    1238           0 :                         if (&child == remote_elem)
    1239           0 :                           neigh_has_remote_children = true;
    1240           0 :                       libmesh_assert(neigh_has_remote_children);
    1241             : 
    1242             :                       // And let's double-check that we don't have
    1243             :                       // a remote_elem neighboring an active local element
    1244           0 :                       if (current_elem->active())
    1245           0 :                         libmesh_assert_not_equal_to (current_elem->processor_id(),
    1246             :                                                      this->processor_id());
    1247             : #endif // DEBUG
    1248       79598 :                       neigh = const_cast<RemoteElem *>(remote_elem);
    1249             :                     }
    1250             :                   // If neigh and current_elem are more than one level
    1251             :                   // apart, figuring out whether we have a remote
    1252             :                   // neighbor here becomes much harder.
    1253    10404458 :                   else if (neigh && (current_elem->subactive() &&
    1254        7908 :                                      neigh->has_children()))
    1255             :                     {
    1256             :                       // Find the deepest descendant of neigh which
    1257             :                       // we could consider for a neighbor.  If we run
    1258             :                       // out of neigh children, then that's our
    1259             :                       // neighbor.  If we find a potential neighbor
    1260             :                       // with remote_children and we don't find any
    1261             :                       // potential neighbors among its non-remote
    1262             :                       // children, then our neighbor must be remote.
    1263           0 :                       while (neigh != remote_elem &&
    1264           0 :                              neigh->has_children())
    1265             :                         {
    1266           0 :                           bool found_neigh = false;
    1267           0 :                           for (unsigned int c = 0, nc = neigh->n_children();
    1268           0 :                                !found_neigh && c != nc; ++c)
    1269             :                             {
    1270           0 :                               Elem * child = neigh->child_ptr(c);
    1271           0 :                               if (child == remote_elem)
    1272           0 :                                 continue;
    1273           0 :                               for (auto ncn : child->neighbor_ptr_range())
    1274             :                                 {
    1275           0 :                                   if (ncn != remote_elem &&
    1276           0 :                                       ncn->is_ancestor_of(current_elem))
    1277             :                                     {
    1278           0 :                                       neigh = ncn;
    1279           0 :                                       found_neigh = true;
    1280           0 :                                       break;
    1281             :                                     }
    1282             :                                 }
    1283             :                             }
    1284           0 :                           if (!found_neigh)
    1285           0 :                             neigh = const_cast<RemoteElem *>(remote_elem);
    1286             :                         }
    1287             :                     }
    1288    10476148 :                   current_elem->set_neighbor(s, neigh);
    1289             : #ifdef DEBUG
    1290      234396 :                   if (neigh != nullptr && neigh != remote_elem)
    1291             :                     // We ignore subactive elements here because
    1292             :                     // we don't care about neighbors of subactive element.
    1293      107060 :                     if ((!neigh->active()) && (!current_elem->subactive()))
    1294             :                       {
    1295           0 :                         libMesh::err << "On processor " << this->processor_id()
    1296           0 :                                      << std::endl;
    1297           0 :                         libMesh::err << "Bad element ID = " << current_elem->id()
    1298           0 :                                      << ", Side " << s << ", Bad neighbor ID = " << neigh->id() << std::endl;
    1299           0 :                         libMesh::err << "Bad element proc_ID = " << current_elem->processor_id()
    1300           0 :                                      << ", Bad neighbor proc_ID = " << neigh->processor_id() << std::endl;
    1301           0 :                         libMesh::err << "Bad element size = " << current_elem->hmin()
    1302           0 :                                      << ", Bad neighbor size = " << neigh->hmin() << std::endl;
    1303           0 :                         libMesh::err << "Bad element center = " << current_elem->vertex_average()
    1304           0 :                                      << ", Bad neighbor center = " << neigh->vertex_average() << std::endl;
    1305           0 :                         libMesh::err << "ERROR: "
    1306           0 :                                      << (current_elem->active()?"Active":"Ancestor")
    1307           0 :                                      << " Element at level "
    1308           0 :                                      << current_elem->level() << std::endl;
    1309           0 :                         libMesh::err << "with "
    1310           0 :                                      << (parent->active()?"active":
    1311           0 :                                          (parent->subactive()?"subactive":"ancestor"))
    1312           0 :                                      << " parent share "
    1313           0 :                                      << (neigh->subactive()?"subactive":"ancestor")
    1314           0 :                                      << " neighbor at level " << neigh->level()
    1315           0 :                                      << std::endl;
    1316           0 :                         NameBasedIO(*this).write ("bad_mesh.gmv");
    1317           0 :                         libmesh_error_msg("Problematic mesh written to bad_mesh.gmv.");
    1318             :                       }
    1319             : #endif // DEBUG
    1320             :                 }
    1321             :             }
    1322             : 
    1323             :           // We can skip to the next element if we're full-dimension
    1324             :           // and therefore don't have any interior parents
    1325    49893165 :           if (current_elem->dim() >= LIBMESH_DIM)
    1326     7707312 :             continue;
    1327             : 
    1328             :           // We have no interior parents unless we can find one later
    1329    42606431 :           current_elem->set_interior_parent(nullptr);
    1330             : 
    1331    42606431 :           Elem * pip = parent->interior_parent();
    1332             : 
    1333    42606431 :           if (!pip)
    1334    41956586 :             continue;
    1335             : 
    1336             :           // If there's no interior_parent children, whether due to a
    1337             :           // remote element or a non-conformity, then there's no
    1338             :           // children to search.
    1339       24467 :           if (pip == remote_elem || pip->active())
    1340             :             {
    1341        2052 :               current_elem->set_interior_parent(pip);
    1342        2052 :               continue;
    1343             :             }
    1344             : 
    1345             :           // For node comparisons we'll need a sensible tolerance
    1346       22415 :           Real node_tolerance = current_elem->hmin() * TOLERANCE;
    1347             : 
    1348             :           // Otherwise our interior_parent should be a child of our
    1349             :           // parent's interior_parent.
    1350       74887 :           for (auto & child : pip->child_ref_range())
    1351             :             {
    1352             :               // If we have a remote_elem, that might be our
    1353             :               // interior_parent.  We'll set it provisionally now and
    1354             :               // keep trying to find something better.
    1355       73749 :               if (&child == remote_elem)
    1356             :                 {
    1357             :                   current_elem->set_interior_parent
    1358        4788 :                     (const_cast<RemoteElem *>(remote_elem));
    1359        4788 :                   continue;
    1360             :                 }
    1361             : 
    1362        3008 :               bool child_contains_our_nodes = true;
    1363      139404 :               for (auto & n : current_elem->node_ref_range())
    1364             :                 {
    1365        5220 :                   bool child_contains_this_node = false;
    1366      764036 :                   for (auto & cn : child.node_ref_range())
    1367      716352 :                     if (cn.absolute_fuzzy_equals
    1368      685152 :                         (n, node_tolerance))
    1369             :                       {
    1370        3212 :                         child_contains_this_node = true;
    1371        3212 :                         break;
    1372             :                       }
    1373      115119 :                   if (!child_contains_this_node)
    1374             :                     {
    1375        2008 :                       child_contains_our_nodes = false;
    1376        2008 :                       break;
    1377             :                     }
    1378             :                 }
    1379       68961 :               if (child_contains_our_nodes)
    1380             :                 {
    1381       21277 :                   current_elem->set_interior_parent(&child);
    1382        1000 :                   break;
    1383             :                 }
    1384             :             }
    1385             : 
    1386             :           // We should have found *some* interior_parent at this
    1387             :           // point, whether semilocal or remote.
    1388        1000 :           libmesh_assert(current_elem->interior_parent());
    1389      266557 :         }
    1390             :     }
    1391             : #endif // AMR
    1392             : 
    1393             : #ifdef DEBUG
    1394       17966 :   if (assert_valid)
    1395             :     {
    1396       17830 :       MeshTools::libmesh_assert_valid_neighbors(*this,
    1397       17830 :                                                 !reset_remote_elements);
    1398       17830 :       MeshTools::libmesh_assert_valid_amr_interior_parents(*this);
    1399             :     }
    1400             : #else
    1401             :   libmesh_ignore(assert_valid);
    1402             : #endif
    1403             : 
    1404      781732 :   this->_preparation.has_neighbor_ptrs = true;
    1405      781732 : }
    1406             : 
    1407             : 
    1408             : 
    1409        5776 : void UnstructuredMesh::read (const std::string & name,
    1410             :                              void *,
    1411             :                              bool skip_renumber_nodes_and_elements,
    1412             :                              bool skip_find_neighbors,
    1413             :                              bool skip_detect_interior_parents)
    1414             : {
    1415             :   // Set the skip_renumber_nodes_and_elements flag on all processors
    1416             :   // if necessary.
    1417             :   // This ensures that renumber_nodes_and_elements is *not* called
    1418             :   // during prepare_for_use() for certain types of mesh files.
    1419             :   // This is required in cases where there is an associated solution
    1420             :   // file which expects a certain ordering of the nodes.
    1421        5776 :   if (Utility::ends_with(name, ".gmv"))
    1422           0 :     this->allow_renumbering(false);
    1423             : 
    1424        5776 :   NameBasedIO(*this).read(name);
    1425             : 
    1426        5776 :   if (skip_renumber_nodes_and_elements)
    1427             :     {
    1428             :       // Use MeshBase::allow_renumbering() yourself instead.
    1429             :       libmesh_deprecated();
    1430           0 :       this->allow_renumbering(false);
    1431             :     }
    1432             : 
    1433             :   // Done reading the mesh.  Now prepare it for use.
    1434         356 :   const bool old_allow_find_neighbors = this->allow_find_neighbors();
    1435         356 :   const bool old_allow_detect_interior_parents = this->allow_detect_interior_parents();
    1436             : 
    1437         178 :   this->allow_find_neighbors(!skip_find_neighbors);
    1438         178 :   this->allow_detect_interior_parents(!skip_detect_interior_parents);
    1439             : 
    1440        5776 :   this->prepare_for_use();
    1441             : 
    1442         178 :   this->allow_find_neighbors(old_allow_find_neighbors);
    1443         178 :   this->allow_detect_interior_parents(old_allow_detect_interior_parents);
    1444        5776 : }
    1445             : 
    1446             : 
    1447             : 
    1448        2938 : void UnstructuredMesh::write (const std::string & name) const
    1449             : {
    1450        1196 :   LOG_SCOPE("write()", "Mesh");
    1451             : 
    1452        3536 :   NameBasedIO(*this).write(name);
    1453        2938 : }
    1454             : 
    1455             : 
    1456             : 
    1457           0 : void UnstructuredMesh::write (const std::string & name,
    1458             :                               const std::vector<Number> & v,
    1459             :                               const std::vector<std::string> & vn) const
    1460             : {
    1461           0 :   LOG_SCOPE("write()", "Mesh");
    1462             : 
    1463           0 :   NameBasedIO(*this).write_nodal_data(name, v, vn);
    1464           0 : }
    1465             : 
    1466             : 
    1467             : 
    1468             : 
    1469             : 
    1470           0 : void UnstructuredMesh::create_pid_mesh(UnstructuredMesh & pid_mesh,
    1471             :                                        const processor_id_type pid) const
    1472             : {
    1473             : 
    1474             :   // Issue a warning if the number the number of processors
    1475             :   // currently available is less that that requested for
    1476             :   // partitioning.  This is not necessarily an error since
    1477             :   // you may run on one processor and still partition the
    1478             :   // mesh into several partitions.
    1479             : #ifdef DEBUG
    1480           0 :   if (this->n_processors() < pid)
    1481             :     {
    1482           0 :       libMesh::out << "WARNING:  You are creating a "
    1483           0 :                    << "mesh for a processor id (="
    1484           0 :                    << pid
    1485           0 :                    << ") greater than "
    1486           0 :                    << "the number of processors available for "
    1487           0 :                    << "the calculation. (="
    1488           0 :                    << this->n_processors()
    1489           0 :                    << ")."
    1490           0 :                    << std::endl;
    1491             :     }
    1492             : #endif
    1493             : 
    1494           0 :   this->create_submesh (pid_mesh,
    1495           0 :                         this->active_pid_elements_begin(pid),
    1496           0 :                         this->active_pid_elements_end(pid));
    1497           0 : }
    1498             : 
    1499             : 
    1500             : 
    1501             : 
    1502             : 
    1503             : 
    1504             : 
    1505           0 : void UnstructuredMesh::create_submesh (UnstructuredMesh & new_mesh,
    1506             :                                        const const_element_iterator & it,
    1507             :                                        const const_element_iterator & it_end) const
    1508             : {
    1509             :   // Just in case the subdomain_mesh already has some information
    1510             :   // in it, get rid of it.
    1511           0 :   new_mesh.clear();
    1512             : 
    1513             :   // If we're not serial, our submesh isn't either.
    1514             :   // There are no remote elements to delete on an empty mesh, but
    1515             :   // calling the method to do so marks the mesh as parallel.
    1516           0 :   if (!this->is_serial())
    1517           0 :     new_mesh.delete_remote_elements();
    1518             : 
    1519             :   // Fail if (*this == new_mesh), we cannot create a submesh inside ourself!
    1520             :   // This may happen if the user accidentally passes the original mesh into
    1521             :   // this function!  We will check this by making sure we did not just
    1522             :   // clear ourself.
    1523           0 :   libmesh_assert_not_equal_to (this->n_nodes(), 0);
    1524           0 :   libmesh_assert_not_equal_to (this->n_elem(), 0);
    1525             : 
    1526             :   // Container to catch boundary IDs handed back by BoundaryInfo
    1527           0 :   std::vector<boundary_id_type> bc_ids;
    1528             : 
    1529             :   // Put any extra integers on the new mesh too
    1530           0 :   new_mesh.merge_extra_integer_names(*this);
    1531           0 :   const unsigned int n_node_ints = _node_integer_names.size();
    1532             : 
    1533           0 :   for (const auto & old_elem : as_range(it, it_end))
    1534             :     {
    1535             :       // Add an equivalent element type to the new_mesh.
    1536             :       // disconnected_clone() copies ids, extra element integers, etc.
    1537           0 :       auto uelem = old_elem->disconnected_clone();
    1538           0 :       Elem * new_elem = new_mesh.add_elem(std::move(uelem));
    1539           0 :       libmesh_assert(new_elem);
    1540             : 
    1541             :       // Loop over the nodes on this element.
    1542           0 :       for (auto n : old_elem->node_index_range())
    1543             :         {
    1544           0 :           const dof_id_type this_node_id = old_elem->node_id(n);
    1545             : 
    1546             :           // Add this node to the new mesh if it's not there already
    1547           0 :           if (!new_mesh.query_node_ptr(this_node_id))
    1548             :             {
    1549             :               Node * newn =
    1550           0 :                 new_mesh.add_point (old_elem->point(n),
    1551             :                                     this_node_id,
    1552           0 :                                     old_elem->node_ptr(n)->processor_id());
    1553             : 
    1554           0 :               newn->add_extra_integers(n_node_ints);
    1555           0 :               for (unsigned int i = 0; i != n_node_ints; ++i)
    1556           0 :                 newn->set_extra_integer(i, old_elem->node_ptr(n)->get_extra_integer(i));
    1557             : 
    1558             : #ifdef LIBMESH_ENABLE_UNIQUE_ID
    1559           0 :               newn->set_unique_id(old_elem->node_ptr(n)->unique_id());
    1560             : #endif
    1561             :             }
    1562             : 
    1563             :           // Define this element's connectivity on the new mesh
    1564           0 :           new_elem->set_node(n, new_mesh.node_ptr(this_node_id));
    1565             :         }
    1566             : 
    1567             :       // Maybe add boundary conditions for this element
    1568           0 :       for (auto s : old_elem->side_index_range())
    1569             :         {
    1570           0 :           this->get_boundary_info().boundary_ids(old_elem, s, bc_ids);
    1571           0 :           new_mesh.get_boundary_info().add_side (new_elem, s, bc_ids);
    1572             :         }
    1573           0 :     } // end loop over elements
    1574             : 
    1575             :   // Prepare the new_mesh for use
    1576           0 :   new_mesh.prepare_for_use();
    1577           0 : }
    1578             : 
    1579             : 
    1580             : 
    1581             : #ifdef LIBMESH_ENABLE_AMR
    1582       25897 : bool UnstructuredMesh::contract ()
    1583             : {
    1584        1720 :   LOG_SCOPE ("contract()", "Mesh");
    1585             : 
    1586             :   // Flag indicating if this call actually changes the mesh
    1587         860 :   bool mesh_changed = false;
    1588             : 
    1589             : #ifdef DEBUG
    1590      545194 :   for (const auto & elem : this->element_ptr_range())
    1591      544334 :     libmesh_assert(elem->active() || elem->subactive() || elem->ancestor());
    1592             : #endif
    1593             : 
    1594             :   // Loop over the elements.
    1595    19657668 :   for (auto & elem : this->element_ptr_range())
    1596             :     {
    1597             :       // Delete all the subactive ones
    1598    10347701 :       if (elem->subactive())
    1599             :         {
    1600             :           // No level-0 element should be subactive.
    1601             :           // Note that we CAN'T test elem->level(), as that
    1602             :           // touches elem->parent()->dim(), and elem->parent()
    1603             :           // might have already been deleted!
    1604       71824 :           libmesh_assert(elem->parent());
    1605             : 
    1606             :           // Delete the element
    1607             :           // This just sets a pointer to nullptr, and doesn't
    1608             :           // invalidate any iterators
    1609     1493226 :           this->delete_elem(elem);
    1610             : 
    1611             :           // the mesh has certainly changed
    1612       71824 :           mesh_changed = true;
    1613             :         }
    1614             :       else
    1615             :         {
    1616             :           // Compress all the active ones
    1617      472510 :           if (elem->active())
    1618     6633174 :             elem->contract();
    1619             :           else
    1620      113318 :             libmesh_assert (elem->ancestor());
    1621             :         }
    1622       24177 :     }
    1623             : 
    1624             :   // Strip any newly-created nullptr voids out of the element array
    1625       25897 :   this->renumber_nodes_and_elements();
    1626             : 
    1627             :   // FIXME: Need to understand why deleting subactive children
    1628             :   // invalidates the point locator.  For now we will clear it explicitly
    1629       25897 :   this->clear_point_locator();
    1630             : 
    1631             :   // Allow our GhostingFunctor objects to reinit if necessary.
    1632       27863 :   for (auto & gf : as_range(this->ghosting_functors_begin(),
    1633      116549 :                             this->ghosting_functors_end()))
    1634             :     {
    1635        2826 :       libmesh_assert(gf);
    1636       86966 :       gf->mesh_reinit();
    1637             :     }
    1638             : 
    1639       26757 :   return mesh_changed;
    1640             : }
    1641             : #endif // #ifdef LIBMESH_ENABLE_AMR
    1642             : 
    1643             : 
    1644             : 
    1645       11401 : void UnstructuredMesh::all_first_order ()
    1646             : {
    1647        1188 :   LOG_SCOPE("all_first_order()", "Mesh");
    1648             : 
    1649             :   /**
    1650             :    * Prepare to identify (and then delete) a bunch of no-longer-used nodes.
    1651             :    */
    1652       11797 :   std::vector<bool> node_touched_by_me(this->max_node_id(), false);
    1653             : 
    1654             :   // Loop over the high-ordered elements.
    1655             :   // First make sure they _are_ indeed high-order, and then replace
    1656             :   // them with an equivalent first-order element.
    1657      484130 :   for (auto & so_elem : element_ptr_range())
    1658             :     {
    1659       25880 :       libmesh_assert(so_elem);
    1660             : 
    1661             :       /*
    1662             :        * build the first-order equivalent, add to
    1663             :        * the new_elements list.
    1664             :        */
    1665             :       auto lo_elem = Elem::build
    1666             :         (Elem::first_order_equivalent_type
    1667      282622 :          (so_elem->type()), so_elem->parent());
    1668             : 
    1669      256742 :       const unsigned short n_sides = so_elem->n_sides();
    1670             : 
    1671     1224830 :       for (unsigned short s=0; s != n_sides; ++s)
    1672     1065988 :         if (so_elem->neighbor_ptr(s) == remote_elem)
    1673           0 :           lo_elem->set_neighbor(s, const_cast<RemoteElem *>(remote_elem));
    1674             : 
    1675             : #ifdef LIBMESH_ENABLE_AMR
    1676             :       /*
    1677             :        * Reset the parent links of any child elements
    1678             :        */
    1679      256742 :       if (so_elem->has_children())
    1680      376641 :         for (unsigned int c = 0, nc = so_elem->n_children(); c != nc; ++c)
    1681             :           {
    1682      295548 :             Elem * child = so_elem->child_ptr(c);
    1683      295548 :             if (child != remote_elem)
    1684       48208 :               child->set_parent(lo_elem.get());
    1685      295548 :             lo_elem->add_child(child, c);
    1686             :           }
    1687             : 
    1688             :       /*
    1689             :        * Reset the child link of any parent element
    1690             :        */
    1691      282622 :       if (so_elem->parent())
    1692             :         {
    1693             :           unsigned int c =
    1694      230953 :             so_elem->parent()->which_child_am_i(so_elem);
    1695      255057 :           lo_elem->parent()->replace_child(lo_elem.get(), c);
    1696             :         }
    1697             : 
    1698             :       /*
    1699             :        * Copy as much data to the new element as makes sense
    1700             :        */
    1701      282622 :       lo_elem->set_p_level(so_elem->p_level());
    1702      256742 :       lo_elem->set_refinement_flag(so_elem->refinement_flag());
    1703       51760 :       lo_elem->set_p_refinement_flag(so_elem->p_refinement_flag());
    1704             : #endif
    1705             : 
    1706       25880 :       libmesh_assert_equal_to (lo_elem->n_vertices(), so_elem->n_vertices());
    1707             : 
    1708             :       /*
    1709             :        * By definition the vertices of the linear and
    1710             :        * second order element are identically numbered.
    1711             :        * transfer these.
    1712             :        */
    1713     1233660 :       for (unsigned int v=0, snv=so_elem->n_vertices(); v < snv; v++)
    1714             :         {
    1715     1075298 :           lo_elem->set_node(v, so_elem->node_ptr(v));
    1716      295140 :           node_touched_by_me[lo_elem->node_id(v)] = true;
    1717             :         }
    1718             : 
    1719             :       /*
    1720             :        * find_neighbors relies on remote_elem neighbor links being
    1721             :        * properly maintained.
    1722             :        */
    1723     1224830 :       for (unsigned short s=0; s != n_sides; s++)
    1724             :         {
    1725     1065988 :           if (so_elem->neighbor_ptr(s) == remote_elem)
    1726           0 :             lo_elem->set_neighbor(s, const_cast<RemoteElem*>(remote_elem));
    1727             :         }
    1728             : 
    1729             :       /**
    1730             :        * If the second order element had any boundary conditions they
    1731             :        * should be transferred to the first-order element.  The old
    1732             :        * boundary conditions will be removed from the BoundaryInfo
    1733             :        * data structure by insert_elem.
    1734             :        */
    1735       25880 :       this->get_boundary_info().copy_boundary_ids
    1736      256742 :         (this->get_boundary_info(), so_elem, lo_elem.get());
    1737             : 
    1738             :       /*
    1739             :        * The new first-order element is ready.
    1740             :        * Inserting it into the mesh will replace and delete
    1741             :        * the second-order element.
    1742             :        */
    1743      256742 :       lo_elem->set_id(so_elem->id());
    1744             : #ifdef LIBMESH_ENABLE_UNIQUE_ID
    1745       51760 :       lo_elem->set_unique_id(so_elem->unique_id());
    1746             : #endif
    1747             : 
    1748      256742 :       const unsigned int nei = so_elem->n_extra_integers();
    1749      256742 :       lo_elem->add_extra_integers(nei);
    1750      259569 :       for (unsigned int i=0; i != nei; ++i)
    1751        2827 :         lo_elem->set_extra_integer(i, so_elem->get_extra_integer(i));
    1752             : 
    1753      256742 :       lo_elem->inherit_data_from(*so_elem);
    1754             : 
    1755      308502 :       this->insert_elem(std::move(lo_elem));
    1756      215591 :     }
    1757             : 
    1758             :   // Deleting nodes does not invalidate iterators, so this is safe.
    1759     1699716 :   for (const auto & node : this->node_ptr_range())
    1760     1013691 :     if (!node_touched_by_me[node->id()])
    1761      630693 :       this->delete_node(node);
    1762             : 
    1763             :   // If crazy people applied boundary info to non-vertices and then
    1764             :   // deleted those non-vertices, we should make sure their boundary id
    1765             :   // caches are correct.
    1766       11401 :   this->get_boundary_info().regenerate_id_sets();
    1767             : 
    1768             :   // On hanging nodes that used to also be second order nodes, we
    1769             :   // might now have an invalid nodal processor_id()
    1770       11401 :   Partitioner::set_node_processor_ids(*this);
    1771             : 
    1772             :   // delete or renumber nodes if desired
    1773       11401 :   this->prepare_for_use();
    1774       11401 : }
    1775             : 
    1776             : 
    1777             : 
    1778             : void
    1779       26814 : UnstructuredMesh::all_second_order_range (const SimpleRange<element_iterator> & range,
    1780             :                                           const bool full_ordered)
    1781             : {
    1782        1548 :   LOG_SCOPE("all_second_order_range()", "Mesh");
    1783             : 
    1784             :   /*
    1785             :    * The maximum number of new second order nodes we might be adding,
    1786             :    * for use when picking unique unique_id values later. This variable
    1787             :    * is not used unless unique ids are enabled.
    1788             :    */
    1789             :   unsigned int max_new_nodes_per_elem;
    1790             : 
    1791             :   /*
    1792             :    * For speed-up of the \p add_point() method, we
    1793             :    * can reserve memory.  Guess the number of additional
    1794             :    * nodes based on the element spatial dimensions and the
    1795             :    * total number of nodes in the mesh as an upper bound.
    1796             :    */
    1797       26814 :   switch (this->mesh_dimension())
    1798             :     {
    1799         923 :     case 1:
    1800             :       /*
    1801             :        * in 1D, there can only be order-increase from Edge2
    1802             :        * to Edge3.  Something like 1/2 of n_nodes() have
    1803             :        * to be added
    1804             :        */
    1805          26 :       max_new_nodes_per_elem = 3 - 2;
    1806        1846 :       this->reserve_nodes(static_cast<unsigned int>
    1807         923 :                           (1.5*static_cast<double>(this->n_nodes())));
    1808         897 :       break;
    1809             : 
    1810        3728 :     case 2:
    1811             :       /*
    1812             :        * in 2D, either refine from Tri3 to Tri6 (double the nodes)
    1813             :        * or from Quad4 to Quad8 (again, double) or Quad9 (2.25 that much)
    1814             :        */
    1815         120 :       max_new_nodes_per_elem = 9 - 4;
    1816        7456 :       this->reserve_nodes(static_cast<unsigned int>
    1817        3728 :                           (2*static_cast<double>(this->n_nodes())));
    1818        3608 :       break;
    1819             : 
    1820             : 
    1821       22163 :     case 3:
    1822             :       /*
    1823             :        * in 3D, either refine from Tet4 to Tet10 (factor = 2.5) up to
    1824             :        * Hex8 to Hex27 (something  > 3).  Since in 3D there _are_ already
    1825             :        * quite some nodes, and since we do not want to overburden the memory by
    1826             :        * a too conservative guess, use the lower bound
    1827             :        */
    1828         628 :       max_new_nodes_per_elem = 27 - 8;
    1829       44326 :       this->reserve_nodes(static_cast<unsigned int>
    1830       22163 :                           (2.5*static_cast<double>(this->n_nodes())));
    1831       21535 :       break;
    1832             : 
    1833           0 :     default:
    1834             :       // Hm?
    1835           0 :       libmesh_error_msg("Unknown mesh dimension " << this->mesh_dimension());
    1836             :     }
    1837             : 
    1838             :   // All the real work is done in the helper function
    1839       26814 :   all_increased_order_range(*this, range, max_new_nodes_per_elem,
    1840      106982 :     [full_ordered](ElemType t) {
    1841     2575645 :       return Elem::second_order_equivalent_type(t, full_ordered);
    1842             :     });
    1843       26814 : }
    1844             : 
    1845             : 
    1846             : 
    1847       26899 : void UnstructuredMesh::all_complete_order_range(const SimpleRange<element_iterator> & range)
    1848             : {
    1849        1508 :   LOG_SCOPE("all_complete_order()", "Mesh");
    1850             : 
    1851             :   /*
    1852             :    * The maximum number of new higher-order nodes we might be adding,
    1853             :    * for use when picking unique unique_id values later. This variable
    1854             :    * is not used unless unique ids are enabled.
    1855             :    */
    1856             :   unsigned int max_new_nodes_per_elem;
    1857             : 
    1858             :   /*
    1859             :    * for speed-up of the \p add_point() method, we
    1860             :    * can reserve memory.  Guess the number of additional
    1861             :    * nodes based on the element spatial dimensions and the
    1862             :    * total number of nodes in the mesh as an upper bound.
    1863             :    */
    1864       26899 :   switch (this->mesh_dimension())
    1865             :     {
    1866           0 :     case 1:
    1867             :       /*
    1868             :        * in 1D, there can only be order-increase from Edge2
    1869             :        * to Edge3.  Something like 1/2 of n_nodes() have
    1870             :        * to be added
    1871             :        */
    1872           0 :       max_new_nodes_per_elem = 3 - 2;
    1873           0 :       this->reserve_nodes(static_cast<unsigned int>
    1874           0 :                           (1.5*static_cast<double>(this->n_nodes())));
    1875           0 :       break;
    1876             : 
    1877        1775 :     case 2:
    1878             :       /*
    1879             :        * in 2D, we typically refine from Tri3 or Tri6 to Tri7 (2.3333
    1880             :        * or 1.1667 times the nodes) but might refine from Quad4 to
    1881             :        * Quad9 (2.25 times the nodes)
    1882             :        */
    1883          50 :       max_new_nodes_per_elem = 9 - 4;
    1884        3550 :       this->reserve_nodes(static_cast<unsigned int>
    1885        1775 :                           (2*static_cast<double>(this->n_nodes())));
    1886        1725 :       break;
    1887             : 
    1888             : 
    1889       25124 :     case 3:
    1890             :       /*
    1891             :        * in 3D, we typically refine from Tet10 to Tet14 (factor = 1.4)
    1892             :        * but may go Hex8 to Hex27 or Tet4 to Tet14 (something  > 3).
    1893             :        * Since in 3D there _are_ already quite some nodes, and since
    1894             :        * we do not want to overburden the memory by a too-conservative
    1895             :        * guess, use a moderate bound
    1896             :        */
    1897         704 :       max_new_nodes_per_elem = 27 - 8;
    1898       50248 :       this->reserve_nodes(static_cast<unsigned int>
    1899       25124 :                           (2.5*static_cast<double>(this->n_nodes())));
    1900       24420 :       break;
    1901             : 
    1902           0 :     default:
    1903             :       // Hm?
    1904           0 :       libmesh_error_msg("Unknown mesh dimension " << this->mesh_dimension());
    1905             :     }
    1906             : 
    1907             :   // All the real work is done in the helper function
    1908       26899 :   all_increased_order_range(*this, range, max_new_nodes_per_elem,
    1909      164585 :     [](ElemType t) {
    1910     5795921 :       return Elem::complete_order_equivalent_type(t);
    1911             :     });
    1912       26899 : }
    1913             : 
    1914             : 
    1915             : std::size_t
    1916        1633 : UnstructuredMesh::stitch_meshes (const MeshBase & other_mesh,
    1917             :                                  boundary_id_type this_mesh_boundary_id,
    1918             :                                  boundary_id_type other_mesh_boundary_id,
    1919             :                                  Real tol,
    1920             :                                  bool clear_stitched_boundary_ids,
    1921             :                                  bool verbose,
    1922             :                                  bool use_binary_search,
    1923             :                                  bool enforce_all_nodes_match_on_boundaries,
    1924             :                                  bool merge_boundary_nodes_all_or_nothing,
    1925             :                                  bool remap_subdomain_ids,
    1926             :                                  bool prepare_after_stitching)
    1927             : {
    1928         138 :   LOG_SCOPE("stitch_meshes()", "UnstructuredMesh");
    1929        1633 :   return stitching_helper(&other_mesh,
    1930             :                           this_mesh_boundary_id,
    1931             :                           other_mesh_boundary_id,
    1932             :                           tol,
    1933             :                           clear_stitched_boundary_ids,
    1934             :                           verbose,
    1935             :                           use_binary_search,
    1936             :                           enforce_all_nodes_match_on_boundaries,
    1937             :                           true,
    1938             :                           merge_boundary_nodes_all_or_nothing,
    1939             :                           remap_subdomain_ids,
    1940        1533 :                           prepare_after_stitching);
    1941             : }
    1942             : 
    1943             : 
    1944             : std::size_t
    1945         213 : UnstructuredMesh::stitch_surfaces (boundary_id_type boundary_id_1,
    1946             :                                    boundary_id_type boundary_id_2,
    1947             :                                    Real tol,
    1948             :                                    bool clear_stitched_boundary_ids,
    1949             :                                    bool verbose,
    1950             :                                    bool use_binary_search,
    1951             :                                    bool enforce_all_nodes_match_on_boundaries,
    1952             :                                    bool merge_boundary_nodes_all_or_nothing,
    1953             :                                    bool prepare_after_stitching)
    1954             : 
    1955             : {
    1956         213 :   return stitching_helper(nullptr,
    1957             :                           boundary_id_1,
    1958             :                           boundary_id_2,
    1959             :                           tol,
    1960             :                           clear_stitched_boundary_ids,
    1961             :                           verbose,
    1962             :                           use_binary_search,
    1963             :                           enforce_all_nodes_match_on_boundaries,
    1964             :                           /* skip_find_neighbors = */ true,
    1965             :                           merge_boundary_nodes_all_or_nothing,
    1966             :                           /* remap_subdomain_ids = */ false,
    1967         213 :                           prepare_after_stitching);
    1968             : }
    1969             : 
    1970             : 
    1971             : std::size_t
    1972        1846 : UnstructuredMesh::stitching_helper (const MeshBase * other_mesh,
    1973             :                                     boundary_id_type this_mesh_boundary_id,
    1974             :                                     boundary_id_type other_mesh_boundary_id,
    1975             :                                     Real tol,
    1976             :                                     bool clear_stitched_boundary_ids,
    1977             :                                     bool verbose,
    1978             :                                     bool use_binary_search,
    1979             :                                     bool enforce_all_nodes_match_on_boundaries,
    1980             :                                     bool skip_find_neighbors,
    1981             :                                     bool merge_boundary_nodes_all_or_nothing,
    1982             :                                     bool remap_subdomain_ids,
    1983             :                                     bool prepare_after_stitching)
    1984             : {
    1985             : #ifdef DEBUG
    1986             :   // We rely on neighbor links here
    1987          52 :   MeshTools::libmesh_assert_valid_neighbors(*this);
    1988             : #endif
    1989             : 
    1990          52 :   bool is_valid_disjoint_pair_to_stitch = false;
    1991             : 
    1992             : #ifdef LIBMESH_ENABLE_PERIODIC
    1993        1846 :   auto * this_db  = this->get_disjoint_neighbor_boundary_pairs();
    1994        1846 :   auto * other_db = (other_mesh ? other_mesh->get_disjoint_neighbor_boundary_pairs() : nullptr);
    1995             :   const bool have_disc_bdys =
    1996        1846 :     (this_db && !this_db->empty()) || (other_db && !other_db->empty());
    1997             : 
    1998          52 :   if (have_disc_bdys)
    1999             :     {
    2000          10 :       const boundary_id_type a = this_mesh_boundary_id;
    2001          10 :       const boundary_id_type b = other_mesh_boundary_id;
    2002             : 
    2003          40 :       auto get_pb = [](const PeriodicBoundaries * db, boundary_id_type id)
    2004             :         {
    2005         539 :           return db ? db->boundary(id) : nullptr;
    2006             :         };
    2007             : 
    2008             :       // this mesh
    2009         355 :       const auto * pb_this_a = get_pb(this_db, a);
    2010         355 :       const auto * pb_this_b = get_pb(this_db, b);
    2011          10 :       const bool in_this =
    2012         355 :         (pb_this_a && pb_this_a->pairedboundary == b) ||
    2013           0 :         (pb_this_b && pb_this_b->pairedboundary == a);
    2014             : 
    2015             :       // other mesh
    2016         345 :       const auto * pb_other_b = get_pb(other_db, b);
    2017          10 :       const auto * pb_other_a = get_pb(other_db, a);
    2018          10 :       const bool in_other =
    2019         355 :         (pb_other_b && pb_other_b->pairedboundary == a) ||
    2020           0 :         (pb_other_a && pb_other_a->pairedboundary == b);
    2021             : 
    2022             :       // Conflict conditions:
    2023             :       // Case 1: On "this" mesh, a or b exist but are not paired,
    2024             :       //         while the other mesh pairs them.
    2025         355 :       if (!in_this && (pb_this_a || pb_this_b) && in_other)
    2026         146 :         libmesh_error_msg("Disjoint neighbor boundary pairing mismatch: on 'this' mesh, "
    2027             :                           "boundary (" << a << " or " << b
    2028             :                           << ") exists but is not paired; on 'other' mesh the pair is present.");
    2029             : 
    2030             :       // Case 2: On "other" mesh, a or b exist but are not paired,
    2031             :       //         while this mesh pairs them.
    2032         284 :       if (!in_other && (pb_other_a || pb_other_b) && in_this)
    2033           0 :         libmesh_error_msg("Disjoint neighbor boundary pairing mismatch: on 'other' mesh, "
    2034             :                           "boundary (" << a << " or " << b
    2035             :                           << ") exists but is not paired; on 'this' mesh the pair is present.");
    2036             : 
    2037             :       // Legal conditions: either side has a correct pairing
    2038         284 :       if (in_this || in_other)
    2039           6 :         is_valid_disjoint_pair_to_stitch = true;
    2040             :     }
    2041             : #endif // LIBMESH_ENABLE_PERIODIC
    2042             : 
    2043             :   // We can't even afford any unset neighbor links here.
    2044        1775 :   if (!this->is_prepared())
    2045          71 :     this->find_neighbors();
    2046             : 
    2047             :   // FIXME: make distributed mesh support efficient.
    2048             :   // Yes, we currently suck.
    2049        1875 :   MeshSerializer serialize(*this);
    2050             : 
    2051             :   // *Badly*.
    2052        1725 :   std::unique_ptr<MeshSerializer> serialize_other;
    2053        1775 :   if (other_mesh)
    2054             :     serialize_other = std::make_unique<MeshSerializer>
    2055        3036 :       (*const_cast<MeshBase *>(other_mesh));
    2056             : 
    2057         102 :   std::map<dof_id_type, dof_id_type> node_to_node_map, other_to_this_node_map; // The second is the inverse map of the first
    2058         100 :   std::map<dof_id_type, std::vector<dof_id_type>> node_to_elems_map;
    2059             : 
    2060             :   typedef dof_id_type                     key_type;
    2061             :   typedef std::pair<const Elem *, unsigned char> val_type;
    2062             :   typedef std::pair<key_type, val_type>   key_val_pair;
    2063             :   typedef std::unordered_multimap<key_type, val_type> map_type;
    2064             :   // Mapping between all side keys in this mesh and elements+side numbers relevant to the boundary in this mesh as well.
    2065         100 :   map_type side_to_elem_map;
    2066             : 
    2067             :   // If there is only one mesh (i.e. other_mesh == nullptr), then loop over this mesh twice
    2068        1775 :   if (!other_mesh)
    2069             :     {
    2070           6 :       other_mesh = this;
    2071             :     }
    2072             : 
    2073        1775 :   if ((this_mesh_boundary_id  != BoundaryInfo::invalid_id) &&
    2074          50 :       (other_mesh_boundary_id != BoundaryInfo::invalid_id))
    2075             :     {
    2076         150 :       LOG_SCOPE("stitch_meshes node merging", "UnstructuredMesh");
    2077             : 
    2078             :       // While finding nodes on the boundary, also find the minimum edge length
    2079             :       // of all faces on both boundaries.  This will later be used in relative
    2080             :       // distance checks when stitching nodes.
    2081        1775 :       Real h_min = std::numeric_limits<Real>::max();
    2082          50 :       bool h_min_updated = false;
    2083             : 
    2084             :       // Loop below fills in these sets for the two meshes.
    2085         100 :       std::set<dof_id_type> this_boundary_node_ids, other_boundary_node_ids;
    2086             : 
    2087             :       // Pull objects out of the loop to reduce heap operations
    2088        1775 :       std::unique_ptr<const Elem> side;
    2089             : 
    2090             :       {
    2091             :         // Make temporary fixed-size arrays for loop
    2092        1775 :         boundary_id_type id_array[2]         = {this_mesh_boundary_id, other_mesh_boundary_id};
    2093        1775 :         std::set<dof_id_type> * set_array[2] = {&this_boundary_node_ids, &other_boundary_node_ids};
    2094        1775 :         const MeshBase * mesh_array[2] = {this, other_mesh};
    2095             : 
    2096        5325 :         for (unsigned i=0; i<2; ++i)
    2097             :           {
    2098             :             // First we deal with node boundary IDs.  We only enter
    2099             :             // this loop if we have at least one nodeset. Note that we
    2100             :             // do not attempt to make an h_min determination here.
    2101             :             // The h_min determination is done while looping over the
    2102             :             // Elems and checking their sides and edges for boundary
    2103             :             // information, below.
    2104        3650 :             if (mesh_array[i]->get_boundary_info().n_nodeset_conds() > 0)
    2105             :               {
    2106             :                 // build_node_list() returns a vector of (node-id, bc-id) tuples
    2107      324270 :                 for (const auto & t : mesh_array[i]->get_boundary_info().build_node_list())
    2108             :                   {
    2109      321204 :                     boundary_id_type node_bc_id = std::get<1>(t);
    2110      321204 :                     if (node_bc_id == id_array[i])
    2111             :                       {
    2112       61415 :                         dof_id_type this_node_id = std::get<0>(t);
    2113       61415 :                         set_array[i]->insert( this_node_id );
    2114             :                       }
    2115             :                   }
    2116             :               }
    2117             : 
    2118             :             // Container to catch boundary IDs passed back from BoundaryInfo.
    2119         200 :             std::vector<boundary_id_type> bc_ids;
    2120             : 
    2121             :             // Pointers to boundary NodeElems encountered while looping over the entire Mesh
    2122             :             // and checking side and edge boundary ids. The Nodes associated with NodeElems
    2123             :             // may be in a boundary nodeset, but not connected to any other Elems. In this
    2124             :             // case, we also consider the "minimum node separation distance" amongst all
    2125             :             // NodeElems when determining the relevant h_min value for this mesh.
    2126         200 :             std::vector<const Elem *> boundary_node_elems;
    2127             : 
    2128       86902 :             for (auto & el : mesh_array[i]->element_ptr_range())
    2129             :               {
    2130             :                 // Now check whether elem has a face on the specified boundary
    2131      267337 :                 for (auto side_id : el->side_index_range())
    2132             :                   {
    2133             :                     bool should_stitch_this_side =
    2134      231450 :                       (el->neighbor_ptr(side_id) == nullptr) ||
    2135        1420 :                       (is_valid_disjoint_pair_to_stitch &&
    2136        1460 :                       mesh_array[i]->get_boundary_info().has_boundary_id(el, side_id, id_array[i]));
    2137             : 
    2138        6340 :                     if (should_stitch_this_side)
    2139             :                       {
    2140             :                         // Get *all* boundary IDs on this side, not just the first one!
    2141       99718 :                         mesh_array[i]->get_boundary_info().boundary_ids (el, side_id, bc_ids);
    2142             : 
    2143       99718 :                         if (std::find(bc_ids.begin(), bc_ids.end(), id_array[i]) != bc_ids.end())
    2144             :                           {
    2145       16472 :                             el->build_side_ptr(side, side_id);
    2146      112535 :                             for (auto & n : side->node_ref_range())
    2147       96063 :                               set_array[i]->insert(n.id());
    2148             : 
    2149       16472 :                             h_min = std::min(h_min, side->hmin());
    2150         464 :                             h_min_updated = true;
    2151             : 
    2152             :                             // This side is on the boundary, add its information to side_to_elem
    2153       16472 :                             if (skip_find_neighbors && (i==0))
    2154             :                               {
    2155        8236 :                                 key_type key = el->low_order_key(side_id);
    2156         232 :                                 val_type val;
    2157        8236 :                                 val.first = el;
    2158         232 :                                 val.second = cast_int<unsigned char>(side_id);
    2159             : 
    2160        8236 :                                 key_val_pair kvp;
    2161        8236 :                                 kvp.first = key;
    2162         232 :                                 kvp.second = val;
    2163         232 :                                 side_to_elem_map.insert (kvp);
    2164             :                               }
    2165             :                           }
    2166             : 
    2167             :                         // Also, check the edges on this side. We don't have to worry about
    2168             :                         // updating neighbor info in this case since elements don't store
    2169             :                         // neighbor info on edges.
    2170     1211294 :                         for (auto edge_id : el->edge_index_range())
    2171             :                           {
    2172     1111576 :                             if (el->is_edge_on_side(edge_id, side_id))
    2173             :                               {
    2174             :                                 // Get *all* boundary IDs on this edge, not just the first one!
    2175      368490 :                                 mesh_array[i]->get_boundary_info().edge_boundary_ids (el, edge_id, bc_ids);
    2176             : 
    2177      368490 :                                 if (std::find(bc_ids.begin(), bc_ids.end(), id_array[i]) != bc_ids.end())
    2178             :                                   {
    2179           0 :                                     std::unique_ptr<const Elem> edge (el->build_edge_ptr(edge_id));
    2180           0 :                                     for (auto & n : edge->node_ref_range())
    2181           0 :                                       set_array[i]->insert( n.id() );
    2182             : 
    2183           0 :                                     h_min = std::min(h_min, edge->hmin());
    2184           0 :                                     h_min_updated = true;
    2185           0 :                                   }
    2186             :                               }
    2187             :                           } // end for (edge_id)
    2188             :                       } // end if (should_stitch_this_side)
    2189             :                   } // end for (side_id)
    2190             : 
    2191             :                 // Alternatively, is this a boundary NodeElem? If so,
    2192             :                 // add it to a list of NodeElems that will later be
    2193             :                 // used to set h_min based on the minimum node
    2194             :                 // separation distance between all pairs of boundary
    2195             :                 // NodeElems.
    2196       41109 :                 if (el->type() == NODEELEM)
    2197             :                   {
    2198        2700 :                     mesh_array[i]->get_boundary_info().boundary_ids(el->node_ptr(0), bc_ids);
    2199        2628 :                     if (std::find(bc_ids.begin(), bc_ids.end(), id_array[i]) != bc_ids.end())
    2200             :                       {
    2201        2556 :                         boundary_node_elems.push_back(el);
    2202             : 
    2203             :                         // Debugging:
    2204             :                         // libMesh::out << "Elem " << el->id() << " is a NodeElem on boundary " << id_array[i] << std::endl;
    2205             :                       }
    2206             :                   } // end if (el->type() == NODEELEM)
    2207        3350 :               } // end for (el)
    2208             : 
    2209             :             // Compute the minimum node separation distance amongst
    2210             :             // all boundary NodeElem pairs.
    2211             :             {
    2212         200 :               const auto N = boundary_node_elems.size();
    2213        6106 :               for (auto node_elem_i : make_range(N))
    2214       47286 :                 for (auto node_elem_j : make_range(node_elem_i+1, N))
    2215             :                   {
    2216             :                     Real node_sep =
    2217       47250 :                       (boundary_node_elems[node_elem_i]->point(0) - boundary_node_elems[node_elem_j]->point(0)).norm();
    2218             : 
    2219             :                     // We only want to consider non-coincident
    2220             :                     // boundary NodeElem pairs when determining the
    2221             :                     // minimum node separation distance.
    2222       44730 :                     if (node_sep > 0.)
    2223             :                       {
    2224       44730 :                         h_min = std::min(h_min, node_sep);
    2225        1260 :                         h_min_updated = true;
    2226             :                       }
    2227             :                   } // end for (node_elem_j)
    2228             :             } // end minimum NodeElem separation scope
    2229             :           } // end for (i)
    2230             :       } // end scope
    2231             : 
    2232        1775 :       if (verbose)
    2233             :         {
    2234          14 :           libMesh::out << "In UnstructuredMesh::stitch_meshes:\n"
    2235          14 :                        << "This mesh has "  << this_boundary_node_ids.size()
    2236          14 :                        << " nodes on boundary `"
    2237         497 :                        << this->get_boundary_info().get_sideset_name(this_mesh_boundary_id)
    2238          14 :                        << "' (" << this_mesh_boundary_id  << ").\n"
    2239          14 :                        << "Other mesh has " << other_boundary_node_ids.size()
    2240          14 :                        << " nodes on boundary `"
    2241         497 :                        << other_mesh->get_boundary_info().get_sideset_name(other_mesh_boundary_id)
    2242          14 :                        << "' (" << other_mesh_boundary_id  << ").\n";
    2243             : 
    2244         497 :           if (h_min_updated)
    2245             :             {
    2246          28 :               libMesh::out << "Minimum edge length on both surfaces is " << h_min << ".\n";
    2247             :             }
    2248             :           else
    2249             :             {
    2250           0 :               libMesh::out << "No minimum edge length determined on specified surfaces." << std::endl;
    2251             :             }
    2252             :         }
    2253             : 
    2254             :       // At this point, if h_min==0 it means that there were at least two coincident
    2255             :       // nodes on the surfaces being stitched, and we don't currently support that case.
    2256             :       // (It might be possible to support, but getting it exactly right would be tricky
    2257             :       // and probably not worth the extra complications to the "normal" case.)
    2258        1775 :       libmesh_error_msg_if(h_min < std::numeric_limits<Real>::epsilon(),
    2259             :                            "Coincident nodes detected on source and/or target "
    2260             :                            "surface, stitching meshes is not possible.");
    2261             : 
    2262             :       // We require nanoflann for the "binary search" (really kd-tree)
    2263             :       // option to work. If it's not available, turn that option off,
    2264             :       // warn the user, and fall back on the N^2 search algorithm.
    2265             :       if (use_binary_search)
    2266             :         {
    2267             : #ifndef LIBMESH_HAVE_NANOFLANN
    2268             :           use_binary_search = false;
    2269             :           libmesh_warning("The use_binary_search option in the "
    2270             :                           "UnstructuredMesh stitching algorithms requires nanoflann "
    2271             :                           "support. Falling back on N^2 search algorithm.");
    2272             : #endif
    2273             :         }
    2274             : 
    2275        1775 :       if (!this_boundary_node_ids.empty())
    2276             :       {
    2277        1775 :         if (use_binary_search)
    2278             :         {
    2279             : #ifdef LIBMESH_HAVE_NANOFLANN
    2280             :           typedef nanoflann::KDTreeSingleIndexAdaptor<nanoflann::L2_Simple_Adaptor<Real, VectorOfNodesAdaptor>,
    2281             :             VectorOfNodesAdaptor, 3, std::size_t> kd_tree_t;
    2282             : 
    2283             :           // Create the dataset needed to build the kd tree with nanoflann
    2284           0 :           std::vector<std::pair<Point, dof_id_type>> this_mesh_nodes(this_boundary_node_ids.size());
    2285             : 
    2286           0 :           for (auto [it, ctr] = std::make_tuple(this_boundary_node_ids.begin(), 0u);
    2287           0 :                it != this_boundary_node_ids.end(); ++it, ++ctr)
    2288             :           {
    2289           0 :             this_mesh_nodes[ctr].first = this->point(*it);
    2290           0 :             this_mesh_nodes[ctr].second = *it;
    2291             :           }
    2292             : 
    2293           0 :           VectorOfNodesAdaptor vec_nodes_adaptor(this_mesh_nodes);
    2294             : 
    2295           0 :           kd_tree_t this_kd_tree(3, vec_nodes_adaptor, 10);
    2296           0 :           this_kd_tree.buildIndex();
    2297             : 
    2298             :           // Storage for nearest neighbor in the loop below
    2299             :           std::size_t ret_index;
    2300             :           Real ret_dist_sqr;
    2301             : 
    2302             :           // Loop over other mesh. For each node, find its nearest neighbor in this mesh, and fill in the maps.
    2303           0 :           for (const auto & node_id : other_boundary_node_ids)
    2304             :           {
    2305           0 :             const auto & p = other_mesh->point(node_id);
    2306           0 :             const Real query_pt[] = {p(0), p(1), p(2)};
    2307           0 :             this_kd_tree.knnSearch(&query_pt[0], 1, &ret_index, &ret_dist_sqr);
    2308             : 
    2309             :             // TODO: here we should use the user's specified tolerance
    2310             :             // and the previously determined value of h_min in the
    2311             :             // distance comparison, not just TOLERANCE^2.
    2312           0 :             if (ret_dist_sqr < TOLERANCE*TOLERANCE)
    2313             :             {
    2314           0 :               node_to_node_map[this_mesh_nodes[ret_index].second] = node_id;
    2315           0 :               other_to_this_node_map[node_id] = this_mesh_nodes[ret_index].second;
    2316             :             }
    2317             :           }
    2318             : 
    2319             :           // If the two maps don't have the same size, it means one
    2320             :           // node in this mesh is the nearest neighbor of several
    2321             :           // nodes in other mesh. Since the stitching is ambiguous in
    2322             :           // this case, we throw an error.
    2323           0 :           libmesh_error_msg_if(node_to_node_map.size() != other_to_this_node_map.size(),
    2324             :                                "Error: Found multiple matching nodes in stitch_meshes");
    2325             : #endif
    2326             :         }
    2327             :         else // !use_binary_search
    2328             :         {
    2329             :           // In the unlikely event that two meshes composed entirely of
    2330             :           // NodeElems are being stitched together, we will not have
    2331             :           // selected a valid h_min value yet, and the distance
    2332             :           // comparison below will be true for essentially any two
    2333             :           // nodes. In this case we simply fall back on an absolute
    2334             :           // distance check.
    2335        1775 :           if (!h_min_updated)
    2336             :             {
    2337             :               libmesh_warning("No valid h_min value was found, falling back on "
    2338             :                               "absolute distance check in the N^2 search algorithm.");
    2339           0 :               h_min = 1.;
    2340             :             }
    2341             : 
    2342             :           // Otherwise, use a simple N^2 search to find the closest matching points. This can be helpful
    2343             :           // in the case that we have tolerance issues which cause mismatch between the two surfaces
    2344             :           // that are being stitched.
    2345       32944 :           for (const auto & this_node_id : this_boundary_node_ids)
    2346             :           {
    2347       31169 :             Node & this_node = this->node_ref(this_node_id);
    2348             : 
    2349         878 :             bool found_matching_nodes = false;
    2350             : 
    2351      928538 :             for (const auto & other_node_id : other_boundary_node_ids)
    2352             :             {
    2353      897369 :               const Node & other_node = other_mesh->node_ref(other_node_id);
    2354             : 
    2355      872091 :               Real node_distance = (this_node - other_node).norm();
    2356             : 
    2357      897369 :               if (node_distance < tol*h_min)
    2358             :               {
    2359             :                 // Make sure we didn't already find a matching node!
    2360       31169 :                 libmesh_error_msg_if(found_matching_nodes,
    2361             :                                      "Error: Found multiple matching nodes in stitch_meshes");
    2362             : 
    2363       31169 :                 node_to_node_map[this_node_id] = other_node_id;
    2364       31169 :                 other_to_this_node_map[other_node_id] = this_node_id;
    2365             : 
    2366         878 :                 found_matching_nodes = true;
    2367             :               }
    2368             :             }
    2369             :           }
    2370             :         }
    2371             :       }
    2372             : 
    2373             :       // Build up the node_to_elems_map, using only one loop over other_mesh
    2374       42830 :       for (auto & el : other_mesh->element_ptr_range())
    2375             :         {
    2376             :           // For each node on the element, find the corresponding node
    2377             :           // on "this" Mesh, 'this_node_id', if it exists, and push
    2378             :           // the current element ID back onto node_to_elems_map[this_node_id].
    2379             :           // For that we will use the reverse mapping we created at
    2380             :           // the same time as the forward mapping.
    2381      294865 :           for (auto & n : el->node_ref_range())
    2382      281780 :             if (const auto it = other_to_this_node_map.find(/*other_node_id=*/n.id());
    2383        7720 :                 it != other_to_this_node_map.end())
    2384       50481 :               node_to_elems_map[/*this_node_id=*/it->second].push_back( el->id() );
    2385        1675 :         }
    2386             : 
    2387        1775 :       if (verbose)
    2388             :         {
    2389          14 :           libMesh::out << "In UnstructuredMesh::stitch_meshes:\n"
    2390          28 :                        << "Found " << node_to_node_map.size()
    2391          14 :                        << " matching nodes.\n"
    2392          14 :                        << std::endl;
    2393             :         }
    2394             : 
    2395        1775 :       if (enforce_all_nodes_match_on_boundaries)
    2396             :         {
    2397           2 :           std::size_t n_matching_nodes = node_to_node_map.size();
    2398           2 :           std::size_t this_mesh_n_nodes = this_boundary_node_ids.size();
    2399           2 :           std::size_t other_mesh_n_nodes = other_boundary_node_ids.size();
    2400          71 :           libmesh_error_msg_if((n_matching_nodes != this_mesh_n_nodes) || (n_matching_nodes != other_mesh_n_nodes),
    2401             :                                "Error: We expected the number of nodes to match.");
    2402             :         }
    2403             : 
    2404        1775 :       if (merge_boundary_nodes_all_or_nothing)
    2405             :         {
    2406           2 :           std::size_t n_matching_nodes = node_to_node_map.size();
    2407           2 :           std::size_t this_mesh_n_nodes = this_boundary_node_ids.size();
    2408           2 :           std::size_t other_mesh_n_nodes = other_boundary_node_ids.size();
    2409          71 :           if ((n_matching_nodes != this_mesh_n_nodes) || (n_matching_nodes != other_mesh_n_nodes))
    2410             :             {
    2411           0 :               if (verbose)
    2412             :                 {
    2413             :                   libMesh::out << "Skipping node merging in "
    2414             :                                   "UnstructuredMesh::stitch_meshes because not "
    2415           0 :                                   "all boundary nodes were matched."
    2416           0 :                                << std::endl;
    2417             :                 }
    2418           0 :               node_to_node_map.clear();
    2419           0 :               other_to_this_node_map.clear();
    2420           0 :               node_to_elems_map.clear();
    2421             :             }
    2422         100 :         }
    2423        3350 :     }
    2424             :   else
    2425             :     {
    2426           0 :       if (verbose)
    2427             :         {
    2428           0 :           libMesh::out << "Skip node merging in UnstructuredMesh::stitch_meshes:" << std::endl;
    2429             :         }
    2430             :     }
    2431             : 
    2432        1775 :   dof_id_type node_delta = this->max_node_id();
    2433        1775 :   dof_id_type elem_delta = this->max_elem_id();
    2434             : 
    2435             :   unique_id_type unique_delta =
    2436             : #ifdef LIBMESH_ENABLE_UNIQUE_ID
    2437        1775 :     this->parallel_max_unique_id();
    2438             : #else
    2439             :     0;
    2440             : #endif
    2441             : 
    2442             :   // If other_mesh != nullptr, then we have to do a bunch of work
    2443             :   // in order to copy it to this mesh
    2444        1775 :   if (this!=other_mesh)
    2445             :     {
    2446         132 :       LOG_SCOPE("stitch_meshes copying", "UnstructuredMesh");
    2447             : 
    2448             : #ifdef LIBMESH_ENABLE_PERIODIC
    2449             :         // Copy disjoint neighbor boundary pairs (PeriodicBoundary objects)
    2450             :         // from `other_mesh` to `this` mesh
    2451        1562 :         if (other_db && !other_db->empty())
    2452             :           {
    2453         213 :             for (const auto & [bdy_id, pb_ptr] : *other_db)
    2454             :               {
    2455           4 :                 const auto & pb = *pb_ptr;
    2456         142 :                 const boundary_id_type a = pb.myboundary;
    2457         142 :                 const boundary_id_type b = pb.pairedboundary;
    2458             : 
    2459         142 :                 if (this_db)
    2460             :                   {
    2461             :                     // Skip if identical pair already exists
    2462         142 :                     if (const auto * existing_pb = this_db->boundary(a))
    2463          71 :                       if ((existing_pb->myboundary == a && existing_pb->pairedboundary == b) ||
    2464           0 :                           (existing_pb->myboundary == b && existing_pb->pairedboundary == a))
    2465          69 :                         continue;
    2466             : 
    2467             :                     // If both boundary ids exist on this mesh but aren't paired here, refuse to create a new pair
    2468           2 :                     const auto & bdy_ids = this->get_boundary_info().get_boundary_ids();
    2469           4 :                     const bool a_exists = bdy_ids.count(a);
    2470           4 :                     const bool b_exists = bdy_ids.count(b);
    2471             :                     // If a and b already exist on `this`, we should be screaming and dying
    2472             :                     // unless they already have PeriodicBoundary objects connecting them too
    2473          71 :                     if (a_exists && b_exists && !this_db->boundary(a))
    2474           0 :                       libmesh_error_msg("Conflict: boundaries " << a << " and " << b
    2475             :                                         << " already exist on this mesh but are not paired.");
    2476             :                   }
    2477             : 
    2478         140 :                 this->add_disjoint_neighbor_boundary_pairs(a, b, pb.get_corresponding_pos(Point(0.0,0.0,0.0)));
    2479             :               }
    2480             :           }
    2481             : #endif // LIBMESH_ENABLE_PERIODIC
    2482             : 
    2483             : 
    2484             :       // Increment the node_to_node_map and node_to_elems_map
    2485             :       // to account for id offsets
    2486       32305 :       for (auto & pr : node_to_node_map)
    2487       30743 :         pr.second += node_delta;
    2488             : 
    2489       32305 :       for (auto & pr : node_to_elems_map)
    2490       80798 :         for (auto & entry : pr.second)
    2491       50055 :           entry += elem_delta;
    2492             : 
    2493             :       // We run into problems when the libMesh subdomain standard (the
    2494             :       // id defines the subdomain; the name was an afterthought) and
    2495             :       // the MOOSE standard (the name defines the subdomain; the id
    2496             :       // might be autogenerated) clash.
    2497             :       //
    2498             :       // Subdomain ids with the same name in both meshes are surely
    2499             :       // meant to represent the same subdomain.  We can just merge
    2500             :       // them.
    2501             :       //
    2502             :       // Subdomain ids which don't have a name in either mesh are
    2503             :       // almost surely meant to represent the same subdomain.  We'll
    2504             :       // just merge them.
    2505             :       //
    2506             :       // Subdomain ids with different names in different meshes, or
    2507             :       // names with different ids in different meshes, are trickier.
    2508             :       // For backwards compatibility we default to the old "just copy
    2509             :       // all the subdomain ids over" behavior, but if requested we'll
    2510             :       // remap any ids that appear to be clear conflicts, and we'll
    2511             :       // scream and die if we see any ids that are ambiguous due to
    2512             :       // being named in one mesh but not the other.
    2513          88 :       std::unordered_map<subdomain_id_type, subdomain_id_type> id_remapping;
    2514        1562 :       if (remap_subdomain_ids)
    2515             :         {
    2516           4 :           const auto & this_map = this->get_subdomain_name_map();
    2517           4 :           const auto & other_map = other_mesh->get_subdomain_name_map();
    2518           8 :           std::unordered_map<std::string, subdomain_id_type> other_map_reversed;
    2519         284 :           for (auto & [sid, sname] : other_map)
    2520           4 :             other_map_reversed.emplace(sname, sid);
    2521             : 
    2522           8 :           std::unordered_map<std::string, subdomain_id_type> this_map_reversed;
    2523         213 :           for (auto & [sid, sname] : this_map)
    2524           2 :             this_map_reversed.emplace(sname, sid);
    2525             : 
    2526             :           // We don't require either mesh to be prepared, but that
    2527             :           // means we need to check for subdomains manually.
    2528         284 :           auto get_subdomains = [](const MeshBase & mesh) {
    2529           8 :             std::set<subdomain_id_type> all_subdomains;
    2530        4976 :             for (auto & el : mesh.element_ptr_range())
    2531        2540 :               all_subdomains.insert(el->subdomain_id());
    2532         284 :             return all_subdomains;
    2533             :           };
    2534             : 
    2535         146 :           const auto this_subdomains = get_subdomains(*this);
    2536         146 :           const auto other_subdomains = get_subdomains(*other_mesh);
    2537             : 
    2538         213 :           for (auto & [sid, sname] : this_map)
    2539             :             {
    2540             :               // The same name with the same id means we're fine.  The
    2541             :               // same name with another id means we remap their id to
    2542             :               // ours
    2543           2 :               if (const auto other_reverse_it = other_map_reversed.find(sname);
    2544          71 :                   other_reverse_it != other_map_reversed.end() && other_reverse_it->second != sid)
    2545          71 :                 id_remapping[other_reverse_it->second] = sid;
    2546             : 
    2547             :               // The same id with a different name, we'll get to
    2548             :               // later.  The same id without any name means we don't
    2549             :               // know what the user wants.
    2550           2 :               if (other_subdomains.count(sid) && !other_map.count(sid))
    2551           0 :                 libmesh_error_msg("Can't safely stitch with a mesh sharing subdomain id "
    2552             :                                   << sid << " but not subdomain name " << sname);
    2553             :             }
    2554             : 
    2555         142 :           subdomain_id_type next_free_id = 0;
    2556             :           // We might try to stitch empty meshes ...
    2557         142 :           if (!this_subdomains.empty())
    2558         142 :             next_free_id = *this_subdomains.rbegin() + 1;
    2559         142 :           if (!other_subdomains.empty())
    2560         142 :             next_free_id =
    2561         142 :               std::max(next_free_id,
    2562             :                        cast_int<subdomain_id_type>
    2563         215 :                          (*other_subdomains.rbegin() + 1));
    2564             : 
    2565         213 :           for (auto & [sid, sname] : other_map)
    2566             :             {
    2567             :               // At this point we've figured out any remapping
    2568             :               // necessary for an sname that we share.  And we don't
    2569             :               // need to remap any sid we don't share.
    2570           8 :               if (!this_map_reversed.count(sname))
    2571             :                 {
    2572             :                   // But if we don't have this sname and we do have this
    2573             :                   // sid then we can't just merge into that.
    2574           2 :                   if (this_subdomains.count(sid))
    2575             :                     {
    2576             :                       // If we have this sid with no name, we don't
    2577             :                       // know what the user wants.
    2578           2 :                       if (!this_map.count(sid))
    2579         211 :                         libmesh_error_msg("Can't safely stitch with a mesh sharing subdomain id "
    2580             :                                           << sid << " but under subdomain name " << sname);
    2581             : 
    2582             :                       // We have this sid under a different name, so
    2583             :                       // we just need to give the other elements a new
    2584             :                       // id.
    2585             : 
    2586             :                       // Users might have done crazy things with id
    2587             :                       // choice so let's make sure they didn't get too
    2588             :                       // crazy.
    2589           0 :                       libmesh_error_msg_if ((!this_subdomains.empty() &&
    2590             :                                              next_free_id < *this_subdomains.rbegin()) ||
    2591             :                                             (!other_subdomains.empty() &&
    2592             :                                              next_free_id < *other_subdomains.rbegin()),
    2593             :                                             "Subdomain id overflow");
    2594             : 
    2595           0 :                       id_remapping[sid] = next_free_id++;
    2596           0 :                       this->set_subdomain_name(next_free_id, sname);
    2597             :                     }
    2598             :                   // If we don't have this subdomain id, well, we're
    2599             :                   // about to, so we should have its name too.
    2600             :                   else
    2601           0 :                     this->set_subdomain_name(sid, sname);
    2602             :                 }
    2603             :             }
    2604             :         }
    2605             : 
    2606             :       // Copy mesh data. If we skip the call to find_neighbors(), the lists
    2607             :       // of neighbors will be copied verbatim from the other mesh
    2608        1491 :       this->copy_nodes_and_elements(*other_mesh, skip_find_neighbors,
    2609             :                                     elem_delta, node_delta,
    2610          84 :                                     unique_delta, &id_remapping);
    2611             : 
    2612             :       // Copy BoundaryInfo from other_mesh too.  We do this via the
    2613             :       // list APIs rather than element-by-element for speed.
    2614          42 :       BoundaryInfo & boundary = this->get_boundary_info();
    2615          42 :       const BoundaryInfo & other_boundary = other_mesh->get_boundary_info();
    2616             : 
    2617      158869 :       for (const auto & t : other_boundary.build_node_list())
    2618      157336 :         boundary.add_node(std::get<0>(t) + node_delta,
    2619      157336 :                           std::get<1>(t));
    2620             : 
    2621       42855 :       for (const auto & t : other_boundary.build_side_list())
    2622       42486 :         boundary.add_side(std::get<0>(t) + elem_delta,
    2623       41322 :                           std::get<1>(t),
    2624       41322 :                           std::get<2>(t));
    2625             : 
    2626        1533 :       for (const auto & t : other_boundary.build_edge_list())
    2627           0 :         boundary.add_edge(std::get<0>(t) + elem_delta,
    2628           0 :                           std::get<1>(t),
    2629           0 :                           std::get<2>(t));
    2630             : 
    2631        1533 :       for (const auto & t : other_boundary.build_shellface_list())
    2632           0 :         boundary.add_shellface(std::get<0>(t) + elem_delta,
    2633           0 :                                std::get<1>(t),
    2634           0 :                                std::get<2>(t));
    2635             : 
    2636          42 :       const auto & other_ns_id_to_name = other_boundary.get_nodeset_name_map();
    2637          42 :       auto & ns_id_to_name = boundary.set_nodeset_name_map();
    2638        1491 :       ns_id_to_name.insert(other_ns_id_to_name.begin(), other_ns_id_to_name.end());
    2639             : 
    2640          42 :       const auto & other_ss_id_to_name = other_boundary.get_sideset_name_map();
    2641          42 :       auto & ss_id_to_name = boundary.set_sideset_name_map();
    2642        1491 :       ss_id_to_name.insert(other_ss_id_to_name.begin(), other_ss_id_to_name.end());
    2643             : 
    2644          42 :       const auto & other_es_id_to_name = other_boundary.get_edgeset_name_map();
    2645          42 :       auto & es_id_to_name = boundary.set_edgeset_name_map();
    2646        1491 :       es_id_to_name.insert(other_es_id_to_name.begin(), other_es_id_to_name.end());
    2647             : 
    2648             :       // Merge other_mesh's elemset information with ours. Throw an
    2649             :       // error if this and other_mesh have overlapping elemset codes
    2650             :       // that refer to different elemset ids.
    2651        1533 :       std::vector<dof_id_type> this_elemset_codes = this->get_elemset_codes();
    2652          84 :       MeshBase::elemset_type this_id_set_to_fill, other_id_set_to_fill;
    2653        1817 :       for (const auto & elemset_code : other_mesh->get_elemset_codes())
    2654             :         {
    2655             :           // Get the elemset ids for this elemset_code on other_mesh
    2656         284 :           other_mesh->get_elemsets(elemset_code, other_id_set_to_fill);
    2657             : 
    2658             :           // Check that this elemset code does not already exist
    2659             :           // in this mesh, or if it does, that it has the same elemset
    2660             :           // ids associated with it.
    2661             :           //
    2662             :           // Note: get_elemset_codes() is guaranteed to return a
    2663             :           // sorted vector, so we can binary search in it.
    2664         268 :           auto it = Utility::binary_find(this_elemset_codes.begin(),
    2665             :                                          this_elemset_codes.end(),
    2666          16 :                                          elemset_code);
    2667             : 
    2668         284 :           if (it != this_elemset_codes.end())
    2669             :             {
    2670             :               // This mesh has the same elemset code. Does it refer to
    2671             :               // the same elemset ids?
    2672           0 :               this->get_elemsets(elemset_code, this_id_set_to_fill);
    2673             : 
    2674             :               // Throw an error if they don't match, otherwise we
    2675             :               // don't need to do anything
    2676           0 :               libmesh_error_msg_if(other_id_set_to_fill != this_id_set_to_fill,
    2677             :                                    "Attempted to stitch together meshes with conflicting elemset codes.");
    2678             :             }
    2679             :           else
    2680             :             {
    2681             :               // Add other_mesh's elemset code to this mesh
    2682         560 :               this->add_elemset_code(elemset_code, other_id_set_to_fill);
    2683             :             }
    2684             :         }
    2685             : 
    2686             :     } // end if (other_mesh)
    2687             : 
    2688             :   // Finally, we need to "merge" the overlapping nodes
    2689             :   // We do this by iterating over node_to_elems_map and updating
    2690             :   // the elements so that they "point" to the nodes that came
    2691             :   // from this mesh, rather than from other_mesh.
    2692             :   // Then we iterate over node_to_node_map and delete the
    2693             :   // duplicate nodes that came from other_mesh.
    2694             : 
    2695             :   {
    2696         144 :     LOG_SCOPE("stitch_meshes node updates", "UnstructuredMesh");
    2697             : 
    2698             :     // Container to catch boundary IDs passed back from BoundaryInfo.
    2699          96 :     std::vector<boundary_id_type> bc_ids;
    2700             : 
    2701       32234 :     for (const auto & [target_node_id, elem_vec] : node_to_elems_map)
    2702             :       {
    2703       30530 :         dof_id_type other_node_id = node_to_node_map[target_node_id];
    2704       30530 :         Node & target_node = this->node_ref(target_node_id);
    2705             : 
    2706        1720 :         std::size_t n_elems = elem_vec.size();
    2707       79875 :         for (std::size_t i=0; i<n_elems; i++)
    2708             :           {
    2709       49345 :             dof_id_type elem_id = elem_vec[i];
    2710       49345 :             Elem * el = this->elem_ptr(elem_id);
    2711             : 
    2712             :             // find the local node index that we want to update
    2713       47955 :             unsigned int local_node_index = el->local_node(other_node_id);
    2714        1390 :             libmesh_assert_not_equal_to(local_node_index, libMesh::invalid_uint);
    2715             : 
    2716             :             // We also need to copy over the nodeset info here,
    2717             :             // because the node will get deleted below
    2718       50735 :             this->get_boundary_info().boundary_ids(el->node_ptr(local_node_index), bc_ids);
    2719       49345 :             el->set_node(local_node_index, &target_node);
    2720       49345 :             this->get_boundary_info().add_node(&target_node, bc_ids);
    2721             :           }
    2722             :       }
    2723             :   }
    2724             : 
    2725             :   {
    2726         144 :     LOG_SCOPE("stitch_meshes node deletion", "UnstructuredMesh");
    2727       32234 :     for (const auto & [other_node_id, this_node_id] : node_to_node_map)
    2728             :       {
    2729             :         // In the case that this==other_mesh, the two nodes might be the same (e.g. if
    2730             :         // we're stitching a "sliver"), hence we need to skip node deletion in that case.
    2731       30530 :         if ((this == other_mesh) && (this_node_id == other_node_id))
    2732           0 :           continue;
    2733             : 
    2734       30530 :         this->delete_node( this->node_ptr(this_node_id) );
    2735             :       }
    2736             :   }
    2737             : 
    2738             :   // If find_neighbors() wasn't called in prepare_for_use(), we need to
    2739             :   // manually loop once more over all elements adjacent to the stitched boundary
    2740             :   // and fix their lists of neighbors.
    2741             :   // This is done according to the following steps:
    2742             :   //   1. Loop over all copied elements adjacent to the boundary using node_to_elems_map (trying to avoid duplicates)
    2743             :   //   2. Look at all their sides with a nullptr neighbor and update them using side_to_elem_map if necessary
    2744             :   //   3. Update the corresponding side in side_to_elem_map as well
    2745        1704 :   if (skip_find_neighbors)
    2746             :     {
    2747         144 :       LOG_SCOPE("stitch_meshes neighbor fixes", "UnstructuredMesh");
    2748             : 
    2749             :       // Pull objects out of the loop to reduce heap operations
    2750        1704 :       std::unique_ptr<const Elem> my_side, their_side;
    2751             : 
    2752          96 :       std::set<dof_id_type> fixed_elems;
    2753       32234 :       for (const auto & pr : node_to_elems_map)
    2754             :         {
    2755        1720 :           std::size_t n_elems = pr.second.size();
    2756       79875 :           for (std::size_t i=0; i<n_elems; i++)
    2757             :             {
    2758       50735 :               dof_id_type elem_id = pr.second[i];
    2759        1390 :               if (!fixed_elems.count(elem_id))
    2760             :                 {
    2761       10508 :                   Elem * el = this->elem_ptr(elem_id);
    2762       10212 :                   fixed_elems.insert(elem_id);
    2763       57226 :                   for (auto s : el->side_index_range())
    2764             :                     {
    2765       46718 :                       bool has_real_neighbor = (el->neighbor_ptr(s) != nullptr);
    2766       47570 :                       bool has_disdjoint_neighbor = is_valid_disjoint_pair_to_stitch &&
    2767         852 :                       (this->get_boundary_info().has_boundary_id(el, s, this_mesh_boundary_id)
    2768         852 :                       || this->get_boundary_info().has_boundary_id(el, s, other_mesh_boundary_id));
    2769             : 
    2770       46718 :                       if (!has_real_neighbor || has_disdjoint_neighbor)
    2771             :                         {
    2772       21016 :                           key_type key = el->low_order_key(s);
    2773         592 :                           auto bounds = side_to_elem_map.equal_range(key);
    2774             : 
    2775       21016 :                           if (bounds.first != bounds.second)
    2776             :                             {
    2777             :                               // Get the side for this element
    2778        7952 :                               el->side_ptr(my_side, s);
    2779             : 
    2780             :                               // Look at all the entries with an equivalent key
    2781        7952 :                               while (bounds.first != bounds.second)
    2782             :                                 {
    2783             :                                   // Get the potential element
    2784        7952 :                                   Elem * neighbor = const_cast<Elem *>(bounds.first->second.first);
    2785             : 
    2786             :                                   // Get the side for the neighboring element
    2787        7952 :                                   const unsigned int ns = bounds.first->second.second;
    2788        7952 :                                   neighbor->side_ptr(their_side, ns);
    2789             :                                   //libmesh_assert(my_side.get());
    2790             :                                   //libmesh_assert(their_side.get());
    2791             : 
    2792             :                                   // If found a match with my side
    2793             :                                   //
    2794             :                                   // We need special tests here for 1D:
    2795             :                                   // since parents and children have an equal
    2796             :                                   // side (i.e. a node), we need to check
    2797             :                                   // ns != ms, and we also check level() to
    2798             :                                   // avoid setting our neighbor pointer to
    2799             :                                   // any of our neighbor's descendants
    2800       15680 :                                   if ((*my_side == *their_side) &&
    2801       15904 :                                       (el->level() == neighbor->level()) &&
    2802        7952 :                                       ((el->dim() != 1) || (ns != s)))
    2803             :                                     {
    2804             :                                       // So share a side.  Is this a mixed pair
    2805             :                                       // of subactive and active/ancestor
    2806             :                                       // elements?
    2807             :                                       // If not, then we're neighbors.
    2808             :                                       // If so, then the subactive's neighbor is
    2809             : 
    2810        8176 :                                       if (el->subactive() ==
    2811        7952 :                                           neighbor->subactive())
    2812             :                                         {
    2813             :                                           // an element is only subactive if it has
    2814             :                                           // been coarsened but not deleted
    2815         448 :                                           el->set_neighbor (s,neighbor);
    2816         448 :                                           neighbor->set_neighbor(ns,el);
    2817             :                                         }
    2818           0 :                                       else if (el->subactive())
    2819             :                                         {
    2820           0 :                                           el->set_neighbor(s,neighbor);
    2821             :                                         }
    2822           0 :                                       else if (neighbor->subactive())
    2823             :                                         {
    2824           0 :                                           neighbor->set_neighbor(ns,el);
    2825             :                                         }
    2826             :                                       // It's OK to invalidate the
    2827             :                                       // bounds.first iterator here,
    2828             :                                       // as we are immediately going
    2829             :                                       // to break out of this while
    2830             :                                       // loop. bounds.first will
    2831             :                                       // therefore not be used for
    2832             :                                       // anything else.
    2833         224 :                                       side_to_elem_map.erase (bounds.first);
    2834         224 :                                       break;
    2835             :                                     }
    2836             : 
    2837           0 :                                   ++bounds.first;
    2838             :                                 }
    2839             :                             }
    2840             :                         }
    2841             :                     }
    2842             :                 }
    2843             :             }
    2844             :         }
    2845        1608 :     }
    2846             : 
    2847             : #ifdef LIBMESH_ENABLE_PERIODIC
    2848             :   // Remove only the disjoint pair that was actually stitched.
    2849             :   // Safe because `is_valid_disjoint_pair_to_stitch` is true
    2850             :   // only if this exact (a,b) pair exists in the registry.
    2851             :   // Other disjoint pairs remain untouched.
    2852        1704 :   if (is_valid_disjoint_pair_to_stitch)
    2853         213 :     this->remove_disjoint_boundary_pair(this_mesh_boundary_id, other_mesh_boundary_id);
    2854             : #endif
    2855             : 
    2856        1704 :   if (prepare_after_stitching)
    2857             :     {
    2858             :       // We set our new neighbor pointers already
    2859          92 :       const bool old_allow_find_neighbors = this->allow_find_neighbors();
    2860          46 :       this->allow_find_neighbors(!skip_find_neighbors);
    2861             : 
    2862             :       // We haven't newly remoted any elements
    2863          92 :       const bool old_allow_remote_element_removal = this->allow_remote_element_removal();
    2864          46 :       this->allow_remote_element_removal(false);
    2865             : 
    2866        1633 :       this->prepare_for_use();
    2867             : 
    2868          46 :       this->allow_find_neighbors(old_allow_find_neighbors);
    2869          46 :       this->allow_remote_element_removal(old_allow_remote_element_removal);
    2870             :     }
    2871             : 
    2872             :   // After the stitching, we may want to clear boundary IDs from element
    2873             :   // faces that are now internal to the mesh
    2874        1704 :   if (clear_stitched_boundary_ids)
    2875             :     {
    2876         138 :       LOG_SCOPE("stitch_meshes clear bcids", "UnstructuredMesh");
    2877             : 
    2878        1633 :       this->get_boundary_info().clear_stitched_boundary_side_ids(
    2879             :           this_mesh_boundary_id, other_mesh_boundary_id, /*clear_nodeset_data=*/true);
    2880             :     }
    2881             : 
    2882             :   // Return the number of nodes which were merged.
    2883        1752 :   return node_to_node_map.size();
    2884        1742 : }
    2885             : 
    2886             : 
    2887             : } // namespace libMesh

Generated by: LCOV version 1.14