https://mooseframework.inl.gov
Terminator.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 "libmesh/libmesh_config.h"
11 
12 #ifdef LIBMESH_HAVE_FPARSER
13 
14 #include "Terminator.h"
15 #include "MooseApp.h"
16 #include "MooseEnum.h"
17 #include "Executioner.h"
18 
19 registerMooseObject("MooseApp", Terminator);
20 
23 {
25  params.addClassDescription("Requests termination of the current solve based on the evaluation of"
26  " a parsed logical expression of the Postprocessor value(s).");
27  params.addRequiredCustomTypeParam<std::string>(
28  "expression",
29  "FunctionExpression",
30  "FParser expression to process Postprocessor values into a boolean value. "
31  "Termination of the simulation occurs when this returns true.");
32  MooseEnum failModeOption("HARD SOFT NONE", "HARD");
33  params.addParam<MooseEnum>(
34  "fail_mode",
35  failModeOption,
36  "Abort entire simulation (HARD), just the current time step (SOFT), or not at all (NONE).");
37  params.addParam<std::string>("message",
38  "An optional message to be output instead of the default message "
39  "when the termination condition is triggered");
40 
41  MooseEnum errorLevel("INFO WARNING ERROR NONE", "INFO");
42  errorLevel.addDocumentation("INFO", "Output an information message once.");
43  errorLevel.addDocumentation("WARNING", "Output a warning message once.");
44  errorLevel.addDocumentation("ERROR",
45  "Throw a MOOSE error, resulting in the termination of the run.");
46  errorLevel.addDocumentation("NONE", "No message will be printed.");
47  params.addParam<MooseEnum>(
48  "error_level",
49  errorLevel,
50  "The error level for the message. A level of ERROR will always lead to a hard "
51  "termination of the entire simulation.");
52  return params;
53 }
54 
56  : GeneralUserObject(parameters),
57  _fail_mode(getParam<MooseEnum>("fail_mode").getEnum<FailMode>()),
58  _msg_type(getParam<MooseEnum>("error_level").getEnum<MessageType>()),
59  _pp_names(),
60  _pp_values(),
61  _expression(getParam<std::string>("expression")),
62  _fp()
63 {
64  // sanity check the parameters
66  paramError("error_level",
67  "Setting the error level to ERROR always causes a hard failure, which is "
68  "incompatible with `fail_mode=SOFT or NONE`.");
69  if (_msg_type == MessageType::NONE && isParamValid("message"))
70  paramError("error_level",
71  "Cannot specify `error_level=NONE` together with the `message` parameter.");
73  paramWarning("error_level",
74  "With the current error level and fail mode settings, the terminator will not "
75  "error or output.");
76 
77  // build the expression object
78  if (_fp.ParseAndDeduceVariables(_expression, _pp_names) >= 0)
79  mooseError(std::string("Invalid function\n" + _expression + "\nin Terminator.\n") +
80  _fp.ErrorMsg());
81 
82  _pp_num = _pp_names.size();
83  _pp_values.resize(_pp_num);
84 
85  // get all necessary postprocessors
86  for (unsigned int i = 0; i < _pp_num; ++i)
88 
89  _params.resize(_pp_num);
90 }
91 
92 void
94 {
95  // Check execution schedule of the postprocessors
97  for (const auto i : make_range(_pp_num))
98  // Make sure the postprocessor is executed at least as often
99  {
100  const auto & pp_exec = _fe_problem.getUserObjectBase(_pp_names[i], _tid).getExecuteOnEnum();
101  for (const auto & flag : getExecuteOnEnum())
102  if (!pp_exec.isValueSet(flag) && flag != EXEC_FINAL)
103  paramWarning("expression",
104  "Postprocessor '" + _pp_names[i] + "' is not executed on " + flag.name() +
105  ", which it really should be to serve in the criterion "
106  "expression for throwing.");
107  }
108 }
109 
110 void
112 {
113  std::string message;
114  if (!isParamValid("message"))
115  {
116  message = "Terminator '" + name() + "' is ";
117  if (_fail_mode == FailMode::HARD)
118  message += "causing the execution to terminate.\n";
119  else if (_fail_mode == FailMode::SOFT)
120  message += "causing a time step cutback by marking the current step as failed.\n";
121  else
122  message += "outputting a message due to the criterion being met";
123  }
124  else
125  message = getParam<std::string>("message");
126 
127  switch (_msg_type)
128  {
129  case MessageType::INFO:
130  mooseInfoRepeated(message);
131  break;
132 
134  mooseWarning(message);
135  break;
136 
137  case MessageType::ERROR:
138  mooseError(message);
139  break;
140 
141  default:
142  break;
143  }
144 }
145 
146 void
148 {
149  // copy current Postprocessor values into the FParser parameter buffer
150  for (unsigned int i = 0; i < _pp_num; ++i)
151  _params[i] = *(_pp_values[i]);
152 
153  // request termination of the run or timestep in case the expression evaluates to true
154  if (_fp.Eval(_params.data()) != 0)
155  {
156  handleMessage();
157  if (_fail_mode == FailMode::HARD)
159  else if (_fail_mode == FailMode::SOFT)
160  {
161  // Within a nonlinear solve, trigger a solve fail
165  // Outside of a solve, trigger a time step fail
166  else
168  }
169  }
170 }
171 
172 #endif
virtual void initialSetup() override
Gets called at the beginning of the simulation before this object is asked to do its job...
Definition: Terminator.C:93
enum Terminator::MessageType _msg_type
static InputParameters validParams()
Terminator(const InputParameters &parameters)
Definition: Terminator.C:55
const ExecFlagType & getCurrentExecuteOnFlag() const
Return/set the current execution flag.
registerMooseObject("MooseApp", Terminator)
void failStep()
Mark the current solve as failed due to external conditions.
std::vector< std::string > _pp_names
Postprocessor names.
Definition: Terminator.h:61
void mooseInfoRepeated(Args &&... args)
Emit an informational message with the given stringified, concatenated args.
Definition: MooseError.h:377
The main MOOSE class responsible for handling user-defined parameters in almost every MOOSE system...
std::vector< Real > _params
Fparser parameter buffer.
Definition: Terminator.h:76
void handleMessage()
handle output of the optional message
Definition: Terminator.C:111
void setFailNextNonlinearConvergenceCheck()
Skip further residual evaluations and fail the next nonlinear convergence check(s) ...
virtual const std::string & name() const
Get the name of the class.
Definition: MooseBase.h:57
void mooseWarning(Args &&... args) const
Emits a warning prefixed with object name and type.
MooseApp & getMooseApp() const
Get the MooseApp this class is associated with.
Definition: MooseBase.h:45
std::string _expression
Expression of the criterion, to be parsed for evaluation.
Definition: Terminator.h:70
bool isParamValid(const std::string &name) const
Test if the supplied parameter is valid.
std::vector< const PostprocessorValue * > _pp_values
Postprocessor values.
Definition: Terminator.h:67
virtual void terminateSolve()
Allow objects to request clean termination of the solve.
Definition: Problem.h:37
const ExecFlagEnum & getExecuteOnEnum() const
Return the execute on MultiMooseEnum for this object.
MessageType
What logging level the terminator message is output with.
Definition: Terminator.h:58
enum Terminator::FailMode _fail_mode
This is a "smart" enum class intended to replace many of the shortcomings in the C++ enum type It sho...
Definition: MooseEnum.h:33
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 ...
This Userobject requests termination of the current solve based on the values of Postprocessors (and ...
Definition: Terminator.h:38
const ExecFlagType EXEC_LINEAR
Definition: Moose.C:29
Executioner * getExecutioner() const
Retrieve the Executioner for this App.
Definition: MooseApp.C:2118
static InputParameters validParams()
Definition: Terminator.C:22
virtual const PostprocessorValue & getPostprocessorValueByName(const PostprocessorName &name) const
Retrieve the value of the Postprocessor.
const ExecFlagType EXEC_NONLINEAR
Definition: Moose.C:31
FEProblemBase & _fe_problem
Reference to the FEProblemBase for this user object.
Definition: UserObject.h:211
FixedPointSolve & fixedPointSolve()
Definition: Executioner.h:124
const THREAD_ID _tid
Thread ID of this postprocessor.
Definition: UserObject.h:218
IntRange< T > make_range(T beg, T end)
void mooseError(Args &&... args) const
Emits an error prefixed with object name and type.
void addRequiredCustomTypeParam(const std::string &name, const std::string &custom_type, const std::string &doc_string)
These methods add an option parameter and with a customer type to the InputParameters object...
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...
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 paramWarning(const std::string &param, Args... args) const
Emits a warning prefixed with the file and line number of the given param (from the input file) along...
const UserObject & getUserObjectBase(const std::string &name, const THREAD_ID tid=0) const
Get the user object by its name.
FailMode
What action the terminator takes when the criteria is met.
Definition: Terminator.h:55
virtual void execute() override
Execute method.
Definition: Terminator.C:147
FunctionParserBase< Real > _fp
Fparser object.
Definition: Terminator.h:73
const ExecFlagType EXEC_FINAL
Definition: Moose.C:44
unsigned int _pp_num
Definition: Terminator.h:64