https://mooseframework.inl.gov
Loading...
Searching...
No Matches
StitchMeshGenerator.C
Go to the documentation of this file.
1//* This file is part of the MOOSE framework
2//* https://mooseframework.inl.gov
3//*
4//* All rights reserved, see COPYRIGHT for full restrictions
5//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
6//*
7//* Licensed under LGPL 2.1, please see LICENSE for details
8//* https://www.gnu.org/licenses/lgpl-2.1.html
9
10#include "StitchMeshGenerator.h"
11
12#include "CastUniquePointer.h"
13#include "MooseUtils.h"
14#include "MooseMeshUtils.h"
15
16#include "libmesh/unstructured_mesh.h"
17
18#include <utility>
19
21 StitchedMeshGenerator,
22 "06/30/2026 24:00",
25
28{
30 params.addRequiredParam<std::vector<MeshGeneratorName>>("inputs", "The input MeshGenerators.");
31 params.addParam<bool>("prevent_boundary_ids_overlap",
32 true,
33 "Whether to re-number boundaries in stitched meshes to prevent merging of "
34 "unrelated boundaries");
35 params.addParam<bool>(
36 "merge_boundaries_with_same_name",
37 true,
38 "If the input meshes have boundaries with the same name (but different IDs), merge them");
39 params.addParam<bool>(
40 "subdomain_remapping",
41 true,
42 "Treat input subdomain names as primary, preserving them and remapping IDs as needed");
43 params.addParam<bool>(
44 "verbose_remapping", false, "Whether mesh subdomain remapping should have verbose output.");
45 params.addParam<bool>(
46 "verbose_stitching", false, "Whether mesh stitching should have verbose output.");
47 params.addParam<bool>(
48 "enforce_all_nodes_match_on_boundaries",
49 false,
50 "Whether to have the stitcher be very picky about the nodes being stitched.");
51 params.addParam<bool>("merge_boundary_nodes_all_or_nothing",
52 false,
53 "Whether the stitcher is set to merge all nodes or none.");
55 "Allows multiple mesh files to be stitched together to form a single mesh.");
56
57 // This is used for compatibility with TestSubGenerators
58 params.addPrivateParam<bool>("_check_inputs", true);
59 return params;
60}
61
63 : StitchMeshGeneratorBase(parameters),
64 _mesh_ptrs(getMeshes("inputs")),
65 _input_names(getParam<std::vector<MeshGeneratorName>>("inputs")),
66 _prevent_boundary_ids_overlap(getParam<bool>("prevent_boundary_ids_overlap")),
67 _merge_boundaries_with_same_name(getParam<bool>("merge_boundaries_with_same_name"))
68{
69 // Check inputs
70 if (_input_names.size() - 1 != _stitch_boundaries_pairs.size() && getParam<bool>("_check_inputs"))
71 paramError("stitch_boundaries_pairs",
72 "Can only stitch one pair of boundary per pair of mesh. We have '" +
73 std::to_string(_input_names.size()) +
74 "' meshes specified (=" + std::to_string(_input_names.size() - 1) +
75 " pairs) and " + std::to_string(_stitch_boundaries_pairs.size()) +
76 " pairs of boundaries specified");
77 for (const auto & pair : _stitch_boundaries_pairs)
78 if (pair.size() != 2)
79 paramError("stitch_boundaries_pairs",
80 "Stitched boundary pair '" + Moose::stringify(pair) +
81 "' is not of length 2, but of length: " + std::to_string(pair.size()));
82}
83
84std::unique_ptr<MeshBase>
86{
87 // Parameters
88 const auto verbose_remapping = getParam<bool>("verbose_remapping");
89
90 // We put the first mesh in a local pointer
91 std::unique_ptr<UnstructuredMesh> mesh = dynamic_pointer_cast<UnstructuredMesh>(*_mesh_ptrs[0]);
92 if (!mesh) // This should never happen until libMesh implements on-the-fly-Elem mesh types
93 mooseError("StitchMeshGenerator is only implemented for unstructured meshes");
94
95 // Reserve spaces for the other meshes (no need to store the first one another time)
96 std::vector<std::unique_ptr<UnstructuredMesh>> meshes(_mesh_ptrs.size() - 1);
97
98 // Read in all of the other meshes
99 for (MooseIndex(_mesh_ptrs) i = 1; i < _mesh_ptrs.size(); ++i)
100 meshes[i - 1] = dynamic_pointer_cast<UnstructuredMesh>(*_mesh_ptrs[i]);
101
102 // Stitch all the meshes to the first one
103 for (MooseIndex(meshes) i = 0; i < meshes.size(); i++)
104 {
105 const auto boundary_pair = _stitch_boundaries_pairs[i];
106
107 // Check the input boundaries
108 const auto first = getBoundaryIdToStitch(
109 *mesh,
110 (_input_names.size() ? _input_names[0] : "(unknown)") +
111 ((i == 0) ? "" : (" (stitched with " + std::to_string(i) + " previous meshes)")),
112 boundary_pair[0]);
113 auto second = getBoundaryIdToStitch(*meshes[i], name(), boundary_pair[1]);
114
115 const bool use_binary_search = (_algorithm == "BINARY");
116
117 // Meshes must be prepared to get the global boundary ids
118 if (!mesh->is_prepared())
119 mesh->prepare_for_use();
120 if (!meshes[i]->is_prepared())
121 meshes[i]->prepare_for_use();
122
123 // Avoid chaotic boundary merging due to overlapping ids in meshes by simply renumbering the
124 // boundaries in the meshes we are going to stitch onto the base mesh
125 // This is only done if there is an overlap
127 {
128 const auto & base_mesh_bids = mesh->get_boundary_info().get_global_boundary_ids();
129 const auto stitched_mesh_bids = meshes[i]->get_boundary_info().get_global_boundary_ids();
130
131 // Check for an overlap
132 bool overlap_found = false;
133 for (const auto & bid : stitched_mesh_bids)
134 if (base_mesh_bids.count(bid))
135 overlap_found = true;
136
137 if (overlap_found)
138 {
139 const auto max_boundary_id =
140 std::max(*base_mesh_bids.rbegin(), *stitched_mesh_bids.rbegin());
141 BoundaryID new_index = 1;
142 for (const auto bid : stitched_mesh_bids)
143 {
144 const auto new_bid = max_boundary_id + (new_index++);
145 meshes[i]->get_boundary_info().renumber_id(bid, new_bid);
146 if (bid == second)
147 second = new_bid;
148 }
149 }
150 }
151 else
152 {
153 // If we don't have renumbering, we can get into situations where the same boundary ID is
154 // associated with different boundary names. In this case when we stitch, we assign the
155 // boundary name of the first mesh to the ID everywhere on the domain. We throw a warning
156 // here to warn the user if this is the case.
157 const auto & base_mesh_bids = mesh->get_boundary_info().get_global_boundary_ids();
158 const auto & other_mesh_bids = meshes[i]->get_boundary_info().get_global_boundary_ids();
159
160 // We check if the same ID is present with different names
161 std::set<boundary_id_type> bd_id_intersection;
162 std::set_intersection(base_mesh_bids.begin(),
163 base_mesh_bids.end(),
164 other_mesh_bids.begin(),
165 other_mesh_bids.end(),
166 std::inserter(bd_id_intersection, bd_id_intersection.begin()));
167
168 for (const auto bid : bd_id_intersection)
169 {
170 const auto & sideset_name_on_first_mesh = mesh->get_boundary_info().get_sideset_name(bid);
171 const auto & sideset_name_on_second_mesh =
172 meshes[i]->get_boundary_info().get_sideset_name(bid);
173
174 if (sideset_name_on_first_mesh != sideset_name_on_second_mesh)
176 "Boundary ID ",
177 bid,
178 " corresponds to different boundary names on the input meshes! On the first "
179 "mesh it corresponds to `",
180 sideset_name_on_first_mesh,
181 "` while on the second mesh it corresponds to `",
182 sideset_name_on_second_mesh,
183 "`. The final mesh will replace boundary `",
184 sideset_name_on_second_mesh,
185 "` with `",
186 sideset_name_on_first_mesh,
187 "`. To avoid this situation, use the `prevent_boundary_ids_overlap` parameter!");
188 }
189 }
190
191 // Remap subdomains in MOOSE to tune the behavior to what we need
192 // TODO: avoid a number of global operations in subdomain ID gathering from the meshes
193 // for performance.
194 if (getParam<bool>("subdomain_remapping"))
195 {
196 const auto secondary_subdomains = MooseMeshUtils::getAllSubdomainNamesAndIDs(*meshes[i]);
197 // the free id must be present in neither mesh
198 auto next_free_id = std::max(MooseMeshUtils::getNextFreeSubdomainID(*mesh),
200
201 // Check subdomains in the secondary mesh for the remapping criteria. The remapping is
202 // gathered first then applied in a single pass, so that swapped IDs are not remapped twice
203 std::unordered_map<subdomain_id_type, subdomain_id_type> id_remapping;
204 for (const auto & [bl_name, bl_id] : secondary_subdomains)
205 {
206 subdomain_id_type new_id = bl_id;
207 // If first mesh has the same-name subdomain, we'll use its subdomainID to merge
208 if (!bl_name.empty() && MooseMeshUtils::hasSubdomainName(*mesh, bl_name))
209 new_id = MooseMeshUtils::getSubdomainID(bl_name, *mesh);
210 // If first mesh has the same ID BUT different name, change the subdomainID to avoid merging
211 else if (MooseMeshUtils::hasSubdomainID(*mesh, bl_id) &&
212 std::as_const(*mesh).subdomain_name(bl_id) != bl_name)
213 {
214 new_id = next_free_id++;
215 // the name is pre-positioned, the ID will be added to mesh after stitching with meshes[i]
216 mesh->set_subdomain_name(new_id, bl_name, true);
217 }
218
219 if (new_id != bl_id)
220 {
221 if (verbose_remapping)
222 _console << "Remapping in input mesh " << _input_names[i + 1] << " subdomain "
223 << bl_name << " (" << bl_id << ") to ID " << new_id << std::endl;
224 id_remapping[bl_id] = new_id;
225 }
226 }
227
228 if (!id_remapping.empty())
229 {
230 for (auto * const elem : meshes[i]->element_ptr_range())
231 if (const auto it = id_remapping.find(elem->subdomain_id()); it != id_remapping.end())
232 elem->subdomain_id() = it->second;
233 // The names of the remapped subdomains are already in the first mesh, under the new IDs
234 auto & secondary_name_map = meshes[i]->set_subdomain_name_map();
235 for (const auto & [old_id, _] : id_remapping)
236 secondary_name_map.erase(old_id);
237 meshes[i]->unset_has_synched_subdomain_name_map();
238 }
239 }
240
241 mesh->stitch_meshes(*meshes[i],
242 first,
243 second,
244 getParam<Real>("stitching_hmin_tolerance_factor"),
246 getParam<bool>("verbose_stitching"),
247 use_binary_search,
248 /*enforce_all_nodes_match_on_boundaries=*/
249 getParam<bool>("enforce_all_nodes_match_on_boundaries"),
250 /*merge_boundary_nodes_all_or_nothing=*/
251 getParam<bool>("merge_boundary_nodes_all_or_nothing"),
252 false /* subdomain remapping done by MOOSE*/);
253
254 // Make sure subdomain names made it across
255 // Overlaps should have been removed already
256 if (getParam<bool>("subdomain_remapping"))
257 for (const auto & [block_id, block_name] : meshes[i]->get_subdomain_name_map())
258 mesh->set_subdomain_name_map().insert(std::make_pair(block_id, block_name));
259
262 }
263
264 mesh->unset_is_prepared();
265 return dynamic_pointer_cast<MeshBase>(mesh);
266}
boundary_id_type BoundaryID
void mooseWarning(Args &&... args)
Emit a warning message with the given stringified, concatenated args.
Definition MooseError.h:345
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application.
Definition MooseError.h:311
registerMooseObject("MooseApp", StitchMeshGenerator)
registerMooseObjectRenamed("MooseApp", StitchedMeshGenerator, "06/30/2026 24:00", StitchMeshGenerator)
const ConsoleStream _console
An instance of helper class to write streams to the Console objects.
The main MOOSE class responsible for handling user-defined parameters in almost every MOOSE system.
void addParam(const std::string &name, const S &value, const std::string &doc_string)
These methods add an optional parameter and a documentation string to the InputParameters object.
void addRequiredParam(const std::string &name, const std::string &doc_string)
This method adds a parameter and documentation string to the InputParameters object that will be extr...
void addPrivateParam(const std::string &name, const T &value)
These method add a parameter to the InputParameters object which can be retrieved like any other para...
void addClassDescription(const std::string &doc_string)
This method adds a description of the class that will be displayed in the input file syntax dump.
const std::string & name() const
Get the name of the class.
Definition MooseBase.h:103
void paramError(const std::string &param, Args... args) const
Emits an error prefixed with the file and line number of the given param (from the input file) along ...
Definition MooseBase.h:457
A base class for mesh generators that stitch boundaries together.
static InputParameters validParams()
boundary_id_type getBoundaryIdToStitch(const MeshBase &mesh, const std::string &input_mg_name, const BoundaryName &bname) const
Get the boundary id from the name of a boundary to stitch.
const bool _clear_stitched_boundary_ids
Whether or not to clear (remove) the stitched boundary IDs.
const std::vector< std::vector< std::string > > _stitch_boundaries_pairs
A transformed version of _stitch_boundaries into a more logical "pairwise" structure.
const MooseEnum _algorithm
Type of algorithm used to find matching nodes (binary or exhaustive)
Allows multiple mesh files to be "stitched" together to form a single mesh.
std::vector< std::unique_ptr< MeshBase > * > _mesh_ptrs
std::unique_ptr< MeshBase > generate() override
Generate / modify the mesh.
StitchMeshGenerator(const InputParameters &parameters)
static InputParameters validParams()
const bool _merge_boundaries_with_same_name
Whether to merge boundaries if they have the same name but different boundary IDs.
const bool _prevent_boundary_ids_overlap
Whether to renumber all boundaries in stitched meshes to prevent accidental merging of sidesets with ...
const std::vector< MeshGeneratorName > & _input_names
The mesh generator inputs to read.
MeshBase & mesh
bool hasSubdomainName(const MeshBase &input_mesh, const SubdomainName &name)
Whether a particular subdomain name exists in the mesh.
std::set< std::pair< SubdomainName, SubdomainID > > getAllSubdomainNamesAndIDs(const libMesh::MeshBase &mesh)
Get all subdomain names and ids from a mesh.
bool hasSubdomainID(const MeshBase &input_mesh, const SubdomainID &id)
Whether a particular subdomain ID exists in the mesh.
void mergeBoundaryIDsWithSameName(MeshBase &mesh)
Merges the boundary IDs of boundaries that have the same names but different IDs.
SubdomainID getNextFreeSubdomainID(MeshBase &input_mesh)
Checks input mesh and returns max(block ID) + 1, which represents a block ID that is not currently in...
SubdomainID getSubdomainID(const SubdomainName &subdomain_name, const MeshBase &mesh)
Gets the subdomain ID associated with the given SubdomainName.
std::string stringify(const T &t)
conversion to string
Definition Conversion.h:65