21#include "libmesh/petsc_vector.h"
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.");
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),
49 _unscale_the_residual(getParam<bool>(
"unscale_the_residual")),
50 _reference_vector_tag_id(
Moose::INVALID_TAG_ID)
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.");
60 const auto residual_vector_tag_id =
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.");
105 mooseAssert(
false,
"This point should not be reached.");
108 paramError(
"reference_vector",
"If local norm is used, a reference_vector must be provided.");
126 auto & s = nonlinear_sys.system();
132 for (
const auto var_num : make_range(s.n_vars()))
134 const auto n_soln_vars = nonlinear_sys.nVariables();
136 const auto converge_on = getParam<std::vector<NonlinearVariableName>>(
"converge_on");
137 if (!converge_on.empty())
140 for (std::size_t i = 0; i < n_soln_vars; ++i)
141 for (
const auto & c : converge_on)
151 unsigned int num_variables_in_groups = 0;
159 " is not grouped with other variables.");
163 unsigned int n_groups = n_soln_vars - num_variables_in_groups +
_group_variables.size();
173 std::set<std::string> check_duplicate;
178 if (check_duplicate.size() != num_variables_in_groups)
179 paramError(
"group_variables",
"A variable cannot be included in multiple groups.");
183 for (
const auto i : make_range(n_soln_vars))
185 bool found_match =
false;
186 for (
const auto var_num : make_range(s.n_vars()))
195 mooseError(
"Could not find solution variable '",
202 unsigned int ungroup_index = 0;
220 "You added variable '",
222 "' to a group but excluded it from the convergence check. This is not "
243 unsigned int num_scalar_vars = 0;
244 unsigned int num_field_vars = 0;
248 for (
const auto var_num : make_range(s.n_vars()))
251 if (nonlinear_sys.isScalarVariable(
_soln_vars[var_num]))
258 if (num_scalar_vars > 0 && num_field_vars > 0)
260 "standard variables and scalar variables are grouped together in group ",
267 std::vector<NonlinearVariableName> names;
274 if (names.size() == 0)
275 mooseError(
"Internal error, something is wrong with variable grouping");
276 else if (names.size() == 1)
281 for (
const auto j : index_range(names))
284 if (j != names.size() - 1)
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)
299 "' is not a variable of nonlinear system '",
304 "The absolute tolerance of variable '",
306 "' must be non-negative.");
312 std::vector<bool> group_seen(n_groups,
false);
317 const auto var_tol = it == var_abs_tol.end() ? std::nullopt : std::optional<Real>(it->second);
318 if (!group_seen[group])
321 group_seen[group] =
true;
325 "The variables in group ",
327 " must all have the same absolute tolerance.");
343 auto & s = nonlinear_sys.system();
346 if (nonlinear_sys.isScalarVariable(
_soln_vars[i]))
358 std::unique_ptr<NumericVector<Number>> inactive_constraint_set_residual;
359 SNES snes = nonlinear_sys.getSNES();
363 PetscObjectTypeCompareAny((PetscObject)snes, &is_vi, SNESVINEWTONRSLS, SNESVINEWTONSSLS,
""));
369 LibmeshPetscCallA(
_fe_problem.
comm().
get(), SNESGetFunction(snes, &f,
nullptr,
nullptr));
370 LibmeshPetscCallA(
_fe_problem.
comm().
get(), SNESVIGetActiveSetIS(snes, x, f, &active_set));
374 VecISSet(cast_ref<PetscVector<Number> &>(*inactive_constraint_set_residual).vec(),
379 const auto & residual =
380 inactive_constraint_set_residual ? *inactive_constraint_set_residual : *
_residual_vector;
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.");
407 ref->add(std::numeric_limits<Number>::min());
408 auto div = residual.clone();
439 std::ostringstream out;
445 out << std::setprecision(2) << std::scientific;
446 unsigned int var_space = 0;
456 out <<
" " << std::setw(var_space + 8) << std::right <<
_group_names[i] +
"-> res: "
462 out <<
" local res/ref: "
479 _console << out.str() << std::flush;
486 const Real default_abs_tol,
487 const Real default_rel_tol,
489 const Real multiplier)
502 const Real rel_tol = default_rel_tol * multiplier;
503 bool convergedRelative =
true;
506 const Real abs_tol =
groupAbsTol(i, default_abs_tol) * multiplier;
515 return convergedRelative;
524 std::ostringstream & oss)
529 n_iter, fnorm, ref_norm, rel_tol, abs_tol, oss);
533 oss <<
"Converged normally";
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;
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application.
void mooseDeprecated(Args &&... args)
Emit a deprecated code/feature message with the given stringified, concatenated args.
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.
static InputParameters validParams()
FEProblemBase & _fe_problem
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)
const InputParameters & parameters() const
Get the parameters of the object.
void paramError(const std::string ¶m, Args... args) const
Emits an error prefixed with the file and line number of the given param (from the input file) along ...
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.
const std::string & _name
The name of this class.
This is a "smart" enum class intended to replace many of the shortcomings in the C++ enum type It sho...
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 ¶meters)
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 unsigned int _accept_iters
const NumericVector< Number > * _reference_vector
The vector storing the reference residual values.
std::vector< unsigned int > _soln_vars
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< bool > _converge_on_group
std::vector< unsigned int > _group_index
Group number index for each variable.
static InputParameters validParams()
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'.
std::vector< Real > _group_ref_resid
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...
std::vector< Real > _group_resid
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 ¶m, Args... args) const
virtual TagID getVectorTagID(const TagName &tag_name) const
Get a TagID from a TagName.
virtual NumericVector< Number > & getVector(const std::string &name)
Get a raw NumericVector by name.
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)
MOOSE now contains C++17 code, so give a reasonable error message stating what the user can do to add...