https://mooseframework.inl.gov
Loading...
Searching...
No Matches
ReferenceResidualConvergence.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// MOOSE includes
13#include "FEProblemBase.h"
14#include "Executioner.h"
15#include "NonlinearSystemBase.h"
16#include "TaggingInterface.h"
17#include "AuxiliarySystem.h"
18#include "MooseVariableScalar.h"
19#include "NonlinearSystem.h"
20
21#include "libmesh/petsc_vector.h"
22
24
27{
30
32 "Check the convergence of a problem with respect to a user-supplied reference solution."
33 " Replaces ReferenceResidualProblem, currently still used in conjunction with it.");
34
35 return params;
36}
37
39 : DefaultNonlinearConvergence(parameters),
41 _norm_type_enum(getParam<MooseEnum>("normalization_type")),
42 _accept_mult(getParam<Real>("acceptable_multiplier")),
43 _accept_iters(getParam<unsigned int>("acceptable_iterations")),
44 _nl_sys_num(_fe_problem.solverSysNum(getParam<SolverSystemName>("solver_sys"))),
45 _residual_vector(nullptr),
46 _reference_vector(nullptr),
47 _zero_ref_type(
48 getParam<MooseEnum>("zero_reference_residual_treatment").getEnum<ZeroReferenceType>()),
49 _unscale_the_residual(getParam<bool>("unscale_the_residual")),
50 _reference_vector_tag_id(Moose::INVALID_TAG_ID)
51{
52 if (_fe_problem.numNonlinearSystems() > 1 && !isParamSetByUser("solver_sys"))
53 paramError("solver_sys",
54 "Reference residual problem does not currently support multiple nonlinear systems "
55 "in a single Convergence object. Multiple Convergence objects can be used, one for "
56 "each nonlinear system, via the 'solver_sys' parameter.");
57
58 if (parameters.isParamValid("residual_vector"))
59 {
60 const auto residual_vector_tag_id =
61 _fe_problem.getVectorTagID(getParam<TagName>("residual_vector"));
64 }
65 else
67
68 if (parameters.isParamValid("reference_vector"))
69 {
70 _reference_vector_tag_id = _fe_problem.getVectorTagID(getParam<TagName>("reference_vector"));
73 }
74 else
76 "No `reference_vector` is provided, thus the Reference Residual convergence method will "
77 "revert to default tolerance checking. `reference_vector` will become a required parameter "
78 "on June 1st, 2027. If you are using `ReferenceResidualProblem`, either provide a "
79 "reference_vector or use a standard problem type (e.g., remove "
80 "Problem/type=ReferenceResidualProblem from your input file). If you are using "
81 "`ReferenceResidualConvergence`, either provide a reference_vector or utilize "
82 "`DefaultNonlinearConvergence` instead.");
83
84 if (_norm_type_enum == "LOCAL_L2")
85 {
87 _local_norm = true;
88 }
89 else if (_norm_type_enum == "GLOBAL_L2")
90 {
92 _local_norm = false;
93 }
94 else if (_norm_type_enum == "LOCAL_LINF")
95 {
97 _local_norm = true;
98 }
99 else if (_norm_type_enum == "GLOBAL_LINF")
100 {
102 _local_norm = false;
103 }
104 else
105 mooseAssert(false, "This point should not be reached.");
106
107 if (_local_norm && !parameters.isParamValid("reference_vector"))
108 paramError("reference_vector", "If local norm is used, a reference_vector must be provided.");
109}
110
116
117void
119{
121 // If no refernce_vector is provided, just revert to DefaultNonlinearConvergence behavior
123 return;
124
125 auto & nonlinear_sys = nonlinearSystem();
126 auto & s = nonlinear_sys.system();
127
128 // If the user provides reference_vector, that implies that they want the
129 // individual variables compared against their reference quantities in the
130 // tag vector. The code depends on having _soln_var_names populated,
131 // so fill that out if they didn't specify solution_variables.
132 for (const auto var_num : make_range(s.n_vars()))
133 _soln_var_names.push_back(s.variable_name(var_num));
134 const auto n_soln_vars = nonlinear_sys.nVariables();
135
136 const auto converge_on = getParam<std::vector<NonlinearVariableName>>("converge_on");
137 if (!converge_on.empty())
138 {
139 _converge_on_var.assign(n_soln_vars, false);
140 for (std::size_t i = 0; i < n_soln_vars; ++i)
141 for (const auto & c : converge_on)
143 {
144 _converge_on_var[i] = true;
145 break;
146 }
147 }
148 else
149 _converge_on_var.assign(n_soln_vars, true);
150
151 unsigned int num_variables_in_groups = 0;
152 for (const auto i : index_range(_group_variables))
153 {
154 num_variables_in_groups += _group_variables[i].size();
155 if (_group_variables[i].size() == 1)
156 paramError("group_variables",
157 "variable ",
158 _group_variables[i][0],
159 " is not grouped with other variables.");
160 }
161
162 // If no groups, size = n_soln_vars
163 unsigned int n_groups = n_soln_vars - num_variables_in_groups + _group_variables.size();
164 _group_ref_resid.resize(n_groups);
165 _group_resid.resize(n_groups);
166 _group_names.resize(n_groups);
167 _converge_on_group.assign(n_groups, true);
168 _scaling_factors.resize(n_soln_vars);
169
170 // Check to make sure variables aren't in multiple groups
172 {
173 std::set<std::string> check_duplicate;
174 for (const auto i : index_range(_group_variables))
175 for (const auto j : index_range(_group_variables[i]))
176 check_duplicate.insert(_group_variables[i][j]);
177
178 if (check_duplicate.size() != num_variables_in_groups)
179 paramError("group_variables", "A variable cannot be included in multiple groups.");
180 }
181
182 _soln_vars.clear();
183 for (const auto i : make_range(n_soln_vars))
184 {
185 bool found_match = false;
186 for (const auto var_num : make_range(s.n_vars()))
187 if (_soln_var_names[i] == s.variable_name(var_num))
188 {
189 _soln_vars.push_back(var_num);
190 found_match = true;
191 break;
192 }
193
194 if (!found_match)
195 mooseError("Could not find solution variable '",
197 "' in system '",
198 s.name(),
199 "'.");
200 }
201
202 unsigned int ungroup_index = 0;
204 ungroup_index = _group_variables.size();
205
206 // Determine which group each variable belongs to
207 _group_index.resize(n_soln_vars);
208 _is_var_grouped.assign(n_soln_vars, false);
209 for (const auto i : index_range(_soln_vars))
210 {
212 {
213 for (const auto j : index_range(_group_variables))
214 if (std::find(_group_variables[j].begin(),
215 _group_variables[j].end(),
216 s.variable_name(_soln_vars[i])) != _group_variables[j].end())
217 {
218 if (!_converge_on_var[i])
219 paramError("converge_on",
220 "You added variable '",
222 "' to a group but excluded it from the convergence check. This is not "
223 "permitted.");
224
225 _group_index[i] = j;
226 _is_var_grouped[i] = true;
227 break;
228 }
229
230 if (!_is_var_grouped[i])
231 {
232 _group_index[i] = ungroup_index;
233 ungroup_index++;
234 }
235 }
236 else
237 _group_index[i] = i;
238 }
239
240 // Check for variable groups containing both field and scalar variables
241 for (const auto i : index_range(_group_variables))
242 {
243 unsigned int num_scalar_vars = 0;
244 unsigned int num_field_vars = 0;
245 if (_group_variables[i].size() > 1)
246 {
247 for (const auto j : index_range(_group_variables[i]))
248 for (const auto var_num : make_range(s.n_vars()))
249 if (_group_variables[i][j] == s.variable_name(var_num))
250 {
251 if (nonlinear_sys.isScalarVariable(_soln_vars[var_num]))
252 ++num_scalar_vars;
253 else
254 ++num_field_vars;
255 break;
256 }
257 }
258 if (num_scalar_vars > 0 && num_field_vars > 0)
259 paramWarning("group_variables",
260 "standard variables and scalar variables are grouped together in group ",
261 i);
262 }
263
264 for (const auto i : index_range(_group_names))
265 {
266 // Accumulate names for a given group
267 std::vector<NonlinearVariableName> names;
268 for (const auto j : index_range(_group_index))
269 if (_group_index[j] == i)
270 {
271 names.push_back(_soln_var_names[j]);
273 }
274 if (names.size() == 0)
275 mooseError("Internal error, something is wrong with variable grouping");
276 else if (names.size() == 1)
277 _group_names[i] = names[0];
278 else
279 {
280 _group_names[i] = "(";
281 for (const auto j : index_range(names))
282 {
283 _group_names[i] += names[j];
284 if (j != names.size() - 1)
285 _group_names[i] += ", ";
286 }
287 _group_names[i] += ")";
288 }
289 }
290
291 const auto & var_abs_tol = getParam<std::map<std::string, Real>>("variable_nl_abs_tol");
292 for (const auto & [var_name, abs_tol] : var_abs_tol)
293 {
294 if (std::find(_soln_var_names.begin(), _soln_var_names.end(), var_name) ==
295 _soln_var_names.end())
296 paramError("variable_nl_abs_tol",
297 "Variable '",
298 var_name,
299 "' is not a variable of nonlinear system '",
300 s.name(),
301 "'.");
302 if (abs_tol < 0)
303 paramError("variable_nl_abs_tol",
304 "The absolute tolerance of variable '",
305 var_name,
306 "' must be non-negative.");
307 }
308
309 // A group is checked against one residual norm, so its variables must share one tolerance:
310 // either all of them have the same variable_nl_abs_tol entry, or none has an entry
311 _group_abs_tol.assign(n_groups, std::nullopt);
312 std::vector<bool> group_seen(n_groups, false);
313 for (const auto i : index_range(_soln_var_names))
314 {
315 const auto group = _group_index[i];
316 const auto it = var_abs_tol.find(_soln_var_names[i]);
317 const auto var_tol = it == var_abs_tol.end() ? std::nullopt : std::optional<Real>(it->second);
318 if (!group_seen[group])
319 {
320 _group_abs_tol[group] = var_tol;
321 group_seen[group] = true;
322 }
323 else if (var_tol != _group_abs_tol[group])
324 paramError("variable_nl_abs_tol",
325 "The variables in group ",
326 _group_names[group],
327 " must all have the same absolute tolerance.");
328 }
329}
330
331Real
332ReferenceResidualConvergence::groupAbsTol(const std::size_t group, const Real abs_tol) const
333{
334 return _group_abs_tol[group] ? *_group_abs_tol[group] : abs_tol;
335}
336
337void
339{
340 // If no reference_vector is provided, this method is completely skipped
341
342 auto & nonlinear_sys = nonlinearSystem();
343 auto & s = nonlinear_sys.system();
344
345 for (const auto i : index_range(_scaling_factors))
346 if (nonlinear_sys.isScalarVariable(_soln_vars[i]))
347 _scaling_factors[i] = nonlinear_sys.getScalarVariable(0, _soln_vars[i]).scalingFactor();
348 else
349 _scaling_factors[i] = nonlinear_sys.getVariable(/*tid*/ 0, _soln_vars[i]).scalingFactor();
350
351 std::fill(_group_resid.begin(), _group_resid.end(), 0.0);
352 std::fill(_group_ref_resid.begin(), _group_ref_resid.end(), 0.0);
353
354 // With a variational inequality (VI) solver, the residual at degrees of freedom in the active
355 // set of constraints (those held at a bound) is not driven to zero: there the bound constraint
356 // holds in place of the residual equation. Exclude those entries from the residual norms,
357 // matching the norm PETSc uses for its own VI convergence test.
358 std::unique_ptr<NumericVector<Number>> inactive_constraint_set_residual;
359 SNES snes = nonlinear_sys.getSNES();
360 PetscBool is_vi;
361 LibmeshPetscCallA(
362 _fe_problem.comm().get(),
363 PetscObjectTypeCompareAny((PetscObject)snes, &is_vi, SNESVINEWTONRSLS, SNESVINEWTONSSLS, ""));
364 if (is_vi)
365 {
366 Vec x, f;
367 IS active_set;
368 LibmeshPetscCallA(_fe_problem.comm().get(), SNESGetSolution(snes, &x));
369 LibmeshPetscCallA(_fe_problem.comm().get(), SNESGetFunction(snes, &f, nullptr, nullptr));
370 LibmeshPetscCallA(_fe_problem.comm().get(), SNESVIGetActiveSetIS(snes, x, f, &active_set));
371 inactive_constraint_set_residual = _residual_vector->clone();
372 LibmeshPetscCallA(
373 _fe_problem.comm().get(),
374 VecISSet(cast_ref<PetscVector<Number> &>(*inactive_constraint_set_residual).vec(),
375 active_set,
376 0));
377 LibmeshPetscCallA(_fe_problem.comm().get(), ISDestroy(&active_set));
378 }
379 const auto & residual =
380 inactive_constraint_set_residual ? *inactive_constraint_set_residual : *_residual_vector;
381
382 for (const auto i : index_range(_soln_vars))
383 {
384 if (_converge_on_var[i])
385 {
386 const auto group = _group_index[i];
387
388 // Prepare residual
389 auto resid = Utility::pow<2>(s.calculate_norm(residual, _soln_vars[i], _norm_type));
391 {
392 mooseAssert(_scaling_factors[i], "Scaling factor must not be zero");
393 resid /= Utility::pow<2>(_scaling_factors[i]);
394 }
395 _group_resid[group] += resid;
396
397 // Prepare reference residual. If local norm, this is actually the ratio of the residual
398 // dividied by the reference at all DOF
399 Real ref_resid;
400 if (_local_norm)
401 {
402 mooseAssert(residual.size() == (*_reference_vector).size(),
403 "Sizes of nonlinear RHS and reference vector should be the same.");
404 mooseAssert((*_reference_vector).size(), "Reference vector must be provided.");
405 auto ref = _reference_vector->clone();
406 // Add a tiny number to the reference to prevent a divide by zero.
407 ref->add(std::numeric_limits<Number>::min());
408 auto div = residual.clone();
409 *div /= *ref;
410 ref_resid = Utility::pow<2>(s.calculate_norm(*div, _soln_vars[i], _norm_type));
411 }
412 else
413 {
414 ref_resid =
415 Utility::pow<2>(s.calculate_norm(*_reference_vector, _soln_vars[i], _norm_type));
417 ref_resid /= Utility::pow<2>(_scaling_factors[i]);
418 }
419 _group_ref_resid[group] += ref_resid;
420 }
421 }
422
423 for (const auto i : index_range(_group_resid))
424 {
425 _group_resid[i] = std::sqrt(_group_resid[i]);
426 _group_ref_resid[i] = std::sqrt(_group_ref_resid[i]);
427 }
428}
429
430void
432{
433 // If no refernce_vector is provided, just revert to DefaultNonlinearConvergence behavior
435 return;
436
438
439 std::ostringstream out;
440 out << _name << ": " << _norm_type_enum << " Reference Residual check\n";
441
442 if (_group_names.size() > 0)
443 {
444 // Set residual and references so that they always have a spacing of 8
445 out << std::setprecision(2) << std::scientific;
446 unsigned int var_space = 0;
447 for (const auto i : index_range(_group_names))
448 if (_group_names[i].size() > var_space)
449 var_space = _group_names[i].size();
450
451 for (const auto i : index_range(_group_names))
452 {
453 if (_converge_on_group[i])
454 {
455 // Print residual
456 out << " " << std::setw(var_space + 8) << std::right << _group_names[i] + "-> res: "
457 << (_group_resid[i] < groupAbsTol(i, _nl_abs_tol) ? COLOR_YELLOW : COLOR_DEFAULT)
458 << std::setw(8) << _group_resid[i] << COLOR_DEFAULT;
459
460 // Print res/ref ratio
461 if (_local_norm)
462 out << " local res/ref: "
463 << (_group_resid[i] / _group_ref_resid[i] < _nl_rel_tol ? COLOR_GREEN : COLOR_DEFAULT)
464 << std::setw(8) << _group_ref_resid[i] << COLOR_DEFAULT << "\n";
465 else
466 {
467 // Print reference first if not local norm
468 out << " ref: " << std::setw(8) << _group_ref_resid[i] << " res/ref: ";
469
470 if (!_group_ref_resid[i])
471 out << _group_resid[i] << "\n";
472 else
473 out << (_group_resid[i] / _group_ref_resid[i] < _nl_rel_tol ? COLOR_GREEN
474 : COLOR_DEFAULT)
475 << std::setw(8) << _group_resid[i] / _group_ref_resid[i] << COLOR_DEFAULT << "\n";
476 }
477 }
478 }
479 _console << out.str() << std::flush;
480 }
481}
482
483bool
485 const Real /*fnorm*/,
486 const Real default_abs_tol,
487 const Real default_rel_tol,
488 const Real /*initial_residual_before_preset_bcs*/,
489 const Real multiplier)
490{
491 // Convergence is checked via:
492 // 1) Ratio of group residual to reference is less than relative tolerance
493 // 2) if group residual is less than absolute tolerance, from variable_nl_abs_tol if given, else
494 // the generic absolute tolerance
495 // 3) if group reference residual is zero and:
496 // 3.1) Convergence type is ZERO_TOLERANCE and group residual is zero (rare, but possible, and
497 // historically implemented that way)
498 // 3.2) Convergence type is RELATIVE_TOLERANCE and group residual
499 // is less than relative tolerance. (i.e., using the relative tolerance to check group
500 // convergence in an absolute way)
501
502 const Real rel_tol = default_rel_tol * multiplier;
503 bool convergedRelative = true;
504 for (const auto i : index_range(_group_resid))
505 {
506 const Real abs_tol = groupAbsTol(i, default_abs_tol) * multiplier;
507 convergedRelative &=
508 ((!_local_norm && _group_resid[i] < _group_ref_resid[i] * rel_tol) ||
509 (_local_norm && _group_ref_resid[i] < rel_tol) || _group_resid[i] < abs_tol ||
510 (!_group_ref_resid[i] && !_local_norm &&
513 _group_resid[i] <= rel_tol))));
514 }
515 return convergedRelative;
516}
517
518bool
520 const Real fnorm,
521 const Real ref_norm,
522 const Real rel_tol,
523 const Real abs_tol,
524 std::ostringstream & oss)
525{
526 // If no refernce_vector is provided, just revert to DefaultNonlinearConvergence behavior
529 n_iter, fnorm, ref_norm, rel_tol, abs_tol, oss);
530
531 if (checkConvergenceIndividVars(fnorm, abs_tol, rel_tol, ref_norm))
532 {
533 oss << "Converged normally";
534 return true;
535 }
536 else if (n_iter >= _accept_iters &&
537 checkConvergenceIndividVars(fnorm, abs_tol, rel_tol, ref_norm, _accept_mult))
538 {
539 oss << " Converged due a larger acceptable tolerance due to `acceptible_multiplier` after "
540 "`acceptible_iterations`.";
541 _console << " Converged due to ACCEPTABLE tolerances" << std::endl;
542 return true;
543 }
544
545 return false;
546}
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application.
Definition MooseError.h:311
void mooseDeprecated(Args &&... args)
Emit a deprecated code/feature message with the given stringified, concatenated args.
Definition MooseError.h:363
registerMooseObject("MooseApp", ReferenceResidualConvergence)
void ErrorVector unsigned int
const ConsoleStream _console
An instance of helper class to write streams to the Console objects.
Default nonlinear convergence criteria for FEProblem.
virtual void initialSetup() override
Gets called at the beginning of the simulation before this object is asked to do its job.
Real _nl_rel_tol
Nonlinear relative tolerance (modifiable by setRelativeTolerance)
virtual bool checkResidualConvergence(const unsigned int n_iter, const Real fnorm, const Real ref_norm, const Real rel_tol, const Real abs_tol, std::ostringstream &oss)
Check the absolute and relative convergence of the nonlinear solution.
Real _nl_abs_tol
Nonlinear absolute tolerance (modifiable by setAbsoluteTolerance)
virtual std::size_t numNonlinearSystems() const override
NonlinearSystemBase & getNonlinearSystemBase(const unsigned int sys_num)
The main MOOSE class responsible for handling user-defined parameters in almost every MOOSE system.
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.
bool isParamValid(const std::string &name) const
This method returns parameters that have been initialized in one fashion or another,...
const InputParameters & parameters() const
Get the parameters of the object.
Definition MooseBase.h:131
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
bool isParamSetByUser(const std::string &name) const
Test if the supplied parameter is set by a user, as opposed to not set or set to default.
Definition MooseBase.h:205
const std::string & _name
The name of this class.
Definition MooseBase.h:381
This is a "smart" enum class intended to replace many of the shortcomings in the C++ enum type It sho...
Definition MooseEnum.h:55
Nonlinear system to be solved.
virtual NumericVector< Number > & RHS()=0
Uses a reference residual to define relative convergence criteria.
virtual void nonlinearConvergenceSetup() override
Performs setup necessary for each call to checkConvergence.
ZeroReferenceType
Container for convergence treatment when the reference residual is zero.
ReferenceResidualConvergence(const InputParameters &parameters)
virtual bool checkResidualConvergence(const unsigned int n_iter, const Real fnorm, const Real ref_norm, const Real rel_tol, const Real abs_tol, std::ostringstream &oss) override
Check the absolute and relative convergence of the nonlinear solution.
enum ReferenceResidualConvergence::ZeroReferenceType _zero_ref_type
std::vector< bool > _is_var_grouped
Vector of bools to signify if variable is in a group.
const NumericVector< Number > * _reference_vector
The vector storing the reference residual values.
bool checkConvergenceIndividVars(const Real fnorm, const Real default_abs_tol, const Real default_rel_tol, const Real initial_residual_before_preset_bcs, const Real multiplier=1)
Check the convergence by comparing the norm of each variable's residual separately against its refere...
const bool _unscale_the_residual
Bool to unscale the residual before convergence checks and screen output.
const MooseEnum _norm_type_enum
Enum holding the normalization type.
virtual void initialSetup() override
Gets called at the beginning of the simulation before this object is asked to do its job.
void updateReferenceResidual()
Computes the reference residuals for each group.
const unsigned int _nl_sys_num
Nonlinear system to which this convergence object applies.
virtual NonlinearSystemBase & nonlinearSystem() override
Nonlinear system whose convergence state should be checked.
libMesh::FEMNormType _norm_type
Container for normalization type.
std::vector< NonlinearVariableName > _group_names
std::vector< unsigned int > _group_index
Group number index for each variable.
std::vector< Real > _scaling_factors
Local storage for the scaling factors applied to each of the variables to apply to _ref_resid_vars.
std::vector< bool > _converge_on_var
Flag for each solution variable or group being in 'converge_on'.
const NumericVector< Number > * _residual_vector
The optional vector storing the reference residual values.
TagID _reference_vector_tag_id
The reference vector tag id.
std::vector< std::optional< Real > > _group_abs_tol
Absolute tolerance of each group from variable_nl_abs_tol, unset for groups that use the default abso...
bool _local_norm
Flag to optionally perform normalization of residual by reference residual before or after L2 norm is...
Real groupAbsTol(const std::size_t group, const Real abs_tol) const
The absolute tolerance of group group, where abs_tol applies to groups without a variable_nl_abs_tol ...
std::vector< NonlinearVariableName > _soln_var_names
Interface class shared between ReferenceResidualProblem and ReferenceResidualConvergence.
static InputParameters validParams()
bool _use_group_variables
True if any variables are grouped.
std::vector< std::vector< NonlinearVariableName > > _group_variables
Name of variables that are grouped together to check convergence.
void paramWarning(const std::string &param, Args... args) const
virtual TagID getVectorTagID(const TagName &tag_name) const
Get a TagID from a TagName.
Definition SubProblem.C:195
virtual NumericVector< Number > & getVector(const std::string &name)
Get a raw NumericVector by name.
Definition SystemBase.C:933
virtual std::unique_ptr< NumericVector< T > > clone() const=0
const Parallel::Communicator & comm() const
bool globCompare(const std::string &candidate, const std::string &pattern, std::size_t c, std::size_t p)
Definition MooseUtils.C:995
MOOSE now contains C++17 code, so give a reasonable error message stating what the user can do to add...