https://mooseframework.inl.gov
Loading...
Searching...
No Matches
NodalConstraint.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 "NodalConstraint.h"
11
12// MOOSE includes
13#include "Assembly.h"
14#include "DisplacedProblem.h"
15#include "MooseMesh.h"
16#include "MooseVariableFE.h"
17#include "SubProblem.h"
18#include "SystemBase.h"
19
20#include "libmesh/compare_elems_by_level.h"
21#include "libmesh/distributed_mesh.h"
22#include "libmesh/null_output_iterator.h"
23#include "libmesh/parallel_elem.h"
24#include "libmesh/parallel_node.h"
25#include "libmesh/sparse_matrix.h"
26
27#include <algorithm>
28
31{
33 MooseEnum formulationtype("penalty kinematic", "penalty");
34 params.addParam<MooseEnum>("formulation",
35 formulationtype,
36 "Formulation used to calculate constraint - penalty or kinematic.");
37 params.addParam<NonlinearVariableName>("variable_secondary",
38 "The name of the variable for the secondary nodes, if it "
39 "is different from the primary nodes' variable");
40 return params;
41}
42
44 : Constraint(parameters),
47 this, true, Moose::VarKindType::VAR_SOLVER, Moose::VarFieldType::VAR_FIELD_STANDARD),
48 _var(_sys.getFieldVariable<Real>(_tid, parameters.get<NonlinearVariableName>("variable"))),
49 _var_secondary(_sys.getFieldVariable<Real>(
50 _tid,
51 isParamValid("variable_secondary")
52 ? parameters.get<NonlinearVariableName>("variable_secondary")
53 : parameters.get<NonlinearVariableName>("variable"))),
54 _u_secondary(_var_secondary.dofValuesNeighbor()),
55 _u_primary(_var.dofValues())
56{
59
60 MooseEnum temp_formulation = getParam<MooseEnum>("formulation");
61 if (temp_formulation == "penalty")
63 else if (temp_formulation == "kinematic")
65 else
66 mooseError("Formulation must be either Penalty or Kinematic");
67}
68
69std::vector<dof_id_type>
71 const std::vector<dof_id_type> & node_ids)
72{
73 const auto & node_to_elem_map = mesh.nodeToElemMap();
74 auto * const distributed_mesh = dynamic_cast<libMesh::DistributedMesh *>(&mesh.getMesh());
75
76 // local reference to the retained elements for this mesh, so we don't have to look it up in the
77 // map every time
78 auto & retained_elems = _retained_elems[&mesh];
79
80 // Elements connected to these nodes may already be remote on a distributed mesh, so gather
81 // gather one locally available connected element for each node before rebuilding the connectivity
82 // map.
83 if (distributed_mesh)
84 {
85 // Mesh adaptation may delete elements retained by a previous invocation. Remove their raw
86 // pointers from DistributedMesh before replacing them with the current connected elements.
87 distributed_mesh->clear_extra_ghost_elems(retained_elems);
88 retained_elems.clear();
89
90 std::set<Elem *, libMesh::CompareElemIdsByLevel> elems_to_ghost;
91 std::set<Node *> nodes_to_ghost;
92
93 // Loop over each node, and find one element connected to it.
94 for (const auto node_id : node_ids)
95 {
96 const auto node_to_elem_pair = node_to_elem_map.find(node_id);
97#ifndef NDEBUG
98 // Debugging check should be per node (inside the node loop)
99 bool someone_found_elem = false;
100#endif
101
102 if (node_to_elem_pair != node_to_elem_map.end())
103 for (const auto elem_id : node_to_elem_pair->second)
104 if (auto * const elem = mesh.queryElemPtr(elem_id))
105 {
106 elems_to_ghost.insert(elem);
107 for (const auto n : make_range(elem->n_nodes()))
108 nodes_to_ghost.insert(elem->node_ptr(n));
109#ifndef NDEBUG
110 someone_found_elem = true;
111#endif
112 break; // Only need one element to retain the node
113 }
114#ifndef NDEBUG
115 // gather through all processors to make sure at least one processor found an element for this
116 // node
117 mesh.getMesh().comm().max(someone_found_elem);
118 mooseAssert(someone_found_elem || node_ids.empty(), "Missing entry in node to elem map");
119#endif
120 }
121
122 // Send nodes first since elements need them.
123 mesh.getMesh().comm().allgather_packed_range(&mesh.getMesh(),
124 nodes_to_ghost.begin(),
125 nodes_to_ghost.end(),
127 mesh.getMesh().comm().allgather_packed_range(&mesh.getMesh(),
128 elems_to_ghost.begin(),
129 elems_to_ghost.end(),
131
132 // Rebuild the node-to-element map after gathering the remote mesh entities.
133 mesh.update();
134 }
135
136 // After rebuilding connectivity, select one canonical element ID per node.
137 std::vector<dof_id_type> elem_ids;
138 for (const auto node_id : node_ids)
139 {
140 // Reacquire the iterator after mesh.update().
141 const auto node_to_elem_pair = node_to_elem_map.find(node_id);
142 if (node_to_elem_pair == node_to_elem_map.end() || node_to_elem_pair->second.empty())
143 mooseError("Couldn't find any elements connected to primary node");
144
145 const auto elem_id =
146 node_to_elem_pair->second.front(); // Just need one element to retain the node, like above,
147 // just need one element to be ghosted
148 elem_ids.push_back(elem_id);
149
150 // Keep gathered elements when libMesh later deletes unneeded remote elements.
151 if (distributed_mesh)
152 {
153 auto * const elem = mesh.elemPtr(elem_id);
154 distributed_mesh->add_extra_ghost_elem(elem);
155 retained_elems.insert(elem);
156 }
157 }
158
159 // We only need one element per node.
160 mooseAssert(node_ids.size() == elem_ids.size(),
161 "Mismatch between number of primary nodes and connected elements");
162
163 return elem_ids;
164}
165
166std::vector<dof_id_type>
167NodalConstraint::localSecondaryNodes(const std::vector<dof_id_type> & node_ids) const
168{
169 const auto & lm_mesh = _mesh.getMesh();
170
171 std::vector<dof_id_type> local_nodes;
172 for (const auto node_id : node_ids)
173 {
174 // The node may be remote, and therefore absent, on a distributed mesh.
175 const Node * const node = lm_mesh.query_node_ptr(node_id);
176 if (node && node->processor_id() == lm_mesh.processor_id())
177 local_nodes.push_back(node_id);
178 }
179
180 return local_nodes;
181}
182
183void
193
194void
195NodalConstraint::ghostConnectedElems(const std::vector<dof_id_type> & node_ids)
196{
197 // The gather is collective, so every process takes part in it even when it holds no secondary
198 // node of its own.
199 const auto elem_ids = gatherAndRetainConnectedElems(_fe_problem.mesh(), node_ids);
200
201 // Only a process that owns a secondary node assembles this constraint, and so only it reads the
202 // primary values. Ghosting the primary elements anywhere else would ghost degrees of freedom
203 // that are never used.
204 if (!_connected_nodes.empty())
205 for (const auto elem_id : elem_ids)
207
209 {
210 const auto displaced_elem_ids =
212 if (displaced_elem_ids != elem_ids)
213 mooseError("Reference and displaced meshes selected different primary elements");
214 }
215}
216
217void
219{
220 // _subproblem is the displaced problem when this constraint uses the displaced mesh, which is
221 // where its variables (and therefore the dof indices the assembly loops iterate over) live.
224
225 // Derived classes index per-primary data by position in the primary node list (weights, for
226 // instance), so a primary node that contributes no dof would silently shift every subsequent
227 // entry. reinitNodes() drops nodes that are not semilocal or that the variable is not defined
228 // on, so compare the counts. Only processes that own a secondary node call this method, and
229 // each such process ghosts every primary node. So a mismatch between the number of nodes and
230 // the number of degrees of freedom here means the variable is missing on one of the primary
231 // nodes.
232 const auto n_primary_dofs = _var.dofIndices().size();
233 if (n_primary_dofs != _primary_node_vector.size())
234 mooseError("Found ",
235 n_primary_dofs,
236 " primary degrees of freedom for ",
238 " primary nodes. Nodal constraints index per-primary data by position in the "
239 "primary node list, so variable '",
240 _var.name(),
241 "' must be defined on every primary node.");
242}
243
244void
245NodalConstraint::computeResidual(const NumericVector<Number> & residual)
246{
247 if ((_weights.size() == 0) && (_primary_node_vector.size() == 1))
248 _weights.push_back(1.0);
249
250 std::vector<dof_id_type> primarydof = _var.dofIndices();
251 std::vector<dof_id_type> secondarydof = _var_secondary.dofIndicesNeighbor();
252
253 DenseVector<Number> re(primarydof.size());
254 DenseVector<Number> neighbor_re(secondarydof.size());
255
256 re.zero();
257 neighbor_re.zero();
258
259 for (_i = 0; _i < secondarydof.size(); ++_i)
260 {
261 for (_j = 0; _j < primarydof.size(); ++_j)
262 {
263 switch (_formulation)
264 {
265 case Moose::Penalty:
268 break;
269 case Moose::Kinematic:
270 // Transfer the current residual of the secondary node to the primary nodes
271 Real res = residual(secondarydof[_i]);
272 re(_j) += res * _weights[_j];
273 neighbor_re(_i) +=
275 break;
276 }
277 }
278 }
279 // We've already applied scaling
280 if (!primarydof.empty())
281 addResiduals(_assembly, re, primarydof, /*scaling_factor=*/1);
282 if (!secondarydof.empty())
283 addResiduals(_assembly, neighbor_re, secondarydof, /*scaling_factor=*/1);
284}
285
286void
287NodalConstraint::computeJacobian(const SparseMatrix<Number> & jacobian)
288{
289 if ((_weights.size() == 0) && (_primary_node_vector.size() == 1))
290 _weights.push_back(1.0);
291
292 // Calculate the dense-block Jacobian entries
293 std::vector<dof_id_type> secondarydof = _var_secondary.dofIndicesNeighbor();
294 std::vector<dof_id_type> primarydof = _var.dofIndices();
295
296 DenseMatrix<Number> Ken(primarydof.size(), secondarydof.size());
297 DenseMatrix<Number> Kne(secondarydof.size(), primarydof.size());
298
299 Ken.zero();
300 Kne.zero();
301
302 // The primary-primary and secondary-secondary couplings are both diagonal under either
303 // formulation, so they are accumulated here and cached one entry at a time below. Inserting
304 // them as dense blocks would instead demand sparsity for entries that are always zero, and two
305 // primary nodes are only coupled in the sparsity pattern when they happen to share an element.
306 std::vector<Number> Kee_diag(primarydof.size(), 0.);
307 std::vector<Number> Knn_diag(secondarydof.size(), 0.);
308
309 for (_i = 0; _i < secondarydof.size(); ++_i)
310 {
311 for (_j = 0; _j < primarydof.size(); ++_j)
312 {
313 switch (_formulation)
314 {
315 case Moose::Penalty:
319 // Accumulated over the primary nodes to match the secondary residual, which sums one
320 // contribution per primary node.
322 break;
323 case Moose::Kinematic:
324 Kee_diag[_j] = 0.;
325 Ken(_j, _i) += jacobian(secondarydof[_i], primarydof[_j]) * _weights[_j];
326 Kne(_i, _j) += -jacobian(secondarydof[_i], primarydof[_j]) / primarydof.size() +
328 Knn_diag[_i] += -jacobian(secondarydof[_i], secondarydof[_i]) / primarydof.size() +
330 break;
331 }
332 }
333 }
334 addJacobian(_assembly, Ken, primarydof, secondarydof, _var.scalingFactor());
335 addJacobian(_assembly, Kne, secondarydof, primarydof, _var_secondary.scalingFactor());
336
337 for (const auto j : index_range(primarydof))
338 addJacobianElement(_assembly, Kee_diag[j], primarydof[j], primarydof[j], _var.scalingFactor());
339
340 for (const auto i : index_range(secondarydof))
342 _assembly, Knn_diag[i], secondarydof[i], secondarydof[i], _var_secondary.scalingFactor());
343}
344
345void
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application.
Definition MooseError.h:311
std::shared_ptr< DisplacedProblem > displaced_problem
Base class for all Constraint types.
Definition Constraint.h:20
static InputParameters validParams()
Definition Constraint.C:15
virtual std::shared_ptr< const DisplacedProblem > getDisplacedProblem() const
virtual MooseMesh & mesh() override
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.
const std::string & name() const
Get the name of the class.
Definition MooseBase.h:103
This is a "smart" enum class intended to replace many of the shortcomings in the C++ enum type It sho...
Definition MooseEnum.h:55
MooseMesh wraps a libMesh::Mesh object and enhances its capabilities by caching additional data and s...
Definition MooseMesh.h:95
MeshBase & getMesh()
Accessor for the underlying libMesh Mesh object.
Definition MooseMesh.C:3581
void scalingFactor(const std::vector< Real > &factor)
Set the scaling factor for this variable.
void addMooseVariableDependency(MooseVariableFieldBase *var)
Call this function to add the passed in MooseVariableFieldBase as a variable that this object depends...
const std::vector< dof_id_type > & dofIndicesNeighbor() const final
Get neighbor DOF indices for currently selected element.
const std::vector< dof_id_type > & dofIndices() const final
Get local DoF indices.
Intermediate base class that ties together all the interfaces for getting MooseVariables with the Moo...
Enhances MooseVariableInterface interface provide values from neighbor elements.
virtual void computeResidual() override final
Computes the nodal residual.
Moose::ConstraintFormulationType _formulation
Specifies formulation type used to apply constraints.
std::vector< dof_id_type > localSecondaryNodes(const std::vector< dof_id_type > &node_ids) const
Select the nodes of 'node_ids' that this process owns, which are the secondary nodes it is responsibl...
unsigned int _i
Counter for primary and secondary nodes.
virtual Real computeQpResidual(Moose::ConstraintType type)=0
This is the virtual that derived classes should override for computing the residual on neighboring el...
std::vector< dof_id_type > _primary_node_vector
node IDs of the primary node
NodalConstraint(const InputParameters &parameters)
std::vector< dof_id_type > _connected_nodes
node IDs connected to the primary node (secondary nodes)
void updateConstrainedNodes()
Rebuild the constrained node lists and the ghosting they require.
std::vector< Real > _weights
When the secondary node is constrained to move as a linear combination of the primary nodes,...
std::vector< dof_id_type > gatherAndRetainConnectedElems(MooseMesh &mesh, const std::vector< dof_id_type > &node_ids)
Gather and retain elements connected to the provided nodes on the provided mesh.
std::map< MooseMesh *, std::set< Elem * > > _retained_elems
Elements this constraint retained on each distributed mesh during the previous mesh update.
static InputParameters validParams()
virtual void updateConnectivity()
Fill _primary_node_vector and _connected_nodes for this constraint.
virtual Real computeQpJacobian(Moose::ConstraintJacobianType type)=0
This is the virtual that derived classes should override for computing the Jacobian on neighboring el...
MooseVariable & _var
virtual void computeJacobian() override final
Computes the jacobian for the current element.
MooseVariable & _var_secondary
void reinitConstraintNodes()
Reinitialize the primary and secondary nodes on the SubProblem that owns this constraint's variables.
void ghostConnectedElems(const std::vector< dof_id_type > &node_ids)
Gather and retain one element per node on the reference mesh, and on the displaced mesh when one exis...
THREAD_ID _tid
The thread ID for this kernel.
MooseMesh & _mesh
Reference to this Kernel's mesh object.
Assembly & _assembly
Reference to this Kernel's assembly object.
SubProblem & _subproblem
Reference to this kernel's SubProblem.
FEProblemBase & _fe_problem
Reference to this kernel's FEProblemBase.
void reinitNodesNeighbor(const std::vector< dof_id_type > &nodes, const THREAD_ID tid)
void reinitNodes(const std::vector< dof_id_type > &nodes, const THREAD_ID tid)
virtual void addGhostedElem(dof_id_type elem_id)=0
Will make sure that all dofs connected to elem_id are ghosted to this processor.
void addJacobianElement(Assembly &assembly, Real value, dof_id_type row_index, dof_id_type column_index, Real scaling_factor)
Add into a single Jacobian element.
void addJacobian(Assembly &assembly, const Residuals &residuals, const Indices &dof_indices, Real scaling_factor)
Add the provided residual derivatives into the Jacobian for the provided dof indices.
void addResiduals(Assembly &assembly, const Residuals &residuals, const Indices &dof_indices, Real scaling_factor)
Add the provided incoming residuals corresponding to the provided dof indices.
virtual void clear_extra_ghost_elems()
MeshBase & mesh
MOOSE now contains C++17 code, so give a reasonable error message stating what the user can do to add...
@ Penalty
Definition MooseTypes.h:978
@ Kinematic
Definition MooseTypes.h:979
@ Primary
Definition MooseTypes.h:819
@ Secondary
Definition MooseTypes.h:818
@ SecondarySecondary
Definition MooseTypes.h:857
@ SecondaryPrimary
Definition MooseTypes.h:858
@ PrimarySecondary
Definition MooseTypes.h:859
@ PrimaryPrimary
Definition MooseTypes.h:860