https://mooseframework.inl.gov
Public Types | Public Member Functions | Static Public Member Functions | Protected Types | Protected Member Functions | Protected Attributes | Static Protected Attributes | List of all members
FunctionParserUtils< is_ad > Class Template Reference

#include <FunctionParserUtils.h>

Inheritance diagram for FunctionParserUtils< is_ad >:
[legend]

Public Types

typedef GenericSymFunction< is_ad > SymFunction
 Shorthand for an autodiff function parser object. More...
 
typedef std::shared_ptr< SymFunctionSymFunctionPtr
 Shorthand for an smart pointer to an autodiff function parser object. More...
 

Public Member Functions

 FunctionParserUtils (const InputParameters &parameters)
 
void setParserFeatureFlags (SymFunctionPtr &) const
 apply input parameters to internal feature flags of the parser object More...
 

Static Public Member Functions

static InputParameters validParams ()
 

Protected Types

enum  FailureMethod { FailureMethod::nan, FailureMethod::nan_warning, FailureMethod::error, FailureMethod::exception }
 Enum for failure method. More...
 

Protected Member Functions

GenericReal< is_ad > evaluate (SymFunctionPtr &, const std::string &object_name="")
 Evaluate FParser object and check EvalError. More...
 
GenericReal< is_ad > evaluate (SymFunctionPtr &, const std::vector< GenericReal< is_ad >> &, const std::string &object_name="")
 Evaluate FParser object and check EvalError. More...
 
void addFParserConstants (SymFunctionPtr &parser, const std::vector< std::string > &constant_names, const std::vector< std::string > &constant_expressions) const
 add constants (which can be complex expressions) to the parser object More...
 
virtual void functionsOptimize (SymFunctionPtr &parsed_function)
 run FPOptimizer on the parsed function More...
 
void parsedFunctionSetup (SymFunctionPtr &function, const std::string &expression, const std::string &variables, const std::vector< std::string > &constant_names, const std::vector< std::string > &constant_expressions, const libMesh::Parallel::Communicator &comm) const
 Performs setup steps on a SymFunction. More...
 
template<>
void functionsOptimize (SymFunctionPtr &parsed_function)
 
template<>
void functionsOptimize (SymFunctionPtr &parsed_function)
 

Protected Attributes

enum FunctionParserUtils::FailureMethod _evalerror_behavior
 
const Real _quiet_nan
 appropriate not a number value to return More...
 
std::vector< GenericReal< is_ad > > _func_params
 Array to stage the parameters passed to the functions when calling Eval. More...
 
const Real _epsilon
 fuzzy comparison tolerance More...
 
bool _enable_jit
 feature flags More...
 
bool _enable_ad_cache
 
bool _disable_fpoptimizer
 
bool _enable_auto_optimize
 

Static Protected Attributes

static const char * _eval_error_msg []
 table of FParser eval error codes More...
 

Detailed Description

template<bool is_ad = false>
class FunctionParserUtils< is_ad >

Definition at line 54 of file FunctionParserUtils.h.

Member Typedef Documentation

◆ SymFunction

template<bool is_ad = false>
typedef GenericSymFunction<is_ad> FunctionParserUtils< is_ad >::SymFunction

Shorthand for an autodiff function parser object.

Definition at line 62 of file FunctionParserUtils.h.

◆ SymFunctionPtr

template<bool is_ad = false>
typedef std::shared_ptr<SymFunction> FunctionParserUtils< is_ad >::SymFunctionPtr

Shorthand for an smart pointer to an autodiff function parser object.

Definition at line 65 of file FunctionParserUtils.h.

Member Enumeration Documentation

◆ FailureMethod

template<bool is_ad = false>
enum FunctionParserUtils::FailureMethod
strongprotected

Enum for failure method.

Enumerator
nan 
nan_warning 
error 
exception 

Definition at line 116 of file FunctionParserUtils.h.

116 { nan, nan_warning, error, exception } _evalerror_behavior;
enum FunctionParserUtils::FailureMethod _evalerror_behavior

Constructor & Destructor Documentation

◆ FunctionParserUtils()

template<bool is_ad>
FunctionParserUtils< is_ad >::FunctionParserUtils ( const InputParameters parameters)

Definition at line 59 of file FunctionParserUtils.C.

60  : _enable_jit(parameters.isParamValid("enable_jit") && parameters.get<bool>("enable_jit")),
61  _enable_ad_cache(parameters.get<bool>("enable_ad_cache")),
62  _disable_fpoptimizer(parameters.get<bool>("disable_fpoptimizer")),
63  _enable_auto_optimize(parameters.get<bool>("enable_auto_optimize") && !_disable_fpoptimizer),
64  _evalerror_behavior(parameters.get<MooseEnum>("evalerror_behavior").getEnum<FailureMethod>()),
65  _quiet_nan(std::numeric_limits<Real>::quiet_NaN()),
66  _epsilon(parameters.get<Real>("epsilon"))
67 {
68 #ifndef LIBMESH_HAVE_FPARSER_JIT
69  if (_enable_jit)
70  {
71  mooseWarning("Tried to enable FParser JIT but libmesh does not have it compiled in.");
72  _enable_jit = false;
73  }
74 #endif
75 }
std::vector< std::pair< R1, R2 > > get(const std::string &param1, const std::string &param2) const
Combine two vector parameters into a single vector of pairs.
void mooseWarning(Args &&... args)
Emit a warning message with the given stringified, concatenated args.
Definition: MooseError.h:357
T getEnum() const
get the current value cast to the enum type T
Definition: MooseEnum.h:151
bool _enable_jit
feature flags
enum FunctionParserUtils::FailureMethod _evalerror_behavior
FailureMethod
Enum for failure method.
This is a "smart" enum class intended to replace many of the shortcomings in the C++ enum type It sho...
Definition: MooseEnum.h:33
const Real _quiet_nan
appropriate not a number value to return
const Real _epsilon
fuzzy comparison tolerance
bool isParamValid(const std::string &name) const
This method returns parameters that have been initialized in one fashion or another, i.e.

Member Function Documentation

◆ addFParserConstants()

template<bool is_ad>
void FunctionParserUtils< is_ad >::addFParserConstants ( SymFunctionPtr parser,
const std::vector< std::string > &  constant_names,
const std::vector< std::string > &  constant_expressions 
) const
protected

add constants (which can be complex expressions) to the parser object

Definition at line 153 of file FunctionParserUtils.C.

157 {
158  // check constant vectors
159  unsigned int nconst = constant_expressions.size();
160  if (nconst != constant_names.size())
161  mooseError("The parameter vectors constant_names (size " +
162  std::to_string(constant_names.size()) + ") and constant_expressions (size " +
163  std::to_string(nconst) + ") must have equal length.");
164 
165  // previously evaluated constant_expressions may be used in following constant_expressions
166  std::vector<Real> constant_values(nconst);
167 
168  for (unsigned int i = 0; i < nconst; ++i)
169  {
170  // no need to use dual numbers for the constant expressions
171  auto expression = std::make_shared<FunctionParserADBase<Real>>();
172 
173  // add previously evaluated constants
174  for (unsigned int j = 0; j < i; ++j)
175  if (!expression->AddConstant(constant_names[j], constant_values[j]))
176  mooseError("Invalid constant name: ", constant_names[j], " and value ", constant_values[j]);
177 
178  // build the temporary constant expression function
179  if (expression->Parse(constant_expressions[i], "") >= 0)
180  mooseError("Invalid constant expression\n",
181  constant_expressions[i],
182  "\n in parsed function object.\n",
183  expression->ErrorMsg());
184 
185  constant_values[i] = expression->Eval(NULL);
186 
187  if (!parser->AddConstant(constant_names[i], constant_values[i]))
188  mooseError("Invalid constant name in parsed function object");
189  }
190 }
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:323

◆ evaluate() [1/2]

template<bool is_ad>
GenericReal< is_ad > FunctionParserUtils< is_ad >::evaluate ( SymFunctionPtr parser,
const std::string &  object_name = "" 
)
protected

Evaluate FParser object and check EvalError.

Definition at line 87 of file FunctionParserUtils.C.

Referenced by ParsedFunctorMaterialTempl< is_ad >::ParsedFunctorMaterialTempl().

88 {
89  return evaluate(parser, _func_params, name);
90 }
GenericReal< is_ad > evaluate(SymFunctionPtr &, const std::string &object_name="")
Evaluate FParser object and check EvalError.
std::vector< GenericReal< is_ad > > _func_params
Array to stage the parameters passed to the functions when calling Eval.

◆ evaluate() [2/2]

template<bool is_ad>
GenericReal< is_ad > FunctionParserUtils< is_ad >::evaluate ( SymFunctionPtr parser,
const std::vector< GenericReal< is_ad >> &  func_params,
const std::string &  object_name = "" 
)
protected

Evaluate FParser object and check EvalError.

This version uses a supplied vector of function parameters, which is useful if an object uses more than one parsed function, which may have different function parameter values.

Definition at line 94 of file FunctionParserUtils.C.

97 {
98  using std::isnan;
99 
100  // null pointer is a shortcut for vanishing derivatives, see functionsOptimize()
101  if (parser == NULL)
102  return 0.0;
103 
104  // set desired epsilon
105  auto tmp_eps = parser->epsilon();
106  parser->setEpsilon(_epsilon);
107 
108  // evaluate expression
109  auto result = parser->Eval(func_params.data());
110 
111  // restore epsilon
112  parser->setEpsilon(tmp_eps);
113 
114  // fetch fparser evaluation error (set to unknown if the JIT result is nan)
115  int error_code = _enable_jit ? (isnan(result) ? -1 : 0) : parser->EvalError();
116 
117  // no error
118  if (error_code == 0)
119  return result;
120 
121  // hard fail or return not a number
122  switch (_evalerror_behavior)
123  {
124  case FailureMethod::nan:
125  return _quiet_nan;
126 
128  mooseWarning("In ",
129  name,
130  ": Parsed function evaluation encountered an error: ",
131  _eval_error_msg[(error_code < 0 || error_code > 5) ? 0 : error_code]);
132  return _quiet_nan;
133 
135  mooseError("In ",
136  name,
137  ": Parsed function evaluation encountered an error: ",
138  _eval_error_msg[(error_code < 0 || error_code > 5) ? 0 : error_code]);
139 
141  mooseException("In ",
142  name,
143  ": Parsed function evaluation encountered an error: ",
144  _eval_error_msg[(error_code < 0 || error_code > 5) ? 0 : error_code],
145  "\n Cutting timestep");
146  }
147 
148  return _quiet_nan;
149 }
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:323
void mooseWarning(Args &&... args)
Emit a warning message with the given stringified, concatenated args.
Definition: MooseError.h:357
bool _enable_jit
feature flags
enum FunctionParserUtils::FailureMethod _evalerror_behavior
const Real _quiet_nan
appropriate not a number value to return
static const char * _eval_error_msg[]
table of FParser eval error codes
const Real _epsilon
fuzzy comparison tolerance

◆ functionsOptimize() [1/3]

template<bool is_ad = false>
virtual void FunctionParserUtils< is_ad >::functionsOptimize ( SymFunctionPtr parsed_function)
protectedvirtual

run FPOptimizer on the parsed function

Referenced by DerivativeParsedMaterialHelperTempl< is_ad >::functionsPostParse().

◆ functionsOptimize() [2/3]

template<>
void FunctionParserUtils< true >::functionsOptimize ( SymFunctionPtr parsed_function)
protected

◆ functionsOptimize() [3/3]

template<>
void FunctionParserUtils< true >::functionsOptimize ( SymFunctionPtr parsed_function)
protected

Definition at line 211 of file FunctionParserUtils.C.

212 {
213  // set desired epsilon for optimization!
214  auto tmp_eps = parsed_function->epsilon();
215  parsed_function->setEpsilon(_epsilon);
216 
217  // base function
219  parsed_function->Optimize();
220  if (!_enable_jit || !parsed_function->JITCompile())
221  mooseError("AD parsed objects require JIT compilation to be enabled and working.");
222 
223  parsed_function->setEpsilon(tmp_eps);
224 }
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:323
bool _enable_jit
feature flags
const Real _epsilon
fuzzy comparison tolerance

◆ parsedFunctionSetup()

template<bool is_ad>
void FunctionParserUtils< is_ad >::parsedFunctionSetup ( SymFunctionPtr function,
const std::string &  expression,
const std::string &  variables,
const std::vector< std::string > &  constant_names,
const std::vector< std::string > &  constant_expressions,
const libMesh::Parallel::Communicator comm 
) const
protected

Performs setup steps on a SymFunction.

Parameters
functionreference to pointer to the function to set up
expressionexpression to parse
variablescomma separated string holding all the variables of the expression
constant_namesvector of names (symbols) of constants in the expression
constant_expressionsvectors of expressions (=values) of constants in the expression
commcommunicator used to stagger JIT file creations

Definition at line 228 of file FunctionParserUtils.C.

235 {
236  // set FParser internal feature flags
237  setParserFeatureFlags(function);
238 
239  // add the constant expressions
240  addFParserConstants(function, constant_names, constant_expressions);
241 
242  // parse function
243  if (function->Parse(expression, variables) >= 0)
244  mooseError("Invalid function\n", expression, "\nError:\n", function->ErrorMsg());
245 
246  // optimize
248  function->Optimize();
249 
250  // just-in-time compile
251  if (_enable_jit)
252  {
253  // let rank 0 do the JIT compilation first
254  if (comm.rank() != 0)
255  comm.barrier();
256 
257  function->JITCompile();
258 
259  // wait for ranks > 0 to catch up
260  if (comm.rank() == 0)
261  comm.barrier();
262  }
263 }
void addFParserConstants(SymFunctionPtr &parser, const std::vector< std::string > &constant_names, const std::vector< std::string > &constant_expressions) const
add constants (which can be complex expressions) to the parser object
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:323
processor_id_type rank() const
bool _enable_jit
feature flags
void setParserFeatureFlags(SymFunctionPtr &) const
apply input parameters to internal feature flags of the parser object

◆ setParserFeatureFlags()

template<bool is_ad>
void FunctionParserUtils< is_ad >::setParserFeatureFlags ( SymFunctionPtr parser) const

apply input parameters to internal feature flags of the parser object

Definition at line 79 of file FunctionParserUtils.C.

80 {
81  parser->SetADFlags(SymFunction::ADCacheDerivatives, _enable_ad_cache);
82  parser->SetADFlags(SymFunction::ADAutoOptimize, _enable_auto_optimize);
83 }

◆ validParams()

template<bool is_ad>
InputParameters FunctionParserUtils< is_ad >::validParams ( )
static

Definition at line 18 of file FunctionParserUtils.C.

Referenced by ArrayParsedAux::validParams(), ParsedAux::validParams(), ParsedPostprocessor::validParams(), ParsedReporterBase::validParams(), ParsedODEKernel::validParams(), ParsedVectorAux::validParams(), Boundary2DDelaunayGenerator::validParams(), ParsedSubdomainGeneratorBase::validParams(), ParsedCurveGenerator::validParams(), ParsedFunctorMaterialTempl< is_ad >::validParams(), ParsedExtraElementIDGenerator::validParams(), ParsedGenerateNodeset::validParams(), ParsedConvergence::validParams(), CutMeshByLevelSetGeneratorBase::validParams(), SolutionUserObject::validParams(), ParsedNodeTransformGenerator::validParams(), ParsedGenerateSideset::validParams(), MFEMParsedFunction::validParams(), TransfiniteMeshGenerator::validParams(), ParsedDownSelectionPositions::validParams(), ParsedElementDeletionGenerator::validParams(), and ParsedMaterialHelper< is_ad >::validParams().

19 {
21 
22  params.addParam<bool>(
23  "enable_jit",
24 #ifdef LIBMESH_HAVE_FPARSER_JIT
25  true,
26 #else
27  false,
28 #endif
29  "Enable just-in-time compilation of function expressions for faster evaluation");
30  params.addParam<bool>(
31  "enable_ad_cache", true, "Enable caching of function derivatives for faster startup time");
32  params.addParam<bool>(
33  "enable_auto_optimize", true, "Enable automatic immediate optimization of derivatives");
34  params.addParam<bool>(
35  "disable_fpoptimizer", false, "Disable the function parser algebraic optimizer");
36  MooseEnum evalerror("nan nan_warning error exception", "nan");
37  params.addParam<MooseEnum>("evalerror_behavior",
38  evalerror,
39  "What to do if evaluation error occurs. Options are to pass a nan, "
40  "pass a nan with a warning, throw a error, or throw an exception");
41 
42  params.addParamNamesToGroup(
43  "enable_jit enable_ad_cache enable_auto_optimize disable_fpoptimizer evalerror_behavior",
44  "Parsed expression advanced");
45  params.addParam<Real>("epsilon", 0, "Fuzzy comparison tolerance");
46  return params;
47 }
The main MOOSE class responsible for handling user-defined parameters in almost every MOOSE system...
InputParameters emptyInputParameters()
This is a "smart" enum class intended to replace many of the shortcomings in the C++ enum type It sho...
Definition: MooseEnum.h:33
DIE A HORRIBLE DEATH HERE typedef LIBMESH_DEFAULT_SCALAR_TYPE Real
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 addParamNamesToGroup(const std::string &space_delim_names, const std::string group_name)
This method takes a space delimited list of parameter names and adds them to the specified group name...

Member Data Documentation

◆ _disable_fpoptimizer

template<bool is_ad = false>
bool FunctionParserUtils< is_ad >::_disable_fpoptimizer
protected

Definition at line 111 of file FunctionParserUtils.h.

◆ _enable_ad_cache

template<bool is_ad = false>
bool FunctionParserUtils< is_ad >::_enable_ad_cache
protected

Definition at line 110 of file FunctionParserUtils.h.

◆ _enable_auto_optimize

template<bool is_ad = false>
bool FunctionParserUtils< is_ad >::_enable_auto_optimize
protected

Definition at line 112 of file FunctionParserUtils.h.

◆ _enable_jit

template<bool is_ad = false>
bool FunctionParserUtils< is_ad >::_enable_jit
protected

feature flags

Definition at line 109 of file FunctionParserUtils.h.

Referenced by FunctionParserUtils< false >::FunctionParserUtils().

◆ _epsilon

template<bool is_ad = false>
const Real FunctionParserUtils< is_ad >::_epsilon
protected

fuzzy comparison tolerance

Definition at line 128 of file FunctionParserUtils.h.

◆ _eval_error_msg

template<bool is_ad = false>
const char * FunctionParserUtils< is_ad >::_eval_error_msg
staticprotected
Initial value:
= {
"Unknown",
"Division by zero",
"Square root of a negative value",
"Logarithm of negative value",
"Trigonometric error (asin or acos of illegal value)",
"Maximum recursion level reached"}

table of FParser eval error codes

Definition at line 122 of file FunctionParserUtils.h.

◆ _evalerror_behavior

template<bool is_ad = false>
enum FunctionParserUtils::FailureMethod FunctionParserUtils< is_ad >::_evalerror_behavior
protected

◆ _func_params

template<bool is_ad = false>
std::vector<GenericReal<is_ad> > FunctionParserUtils< is_ad >::_func_params
protected

Array to stage the parameters passed to the functions when calling Eval.

Definition at line 125 of file FunctionParserUtils.h.

Referenced by ParsedFunctorMaterialTempl< is_ad >::ParsedFunctorMaterialTempl().

◆ _quiet_nan

template<bool is_ad = false>
const Real FunctionParserUtils< is_ad >::_quiet_nan
protected

appropriate not a number value to return

Definition at line 119 of file FunctionParserUtils.h.


The documentation for this class was generated from the following files: