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

Generated by: LCOV version 1.14