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