LCOV - code coverage report
Current view: top level - src/mesh - unstructured_mesh.C (source / functions) Hit Total Coverage
Test: libMesh/libmesh: #4554 (5a536d) with base 54e0d5 Lines: 804 1025 78.4 %
Date: 2026-09-16 12:37:14 Functions: 36 48 75.0 %
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     3378378 : 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     3378378 :     hi_elem.n_second_order_adjacent_vertices(hon);
      75             : 
      76     3378378 :   std::vector<dof_id_type> adjacent_vertices_ids(n_adjacent_vertices);
      77             : 
      78    11422443 :   for (unsigned int v=0; v<n_adjacent_vertices; v++)
      79    10267495 :     adjacent_vertices_ids[v] =
      80     8044065 :       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     3378378 :   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     5245450 :   return adj_vertices_to_ho_nodes.try_emplace(adjacent_vertices_ids, nullptr).first;
      94             : }
      95             : 
      96      355437 : 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       98370 :   libmesh_assert_equal_to (lo_elem.n_vertices(), hi_elem->n_vertices());
     107             : 
     108      196740 :   const processor_id_type my_pid = mesh.processor_id();
     109      355437 :   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      355437 :   const unsigned int hon_begin = lo_elem.n_nodes();
     120      355437 :   const unsigned int hon_end   = hi_elem->n_nodes();
     121             : 
     122       98370 :   libmesh_assert_less (hon_begin, hon_end);
     123             : #ifdef LIBMESH_ENABLE_UNIQUE_ID
     124       98370 :   libmesh_assert_less_equal
     125             :     (hon_end-hon_begin, max_new_nodes_per_elem);
     126             : #endif
     127             : 
     128     3685648 :   for (unsigned int hon=hon_begin; hon<hon_end; hon++)
     129             :     {
     130     3330211 :       auto pos = map_hi_order_node(hon, *hi_elem, adj_vertices_to_ho_nodes);
     131             : 
     132             :       // no, not added yet
     133     3330211 :       if (!pos->second)
     134             :         {
     135      331976 :           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      331976 :           Point new_location = 0;
     145     4329592 :           for (dof_id_type vertex_id : adjacent_vertices_ids)
     146     3129526 :             new_location += mesh.point(vertex_id);
     147             : 
     148     1532042 :           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     1200066 :             (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     1200066 :           unique_id_type new_unique_id = max_unique_id +
     183     1532042 :             max_new_nodes_per_elem * lo_elem.id() +
     184     1200066 :             hon - hon_begin;
     185             : 
     186      331976 :           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     1200066 :           pos->second = hi_node;
     196             : 
     197     1200066 :           hi_elem->set_node(hon, hi_node);
     198             :         }
     199             :       // yes, already added.
     200             :       else
     201             :         {
     202      587798 :           Node * hi_node = pos->second;
     203      587798 :           libmesh_assert(hi_node);
     204      587798 :           libmesh_assert_equal_to(mesh.node_ptr(hi_node->id()), hi_node);
     205             : 
     206     2130145 :           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     2130145 :             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     2130145 :           if (!mesh.is_replicated() &&
     220     2130145 :               hi_node->processor_id() != my_pid &&
     221             :               chosen_pid == my_pid)
     222           0 :             mesh.own_node(*hi_node);
     223             : 
     224     2130145 :           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     1835743 :   for (auto s : lo_elem.side_index_range())
     235             :     {
     236     1480306 :       Elem * neigh = lo_elem.neighbor_ptr(s);
     237     1480306 :       if (!neigh)
     238      998027 :         continue;
     239             : 
     240      102149 :       if (neigh != remote_elem)
     241             :         {
     242             :           // We don't support AMR even outside our own range yet.
     243       30346 :           libmesh_assert_equal_to (neigh->level(), 0);
     244             : 
     245      101669 :           const unsigned int ns = neigh->which_neighbor_am_i(&lo_elem);
     246       30346 :           libmesh_assert_not_equal_to(ns, libMesh::invalid_uint);
     247             : 
     248       60692 :           neigh->set_neighbor(ns, hi_elem.get());
     249             :         }
     250             : 
     251       61012 :       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      355437 :   Elem * interior_p = lo_elem.interior_parent();
     261      355437 :   if (interior_p)
     262           0 :     hi_elem->set_interior_parent(interior_p);
     263             : 
     264      355437 :   if (auto parent_exterior_it = exterior_children_of.find(interior_p);
     265       98370 :       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      453807 :   if (auto exterior_it = exterior_children_of.find(&lo_elem);
     281       98370 :       exterior_it != exterior_children_of.end())
     282             :     {
     283      355437 :       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       98370 :   mesh.get_boundary_info().copy_boundary_ids
     302      355437 :     (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      196740 :   hi_elem->set_id(lo_elem.id());
     310             : #ifdef LIBMESH_ENABLE_UNIQUE_ID
     311      196740 :   hi_elem->set_unique_id(lo_elem.unique_id());
     312             : #endif
     313             : 
     314      355437 :   const unsigned int nei = lo_elem.n_extra_integers();
     315      355437 :   hi_elem->add_extra_integers(nei);
     316      355532 :   for (unsigned int i=0; i != nei; ++i)
     317          95 :     hi_elem->set_extra_integer(i, lo_elem.get_extra_integer(i));
     318             : 
     319      257067 :   hi_elem->inherit_data_from(lo_elem);
     320             : 
     321      453807 :   mesh.insert_elem(std::move(hi_elem));
     322      355437 : }
     323             : 
     324             : 
     325             : template <typename ElemTypeConverter>
     326             : void
     327        4482 : 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        1286 :   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        1286 :   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        4482 :   mesh.update_parallel_id_counts();
     348             : 
     349             :   /*
     350             :    * If the mesh is empty then we have nothing to do
     351             :    */
     352        4482 :   if (!mesh.n_elem())
     353         400 :     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       11327 :   auto is_higher_order = [&elem_type_converter](const Elem * elem) {
     366        4903 :     ElemType old_type = elem->type();
     367        2210 :     ElemType new_type = elem_type_converter(old_type);
     368        4903 :     return old_type == new_type;
     369             :   };
     370             : 
     371        4482 :   bool already_higher_order =
     372        7678 :     std::all_of(range.begin(), range.end(), is_higher_order);
     373             : 
     374             :   // Check with other processors and possibly return early
     375        4482 :   mesh.comm().min(already_higher_order);
     376        4482 :   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        2340 :   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        2340 :   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        4082 :   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        1170 :   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      625748 :   auto track_if_necessary = [&adj_vertices_to_ho_nodes,
     437             :                              &exterior_children_of,
     438      200604 :                              &elem_type_converter](Elem * elem) {
     439      362199 :     if (elem && elem != remote_elem)
     440             :       {
     441      362199 :         if (elem->default_order() != FIRST)
     442       51569 :           for (unsigned int hon : make_range(elem->n_vertices(), elem->n_nodes()))
     443             :             {
     444       48167 :               auto pos = map_hi_order_node(hon, *elem, adj_vertices_to_ho_nodes);
     445       61929 :               pos->second = elem->node_ptr(hon);
     446             :             }
     447             : 
     448      362199 :         const ElemType old_type = elem->type();
     449      136550 :         const ElemType new_type = elem_type_converter(old_type);
     450      362199 :         if (old_type != new_type)
     451      358797 :           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       13192 :   if (range.begin() == mesh.elements_begin() &&
     458       13036 :       range.end() == mesh.elements_end())
     459             :     {
     460      516580 :       for (auto & elem : range)
     461      354595 :         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        1032 :       point_neighbor_finder(range.begin(), range.end(),
     469             :                             mesh.n_processors(),
     470             :                             point_neighbor_elements);
     471             : 
     472        8028 :       for (auto & [elem, coupling_map] : point_neighbor_elements)
     473             :         {
     474        2168 :           libmesh_ignore(coupling_map);
     475        7604 :           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      543120 :   for (auto & elem : mesh.element_ptr_range())
     484      472032 :     if (auto exterior_map_it = exterior_children_of.find(elem->interior_parent());
     485      102420 :         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      518326 :   for (auto & lo_elem : range)
     495             :     {
     496             :       // Now we can skip the elements in the range that are already
     497             :       // higher-order.
     498      355514 :       const ElemType old_type = lo_elem->type();
     499      134178 :       const ElemType new_type = elem_type_converter(old_type);
     500             : 
     501      355514 :       if (old_type == new_type)
     502          77 :         continue;
     503             : 
     504             :       // this does _not_ work for refined elements
     505       98370 :       libmesh_assert_equal_to (lo_elem->level(), 0);
     506             : 
     507      355437 :       if (lo_elem->processor_id() == DofObject::invalid_processor_id)
     508      335155 :         ++n_unpartitioned_elem;
     509             : 
     510             :       /*
     511             :        * Build the higher-order equivalent; add to
     512             :        * the new_elements list.
     513             :        */
     514      355437 :       auto ho_elem = Elem::build (new_type);
     515             : 
     516       98370 :       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     1866249 :       for (unsigned int v=0, lnn=lo_elem->n_nodes(); v < lnn; v++)
     523     1930588 :         ho_elem->set_node(v, lo_elem->node_ptr(v));
     524             : 
     525      552177 :       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        1170 :   adj_vertices_to_ho_nodes.clear();
     535             : 
     536             : #ifdef LIBMESH_ENABLE_UNIQUE_ID
     537        4082 :   const unique_id_type new_max_unique_id = max_unique_id +
     538        4082 :     max_new_nodes_per_elem * mesh.n_elem();
     539        4082 :   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        4082 :   if (!mesh.is_replicated())
     549             :     {
     550          98 :       dof_id_type max_unpartitioned_elem = n_unpartitioned_elem;
     551          98 :       mesh.comm().max(max_unpartitioned_elem);
     552          98 :       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          77 :           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          21 :           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        2340 :   const bool old_find_neighbors = mesh.allow_find_neighbors();
     573        4082 :   if (mesh.is_prepared())
     574         264 :     mesh.allow_find_neighbors(false);
     575        4082 :   mesh.prepare_for_use();
     576        1170 :   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       36565 : UnstructuredMesh::UnstructuredMesh (const Parallel::Communicator & comm_in,
     632       36565 :                                     unsigned char d) :
     633       36565 :   MeshBase (comm_in,d)
     634             : {
     635       10570 :   libmesh_assert (libMesh::initialized());
     636       36565 : }
     637             : 
     638             : 
     639             : 
     640        2661 : UnstructuredMesh::UnstructuredMesh (const MeshBase & other_mesh) :
     641        2661 :   MeshBase (other_mesh)
     642             : {
     643         818 :   libmesh_assert (libMesh::initialized());
     644        2661 : }
     645             : 
     646             : 
     647             : 
     648        2836 : 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        1736 :   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         868 :   libmesh_assert(!skip_preparation || skip_find_neighbors);
     666             : 
     667             :   std::pair<std::vector<unsigned int>, std::vector<unsigned int>>
     668        4548 :     extra_int_maps = this->merge_extra_integer_names(other_mesh);
     669             : 
     670        2836 :   const unsigned int n_old_node_ints = extra_int_maps.second.size(),
     671        2836 :                      n_new_node_ints = _node_integer_names.size(),
     672        2836 :                      n_old_elem_ints = extra_int_maps.first.size(),
     673        2836 :                      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        1712 :   bool wrap_proc_ids = (this->n_processors() <
     681        1712 :                         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         868 :   MeshTools::libmesh_assert_valid_amr_elem_ids(other_mesh);
     690         868 :   MeshTools::libmesh_assert_parallel_consistent_procids<Node>(other_mesh);
     691             : #endif
     692             : 
     693             :   //Copy in Nodes
     694             :   {
     695             :     //Preallocate Memory if necessary
     696        2836 :     this->reserve_nodes(other_mesh.n_nodes());
     697             : 
     698      815562 :     for (const auto & oldn : other_mesh.node_ptr_range())
     699             :       {
     700             :         processor_id_type added_pid = cast_int<processor_id_type>
     701      590089 :           (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     1147603 :           this->add_point(*oldn,
     706      590089 :                           oldn->id() + node_id_offset,
     707      369420 :                           added_pid);
     708             : 
     709      590089 :         newn->add_extra_integers(n_new_node_ints);
     710      629743 :         for (unsigned int i = 0; i != n_old_node_ints; ++i)
     711       51602 :           newn->set_extra_integer(extra_int_maps.second[i],
     712       39654 :                                   oldn->get_extra_integer(i));
     713             : 
     714             : #ifdef LIBMESH_ENABLE_UNIQUE_ID
     715      590089 :         newn->set_unique_id(oldn->unique_id() + unique_id_offset);
     716             : #endif
     717        1124 :       }
     718             :   }
     719             : 
     720             :   //Copy in Elements
     721             :   {
     722             :     //Preallocate Memory if necessary
     723        2836 :     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        1736 :     map_type old_elems_to_new_elems, ip_map;
     728             : 
     729             :     // Loop over the elements
     730     1294894 :     for (const auto & old : other_mesh.element_ptr_range())
     731             :       {
     732             :         // Build a new element
     733     1275509 :         Elem * newparent = old->parent() ?
     734       79224 :           this->elem_ptr(old->parent()->id() + element_id_offset) :
     735      323398 :           nullptr;
     736     1286397 :         auto el = old->disconnected_clone();
     737      635908 :         el->set_parent(newparent);
     738             : 
     739      962999 :         subdomain_id_type sbd_id = old->subdomain_id();
     740      962999 :         if (id_remapping)
     741             :           {
     742         538 :             auto remapping_it = id_remapping->find(sbd_id);
     743        1883 :             if (remapping_it != id_remapping->end())
     744          56 :               sbd_id = remapping_it->second;
     745             :           }
     746      962999 :         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      962999 :         if (old->interior_parent())
     751           0 :           ip_map[old] = el.get();
     752             : 
     753             : #ifdef LIBMESH_ENABLE_AMR
     754      962999 :         if (old->has_children())
     755      101345 :           for (unsigned int c = 0, nc = old->n_children(); c != nc; ++c)
     756      103708 :             if (old->child_ptr(c) == remote_elem)
     757          60 :               el->add_child(const_cast<RemoteElem *>(remote_elem), c);
     758             : 
     759             :         //Create the parent's child pointers if necessary
     760      962999 :         if (newparent)
     761             :           {
     762      103628 :             unsigned int oldc = old->parent()->which_child_am_i(old);
     763       79224 :             newparent->add_child(el.get(), oldc);
     764             :           }
     765             : 
     766             :         // Copy the refinement flags
     767      962999 :         el->set_refinement_flag(old->refinement_flag());
     768             : 
     769             :         // Use hack_p_level since we may not have sibling elements
     770             :         // added yet
     771      635908 :         el->hack_p_level(old->p_level());
     772             : 
     773      635908 :         el->set_p_refinement_flag(old->p_refinement_flag());
     774             : #endif // #ifdef LIBMESH_ENABLE_AMR
     775             : 
     776             :         //Assign all the nodes
     777     5378832 :         for (auto i : el->node_index_range())
     778     5879821 :           el->set_node(i,
     779     4415833 :             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      962999 :         el->processor_id() = cast_int<processor_id_type>
     783      962999 :           (wrap_proc_ids ? old->processor_id() % this->n_processors() : old->processor_id());
     784             : 
     785             :         // Give it the same element and unique ids
     786      962999 :         el->set_id(old->id() + element_id_offset);
     787             : 
     788      962999 :         el->add_extra_integers(n_new_elem_ints);
     789      964700 :         for (unsigned int i = 0; i != n_old_elem_ints; ++i)
     790        2673 :           el->set_extra_integer(extra_int_maps.first[i],
     791        1701 :                                 old->get_extra_integer(i));
     792             : 
     793             : #ifdef LIBMESH_ENABLE_UNIQUE_ID
     794      962999 :         el->set_unique_id(old->unique_id() + unique_id_offset);
     795             : #endif
     796             : 
     797             :         //Hold onto it
     798      962999 :         if (!skip_find_neighbors)
     799             :           {
     800       24960 :             for (auto s : old->side_index_range())
     801       25600 :               if (old->neighbor_ptr(s) == remote_elem)
     802         256 :                 el->set_neighbor(s, const_cast<RemoteElem *>(remote_elem));
     803        7808 :             this->add_elem(std::move(el));
     804             :           }
     805             :         else
     806             :           {
     807     1269109 :             Elem * new_el = this->add_elem(std::move(el));
     808      958007 :             old_elems_to_new_elems[old] = new_el;
     809             :           }
     810      328215 :       }
     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        2836 :     if (!ip_map.empty())
     819             :       {
     820           0 :         std::atomic<bool> existing_interior_parents{false};
     821             : 
     822             :         Threads::parallel_for
     823           0 :           (this->element_stored_range(),
     824           0 :            [&existing_interior_parents](const ElemRange & range)
     825             :            {
     826           0 :              for (Elem * elem : range)
     827           0 :                if (elem->interior_parent())
     828             :                  {
     829           0 :                    existing_interior_parents = true;
     830           0 :                    break;
     831             :                  }
     832           0 :            });
     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           0 :         if (!existing_interior_parents)
     841             :           {
     842           0 :             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           0 :         if (other_interior_mesh == &other_mesh &&
     849           0 :             _interior_mesh == this)
     850           0 :           for (auto & elem_pair : ip_map)
     851           0 :             elem_pair.second->set_interior_parent(
     852           0 :               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        2836 :     if (skip_find_neighbors)
     867             :       {
     868        2808 :         old_elems_to_new_elems[remote_elem] = const_cast<RemoteElem*>(remote_elem);
     869             : 
     870     1287678 :         for (const auto & old_elem : other_mesh.element_ptr_range())
     871             :           {
     872      958007 :             Elem * new_elem = old_elems_to_new_elems[old_elem];
     873     5070365 :             for (auto s : old_elem->side_index_range())
     874             :               {
     875     5036872 :                 const Elem * old_neighbor = old_elem->neighbor_ptr(s);
     876     3801256 :                 Elem * new_neighbor = old_elems_to_new_elems[old_neighbor];
     877     2514662 :                 new_elem->set_neighbor(s, new_neighbor);
     878             :               }
     879        1112 :           }
     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        2836 :   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        2836 :   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         175 :       const bool was_prepared = this->is_prepared();
     915         175 :       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         183 :       if (skip_find_neighbors ||
     928         175 :           !was_prepared || !other_mesh.is_prepared())
     929         147 :         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        2836 : }
     944             : 
     945             : 
     946             : 
     947       39226 : UnstructuredMesh::~UnstructuredMesh ()
     948             : {
     949             :   //  this->clear ();  // Nothing to clear at this level
     950             : 
     951       11388 :   libmesh_exceptionless_assert (!libMesh::closed());
     952       39226 : }
     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     8623710 : bool sides_are_the_same_elem(const Elem & a, const Elem & b)
     972             : {
     973     8623710 :   if (a == b)
     974     2632330 :     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          14 :   if (!a.runtime_topology() && !b.runtime_topology())
     979           0 :     return false;
     980             : 
     981          14 :   const unsigned int nv = a.n_vertices();
     982          14 :   if (nv != b.n_vertices())
     983           0 :     return false;
     984             : 
     985          22 :   std::vector<dof_id_type> a_ids(nv), b_ids(nv);
     986          56 :   for (unsigned int v = 0; v != nv; ++v)
     987             :     {
     988          54 :       a_ids[v] = a.node_id(v);
     989          66 :       b_ids[v] = b.node_id(v);
     990             :     }
     991          14 :   std::sort(a_ids.begin(), a_ids.end());
     992          14 :   std::sort(b_ids.begin(), b_ids.end());
     993          14 :   return a_ids == b_ids;
     994             : }
     995             : }
     996             : 
     997             : 
     998             : 
     999       48843 : 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       14464 :   parallel_object_only();
    1011             : 
    1012       14464 :   LOG_SCOPE("find_neighbors()", "Mesh");
    1013             : 
    1014             :   //TODO:[BSK] This should be removed later?!
    1015       48843 :   if (reset_current_list)
    1016             :     Threads::parallel_for
    1017       48399 :       (this->element_stored_range(),
    1018       91674 :        [reset_remote_elements](const ElemRange & range)
    1019             :        {
    1020     4765618 :          for (Elem * e : range)
    1021    23636690 :            for (auto s : e->side_index_range())
    1022    24646117 :              if (e->neighbor_ptr(s) != remote_elem || reset_remote_elements)
    1023     5766383 :                e->set_neighbor(s, nullptr);
    1024       48783 :        });
    1025             : 
    1026             :   // Find neighboring elements by first finding elements
    1027             :   // with identical side keys and then check to see if they
    1028             :   // are neighbors
    1029             :   {
    1030             :     // data structures -- Use the hash_multimap if available
    1031             :     typedef dof_id_type                     key_type;
    1032             :     typedef std::pair<Elem *, unsigned char> val_type;
    1033             :     typedef std::unordered_multimap<key_type, val_type> map_type;
    1034             : 
    1035             :     // A map from side keys to corresponding elements & side numbers
    1036       28928 :     map_type side_to_elem_map;
    1037             : 
    1038             :     // Pull objects out of the loop to reduce heap operations
    1039       48843 :     std::unique_ptr<Elem> my_side, their_side;
    1040             : 
    1041     6704572 :     for (const auto & element : this->element_ptr_range())
    1042             :       {
    1043    25303884 :         for (auto ms : element->side_index_range())
    1044             :           {
    1045    27724305 :           next_side:
    1046             :             // If we haven't yet found a neighbor on this side, try.
    1047             :             // Even if we think our neighbor is remote, that
    1048             :             // information may be out of date.
    1049             :             //
    1050             :             // If we're only checking remote neighbors, after a
    1051             :             // redistribution, then we'll skip the non-remote ones
    1052    38813810 :             if ((element->neighbor_ptr(ms) == nullptr && check_non_remote) ||
    1053     8799495 :                 element->neighbor_ptr(ms) == remote_elem)
    1054             :               {
    1055             :                 // Get the key for the side of this element.  Use the
    1056             :                 // low_order_key so we can find neighbors in
    1057             :                 // mixed-order meshes if necessary.
    1058    18943213 :                 const dof_id_type key = element->low_order_key(ms);
    1059             : 
    1060             :                 // Look for elements that have an identical side key
    1061     5777386 :                 auto bounds = side_to_elem_map.equal_range(key);
    1062             : 
    1063             :                 // May be multiple keys, check all the possible
    1064             :                 // elements which _might_ be neighbors.
    1065    18943213 :                 if (bounds.first != bounds.second)
    1066             :                   {
    1067             :                     // Get the side for this element
    1068     8617712 :                     element->side_ptr(my_side, ms);
    1069             : 
    1070             :                     // Look at all the entries with an equivalent key
    1071     8628020 :                     while (bounds.first != bounds.second)
    1072             :                       {
    1073             :                         // Get the potential element
    1074     8623710 :                         Elem * neighbor = bounds.first->second.first;
    1075             : 
    1076             :                         // Get the side for the neighboring element
    1077     8623710 :                         const unsigned int ns = bounds.first->second.second;
    1078     8623710 :                         neighbor->side_ptr(their_side, ns);
    1079             :                         //libmesh_assert(my_side.get());
    1080             :                         //libmesh_assert(their_side.get());
    1081             : 
    1082             :                         // If found a match with my side
    1083             :                         //
    1084             :                         // In 1D, since parents and children have an
    1085             :                         // equal side (i.e. a node) we need to check
    1086             :                         // for matching level() to avoid setting our
    1087             :                         // neighbor pointer to any of our neighbor's
    1088             :                         // descendants.
    1089    17247420 :                         if (sides_are_the_same_elem(*my_side, *their_side) &&
    1090     8623710 :                             (element->level() == neighbor->level()))
    1091             :                           {
    1092             :                             // So share a side.  Is this a mixed pair
    1093             :                             // of subactive and active/ancestor
    1094             :                             // elements?
    1095             :                             // If not, then we're neighbors.
    1096             :                             // If so, then the subactive's neighbor is
    1097             : 
    1098    11221462 :                             if (element->subactive() ==
    1099     8613402 :                                 neighbor->subactive())
    1100             :                               {
    1101             :                                 // an element is only subactive if it has
    1102             :                                 // been coarsened but not deleted
    1103     5222970 :                                 element->set_neighbor (ms,neighbor);
    1104     8591146 :                                 neighbor->set_neighbor(ns,element);
    1105             :                               }
    1106       22256 :                             else if (element->subactive())
    1107             :                               {
    1108        5096 :                                 element->set_neighbor(ms,neighbor);
    1109             :                               }
    1110       14344 :                             else if (neighbor->subactive())
    1111             :                               {
    1112        9368 :                                 neighbor->set_neighbor(ns,element);
    1113             :                               }
    1114     2629374 :                             side_to_elem_map.erase (bounds.first);
    1115             : 
    1116             :                             // get out of this nested crap
    1117     8613402 :                             goto next_side;
    1118             :                           }
    1119             : 
    1120        2960 :                         ++bounds.first;
    1121             :                       }
    1122             :                   }
    1123             : 
    1124             :                 // didn't find a match...
    1125             :                 // Build the map entry for this element
    1126             :                 side_to_elem_map.emplace
    1127    10329811 :                   (key, std::make_pair(element, cast_int<unsigned char>(ms)));
    1128             :               }
    1129             :           }
    1130       19939 :       }
    1131       19939 :   }
    1132             : 
    1133             : #ifdef LIBMESH_ENABLE_PERIODIC
    1134             :   // Get the disjoint neighbor boundary pairs object (from periodic BCs)
    1135       48843 :   auto * db = this->get_disjoint_neighbor_boundary_pairs();
    1136             : 
    1137       48843 :   if (db)
    1138             :     {
    1139             :       // Obtain a point locator
    1140          90 :       std::unique_ptr<PointLocatorBase> point_locator = this->sub_point_locator();
    1141             : 
    1142         380 :       for (const auto & element : this->element_ptr_range())
    1143             :         {
    1144         962 :           for (auto ms : element->side_index_range())
    1145             :             {
    1146             :               // Skip if this side already has a valid neighbor (including remote neighbors)
    1147         980 :               if (element->neighbor_ptr(ms) != nullptr &&
    1148         154 :                   element->neighbor_ptr(ms) != remote_elem)
    1149         110 :                 continue;
    1150             : 
    1151        2086 :               for (const auto & [id, boundary_ptr] : *db)
    1152             :                 {
    1153        1512 :                   if (!this->get_boundary_info().has_boundary_id(element, ms, id))
    1154        1414 :                     continue;
    1155             : 
    1156             :                   unsigned int neigh_side;
    1157             :                   const Elem * neigh =
    1158         126 :                     db->neighbor(id, *point_locator, element, ms, &neigh_side);
    1159             : 
    1160          98 :                   if (neigh && neigh != remote_elem && neigh != element)
    1161             :                     {
    1162          98 :                       auto neigh_changeable = this->elem_ptr(neigh->id());
    1163          98 :                       element->set_neighbor(ms, neigh_changeable);
    1164          98 :                       neigh_changeable->set_neighbor(neigh_side, element);
    1165             :                     }
    1166             :                 }
    1167             :             }
    1168          30 :         }
    1169          30 :     }
    1170             : #endif // LIBMESH_ENABLE_PERIODIC
    1171             : 
    1172             : #ifdef LIBMESH_ENABLE_AMR
    1173             : 
    1174             :   /**
    1175             :    * Here we look at all of the child elements which
    1176             :    * don't already have valid neighbors.
    1177             :    *
    1178             :    * If a child element has a nullptr neighbor it is
    1179             :    * either because it is on the boundary or because
    1180             :    * its neighbor is at a different level.  In the
    1181             :    * latter case we must get the neighbor from the
    1182             :    * parent.
    1183             :    *
    1184             :    * If a child element has a remote_elem neighbor
    1185             :    * on a boundary it shares with its parent, that
    1186             :    * info may have become out-dated through coarsening
    1187             :    * of the neighbor's parent.  In this case, if the
    1188             :    * parent's neighbor is active then the child should
    1189             :    * share it.
    1190             :    *
    1191             :    * Furthermore, that neighbor better be active,
    1192             :    * otherwise we missed a child somewhere.
    1193             :    *
    1194             :    *
    1195             :    * We also need to look through children ordered by increasing
    1196             :    * refinement level in order to add new interior_parent() links in
    1197             :    * boundary elements which have just been generated by refinement,
    1198             :    * and fix links in boundary elements whose previous
    1199             :    * interior_parent() has just been coarsened away.
    1200             :    */
    1201       48843 :   const unsigned int n_levels = MeshTools::n_levels(*this);
    1202       63431 :   for (unsigned int level = 1; level < n_levels; ++level)
    1203             :     {
    1204      855958 :       for (auto & current_elem : as_range(level_elements_begin(level),
    1205     4510096 :                                           level_elements_end(level)))
    1206             :         {
    1207      831338 :           libmesh_assert(current_elem);
    1208     2646097 :           Elem * parent = current_elem->parent();
    1209      831338 :           libmesh_assert(parent);
    1210     2646097 :           const unsigned int my_child_num = parent->which_child_am_i(current_elem);
    1211             : 
    1212    13819939 :           for (auto s : current_elem->side_index_range())
    1213             :             {
    1214    16638798 :               if (current_elem->neighbor_ptr(s) == nullptr ||
    1215     9611096 :                   (current_elem->neighbor_ptr(s) == remote_elem &&
    1216        7830 :                    parent->is_child_on_side(my_child_num, s)))
    1217             :                 {
    1218      468992 :                   Elem * neigh = parent->neighbor_ptr(s);
    1219             : 
    1220             :                   // If neigh was refined and had non-subactive children
    1221             :                   // made remote earlier, then our current elem should
    1222             :                   // actually have one of those remote children as a
    1223             :                   // neighbor
    1224     1077578 :                   if (neigh &&
    1225      445018 :                       (neigh->ancestor() ||
    1226             :                        // If neigh has subactive children which should have
    1227             :                        // matched as neighbors of the current element but
    1228             :                        // did not, then those likewise must be remote
    1229             :                        // children.
    1230      336324 :                        (current_elem->subactive() && neigh->has_children() &&
    1231           0 :                         (neigh->level()+1) == current_elem->level())))
    1232             :                     {
    1233             : #ifdef DEBUG
    1234             :                       // Let's make sure that "had children made remote"
    1235             :                       // situation is actually the case
    1236           0 :                       libmesh_assert(neigh->has_children());
    1237           0 :                       bool neigh_has_remote_children = false;
    1238           0 :                       for (auto & child : neigh->child_ref_range())
    1239           0 :                         if (&child == remote_elem)
    1240           0 :                           neigh_has_remote_children = true;
    1241           0 :                       libmesh_assert(neigh_has_remote_children);
    1242             : 
    1243             :                       // And let's double-check that we don't have
    1244             :                       // a remote_elem neighboring an active local element
    1245           0 :                       if (current_elem->active())
    1246           0 :                         libmesh_assert_not_equal_to (current_elem->processor_id(),
    1247             :                                                      this->processor_id());
    1248             : #endif // DEBUG
    1249           0 :                       neigh = const_cast<RemoteElem *>(remote_elem);
    1250             :                     }
    1251             :                   // If neigh and current_elem are more than one level
    1252             :                   // apart, figuring out whether we have a remote
    1253             :                   // neighbor here becomes much harder.
    1254      749154 :                   else if (neigh && (current_elem->subactive() &&
    1255        7900 :                                      neigh->has_children()))
    1256             :                     {
    1257             :                       // Find the deepest descendant of neigh which
    1258             :                       // we could consider for a neighbor.  If we run
    1259             :                       // out of neigh children, then that's our
    1260             :                       // neighbor.  If we find a potential neighbor
    1261             :                       // with remote_children and we don't find any
    1262             :                       // potential neighbors among its non-remote
    1263             :                       // children, then our neighbor must be remote.
    1264           0 :                       while (neigh != remote_elem &&
    1265           0 :                              neigh->has_children())
    1266             :                         {
    1267           0 :                           bool found_neigh = false;
    1268           0 :                           for (unsigned int c = 0, nc = neigh->n_children();
    1269           0 :                                !found_neigh && c != nc; ++c)
    1270             :                             {
    1271           0 :                               Elem * child = neigh->child_ptr(c);
    1272           0 :                               if (child == remote_elem)
    1273           0 :                                 continue;
    1274           0 :                               for (auto ncn : child->neighbor_ptr_range())
    1275             :                                 {
    1276           0 :                                   if (ncn != remote_elem &&
    1277           0 :                                       ncn->is_ancestor_of(current_elem))
    1278             :                                     {
    1279           0 :                                       neigh = ncn;
    1280           0 :                                       found_neigh = true;
    1281           0 :                                       break;
    1282             :                                     }
    1283             :                                 }
    1284             :                             }
    1285           0 :                           if (!found_neigh)
    1286           0 :                             neigh = const_cast<RemoteElem *>(remote_elem);
    1287             :                         }
    1288             :                     }
    1289      741254 :                   current_elem->set_neighbor(s, neigh);
    1290             : #ifdef DEBUG
    1291      234496 :                   if (neigh != nullptr && neigh != remote_elem)
    1292             :                     // We ignore subactive elements here because
    1293             :                     // we don't care about neighbors of subactive element.
    1294      107152 :                     if ((!neigh->active()) && (!current_elem->subactive()))
    1295             :                       {
    1296           0 :                         libMesh::err << "On processor " << this->processor_id()
    1297           0 :                                      << std::endl;
    1298           0 :                         libMesh::err << "Bad element ID = " << current_elem->id()
    1299           0 :                                      << ", Side " << s << ", Bad neighbor ID = " << neigh->id() << std::endl;
    1300           0 :                         libMesh::err << "Bad element proc_ID = " << current_elem->processor_id()
    1301           0 :                                      << ", Bad neighbor proc_ID = " << neigh->processor_id() << std::endl;
    1302           0 :                         libMesh::err << "Bad element size = " << current_elem->hmin()
    1303           0 :                                      << ", Bad neighbor size = " << neigh->hmin() << std::endl;
    1304           0 :                         libMesh::err << "Bad element center = " << current_elem->vertex_average()
    1305           0 :                                      << ", Bad neighbor center = " << neigh->vertex_average() << std::endl;
    1306           0 :                         libMesh::err << "ERROR: "
    1307           0 :                                      << (current_elem->active()?"Active":"Ancestor")
    1308           0 :                                      << " Element at level "
    1309           0 :                                      << current_elem->level() << std::endl;
    1310           0 :                         libMesh::err << "with "
    1311           0 :                                      << (parent->active()?"active":
    1312           0 :                                          (parent->subactive()?"subactive":"ancestor"))
    1313           0 :                                      << " parent share "
    1314           0 :                                      << (neigh->subactive()?"subactive":"ancestor")
    1315           0 :                                      << " neighbor at level " << neigh->level()
    1316           0 :                                      << std::endl;
    1317           0 :                         NameBasedIO(*this).write ("bad_mesh.gmv");
    1318           0 :                         libmesh_error_msg("Problematic mesh written to bad_mesh.gmv.");
    1319             :                       }
    1320             : #endif // DEBUG
    1321             :                 }
    1322             :             }
    1323             : 
    1324             :           // We can skip to the next element if we're full-dimension
    1325             :           // and therefore don't have any interior parents
    1326     2646097 :           if (current_elem->dim() >= LIBMESH_DIM)
    1327     1070670 :             continue;
    1328             : 
    1329             :           // We have no interior parents unless we can find one later
    1330     1996165 :           current_elem->set_interior_parent(nullptr);
    1331             : 
    1332     1996165 :           Elem * pip = parent->interior_parent();
    1333             : 
    1334     1996165 :           if (!pip)
    1335     1367135 :             continue;
    1336             : 
    1337             :           // If there's no interior_parent children, whether due to a
    1338             :           // remote element or a non-conformity, then there's no
    1339             :           // children to search.
    1340        3492 :           if (pip == remote_elem || pip->active())
    1341             :             {
    1342           0 :               current_elem->set_interior_parent(pip);
    1343           0 :               continue;
    1344             :             }
    1345             : 
    1346             :           // For node comparisons we'll need a sensible tolerance
    1347        3492 :           Real node_tolerance = current_elem->hmin() * TOLERANCE;
    1348             : 
    1349             :           // Otherwise our interior_parent should be a child of our
    1350             :           // parent's interior_parent.
    1351       10502 :           for (auto & child : pip->child_ref_range())
    1352             :             {
    1353             :               // If we have a remote_elem, that might be our
    1354             :               // interior_parent.  We'll set it provisionally now and
    1355             :               // keep trying to find something better.
    1356       10502 :               if (&child == remote_elem)
    1357             :                 {
    1358             :                   current_elem->set_interior_parent
    1359           0 :                     (const_cast<RemoteElem *>(remote_elem));
    1360           0 :                   continue;
    1361             :                 }
    1362             : 
    1363        3008 :               bool child_contains_our_nodes = true;
    1364       24726 :               for (auto & n : current_elem->node_ref_range())
    1365             :                 {
    1366        5220 :                   bool child_contains_this_node = false;
    1367      115942 :                   for (auto & cn : child.node_ref_range())
    1368      108932 :                     if (cn.absolute_fuzzy_equals
    1369       77732 :                         (n, node_tolerance))
    1370             :                       {
    1371        3212 :                         child_contains_this_node = true;
    1372        3212 :                         break;
    1373             :                       }
    1374       18226 :                   if (!child_contains_this_node)
    1375             :                     {
    1376        2008 :                       child_contains_our_nodes = false;
    1377        2008 :                       break;
    1378             :                     }
    1379             :                 }
    1380       10502 :               if (child_contains_our_nodes)
    1381             :                 {
    1382        3492 :                   current_elem->set_interior_parent(&child);
    1383        1000 :                   break;
    1384             :                 }
    1385             :             }
    1386             : 
    1387             :           // We should have found *some* interior_parent at this
    1388             :           // point, whether semilocal or remote.
    1389        1000 :           libmesh_assert(current_elem->interior_parent());
    1390        5476 :         }
    1391             :     }
    1392             : #endif // AMR
    1393             : 
    1394             : #ifdef DEBUG
    1395       14464 :   if (assert_valid)
    1396             :     {
    1397       14328 :       MeshTools::libmesh_assert_valid_neighbors(*this,
    1398       14328 :                                                 !reset_remote_elements);
    1399       14328 :       MeshTools::libmesh_assert_valid_amr_interior_parents(*this);
    1400             :     }
    1401             : #else
    1402             :   libmesh_ignore(assert_valid);
    1403             : #endif
    1404             : 
    1405       48843 :   this->_preparation.has_neighbor_ptrs = true;
    1406       48843 : }
    1407             : 
    1408             : 
    1409             : 
    1410         592 : void UnstructuredMesh::read (const std::string & name,
    1411             :                              void *,
    1412             :                              bool skip_renumber_nodes_and_elements,
    1413             :                              bool skip_find_neighbors,
    1414             :                              bool skip_detect_interior_parents)
    1415             : {
    1416             :   // Set the skip_renumber_nodes_and_elements flag on all processors
    1417             :   // if necessary.
    1418             :   // This ensures that renumber_nodes_and_elements is *not* called
    1419             :   // during prepare_for_use() for certain types of mesh files.
    1420             :   // This is required in cases where there is an associated solution
    1421             :   // file which expects a certain ordering of the nodes.
    1422         592 :   if (Utility::ends_with(name, ".gmv"))
    1423           0 :     this->allow_renumbering(false);
    1424             : 
    1425         592 :   NameBasedIO(*this).read(name);
    1426             : 
    1427         592 :   if (skip_renumber_nodes_and_elements)
    1428             :     {
    1429             :       // Use MeshBase::allow_renumbering() yourself instead.
    1430             :       libmesh_deprecated();
    1431           0 :       this->allow_renumbering(false);
    1432             :     }
    1433             : 
    1434             :   // Done reading the mesh.  Now prepare it for use.
    1435         356 :   const bool old_allow_find_neighbors = this->allow_find_neighbors();
    1436         356 :   const bool old_allow_detect_interior_parents = this->allow_detect_interior_parents();
    1437             : 
    1438         178 :   this->allow_find_neighbors(!skip_find_neighbors);
    1439         178 :   this->allow_detect_interior_parents(!skip_detect_interior_parents);
    1440             : 
    1441         592 :   this->prepare_for_use();
    1442             : 
    1443         178 :   this->allow_find_neighbors(old_allow_find_neighbors);
    1444         178 :   this->allow_detect_interior_parents(old_allow_detect_interior_parents);
    1445         592 : }
    1446             : 
    1447             : 
    1448             : 
    1449        1274 : void UnstructuredMesh::write (const std::string & name) const
    1450             : {
    1451         598 :   LOG_SCOPE("write()", "Mesh");
    1452             : 
    1453        1872 :   NameBasedIO(*this).write(name);
    1454        1274 : }
    1455             : 
    1456             : 
    1457             : 
    1458           0 : void UnstructuredMesh::write (const std::string & name,
    1459             :                               const std::vector<Number> & v,
    1460             :                               const std::vector<std::string> & vn) const
    1461             : {
    1462           0 :   LOG_SCOPE("write()", "Mesh");
    1463             : 
    1464           0 :   NameBasedIO(*this).write_nodal_data(name, v, vn);
    1465           0 : }
    1466             : 
    1467             : 
    1468             : 
    1469             : 
    1470             : 
    1471           0 : void UnstructuredMesh::create_pid_mesh(UnstructuredMesh & pid_mesh,
    1472             :                                        const processor_id_type pid) const
    1473             : {
    1474             : 
    1475             :   // Issue a warning if the number the number of processors
    1476             :   // currently available is less that that requested for
    1477             :   // partitioning.  This is not necessarily an error since
    1478             :   // you may run on one processor and still partition the
    1479             :   // mesh into several partitions.
    1480             : #ifdef DEBUG
    1481           0 :   if (this->n_processors() < pid)
    1482             :     {
    1483           0 :       libMesh::out << "WARNING:  You are creating a "
    1484           0 :                    << "mesh for a processor id (="
    1485           0 :                    << pid
    1486           0 :                    << ") greater than "
    1487           0 :                    << "the number of processors available for "
    1488           0 :                    << "the calculation. (="
    1489           0 :                    << this->n_processors()
    1490           0 :                    << ")."
    1491           0 :                    << std::endl;
    1492             :     }
    1493             : #endif
    1494             : 
    1495           0 :   this->create_submesh (pid_mesh,
    1496           0 :                         this->active_pid_elements_begin(pid),
    1497           0 :                         this->active_pid_elements_end(pid));
    1498           0 : }
    1499             : 
    1500             : 
    1501             : 
    1502             : 
    1503             : 
    1504             : 
    1505             : 
    1506           0 : void UnstructuredMesh::create_submesh (UnstructuredMesh & new_mesh,
    1507             :                                        const const_element_iterator & it,
    1508             :                                        const const_element_iterator & it_end) const
    1509             : {
    1510             :   // Just in case the subdomain_mesh already has some information
    1511             :   // in it, get rid of it.
    1512           0 :   new_mesh.clear();
    1513             : 
    1514             :   // If we're not serial, our submesh isn't either.
    1515             :   // There are no remote elements to delete on an empty mesh, but
    1516             :   // calling the method to do so marks the mesh as parallel.
    1517           0 :   if (!this->is_serial())
    1518           0 :     new_mesh.delete_remote_elements();
    1519             : 
    1520             :   // Fail if (*this == new_mesh), we cannot create a submesh inside ourself!
    1521             :   // This may happen if the user accidentally passes the original mesh into
    1522             :   // this function!  We will check this by making sure we did not just
    1523             :   // clear ourself.
    1524           0 :   libmesh_assert_not_equal_to (this->n_nodes(), 0);
    1525           0 :   libmesh_assert_not_equal_to (this->n_elem(), 0);
    1526             : 
    1527             :   // Container to catch boundary IDs handed back by BoundaryInfo
    1528           0 :   std::vector<boundary_id_type> bc_ids;
    1529             : 
    1530             :   // Put any extra integers on the new mesh too
    1531           0 :   new_mesh.merge_extra_integer_names(*this);
    1532           0 :   const unsigned int n_node_ints = _node_integer_names.size();
    1533             : 
    1534           0 :   for (const auto & old_elem : as_range(it, it_end))
    1535             :     {
    1536             :       // Add an equivalent element type to the new_mesh.
    1537             :       // disconnected_clone() copies ids, extra element integers, etc.
    1538           0 :       auto uelem = old_elem->disconnected_clone();
    1539           0 :       Elem * new_elem = new_mesh.add_elem(std::move(uelem));
    1540           0 :       libmesh_assert(new_elem);
    1541             : 
    1542             :       // Loop over the nodes on this element.
    1543           0 :       for (auto n : old_elem->node_index_range())
    1544             :         {
    1545           0 :           const dof_id_type this_node_id = old_elem->node_id(n);
    1546             : 
    1547             :           // Add this node to the new mesh if it's not there already
    1548           0 :           if (!new_mesh.query_node_ptr(this_node_id))
    1549             :             {
    1550             :               Node * newn =
    1551           0 :                 new_mesh.add_point (old_elem->point(n),
    1552             :                                     this_node_id,
    1553           0 :                                     old_elem->node_ptr(n)->processor_id());
    1554             : 
    1555           0 :               newn->add_extra_integers(n_node_ints);
    1556           0 :               for (unsigned int i = 0; i != n_node_ints; ++i)
    1557           0 :                 newn->set_extra_integer(i, old_elem->node_ptr(n)->get_extra_integer(i));
    1558             : 
    1559             : #ifdef LIBMESH_ENABLE_UNIQUE_ID
    1560           0 :               newn->set_unique_id(old_elem->node_ptr(n)->unique_id());
    1561             : #endif
    1562             :             }
    1563             : 
    1564             :           // Define this element's connectivity on the new mesh
    1565           0 :           new_elem->set_node(n, new_mesh.node_ptr(this_node_id));
    1566             :         }
    1567             : 
    1568             :       // Maybe add boundary conditions for this element
    1569           0 :       for (auto s : old_elem->side_index_range())
    1570             :         {
    1571           0 :           this->get_boundary_info().boundary_ids(old_elem, s, bc_ids);
    1572           0 :           new_mesh.get_boundary_info().add_side (new_elem, s, bc_ids);
    1573             :         }
    1574           0 :     } // end loop over elements
    1575             : 
    1576             :   // Prepare the new_mesh for use
    1577           0 :   new_mesh.prepare_for_use();
    1578           0 : }
    1579             : 
    1580             : 
    1581             : 
    1582             : #ifdef LIBMESH_ENABLE_AMR
    1583        2793 : bool UnstructuredMesh::contract ()
    1584             : {
    1585         860 :   LOG_SCOPE ("contract()", "Mesh");
    1586             : 
    1587             :   // Flag indicating if this call actually changes the mesh
    1588         860 :   bool mesh_changed = false;
    1589             : 
    1590             : #ifdef DEBUG
    1591      545354 :   for (const auto & elem : this->element_ptr_range())
    1592      544494 :     libmesh_assert(elem->active() || elem->subactive() || elem->ancestor());
    1593             : #endif
    1594             : 
    1595             :   // Loop over the elements.
    1596     2388222 :   for (auto & elem : this->element_ptr_range())
    1597             :     {
    1598             :       // Delete all the subactive ones
    1599     1736242 :       if (elem->subactive())
    1600             :         {
    1601             :           // No level-0 element should be subactive.
    1602             :           // Note that we CAN'T test elem->level(), as that
    1603             :           // touches elem->parent()->dim(), and elem->parent()
    1604             :           // might have already been deleted!
    1605       71808 :           libmesh_assert(elem->parent());
    1606             : 
    1607             :           // Delete the element
    1608             :           // This just sets a pointer to nullptr, and doesn't
    1609             :           // invalidate any iterators
    1610      236156 :           this->delete_elem(elem);
    1611             : 
    1612             :           // the mesh has certainly changed
    1613       71808 :           mesh_changed = true;
    1614             :         }
    1615             :       else
    1616             :         {
    1617             :           // Compress all the active ones
    1618      472686 :           if (elem->active())
    1619     1140856 :             elem->contract();
    1620             :           else
    1621      113362 :             libmesh_assert (elem->ancestor());
    1622             :         }
    1623        1073 :     }
    1624             : 
    1625             :   // Strip any newly-created nullptr voids out of the element array
    1626        2793 :   this->renumber_nodes_and_elements();
    1627             : 
    1628             :   // FIXME: Need to understand why deleting subactive children
    1629             :   // invalidates the point locator.  For now we will clear it explicitly
    1630        2793 :   this->clear_point_locator();
    1631             : 
    1632             :   // Allow our GhostingFunctor objects to reinit if necessary.
    1633        4759 :   for (auto & gf : as_range(this->ghosting_functors_begin(),
    1634       15621 :                             this->ghosting_functors_end()))
    1635             :     {
    1636        2826 :       libmesh_assert(gf);
    1637        9142 :       gf->mesh_reinit();
    1638             :     }
    1639             : 
    1640        3653 :   return mesh_changed;
    1641             : }
    1642             : #endif // #ifdef LIBMESH_ENABLE_AMR
    1643             : 
    1644             : 
    1645             : 
    1646        1289 : void UnstructuredMesh::all_first_order ()
    1647             : {
    1648         792 :   LOG_SCOPE("all_first_order()", "Mesh");
    1649             : 
    1650             :   /**
    1651             :    * Prepare to identify (and then delete) a bunch of no-longer-used nodes.
    1652             :    */
    1653        1685 :   std::vector<bool> node_touched_by_me(this->max_node_id(), false);
    1654             : 
    1655             :   // Loop over the high-ordered elements.
    1656             :   // First make sure they _are_ indeed high-order, and then replace
    1657             :   // them with an equivalent first-order element.
    1658      117934 :   for (auto & so_elem : element_ptr_range())
    1659             :     {
    1660       25880 :       libmesh_assert(so_elem);
    1661             : 
    1662             :       /*
    1663             :        * build the first-order equivalent, add to
    1664             :        * the new_elements list.
    1665             :        */
    1666             :       auto lo_elem = Elem::build
    1667             :         (Elem::first_order_equivalent_type
    1668      109636 :          (so_elem->type()), so_elem->parent());
    1669             : 
    1670       83756 :       const unsigned short n_sides = so_elem->n_sides();
    1671             : 
    1672      399110 :       for (unsigned short s=0; s != n_sides; ++s)
    1673      413254 :         if (so_elem->neighbor_ptr(s) == remote_elem)
    1674           0 :           lo_elem->set_neighbor(s, const_cast<RemoteElem *>(remote_elem));
    1675             : 
    1676             : #ifdef LIBMESH_ENABLE_AMR
    1677             :       /*
    1678             :        * Reset the parent links of any child elements
    1679             :        */
    1680       83756 :       if (so_elem->has_children())
    1681       99935 :         for (unsigned int c = 0, nc = so_elem->n_children(); c != nc; ++c)
    1682             :           {
    1683       78156 :             Elem * child = so_elem->child_ptr(c);
    1684       78156 :             if (child != remote_elem)
    1685       48208 :               child->set_parent(lo_elem.get());
    1686       78156 :             lo_elem->add_child(child, c);
    1687             :           }
    1688             : 
    1689             :       /*
    1690             :        * Reset the child link of any parent element
    1691             :        */
    1692      109636 :       if (so_elem->parent())
    1693             :         {
    1694             :           unsigned int c =
    1695       78156 :             so_elem->parent()->which_child_am_i(so_elem);
    1696      102260 :           lo_elem->parent()->replace_child(lo_elem.get(), c);
    1697             :         }
    1698             : 
    1699             :       /*
    1700             :        * Copy as much data to the new element as makes sense
    1701             :        */
    1702      109636 :       lo_elem->set_p_level(so_elem->p_level());
    1703       83756 :       lo_elem->set_refinement_flag(so_elem->refinement_flag());
    1704       51760 :       lo_elem->set_p_refinement_flag(so_elem->p_refinement_flag());
    1705             : #endif
    1706             : 
    1707       25880 :       libmesh_assert_equal_to (lo_elem->n_vertices(), so_elem->n_vertices());
    1708             : 
    1709             :       /*
    1710             :        * By definition the vertices of the linear and
    1711             :        * second order element are identically numbered.
    1712             :        * transfer these.
    1713             :        */
    1714      400790 :       for (unsigned int v=0, snv=so_elem->n_vertices(); v < snv; v++)
    1715             :         {
    1716      415414 :           lo_elem->set_node(v, so_elem->node_ptr(v));
    1717      295140 :           node_touched_by_me[lo_elem->node_id(v)] = true;
    1718             :         }
    1719             : 
    1720             :       /*
    1721             :        * find_neighbors relies on remote_elem neighbor links being
    1722             :        * properly maintained.
    1723             :        */
    1724      399110 :       for (unsigned short s=0; s != n_sides; s++)
    1725             :         {
    1726      413254 :           if (so_elem->neighbor_ptr(s) == remote_elem)
    1727           0 :             lo_elem->set_neighbor(s, const_cast<RemoteElem*>(remote_elem));
    1728             :         }
    1729             : 
    1730             :       /**
    1731             :        * If the second order element had any boundary conditions they
    1732             :        * should be transferred to the first-order element.  The old
    1733             :        * boundary conditions will be removed from the BoundaryInfo
    1734             :        * data structure by insert_elem.
    1735             :        */
    1736       25880 :       this->get_boundary_info().copy_boundary_ids
    1737       83756 :         (this->get_boundary_info(), so_elem, lo_elem.get());
    1738             : 
    1739             :       /*
    1740             :        * The new first-order element is ready.
    1741             :        * Inserting it into the mesh will replace and delete
    1742             :        * the second-order element.
    1743             :        */
    1744       83756 :       lo_elem->set_id(so_elem->id());
    1745             : #ifdef LIBMESH_ENABLE_UNIQUE_ID
    1746       51760 :       lo_elem->set_unique_id(so_elem->unique_id());
    1747             : #endif
    1748             : 
    1749       83756 :       const unsigned int nei = so_elem->n_extra_integers();
    1750       83756 :       lo_elem->add_extra_integers(nei);
    1751       84459 :       for (unsigned int i=0; i != nei; ++i)
    1752         703 :         lo_elem->set_extra_integer(i, so_elem->get_extra_integer(i));
    1753             : 
    1754       83756 :       lo_elem->inherit_data_from(*so_elem);
    1755             : 
    1756      135516 :       this->insert_elem(std::move(lo_elem));
    1757       32493 :     }
    1758             : 
    1759             :   // Deleting nodes does not invalidate iterators, so this is safe.
    1760      388442 :   for (const auto & node : this->node_ptr_range())
    1761      368166 :     if (!node_touched_by_me[node->id()])
    1762      198083 :       this->delete_node(node);
    1763             : 
    1764             :   // If crazy people applied boundary info to non-vertices and then
    1765             :   // deleted those non-vertices, we should make sure their boundary id
    1766             :   // caches are correct.
    1767        1289 :   this->get_boundary_info().regenerate_id_sets();
    1768             : 
    1769             :   // On hanging nodes that used to also be second order nodes, we
    1770             :   // might now have an invalid nodal processor_id()
    1771        1289 :   Partitioner::set_node_processor_ids(*this);
    1772             : 
    1773             :   // delete or renumber nodes if desired
    1774        1289 :   this->prepare_for_use();
    1775        1289 : }
    1776             : 
    1777             : 
    1778             : 
    1779             : void
    1780        2329 : UnstructuredMesh::all_second_order_range (const SimpleRange<element_iterator> & range,
    1781             :                                           const bool full_ordered)
    1782             : {
    1783         672 :   LOG_SCOPE("all_second_order_range()", "Mesh");
    1784             : 
    1785             :   /*
    1786             :    * The maximum number of new second order nodes we might be adding,
    1787             :    * for use when picking unique unique_id values later. This variable
    1788             :    * is not used unless unique ids are enabled.
    1789             :    */
    1790             :   unsigned int max_new_nodes_per_elem;
    1791             : 
    1792             :   /*
    1793             :    * For speed-up of the \p add_point() method, we
    1794             :    * can reserve memory.  Guess the number of additional
    1795             :    * nodes based on the element spatial dimensions and the
    1796             :    * total number of nodes in the mesh as an upper bound.
    1797             :    */
    1798        2329 :   switch (this->mesh_dimension())
    1799             :     {
    1800          91 :     case 1:
    1801             :       /*
    1802             :        * in 1D, there can only be order-increase from Edge2
    1803             :        * to Edge3.  Something like 1/2 of n_nodes() have
    1804             :        * to be added
    1805             :        */
    1806          26 :       max_new_nodes_per_elem = 3 - 2;
    1807         182 :       this->reserve_nodes(static_cast<unsigned int>
    1808          91 :                           (1.5*static_cast<double>(this->n_nodes())));
    1809          65 :       break;
    1810             : 
    1811         400 :     case 2:
    1812             :       /*
    1813             :        * in 2D, either refine from Tri3 to Tri6 (double the nodes)
    1814             :        * or from Quad4 to Quad8 (again, double) or Quad9 (2.25 that much)
    1815             :        */
    1816         120 :       max_new_nodes_per_elem = 9 - 4;
    1817         800 :       this->reserve_nodes(static_cast<unsigned int>
    1818         400 :                           (2*static_cast<double>(this->n_nodes())));
    1819         280 :       break;
    1820             : 
    1821             : 
    1822        1838 :     case 3:
    1823             :       /*
    1824             :        * in 3D, either refine from Tet4 to Tet10 (factor = 2.5) up to
    1825             :        * Hex8 to Hex27 (something  > 3).  Since in 3D there _are_ already
    1826             :        * quite some nodes, and since we do not want to overburden the memory by
    1827             :        * a too conservative guess, use the lower bound
    1828             :        */
    1829         526 :       max_new_nodes_per_elem = 27 - 8;
    1830        3676 :       this->reserve_nodes(static_cast<unsigned int>
    1831        1838 :                           (2.5*static_cast<double>(this->n_nodes())));
    1832        1312 :       break;
    1833             : 
    1834           0 :     default:
    1835             :       // Hm?
    1836           0 :       libmesh_error_msg("Unknown mesh dimension " << this->mesh_dimension());
    1837             :     }
    1838             : 
    1839             :   // All the real work is done in the helper function
    1840        2329 :   all_increased_order_range(*this, range, max_new_nodes_per_elem,
    1841       73815 :     [full_ordered](ElemType t) {
    1842      250257 :       return Elem::second_order_equivalent_type(t, full_ordered);
    1843             :     });
    1844        2329 : }
    1845             : 
    1846             : 
    1847             : 
    1848        2153 : void UnstructuredMesh::all_complete_order_range(const SimpleRange<element_iterator> & range)
    1849             : {
    1850         614 :   LOG_SCOPE("all_complete_order()", "Mesh");
    1851             : 
    1852             :   /*
    1853             :    * The maximum number of new higher-order nodes we might be adding,
    1854             :    * for use when picking unique unique_id values later. This variable
    1855             :    * is not used unless unique ids are enabled.
    1856             :    */
    1857             :   unsigned int max_new_nodes_per_elem;
    1858             : 
    1859             :   /*
    1860             :    * for speed-up of the \p add_point() method, we
    1861             :    * can reserve memory.  Guess the number of additional
    1862             :    * nodes based on the element spatial dimensions and the
    1863             :    * total number of nodes in the mesh as an upper bound.
    1864             :    */
    1865        2153 :   switch (this->mesh_dimension())
    1866             :     {
    1867           0 :     case 1:
    1868             :       /*
    1869             :        * in 1D, there can only be order-increase from Edge2
    1870             :        * to Edge3.  Something like 1/2 of n_nodes() have
    1871             :        * to be added
    1872             :        */
    1873           0 :       max_new_nodes_per_elem = 3 - 2;
    1874           0 :       this->reserve_nodes(static_cast<unsigned int>
    1875           0 :                           (1.5*static_cast<double>(this->n_nodes())));
    1876           0 :       break;
    1877             : 
    1878         175 :     case 2:
    1879             :       /*
    1880             :        * in 2D, we typically refine from Tri3 or Tri6 to Tri7 (2.3333
    1881             :        * or 1.1667 times the nodes) but might refine from Quad4 to
    1882             :        * Quad9 (2.25 times the nodes)
    1883             :        */
    1884          50 :       max_new_nodes_per_elem = 9 - 4;
    1885         350 :       this->reserve_nodes(static_cast<unsigned int>
    1886         175 :                           (2*static_cast<double>(this->n_nodes())));
    1887         125 :       break;
    1888             : 
    1889             : 
    1890        1978 :     case 3:
    1891             :       /*
    1892             :        * in 3D, we typically refine from Tet10 to Tet14 (factor = 1.4)
    1893             :        * but may go Hex8 to Hex27 or Tet4 to Tet14 (something  > 3).
    1894             :        * Since in 3D there _are_ already quite some nodes, and since
    1895             :        * we do not want to overburden the memory by a too-conservative
    1896             :        * guess, use a moderate bound
    1897             :        */
    1898         564 :       max_new_nodes_per_elem = 27 - 8;
    1899        3956 :       this->reserve_nodes(static_cast<unsigned int>
    1900        1978 :                           (2.5*static_cast<double>(this->n_nodes())));
    1901        1414 :       break;
    1902             : 
    1903           0 :     default:
    1904             :       // Hm?
    1905           0 :       libmesh_error_msg("Unknown mesh dimension " << this->mesh_dimension());
    1906             :     }
    1907             : 
    1908             :   // All the real work is done in the helper function
    1909        2153 :   all_increased_order_range(*this, range, max_new_nodes_per_elem,
    1910      128203 :     [](ElemType t) {
    1911      472359 :       return Elem::complete_order_equivalent_type(t);
    1912             :     });
    1913        2153 : }
    1914             : 
    1915             : 
    1916             : std::size_t
    1917         161 : UnstructuredMesh::stitch_meshes (const MeshBase & other_mesh,
    1918             :                                  boundary_id_type this_mesh_boundary_id,
    1919             :                                  boundary_id_type other_mesh_boundary_id,
    1920             :                                  Real tol,
    1921             :                                  bool clear_stitched_boundary_ids,
    1922             :                                  bool verbose,
    1923             :                                  bool use_binary_search,
    1924             :                                  bool enforce_all_nodes_match_on_boundaries,
    1925             :                                  bool merge_boundary_nodes_all_or_nothing,
    1926             :                                  bool remap_subdomain_ids,
    1927             :                                  bool prepare_after_stitching)
    1928             : {
    1929          92 :   LOG_SCOPE("stitch_meshes()", "UnstructuredMesh");
    1930         161 :   return stitching_helper(&other_mesh,
    1931             :                           this_mesh_boundary_id,
    1932             :                           other_mesh_boundary_id,
    1933             :                           tol,
    1934             :                           clear_stitched_boundary_ids,
    1935             :                           verbose,
    1936             :                           use_binary_search,
    1937             :                           enforce_all_nodes_match_on_boundaries,
    1938             :                           true,
    1939             :                           merge_boundary_nodes_all_or_nothing,
    1940             :                           remap_subdomain_ids,
    1941         189 :                           prepare_after_stitching);
    1942             : }
    1943             : 
    1944             : 
    1945             : std::size_t
    1946          21 : UnstructuredMesh::stitch_surfaces (boundary_id_type boundary_id_1,
    1947             :                                    boundary_id_type boundary_id_2,
    1948             :                                    Real tol,
    1949             :                                    bool clear_stitched_boundary_ids,
    1950             :                                    bool verbose,
    1951             :                                    bool use_binary_search,
    1952             :                                    bool enforce_all_nodes_match_on_boundaries,
    1953             :                                    bool merge_boundary_nodes_all_or_nothing,
    1954             :                                    bool prepare_after_stitching)
    1955             : 
    1956             : {
    1957          21 :   return stitching_helper(nullptr,
    1958             :                           boundary_id_1,
    1959             :                           boundary_id_2,
    1960             :                           tol,
    1961             :                           clear_stitched_boundary_ids,
    1962             :                           verbose,
    1963             :                           use_binary_search,
    1964             :                           enforce_all_nodes_match_on_boundaries,
    1965             :                           /* skip_find_neighbors = */ true,
    1966             :                           merge_boundary_nodes_all_or_nothing,
    1967             :                           /* remap_subdomain_ids = */ false,
    1968          21 :                           prepare_after_stitching);
    1969             : }
    1970             : 
    1971             : 
    1972             : std::size_t
    1973         182 : UnstructuredMesh::stitching_helper (const MeshBase * other_mesh,
    1974             :                                     boundary_id_type this_mesh_boundary_id,
    1975             :                                     boundary_id_type other_mesh_boundary_id,
    1976             :                                     Real tol,
    1977             :                                     bool clear_stitched_boundary_ids,
    1978             :                                     bool verbose,
    1979             :                                     bool use_binary_search,
    1980             :                                     bool enforce_all_nodes_match_on_boundaries,
    1981             :                                     bool skip_find_neighbors,
    1982             :                                     bool merge_boundary_nodes_all_or_nothing,
    1983             :                                     bool remap_subdomain_ids,
    1984             :                                     bool prepare_after_stitching)
    1985             : {
    1986             : #ifdef DEBUG
    1987             :   // We rely on neighbor links here
    1988          52 :   MeshTools::libmesh_assert_valid_neighbors(*this);
    1989             : #endif
    1990             : 
    1991          52 :   bool is_valid_disjoint_pair_to_stitch = false;
    1992             : 
    1993             : #ifdef LIBMESH_ENABLE_PERIODIC
    1994         182 :   auto * this_db  = this->get_disjoint_neighbor_boundary_pairs();
    1995         182 :   auto * other_db = (other_mesh ? other_mesh->get_disjoint_neighbor_boundary_pairs() : nullptr);
    1996             :   const bool have_disc_bdys =
    1997         182 :     (this_db && !this_db->empty()) || (other_db && !other_db->empty());
    1998             : 
    1999          52 :   if (have_disc_bdys)
    2000             :     {
    2001          10 :       const boundary_id_type a = this_mesh_boundary_id;
    2002          10 :       const boundary_id_type b = other_mesh_boundary_id;
    2003             : 
    2004          40 :       auto get_pb = [](const PeriodicBoundaries * db, boundary_id_type id)
    2005             :         {
    2006          91 :           return db ? db->boundary(id) : nullptr;
    2007             :         };
    2008             : 
    2009             :       // this mesh
    2010          35 :       const auto * pb_this_a = get_pb(this_db, a);
    2011          35 :       const auto * pb_this_b = get_pb(this_db, b);
    2012          10 :       const bool in_this =
    2013          35 :         (pb_this_a && pb_this_a->pairedboundary == b) ||
    2014           0 :         (pb_this_b && pb_this_b->pairedboundary == a);
    2015             : 
    2016             :       // other mesh
    2017          25 :       const auto * pb_other_b = get_pb(other_db, b);
    2018          10 :       const auto * pb_other_a = get_pb(other_db, a);
    2019          10 :       const bool in_other =
    2020          35 :         (pb_other_b && pb_other_b->pairedboundary == a) ||
    2021           0 :         (pb_other_a && pb_other_a->pairedboundary == b);
    2022             : 
    2023             :       // Conflict conditions:
    2024             :       // Case 1: On "this" mesh, a or b exist but are not paired,
    2025             :       //         while the other mesh pairs them.
    2026          35 :       if (!in_this && (pb_this_a || pb_this_b) && in_other)
    2027          18 :         libmesh_error_msg("Disjoint neighbor boundary pairing mismatch: on 'this' mesh, "
    2028             :                           "boundary (" << a << " or " << b
    2029             :                           << ") exists but is not paired; on 'other' mesh the pair is present.");
    2030             : 
    2031             :       // Case 2: On "other" mesh, a or b exist but are not paired,
    2032             :       //         while this mesh pairs them.
    2033          28 :       if (!in_other && (pb_other_a || pb_other_b) && in_this)
    2034           0 :         libmesh_error_msg("Disjoint neighbor boundary pairing mismatch: on 'other' mesh, "
    2035             :                           "boundary (" << a << " or " << b
    2036             :                           << ") exists but is not paired; on 'this' mesh the pair is present.");
    2037             : 
    2038             :       // Legal conditions: either side has a correct pairing
    2039          28 :       if (in_this || in_other)
    2040           6 :         is_valid_disjoint_pair_to_stitch = true;
    2041             :     }
    2042             : #endif // LIBMESH_ENABLE_PERIODIC
    2043             : 
    2044             :   // We can't even afford any unset neighbor links here.
    2045         175 :   if (!this->is_prepared())
    2046           7 :     this->find_neighbors();
    2047             : 
    2048             :   // FIXME: make distributed mesh support efficient.
    2049             :   // Yes, we currently suck.
    2050         275 :   MeshSerializer serialize(*this);
    2051             : 
    2052             :   // *Badly*.
    2053         125 :   std::unique_ptr<MeshSerializer> serialize_other;
    2054         175 :   if (other_mesh)
    2055             :     serialize_other = std::make_unique<MeshSerializer>
    2056         220 :       (*const_cast<MeshBase *>(other_mesh));
    2057             : 
    2058         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
    2059         100 :   std::map<dof_id_type, std::vector<dof_id_type>> node_to_elems_map;
    2060             : 
    2061             :   typedef dof_id_type                     key_type;
    2062             :   typedef std::pair<const Elem *, unsigned char> val_type;
    2063             :   typedef std::pair<key_type, val_type>   key_val_pair;
    2064             :   typedef std::unordered_multimap<key_type, val_type> map_type;
    2065             :   // Mapping between all side keys in this mesh and elements+side numbers relevant to the boundary in this mesh as well.
    2066         100 :   map_type side_to_elem_map;
    2067             : 
    2068             :   // If there is only one mesh (i.e. other_mesh == nullptr), then loop over this mesh twice
    2069         175 :   if (!other_mesh)
    2070             :     {
    2071           6 :       other_mesh = this;
    2072             :     }
    2073             : 
    2074         175 :   if ((this_mesh_boundary_id  != BoundaryInfo::invalid_id) &&
    2075          50 :       (other_mesh_boundary_id != BoundaryInfo::invalid_id))
    2076             :     {
    2077         100 :       LOG_SCOPE("stitch_meshes node merging", "UnstructuredMesh");
    2078             : 
    2079             :       // While finding nodes on the boundary, also find the minimum edge length
    2080             :       // of all faces on both boundaries.  This will later be used in relative
    2081             :       // distance checks when stitching nodes.
    2082         175 :       Real h_min = std::numeric_limits<Real>::max();
    2083          50 :       bool h_min_updated = false;
    2084             : 
    2085             :       // Loop below fills in these sets for the two meshes.
    2086         100 :       std::set<dof_id_type> this_boundary_node_ids, other_boundary_node_ids;
    2087             : 
    2088             :       // Pull objects out of the loop to reduce heap operations
    2089         175 :       std::unique_ptr<const Elem> side;
    2090             : 
    2091             :       {
    2092             :         // Make temporary fixed-size arrays for loop
    2093         175 :         boundary_id_type id_array[2]         = {this_mesh_boundary_id, other_mesh_boundary_id};
    2094         175 :         std::set<dof_id_type> * set_array[2] = {&this_boundary_node_ids, &other_boundary_node_ids};
    2095         175 :         const MeshBase * mesh_array[2] = {this, other_mesh};
    2096             : 
    2097         525 :         for (unsigned i=0; i<2; ++i)
    2098             :           {
    2099             :             // First we deal with node boundary IDs.  We only enter
    2100             :             // this loop if we have at least one nodeset. Note that we
    2101             :             // do not attempt to make an h_min determination here.
    2102             :             // The h_min determination is done while looping over the
    2103             :             // Elems and checking their sides and edges for boundary
    2104             :             // information, below.
    2105         450 :             if (mesh_array[i]->get_boundary_info().n_nodeset_conds() > 0)
    2106             :               {
    2107             :                 // build_node_list() returns a vector of (node-id, bc-id) tuples
    2108       32046 :                 for (const auto & t : mesh_array[i]->get_boundary_info().build_node_list())
    2109             :                   {
    2110       31668 :                     boundary_id_type node_bc_id = std::get<1>(t);
    2111       31668 :                     if (node_bc_id == id_array[i])
    2112             :                       {
    2113        6055 :                         dof_id_type this_node_id = std::get<0>(t);
    2114        6055 :                         set_array[i]->insert( this_node_id );
    2115             :                       }
    2116             :                   }
    2117             :               }
    2118             : 
    2119             :             // Container to catch boundary IDs passed back from BoundaryInfo.
    2120         200 :             std::vector<boundary_id_type> bc_ids;
    2121             : 
    2122             :             // Pointers to boundary NodeElems encountered while looping over the entire Mesh
    2123             :             // and checking side and edge boundary ids. The Nodes associated with NodeElems
    2124             :             // may be in a boundary nodeset, but not connected to any other Elems. In this
    2125             :             // case, we also consider the "minimum node separation distance" amongst all
    2126             :             // NodeElems when determining the relevant h_min value for this mesh.
    2127         200 :             std::vector<const Elem *> boundary_node_elems;
    2128             : 
    2129        6390 :             for (auto & el : mesh_array[i]->element_ptr_range())
    2130             :               {
    2131             :                 // Now check whether elem has a face on the specified boundary
    2132       27401 :                 for (auto side_id : el->side_index_range())
    2133             :                   {
    2134             :                     bool should_stitch_this_side =
    2135       28570 :                       (el->neighbor_ptr(side_id) == nullptr) ||
    2136         140 :                       (is_valid_disjoint_pair_to_stitch &&
    2137         180 :                       mesh_array[i]->get_boundary_info().has_boundary_id(el, side_id, id_array[i]));
    2138             : 
    2139        6340 :                     if (should_stitch_this_side)
    2140             :                       {
    2141             :                         // Get *all* boundary IDs on this side, not just the first one!
    2142       12294 :                         mesh_array[i]->get_boundary_info().boundary_ids (el, side_id, bc_ids);
    2143             : 
    2144       12294 :                         if (std::find(bc_ids.begin(), bc_ids.end(), id_array[i]) != bc_ids.end())
    2145             :                           {
    2146        1624 :                             el->build_side_ptr(side, side_id);
    2147       11095 :                             for (auto & n : side->node_ref_range())
    2148        9471 :                               set_array[i]->insert(n.id());
    2149             : 
    2150        1624 :                             h_min = std::min(h_min, side->hmin());
    2151         464 :                             h_min_updated = true;
    2152             : 
    2153             :                             // This side is on the boundary, add its information to side_to_elem
    2154        1624 :                             if (skip_find_neighbors && (i==0))
    2155             :                               {
    2156         812 :                                 key_type key = el->low_order_key(side_id);
    2157         232 :                                 val_type val;
    2158         812 :                                 val.first = el;
    2159         232 :                                 val.second = cast_int<unsigned char>(side_id);
    2160             : 
    2161         812 :                                 key_val_pair kvp;
    2162         812 :                                 kvp.first = key;
    2163         232 :                                 kvp.second = val;
    2164         232 :                                 side_to_elem_map.insert (kvp);
    2165             :                               }
    2166             :                           }
    2167             : 
    2168             :                         // Also, check the edges on this side. We don't have to worry about
    2169             :                         // updating neighbor info in this case since elements don't store
    2170             :                         // neighbor info on edges.
    2171      121886 :                         for (auto edge_id : el->edge_index_range())
    2172             :                           {
    2173      109592 :                             if (el->is_edge_on_side(edge_id, side_id))
    2174             :                               {
    2175             :                                 // Get *all* boundary IDs on this edge, not just the first one!
    2176       36330 :                                 mesh_array[i]->get_boundary_info().edge_boundary_ids (el, edge_id, bc_ids);
    2177             : 
    2178       36330 :                                 if (std::find(bc_ids.begin(), bc_ids.end(), id_array[i]) != bc_ids.end())
    2179             :                                   {
    2180           0 :                                     std::unique_ptr<const Elem> edge (el->build_edge_ptr(edge_id));
    2181           0 :                                     for (auto & n : edge->node_ref_range())
    2182           0 :                                       set_array[i]->insert( n.id() );
    2183             : 
    2184           0 :                                     h_min = std::min(h_min, edge->hmin());
    2185           0 :                                     h_min_updated = true;
    2186           0 :                                   }
    2187             :                               }
    2188             :                           } // end for (edge_id)
    2189             :                       } // end if (should_stitch_this_side)
    2190             :                   } // end for (side_id)
    2191             : 
    2192             :                 // Alternatively, is this a boundary NodeElem? If so,
    2193             :                 // add it to a list of NodeElems that will later be
    2194             :                 // used to set h_min based on the minimum node
    2195             :                 // separation distance between all pairs of boundary
    2196             :                 // NodeElems.
    2197        4053 :                 if (el->type() == NODEELEM)
    2198             :                   {
    2199         396 :                     mesh_array[i]->get_boundary_info().boundary_ids(el->node_ptr(0), bc_ids);
    2200         324 :                     if (std::find(bc_ids.begin(), bc_ids.end(), id_array[i]) != bc_ids.end())
    2201             :                       {
    2202         252 :                         boundary_node_elems.push_back(el);
    2203             : 
    2204             :                         // Debugging:
    2205             :                         // libMesh::out << "Elem " << el->id() << " is a NodeElem on boundary " << id_array[i] << std::endl;
    2206             :                       }
    2207             :                   } // end if (el->type() == NODEELEM)
    2208         150 :               } // end for (el)
    2209             : 
    2210             :             // Compute the minimum node separation distance amongst
    2211             :             // all boundary NodeElem pairs.
    2212             :             {
    2213         200 :               const auto N = boundary_node_elems.size();
    2214         602 :               for (auto node_elem_i : make_range(N))
    2215        4662 :                 for (auto node_elem_j : make_range(node_elem_i+1, N))
    2216             :                   {
    2217             :                     Real node_sep =
    2218        6930 :                       (boundary_node_elems[node_elem_i]->point(0) - boundary_node_elems[node_elem_j]->point(0)).norm();
    2219             : 
    2220             :                     // We only want to consider non-coincident
    2221             :                     // boundary NodeElem pairs when determining the
    2222             :                     // minimum node separation distance.
    2223        4410 :                     if (node_sep > 0.)
    2224             :                       {
    2225        4410 :                         h_min = std::min(h_min, node_sep);
    2226        1260 :                         h_min_updated = true;
    2227             :                       }
    2228             :                   } // end for (node_elem_j)
    2229             :             } // end minimum NodeElem separation scope
    2230             :           } // end for (i)
    2231             :       } // end scope
    2232             : 
    2233         175 :       if (verbose)
    2234             :         {
    2235          14 :           libMesh::out << "In UnstructuredMesh::stitch_meshes:\n"
    2236          14 :                        << "This mesh has "  << this_boundary_node_ids.size()
    2237          14 :                        << " nodes on boundary `"
    2238          49 :                        << this->get_boundary_info().get_sideset_name(this_mesh_boundary_id)
    2239          14 :                        << "' (" << this_mesh_boundary_id  << ").\n"
    2240          14 :                        << "Other mesh has " << other_boundary_node_ids.size()
    2241          14 :                        << " nodes on boundary `"
    2242          49 :                        << other_mesh->get_boundary_info().get_sideset_name(other_mesh_boundary_id)
    2243          14 :                        << "' (" << other_mesh_boundary_id  << ").\n";
    2244             : 
    2245          49 :           if (h_min_updated)
    2246             :             {
    2247          28 :               libMesh::out << "Minimum edge length on both surfaces is " << h_min << ".\n";
    2248             :             }
    2249             :           else
    2250             :             {
    2251           0 :               libMesh::out << "No minimum edge length determined on specified surfaces." << std::endl;
    2252             :             }
    2253             :         }
    2254             : 
    2255             :       // At this point, if h_min==0 it means that there were at least two coincident
    2256             :       // nodes on the surfaces being stitched, and we don't currently support that case.
    2257             :       // (It might be possible to support, but getting it exactly right would be tricky
    2258             :       // and probably not worth the extra complications to the "normal" case.)
    2259         175 :       libmesh_error_msg_if(h_min < std::numeric_limits<Real>::epsilon(),
    2260             :                            "Coincident nodes detected on source and/or target "
    2261             :                            "surface, stitching meshes is not possible.");
    2262             : 
    2263             :       // We require nanoflann for the "binary search" (really kd-tree)
    2264             :       // option to work. If it's not available, turn that option off,
    2265             :       // warn the user, and fall back on the N^2 search algorithm.
    2266             :       if (use_binary_search)
    2267             :         {
    2268             : #ifndef LIBMESH_HAVE_NANOFLANN
    2269             :           use_binary_search = false;
    2270             :           libmesh_warning("The use_binary_search option in the "
    2271             :                           "UnstructuredMesh stitching algorithms requires nanoflann "
    2272             :                           "support. Falling back on N^2 search algorithm.");
    2273             : #endif
    2274             :         }
    2275             : 
    2276         175 :       if (!this_boundary_node_ids.empty())
    2277             :       {
    2278         175 :         if (use_binary_search)
    2279             :         {
    2280             : #ifdef LIBMESH_HAVE_NANOFLANN
    2281             :           typedef nanoflann::KDTreeSingleIndexAdaptor<nanoflann::L2_Simple_Adaptor<Real, VectorOfNodesAdaptor>,
    2282             :             VectorOfNodesAdaptor, 3, std::size_t> kd_tree_t;
    2283             : 
    2284             :           // Create the dataset needed to build the kd tree with nanoflann
    2285           0 :           std::vector<std::pair<Point, dof_id_type>> this_mesh_nodes(this_boundary_node_ids.size());
    2286             : 
    2287           0 :           for (auto [it, ctr] = std::make_tuple(this_boundary_node_ids.begin(), 0u);
    2288           0 :                it != this_boundary_node_ids.end(); ++it, ++ctr)
    2289             :           {
    2290           0 :             this_mesh_nodes[ctr].first = this->point(*it);
    2291           0 :             this_mesh_nodes[ctr].second = *it;
    2292             :           }
    2293             : 
    2294           0 :           VectorOfNodesAdaptor vec_nodes_adaptor(this_mesh_nodes);
    2295             : 
    2296           0 :           kd_tree_t this_kd_tree(3, vec_nodes_adaptor, 10);
    2297           0 :           this_kd_tree.buildIndex();
    2298             : 
    2299             :           // Storage for nearest neighbor in the loop below
    2300             :           std::size_t ret_index;
    2301             :           Real ret_dist_sqr;
    2302             : 
    2303             :           // Loop over other mesh. For each node, find its nearest neighbor in this mesh, and fill in the maps.
    2304           0 :           for (const auto & node_id : other_boundary_node_ids)
    2305             :           {
    2306           0 :             const auto & p = other_mesh->point(node_id);
    2307           0 :             const Real query_pt[] = {p(0), p(1), p(2)};
    2308           0 :             this_kd_tree.knnSearch(&query_pt[0], 1, &ret_index, &ret_dist_sqr);
    2309             : 
    2310             :             // TODO: here we should use the user's specified tolerance
    2311             :             // and the previously determined value of h_min in the
    2312             :             // distance comparison, not just TOLERANCE^2.
    2313           0 :             if (ret_dist_sqr < TOLERANCE*TOLERANCE)
    2314             :             {
    2315           0 :               node_to_node_map[this_mesh_nodes[ret_index].second] = node_id;
    2316           0 :               other_to_this_node_map[node_id] = this_mesh_nodes[ret_index].second;
    2317             :             }
    2318             :           }
    2319             : 
    2320             :           // If the two maps don't have the same size, it means one
    2321             :           // node in this mesh is the nearest neighbor of several
    2322             :           // nodes in other mesh. Since the stitching is ambiguous in
    2323             :           // this case, we throw an error.
    2324           0 :           libmesh_error_msg_if(node_to_node_map.size() != other_to_this_node_map.size(),
    2325             :                                "Error: Found multiple matching nodes in stitch_meshes");
    2326             : #endif
    2327             :         }
    2328             :         else // !use_binary_search
    2329             :         {
    2330             :           // In the unlikely event that two meshes composed entirely of
    2331             :           // NodeElems are being stitched together, we will not have
    2332             :           // selected a valid h_min value yet, and the distance
    2333             :           // comparison below will be true for essentially any two
    2334             :           // nodes. In this case we simply fall back on an absolute
    2335             :           // distance check.
    2336         175 :           if (!h_min_updated)
    2337             :             {
    2338             :               libmesh_warning("No valid h_min value was found, falling back on "
    2339             :                               "absolute distance check in the N^2 search algorithm.");
    2340           0 :               h_min = 1.;
    2341             :             }
    2342             : 
    2343             :           // Otherwise, use a simple N^2 search to find the closest matching points. This can be helpful
    2344             :           // in the case that we have tolerance issues which cause mismatch between the two surfaces
    2345             :           // that are being stitched.
    2346        3248 :           for (const auto & this_node_id : this_boundary_node_ids)
    2347             :           {
    2348        3073 :             Node & this_node = this->node_ref(this_node_id);
    2349             : 
    2350         878 :             bool found_matching_nodes = false;
    2351             : 
    2352       91546 :             for (const auto & other_node_id : other_boundary_node_ids)
    2353             :             {
    2354       88473 :               const Node & other_node = other_mesh->node_ref(other_node_id);
    2355             : 
    2356       63195 :               Real node_distance = (this_node - other_node).norm();
    2357             : 
    2358       88473 :               if (node_distance < tol*h_min)
    2359             :               {
    2360             :                 // Make sure we didn't already find a matching node!
    2361        3073 :                 libmesh_error_msg_if(found_matching_nodes,
    2362             :                                      "Error: Found multiple matching nodes in stitch_meshes");
    2363             : 
    2364        3073 :                 node_to_node_map[this_node_id] = other_node_id;
    2365        3073 :                 other_to_this_node_map[other_node_id] = this_node_id;
    2366             : 
    2367         878 :                 found_matching_nodes = true;
    2368             :               }
    2369             :             }
    2370             :           }
    2371             :         }
    2372             :       }
    2373             : 
    2374             :       // Build up the node_to_elems_map, using only one loop over other_mesh
    2375        3150 :       for (auto & el : other_mesh->element_ptr_range())
    2376             :         {
    2377             :           // For each node on the element, find the corresponding node
    2378             :           // on "this" Mesh, 'this_node_id', if it exists, and push
    2379             :           // the current element ID back onto node_to_elems_map[this_node_id].
    2380             :           // For that we will use the reverse mapping we created at
    2381             :           // the same time as the forward mapping.
    2382       29585 :           for (auto & n : el->node_ref_range())
    2383       34740 :             if (const auto it = other_to_this_node_map.find(/*other_node_id=*/n.id());
    2384        7720 :                 it != other_to_this_node_map.end())
    2385        4977 :               node_to_elems_map[/*this_node_id=*/it->second].push_back( el->id() );
    2386          75 :         }
    2387             : 
    2388         175 :       if (verbose)
    2389             :         {
    2390          14 :           libMesh::out << "In UnstructuredMesh::stitch_meshes:\n"
    2391          28 :                        << "Found " << node_to_node_map.size()
    2392          14 :                        << " matching nodes.\n"
    2393          14 :                        << std::endl;
    2394             :         }
    2395             : 
    2396         175 :       if (enforce_all_nodes_match_on_boundaries)
    2397             :         {
    2398           2 :           std::size_t n_matching_nodes = node_to_node_map.size();
    2399           2 :           std::size_t this_mesh_n_nodes = this_boundary_node_ids.size();
    2400           2 :           std::size_t other_mesh_n_nodes = other_boundary_node_ids.size();
    2401           7 :           libmesh_error_msg_if((n_matching_nodes != this_mesh_n_nodes) || (n_matching_nodes != other_mesh_n_nodes),
    2402             :                                "Error: We expected the number of nodes to match.");
    2403             :         }
    2404             : 
    2405         175 :       if (merge_boundary_nodes_all_or_nothing)
    2406             :         {
    2407           2 :           std::size_t n_matching_nodes = node_to_node_map.size();
    2408           2 :           std::size_t this_mesh_n_nodes = this_boundary_node_ids.size();
    2409           2 :           std::size_t other_mesh_n_nodes = other_boundary_node_ids.size();
    2410           7 :           if ((n_matching_nodes != this_mesh_n_nodes) || (n_matching_nodes != other_mesh_n_nodes))
    2411             :             {
    2412           0 :               if (verbose)
    2413             :                 {
    2414             :                   libMesh::out << "Skipping node merging in "
    2415             :                                   "UnstructuredMesh::stitch_meshes because not "
    2416           0 :                                   "all boundary nodes were matched."
    2417           0 :                                << std::endl;
    2418             :                 }
    2419           0 :               node_to_node_map.clear();
    2420           0 :               other_to_this_node_map.clear();
    2421           0 :               node_to_elems_map.clear();
    2422             :             }
    2423         100 :         }
    2424         150 :     }
    2425             :   else
    2426             :     {
    2427           0 :       if (verbose)
    2428             :         {
    2429           0 :           libMesh::out << "Skip node merging in UnstructuredMesh::stitch_meshes:" << std::endl;
    2430             :         }
    2431             :     }
    2432             : 
    2433         175 :   dof_id_type node_delta = this->max_node_id();
    2434         175 :   dof_id_type elem_delta = this->max_elem_id();
    2435             : 
    2436             :   unique_id_type unique_delta =
    2437             : #ifdef LIBMESH_ENABLE_UNIQUE_ID
    2438         175 :     this->parallel_max_unique_id();
    2439             : #else
    2440             :     0;
    2441             : #endif
    2442             : 
    2443             :   // If other_mesh != nullptr, then we have to do a bunch of work
    2444             :   // in order to copy it to this mesh
    2445         175 :   if (this!=other_mesh)
    2446             :     {
    2447          88 :       LOG_SCOPE("stitch_meshes copying", "UnstructuredMesh");
    2448             : 
    2449             : #ifdef LIBMESH_ENABLE_PERIODIC
    2450             :         // Copy disjoint neighbor boundary pairs (PeriodicBoundary objects)
    2451             :         // from `other_mesh` to `this` mesh
    2452         154 :         if (other_db && !other_db->empty())
    2453             :           {
    2454          21 :             for (const auto & [bdy_id, pb_ptr] : *other_db)
    2455             :               {
    2456           4 :                 const auto & pb = *pb_ptr;
    2457          14 :                 const boundary_id_type a = pb.myboundary;
    2458          14 :                 const boundary_id_type b = pb.pairedboundary;
    2459             : 
    2460          14 :                 if (this_db)
    2461             :                   {
    2462             :                     // Skip if identical pair already exists
    2463          14 :                     if (const auto * existing_pb = this_db->boundary(a))
    2464           7 :                       if ((existing_pb->myboundary == a && existing_pb->pairedboundary == b) ||
    2465           0 :                           (existing_pb->myboundary == b && existing_pb->pairedboundary == a))
    2466           5 :                         continue;
    2467             : 
    2468             :                     // If both boundary ids exist on this mesh but aren't paired here, refuse to create a new pair
    2469           2 :                     const auto & bdy_ids = this->get_boundary_info().get_boundary_ids();
    2470           4 :                     const bool a_exists = bdy_ids.count(a);
    2471           4 :                     const bool b_exists = bdy_ids.count(b);
    2472             :                     // If a and b already exist on `this`, we should be screaming and dying
    2473             :                     // unless they already have PeriodicBoundary objects connecting them too
    2474           7 :                     if (a_exists && b_exists && !this_db->boundary(a))
    2475           0 :                       libmesh_error_msg("Conflict: boundaries " << a << " and " << b
    2476             :                                         << " already exist on this mesh but are not paired.");
    2477             :                   }
    2478             : 
    2479          12 :                 this->add_disjoint_neighbor_boundary_pairs(a, b, pb.get_corresponding_pos(Point(0.0,0.0,0.0)));
    2480             :               }
    2481             :           }
    2482             : #endif // LIBMESH_ENABLE_PERIODIC
    2483             : 
    2484             : 
    2485             :       // Increment the node_to_node_map and node_to_elems_map
    2486             :       // to account for id offsets
    2487        3185 :       for (auto & pr : node_to_node_map)
    2488        3031 :         pr.second += node_delta;
    2489             : 
    2490        3185 :       for (auto & pr : node_to_elems_map)
    2491        7966 :         for (auto & entry : pr.second)
    2492        4935 :           entry += elem_delta;
    2493             : 
    2494             :       // We run into problems when the libMesh subdomain standard (the
    2495             :       // id defines the subdomain; the name was an afterthought) and
    2496             :       // the MOOSE standard (the name defines the subdomain; the id
    2497             :       // might be autogenerated) clash.
    2498             :       //
    2499             :       // Subdomain ids with the same name in both meshes are surely
    2500             :       // meant to represent the same subdomain.  We can just merge
    2501             :       // them.
    2502             :       //
    2503             :       // Subdomain ids which don't have a name in either mesh are
    2504             :       // almost surely meant to represent the same subdomain.  We'll
    2505             :       // just merge them.
    2506             :       //
    2507             :       // Subdomain ids with different names in different meshes, or
    2508             :       // names with different ids in different meshes, are trickier.
    2509             :       // For backwards compatibility we default to the old "just copy
    2510             :       // all the subdomain ids over" behavior, but if requested we'll
    2511             :       // remap any ids that appear to be clear conflicts, and we'll
    2512             :       // scream and die if we see any ids that are ambiguous due to
    2513             :       // being named in one mesh but not the other.
    2514          88 :       std::unordered_map<subdomain_id_type, subdomain_id_type> id_remapping;
    2515         154 :       if (remap_subdomain_ids)
    2516             :         {
    2517           4 :           const auto & this_map = this->get_subdomain_name_map();
    2518           4 :           const auto & other_map = other_mesh->get_subdomain_name_map();
    2519           8 :           std::unordered_map<std::string, subdomain_id_type> other_map_reversed;
    2520          28 :           for (auto & [sid, sname] : other_map)
    2521           4 :             other_map_reversed.emplace(sname, sid);
    2522             : 
    2523           8 :           std::unordered_map<std::string, subdomain_id_type> this_map_reversed;
    2524          21 :           for (auto & [sid, sname] : this_map)
    2525           2 :             this_map_reversed.emplace(sname, sid);
    2526             : 
    2527             :           // We don't require either mesh to be prepared, but that
    2528             :           // means we need to check for subdomains manually.
    2529          28 :           auto get_subdomains = [](const MeshBase & mesh) {
    2530           8 :             std::set<subdomain_id_type> all_subdomains;
    2531         368 :             for (auto & el : mesh.element_ptr_range())
    2532         236 :               all_subdomains.insert(el->subdomain_id());
    2533          28 :             return all_subdomains;
    2534             :           };
    2535             : 
    2536          18 :           const auto this_subdomains = get_subdomains(*this);
    2537          18 :           const auto other_subdomains = get_subdomains(*other_mesh);
    2538             : 
    2539          21 :           for (auto & [sid, sname] : this_map)
    2540             :             {
    2541             :               // The same name with the same id means we're fine.  The
    2542             :               // same name with another id means we remap their id to
    2543             :               // ours
    2544           2 :               if (const auto other_reverse_it = other_map_reversed.find(sname);
    2545           7 :                   other_reverse_it != other_map_reversed.end() && other_reverse_it->second != sid)
    2546           7 :                 id_remapping[other_reverse_it->second] = sid;
    2547             : 
    2548             :               // The same id with a different name, we'll get to
    2549             :               // later.  The same id without any name means we don't
    2550             :               // know what the user wants.
    2551           2 :               if (other_subdomains.count(sid) && !other_map.count(sid))
    2552           0 :                 libmesh_error_msg("Can't safely stitch with a mesh sharing subdomain id "
    2553             :                                   << sid << " but not subdomain name " << sname);
    2554             :             }
    2555             : 
    2556          14 :           subdomain_id_type next_free_id = 0;
    2557             :           // We might try to stitch empty meshes ...
    2558          14 :           if (!this_subdomains.empty())
    2559          14 :             next_free_id = *this_subdomains.rbegin() + 1;
    2560          14 :           if (!other_subdomains.empty())
    2561          14 :             next_free_id =
    2562          14 :               std::max(next_free_id,
    2563             :                        cast_int<subdomain_id_type>
    2564          23 :                          (*other_subdomains.rbegin() + 1));
    2565             : 
    2566          21 :           for (auto & [sid, sname] : other_map)
    2567             :             {
    2568             :               // At this point we've figured out any remapping
    2569             :               // necessary for an sname that we share.  And we don't
    2570             :               // need to remap any sid we don't share.
    2571           8 :               if (!this_map_reversed.count(sname))
    2572             :                 {
    2573             :                   // But if we don't have this sname and we do have this
    2574             :                   // sid then we can't just merge into that.
    2575           2 :                   if (this_subdomains.count(sid))
    2576             :                     {
    2577             :                       // If we have this sid with no name, we don't
    2578             :                       // know what the user wants.
    2579           2 :                       if (!this_map.count(sid))
    2580          19 :                         libmesh_error_msg("Can't safely stitch with a mesh sharing subdomain id "
    2581             :                                           << sid << " but under subdomain name " << sname);
    2582             : 
    2583             :                       // We have this sid under a different name, so
    2584             :                       // we just need to give the other elements a new
    2585             :                       // id.
    2586             : 
    2587             :                       // Users might have done crazy things with id
    2588             :                       // choice so let's make sure they didn't get too
    2589             :                       // crazy.
    2590           0 :                       libmesh_error_msg_if ((!this_subdomains.empty() &&
    2591             :                                              next_free_id < *this_subdomains.rbegin()) ||
    2592             :                                             (!other_subdomains.empty() &&
    2593             :                                              next_free_id < *other_subdomains.rbegin()),
    2594             :                                             "Subdomain id overflow");
    2595             : 
    2596           0 :                       id_remapping[sid] = next_free_id++;
    2597           0 :                       this->set_subdomain_name(next_free_id, sname);
    2598             :                     }
    2599             :                   // If we don't have this subdomain id, well, we're
    2600             :                   // about to, so we should have its name too.
    2601             :                   else
    2602           0 :                     this->set_subdomain_name(sid, sname);
    2603             :                 }
    2604             :             }
    2605             :         }
    2606             : 
    2607             :       // Copy mesh data. If we skip the call to find_neighbors(), the lists
    2608             :       // of neighbors will be copied verbatim from the other mesh
    2609         147 :       this->copy_nodes_and_elements(*other_mesh, skip_find_neighbors,
    2610             :                                     elem_delta, node_delta,
    2611          84 :                                     unique_delta, &id_remapping);
    2612             : 
    2613             :       // Copy BoundaryInfo from other_mesh too.  We do this via the
    2614             :       // list APIs rather than element-by-element for speed.
    2615          42 :       BoundaryInfo & boundary = this->get_boundary_info();
    2616          42 :       const BoundaryInfo & other_boundary = other_mesh->get_boundary_info();
    2617             : 
    2618       15701 :       for (const auto & t : other_boundary.build_node_list())
    2619       15512 :         boundary.add_node(std::get<0>(t) + node_delta,
    2620       15512 :                           std::get<1>(t));
    2621             : 
    2622        4263 :       for (const auto & t : other_boundary.build_side_list())
    2623        5238 :         boundary.add_side(std::get<0>(t) + elem_delta,
    2624        4074 :                           std::get<1>(t),
    2625        4074 :                           std::get<2>(t));
    2626             : 
    2627         189 :       for (const auto & t : other_boundary.build_edge_list())
    2628           0 :         boundary.add_edge(std::get<0>(t) + elem_delta,
    2629           0 :                           std::get<1>(t),
    2630           0 :                           std::get<2>(t));
    2631             : 
    2632         189 :       for (const auto & t : other_boundary.build_shellface_list())
    2633           0 :         boundary.add_shellface(std::get<0>(t) + elem_delta,
    2634           0 :                                std::get<1>(t),
    2635           0 :                                std::get<2>(t));
    2636             : 
    2637          42 :       const auto & other_ns_id_to_name = other_boundary.get_nodeset_name_map();
    2638          42 :       auto & ns_id_to_name = boundary.set_nodeset_name_map();
    2639         147 :       ns_id_to_name.insert(other_ns_id_to_name.begin(), other_ns_id_to_name.end());
    2640             : 
    2641          42 :       const auto & other_ss_id_to_name = other_boundary.get_sideset_name_map();
    2642          42 :       auto & ss_id_to_name = boundary.set_sideset_name_map();
    2643         147 :       ss_id_to_name.insert(other_ss_id_to_name.begin(), other_ss_id_to_name.end());
    2644             : 
    2645          42 :       const auto & other_es_id_to_name = other_boundary.get_edgeset_name_map();
    2646          42 :       auto & es_id_to_name = boundary.set_edgeset_name_map();
    2647         147 :       es_id_to_name.insert(other_es_id_to_name.begin(), other_es_id_to_name.end());
    2648             : 
    2649             :       // Merge other_mesh's elemset information with ours. Throw an
    2650             :       // error if this and other_mesh have overlapping elemset codes
    2651             :       // that refer to different elemset ids.
    2652         189 :       std::vector<dof_id_type> this_elemset_codes = this->get_elemset_codes();
    2653          84 :       MeshBase::elemset_type this_id_set_to_fill, other_id_set_to_fill;
    2654         217 :       for (const auto & elemset_code : other_mesh->get_elemset_codes())
    2655             :         {
    2656             :           // Get the elemset ids for this elemset_code on other_mesh
    2657          28 :           other_mesh->get_elemsets(elemset_code, other_id_set_to_fill);
    2658             : 
    2659             :           // Check that this elemset code does not already exist
    2660             :           // in this mesh, or if it does, that it has the same elemset
    2661             :           // ids associated with it.
    2662             :           //
    2663             :           // Note: get_elemset_codes() is guaranteed to return a
    2664             :           // sorted vector, so we can binary search in it.
    2665          12 :           auto it = Utility::binary_find(this_elemset_codes.begin(),
    2666             :                                          this_elemset_codes.end(),
    2667          16 :                                          elemset_code);
    2668             : 
    2669          28 :           if (it != this_elemset_codes.end())
    2670             :             {
    2671             :               // This mesh has the same elemset code. Does it refer to
    2672             :               // the same elemset ids?
    2673           0 :               this->get_elemsets(elemset_code, this_id_set_to_fill);
    2674             : 
    2675             :               // Throw an error if they don't match, otherwise we
    2676             :               // don't need to do anything
    2677           0 :               libmesh_error_msg_if(other_id_set_to_fill != this_id_set_to_fill,
    2678             :                                    "Attempted to stitch together meshes with conflicting elemset codes.");
    2679             :             }
    2680             :           else
    2681             :             {
    2682             :               // Add other_mesh's elemset code to this mesh
    2683          48 :               this->add_elemset_code(elemset_code, other_id_set_to_fill);
    2684             :             }
    2685             :         }
    2686             : 
    2687             :     } // end if (other_mesh)
    2688             : 
    2689             :   // Finally, we need to "merge" the overlapping nodes
    2690             :   // We do this by iterating over node_to_elems_map and updating
    2691             :   // the elements so that they "point" to the nodes that came
    2692             :   // from this mesh, rather than from other_mesh.
    2693             :   // Then we iterate over node_to_node_map and delete the
    2694             :   // duplicate nodes that came from other_mesh.
    2695             : 
    2696             :   {
    2697          96 :     LOG_SCOPE("stitch_meshes node updates", "UnstructuredMesh");
    2698             : 
    2699             :     // Container to catch boundary IDs passed back from BoundaryInfo.
    2700          96 :     std::vector<boundary_id_type> bc_ids;
    2701             : 
    2702        3178 :     for (const auto & [target_node_id, elem_vec] : node_to_elems_map)
    2703             :       {
    2704        3010 :         dof_id_type other_node_id = node_to_node_map[target_node_id];
    2705        3010 :         Node & target_node = this->node_ref(target_node_id);
    2706             : 
    2707        1720 :         std::size_t n_elems = elem_vec.size();
    2708        7875 :         for (std::size_t i=0; i<n_elems; i++)
    2709             :           {
    2710        4865 :             dof_id_type elem_id = elem_vec[i];
    2711        4865 :             Elem * el = this->elem_ptr(elem_id);
    2712             : 
    2713             :             // find the local node index that we want to update
    2714        3475 :             unsigned int local_node_index = el->local_node(other_node_id);
    2715        1390 :             libmesh_assert_not_equal_to(local_node_index, libMesh::invalid_uint);
    2716             : 
    2717             :             // We also need to copy over the nodeset info here,
    2718             :             // because the node will get deleted below
    2719        6255 :             this->get_boundary_info().boundary_ids(el->node_ptr(local_node_index), bc_ids);
    2720        4865 :             el->set_node(local_node_index, &target_node);
    2721        4865 :             this->get_boundary_info().add_node(&target_node, bc_ids);
    2722             :           }
    2723             :       }
    2724             :   }
    2725             : 
    2726             :   {
    2727          96 :     LOG_SCOPE("stitch_meshes node deletion", "UnstructuredMesh");
    2728        3178 :     for (const auto & [other_node_id, this_node_id] : node_to_node_map)
    2729             :       {
    2730             :         // In the case that this==other_mesh, the two nodes might be the same (e.g. if
    2731             :         // we're stitching a "sliver"), hence we need to skip node deletion in that case.
    2732        3010 :         if ((this == other_mesh) && (this_node_id == other_node_id))
    2733           0 :           continue;
    2734             : 
    2735        3010 :         this->delete_node( this->node_ptr(this_node_id) );
    2736             :       }
    2737             :   }
    2738             : 
    2739             :   // If find_neighbors() wasn't called in prepare_for_use(), we need to
    2740             :   // manually loop once more over all elements adjacent to the stitched boundary
    2741             :   // and fix their lists of neighbors.
    2742             :   // This is done according to the following steps:
    2743             :   //   1. Loop over all copied elements adjacent to the boundary using node_to_elems_map (trying to avoid duplicates)
    2744             :   //   2. Look at all their sides with a nullptr neighbor and update them using side_to_elem_map if necessary
    2745             :   //   3. Update the corresponding side in side_to_elem_map as well
    2746         168 :   if (skip_find_neighbors)
    2747             :     {
    2748          96 :       LOG_SCOPE("stitch_meshes neighbor fixes", "UnstructuredMesh");
    2749             : 
    2750             :       // Pull objects out of the loop to reduce heap operations
    2751         168 :       std::unique_ptr<const Elem> my_side, their_side;
    2752             : 
    2753          96 :       std::set<dof_id_type> fixed_elems;
    2754        3178 :       for (const auto & pr : node_to_elems_map)
    2755             :         {
    2756        1720 :           std::size_t n_elems = pr.second.size();
    2757        7875 :           for (std::size_t i=0; i<n_elems; i++)
    2758             :             {
    2759        6255 :               dof_id_type elem_id = pr.second[i];
    2760        1390 :               if (!fixed_elems.count(elem_id))
    2761             :                 {
    2762        1036 :                   Elem * el = this->elem_ptr(elem_id);
    2763         740 :                   fixed_elems.insert(elem_id);
    2764        5642 :                   for (auto s : el->side_index_range())
    2765             :                     {
    2766        4606 :                       bool has_real_neighbor = (el->neighbor_ptr(s) != nullptr);
    2767        4690 :                       bool has_disdjoint_neighbor = is_valid_disjoint_pair_to_stitch &&
    2768          84 :                       (this->get_boundary_info().has_boundary_id(el, s, this_mesh_boundary_id)
    2769          84 :                       || this->get_boundary_info().has_boundary_id(el, s, other_mesh_boundary_id));
    2770             : 
    2771        4606 :                       if (!has_real_neighbor || has_disdjoint_neighbor)
    2772             :                         {
    2773        2072 :                           key_type key = el->low_order_key(s);
    2774         592 :                           auto bounds = side_to_elem_map.equal_range(key);
    2775             : 
    2776        2072 :                           if (bounds.first != bounds.second)
    2777             :                             {
    2778             :                               // Get the side for this element
    2779         784 :                               el->side_ptr(my_side, s);
    2780             : 
    2781             :                               // Look at all the entries with an equivalent key
    2782         784 :                               while (bounds.first != bounds.second)
    2783             :                                 {
    2784             :                                   // Get the potential element
    2785         784 :                                   Elem * neighbor = const_cast<Elem *>(bounds.first->second.first);
    2786             : 
    2787             :                                   // Get the side for the neighboring element
    2788         784 :                                   const unsigned int ns = bounds.first->second.second;
    2789         784 :                                   neighbor->side_ptr(their_side, ns);
    2790             :                                   //libmesh_assert(my_side.get());
    2791             :                                   //libmesh_assert(their_side.get());
    2792             : 
    2793             :                                   // If found a match with my side
    2794             :                                   //
    2795             :                                   // We need special tests here for 1D:
    2796             :                                   // since parents and children have an equal
    2797             :                                   // side (i.e. a node), we need to check
    2798             :                                   // ns != ms, and we also check level() to
    2799             :                                   // avoid setting our neighbor pointer to
    2800             :                                   // any of our neighbor's descendants
    2801        1344 :                                   if ((*my_side == *their_side) &&
    2802        1568 :                                       (el->level() == neighbor->level()) &&
    2803         784 :                                       ((el->dim() != 1) || (ns != s)))
    2804             :                                     {
    2805             :                                       // So share a side.  Is this a mixed pair
    2806             :                                       // of subactive and active/ancestor
    2807             :                                       // elements?
    2808             :                                       // If not, then we're neighbors.
    2809             :                                       // If so, then the subactive's neighbor is
    2810             : 
    2811        1008 :                                       if (el->subactive() ==
    2812         784 :                                           neighbor->subactive())
    2813             :                                         {
    2814             :                                           // an element is only subactive if it has
    2815             :                                           // been coarsened but not deleted
    2816         448 :                                           el->set_neighbor (s,neighbor);
    2817         448 :                                           neighbor->set_neighbor(ns,el);
    2818             :                                         }
    2819           0 :                                       else if (el->subactive())
    2820             :                                         {
    2821           0 :                                           el->set_neighbor(s,neighbor);
    2822             :                                         }
    2823           0 :                                       else if (neighbor->subactive())
    2824             :                                         {
    2825           0 :                                           neighbor->set_neighbor(ns,el);
    2826             :                                         }
    2827             :                                       // It's OK to invalidate the
    2828             :                                       // bounds.first iterator here,
    2829             :                                       // as we are immediately going
    2830             :                                       // to break out of this while
    2831             :                                       // loop. bounds.first will
    2832             :                                       // therefore not be used for
    2833             :                                       // anything else.
    2834         224 :                                       side_to_elem_map.erase (bounds.first);
    2835         224 :                                       break;
    2836             :                                     }
    2837             : 
    2838           0 :                                   ++bounds.first;
    2839             :                                 }
    2840             :                             }
    2841             :                         }
    2842             :                     }
    2843             :                 }
    2844             :             }
    2845             :         }
    2846          72 :     }
    2847             : 
    2848             : #ifdef LIBMESH_ENABLE_PERIODIC
    2849             :   // Remove only the disjoint pair that was actually stitched.
    2850             :   // Safe because `is_valid_disjoint_pair_to_stitch` is true
    2851             :   // only if this exact (a,b) pair exists in the registry.
    2852             :   // Other disjoint pairs remain untouched.
    2853         168 :   if (is_valid_disjoint_pair_to_stitch)
    2854          21 :     this->remove_disjoint_boundary_pair(this_mesh_boundary_id, other_mesh_boundary_id);
    2855             : #endif
    2856             : 
    2857         168 :   if (prepare_after_stitching)
    2858             :     {
    2859             :       // We set our new neighbor pointers already
    2860          92 :       const bool old_allow_find_neighbors = this->allow_find_neighbors();
    2861          46 :       this->allow_find_neighbors(!skip_find_neighbors);
    2862             : 
    2863             :       // We haven't newly remoted any elements
    2864          92 :       const bool old_allow_remote_element_removal = this->allow_remote_element_removal();
    2865          46 :       this->allow_remote_element_removal(false);
    2866             : 
    2867         161 :       this->prepare_for_use();
    2868             : 
    2869          46 :       this->allow_find_neighbors(old_allow_find_neighbors);
    2870          46 :       this->allow_remote_element_removal(old_allow_remote_element_removal);
    2871             :     }
    2872             : 
    2873             :   // After the stitching, we may want to clear boundary IDs from element
    2874             :   // faces that are now internal to the mesh
    2875         168 :   if (clear_stitched_boundary_ids)
    2876             :     {
    2877          92 :       LOG_SCOPE("stitch_meshes clear bcids", "UnstructuredMesh");
    2878             : 
    2879         161 :       this->get_boundary_info().clear_stitched_boundary_side_ids(
    2880             :           this_mesh_boundary_id, other_mesh_boundary_id, /*clear_nodeset_data=*/true);
    2881             :     }
    2882             : 
    2883             :   // Return the number of nodes which were merged.
    2884         216 :   return node_to_node_map.size();
    2885          78 : }
    2886             : 
    2887             : 
    2888             : } // namespace libMesh

Generated by: LCOV version 1.14