| 1 |
// ------------------------------------------------------------------------ |
| 2 |
// |
| 3 |
// SPDX-License-Identifier: LGPL-2.1-or-later |
| 4 |
// Copyright (C) 2005 - 2024 by the deal.II authors |
| 5 |
// |
| 6 |
// This file is part of the deal.II library. |
| 7 |
// |
| 8 |
// Part of the source code is dual licensed under Apache-2.0 WITH |
| 9 |
// LLVM-exception OR LGPL-2.1-or-later. Detailed license information |
| 10 |
// governing the source code and code contributions can be found in |
| 11 |
// LICENSE.md and CONTRIBUTING.md at the top level directory of deal.II. |
| 12 |
// |
| 13 |
// ------------------------------------------------------------------------ |
| 14 |
|
| 15 |
#ifndef dealii_function_parser_h |
| 16 |
#define dealii_function_parser_h |
| 17 |
|
| 18 |
|
| 19 |
#include <deal.II/base/config.h> |
| 20 |
|
| 21 |
#include <deal.II/base/auto_derivative_function.h> |
| 22 |
#include <deal.II/base/exceptions.h> |
| 23 |
#include <deal.II/base/mu_parser_internal.h> |
| 24 |
#include <deal.II/base/point.h> |
| 25 |
#include <deal.II/base/tensor.h> |
| 26 |
|
| 27 |
#include <map> |
| 28 |
#include <vector> |
| 29 |
|
| 30 |
DEAL_II_NAMESPACE_OPEN |
| 31 |
|
| 32 |
// Forward declaration |
| 33 |
#ifndef DOXYGEN |
| 34 |
template <typename> |
| 35 |
class Vector; |
| 36 |
#endif |
| 37 |
|
| 38 |
/** |
| 39 |
* This class implements a function object that gets its value by parsing a |
| 40 |
* string describing this function. It is a wrapper class for the muparser |
| 41 |
* library (see https://beltoforion.de/en/muparser/). This class lets you |
| 42 |
* evaluate strings such as "sqrt(1-x^2+y^2)" for given values of 'x' and 'y'. |
| 43 |
* Please refer to the muparser documentation for more information. This class |
| 44 |
* is used in the step-33 and step-36 tutorial programs (the latter being much |
| 45 |
* simpler to understand). |
| 46 |
* |
| 47 |
* In addition to the built-in functions of muparser, namely |
| 48 |
* @code |
| 49 |
* sin, cos, tan, asin, acos, atan, sinh, cosh, tanh, asinh, acosh, atanh, |
| 50 |
* atan2, log2, log10, log, ln, exp, sqrt, sign, rint, abs, min, max, sum, avg |
| 51 |
* @endcode |
| 52 |
* this class also supports the following operations: |
| 53 |
* - <code>if(condition, then-value, else-value)</code> |
| 54 |
* - <code>|</code> and <code>&</code> (logic or and and) |
| 55 |
* - <code>int(x)</code>, <code>ceil(x)</code>, <code>floor(x)</code> (rounding) |
| 56 |
* - <code>cot(x)</code>, <code>csc(x)</code>, <code>sec(x)</code> |
| 57 |
* - <code>pow(x,n)</code>, <code>log(x)</code> |
| 58 |
* - <code>erfc(x)</code> |
| 59 |
* - <code>rand()</code>, <code>rand_seed(seed)</code> |
| 60 |
* |
| 61 |
* @note This class implements the list of functions just mentioned as |
| 62 |
* user-defined functions by extending muparser. This means, in particular, |
| 63 |
* that the `if(condition, then-value, else-value)` syntax evaluates all |
| 64 |
* three arguments before determining whether the condition is true, and |
| 65 |
* then discarding either the "then" or the "else" expressions. In almost |
| 66 |
* all situations, this is not a problem except if the evaluation of |
| 67 |
* one of the expressions throws a floating point exception in cases |
| 68 |
* where it will later be discarded. (Assuming floating point exceptions |
| 69 |
* are switched on, as is the default for deal.II in debug mode on most |
| 70 |
* systems.) An example would be the expression `if(x>0, sqrt(x), 0)` |
| 71 |
* which is mathematically well defined, but on systems where this is |
| 72 |
* enabled will abort the program with a floating point exception when |
| 73 |
* evaluated with a negative `x`. This is because the square root of |
| 74 |
* `x` is computed before the `if` statement's condition is considered |
| 75 |
* to determine whether the result should be the second or third |
| 76 |
* argument. If this kind of behavior is a problem, you can resort to |
| 77 |
* the muparser built-in syntax `(condition ? then-value : else-value)`, |
| 78 |
* using the ternary syntax familiar to C++ programmers. If this |
| 79 |
* syntax is used, muparser uses lazy evaluation in which only one of the |
| 80 |
* branches is evaluated, depending on whether the `condition` is |
| 81 |
* true or false. |
| 82 |
* |
| 83 |
* The following examples shows how to use this class: |
| 84 |
* @code |
| 85 |
* // set up problem: |
| 86 |
* std::string variables = "x,y"; |
| 87 |
* std::string expression = "cos(x) + sqrt(y)"; |
| 88 |
* std::map<std::string, double> constants; |
| 89 |
* |
| 90 |
* // FunctionParser with 2 variables and 1 component: |
| 91 |
* FunctionParser<2> fp(1); |
| 92 |
* fp.initialize(variables, |
| 93 |
* expression, |
| 94 |
* constants); |
| 95 |
* |
| 96 |
* // Point at which we want to evaluate the function |
| 97 |
* Point<2> point(0.0, 4.0); |
| 98 |
* |
| 99 |
* // evaluate the expression at 'point': |
| 100 |
* double result = fp.value(point); |
| 101 |
* |
| 102 |
* deallog << "Function '" << expression << "'" |
| 103 |
* << " @ " << point |
| 104 |
* << " is " << result << std::endl; |
| 105 |
* @endcode |
| 106 |
* The second example is a bit more complex: |
| 107 |
* @code |
| 108 |
* // Define some constants that will be used by the function parser |
| 109 |
* std::map<std::string, double> constants; |
| 110 |
* constants["pi"] = numbers::PI; |
| 111 |
* |
| 112 |
* // Define the variables that will be used inside the expressions |
| 113 |
* std::string variables = "x,y,z"; |
| 114 |
* |
| 115 |
* // Define the expressions of the individual components of a |
| 116 |
* // vector valued function with two components: |
| 117 |
* std::vector<std::string> expressions(2); |
| 118 |
* expressions[0] = "sin(2*pi*x)+sinh(pi*z)"; |
| 119 |
* expressions[1] = "sin(2*pi*y)*exp(x^2)"; |
| 120 |
* |
| 121 |
* // function parser with 3 variables and 2 components |
| 122 |
* FunctionParser<3> vector_function(2); |
| 123 |
* |
| 124 |
* // And populate it with the newly created objects. |
| 125 |
* vector_function.initialize(variables, |
| 126 |
* expressions, |
| 127 |
* constants); |
| 128 |
* |
| 129 |
* // Point at which we want to evaluate the function |
| 130 |
* Point<3> point(0.0, 1.0, 1.0); |
| 131 |
* |
| 132 |
* // This Vector will store the result |
| 133 |
* Vector<double> result(2); |
| 134 |
* |
| 135 |
* // Fill 'result' by evaluating the function |
| 136 |
* vector_function.vector_value(point, result); |
| 137 |
* |
| 138 |
* // We can also only evaluate the 2nd component: |
| 139 |
* const double c = vector_function.value(point, 1); |
| 140 |
* |
| 141 |
* // Output the evaluated function |
| 142 |
* deallog << "Function '" << expressions[0] << ',' << expressions[1] << "'" |
| 143 |
* << " at " << point |
| 144 |
* << " is " << result << std::endl; |
| 145 |
* @endcode |
| 146 |
* |
| 147 |
* This class overloads the virtual methods value() and vector_value() of the |
| 148 |
* Function base class with the byte compiled versions of the expressions |
| 149 |
* given to the initialize() methods. Note that the class will not work unless |
| 150 |
* you first call the initialize() method that accepts the text description of |
| 151 |
* the function as an argument (among other things). |
| 152 |
* |
| 153 |
* The syntax to describe a function follows usual programming practice, and |
| 154 |
* is explained in detail at the homepage of the underlying muparser library |
| 155 |
* at https://beltoforion.de/en/muparser/. |
| 156 |
* |
| 157 |
* If you would like to check that muparser is parsing your functions correctly, |
| 158 |
* and to evaluate the functions at given parameter values, you may consider |
| 159 |
* running your expressions through pymuparser |
| 160 |
* (https://github.com/bobmyhill/pymuparser), |
| 161 |
* which can be installed using pip (python -m pip install pymuparser). |
| 162 |
* This module also allows users to define functions not included in MuParser, |
| 163 |
* such as the extended library provided by deal.II. |
| 164 |
* |
| 165 |
* For a wrapper of the FunctionParser class that supports ParameterHandler, |
| 166 |
* see Functions::ParsedFunction. |
| 167 |
* |
| 168 |
* Vector-valued functions can either be declared using strings where the |
| 169 |
* function components are separated by semicolons, or using a vector of |
| 170 |
* strings each defining one vector component. |
| 171 |
* |
| 172 |
* An example of time dependent scalar function is the following: |
| 173 |
* @code |
| 174 |
* // Empty constants object |
| 175 |
* std::map<std::string,double> constants; |
| 176 |
* |
| 177 |
* // Variables that will be used inside the expressions |
| 178 |
* std::string variables = "x,y,t"; |
| 179 |
* |
| 180 |
* // Define the expression of the scalar time dependent function. |
| 181 |
* std::string expression = "exp(y*x)*exp(-t)"; |
| 182 |
* |
| 183 |
* // Generate an empty scalar function |
| 184 |
* FunctionParser<2> function; |
| 185 |
* |
| 186 |
* // And populate it with the newly created objects. |
| 187 |
* function.initialize(variables, |
| 188 |
* expression, |
| 189 |
* constants, |
| 190 |
* // Treat the last variable ("t") as time. |
| 191 |
* true); |
| 192 |
* @endcode |
| 193 |
* |
| 194 |
* The following is another example of how to instantiate a vector valued |
| 195 |
* function by using a single string: |
| 196 |
* @code |
| 197 |
* // Empty constants object |
| 198 |
* std::map<std::string,double> constants; |
| 199 |
* |
| 200 |
* // Variables that will be used inside the expressions |
| 201 |
* std::string variables = "x,y"; |
| 202 |
* |
| 203 |
* // Define the expression of the vector valued function. |
| 204 |
* std::string expression = "cos(2*pi*x)*y^2; sin(2*pi*x)*exp(y)"; |
| 205 |
* |
| 206 |
* // Generate an empty vector valued function |
| 207 |
* FunctionParser<2> function(2); |
| 208 |
* |
| 209 |
* // And populate it with the newly created objects. |
| 210 |
* function.initialize(variables, |
| 211 |
* expression, |
| 212 |
* constants); |
| 213 |
* @endcode |
| 214 |
* |
| 215 |
* @note The difference between this class and the SymbolicFunction class is |
| 216 |
* that the SymbolicFunction class allows to compute first and second order |
| 217 |
* derivatives (in a symbolic way), while this class computes first order |
| 218 |
* derivatives only, using finite differences. For complicated expressions, |
| 219 |
* this class is generally faster than SymbolicFunction. |
| 220 |
* |
| 221 |
* @ingroup functions |
| 222 |
*/ |
| 223 |
template <int dim> |
| 224 |
class FunctionParser |
| 225 |
: public AutoDerivativeFunction<dim>, |
| 226 |
protected internal::FunctionParser::ParserImplementation<dim, double> |
| 227 |
{ |
| 228 |
public: |
| 229 |
/** |
| 230 |
* Constructor. Its arguments are the same of the base class Function, with |
| 231 |
* the additional parameter @p h, used for the computation of gradients |
| 232 |
* using finite differences. This object needs to be initialized with the |
| 233 |
* initialize() method before you can use it. If an attempt to use this |
| 234 |
* function is made before the initialize() method has been called, then an |
| 235 |
* exception is thrown. |
| 236 |
*/ |
| 237 |
FunctionParser(const unsigned int n_components = 1, |
| 238 |
const double initial_time = 0.0, |
| 239 |
const double h = 1e-8); |
| 240 |
|
| 241 |
/** |
| 242 |
* Constructor for parsed functions. Takes directly a semi-colon separated |
| 243 |
* list of expressions (one for each component of the function), an optional |
| 244 |
* comma-separated list of constants, variable names and step size for the |
| 245 |
* computation of first order derivatives by finite differences. |
| 246 |
*/ |
| 247 |
FunctionParser(const std::string &expression, |
| 248 |
const std::string &constants = "", |
| 249 |
const std::string &variable_names = default_variable_names() + |
| 250 |
",t", |
| 251 |
const double h = 1e-8); |
| 252 |
|
| 253 |
/** |
| 254 |
* Copy constructor. Objects of this type can not be copied, and |
| 255 |
* consequently this constructor is deleted. |
| 256 |
*/ |
| 257 |
FunctionParser(const FunctionParser &) = delete; |
| 258 |
|
| 259 |
/** |
| 260 |
* Move constructor. Objects of this type can not be moved, and |
| 261 |
* consequently this constructor is deleted. |
| 262 |
*/ |
| 263 |
FunctionParser(FunctionParser &&) = delete; |
| 264 |
|
| 265 |
/** |
| 266 |
* Copy operator. Objects of this type can not be copied, and |
| 267 |
* consequently this operator is deleted. |
| 268 |
*/ |
| 269 |
FunctionParser & |
| 270 |
operator=(const FunctionParser &) = delete; |
| 271 |
|
| 272 |
/** |
| 273 |
* Move operator. Objects of this type can not be moved, and |
| 274 |
* consequently this operator is deleted. |
| 275 |
*/ |
| 276 |
FunctionParser & |
| 277 |
operator=(FunctionParser &&) = delete; |
| 278 |
|
| 279 |
/** |
| 280 |
* Type for the constant map. Used by the initialize() method. |
| 281 |
*/ |
| 282 |
using ConstMap = std::map<std::string, double>; |
| 283 |
|
| 284 |
/** |
| 285 |
* Initialize the object by setting the actual parsed functions. |
| 286 |
* |
| 287 |
* @param[in] vars a string with the variables, separated by commas, that will |
| 288 |
* be used by the expressions to be evaluated. Note that the variables can |
| 289 |
* have any name (of course different from the function names defined above!), |
| 290 |
* but the order IS important. The first variable will correspond to the first |
| 291 |
* component of the point in which the function is evaluated, the second |
| 292 |
* variable to the second component and so forth. If this function is also |
| 293 |
* time dependent, then it is necessary to specify it by setting the |
| 294 |
* <code>time_dependent</code> parameter to true. An exception is thrown if |
| 295 |
* the number of variables specified here is different from dim (if this |
| 296 |
* function is not time-dependent) or from dim+1 (if it is time-dependent). |
| 297 |
* |
| 298 |
* @param[in] expressions a list of strings containing the expressions that |
| 299 |
* will be byte compiled by the internal parser (muParser). Note that |
| 300 |
* the size of this vector must match exactly the number of components of |
| 301 |
* the FunctionParser, as declared in the constructor. If this is not the |
| 302 |
* case, an exception is thrown. |
| 303 |
* |
| 304 |
* @param[in] constants a map of constants used to pass any necessary constant |
| 305 |
* that we want to specify in our expressions (in the example above the |
| 306 |
* number pi). An expression is valid if and only if it contains only |
| 307 |
* defined variables and defined constants (other than the functions |
| 308 |
* specified above). If a constant is given whose name is not valid (eg: |
| 309 |
* <code>constants["sin"] = 1.5;</code>) an exception is thrown. |
| 310 |
* |
| 311 |
* @param[in] time_dependent If this is a time dependent function, then the |
| 312 |
* last variable declared in @p vars is assumed to be the time variable, and |
| 313 |
* FunctionTime::get_time() is used to initialize it when evaluating the |
| 314 |
* function. Naturally the number of variables parsed by initialize() in |
| 315 |
* this case is dim+1. The value of this parameter defaults to false, i.e., |
| 316 |
* do not consider time. |
| 317 |
*/ |
| 318 |
virtual void |
| 319 |
initialize(const std::string &vars, |
| 320 |
const std::vector<std::string> &expressions, |
| 321 |
const ConstMap &constants, |
| 322 |
const bool time_dependent = false) override; |
| 323 |
|
| 324 |
/** |
| 325 |
* Initialize the function. Same as above, but accepts a string rather than |
| 326 |
* a vector of strings. If this is a vector valued function, its components |
| 327 |
* are expected to be separated by a semicolon. An exception is thrown if |
| 328 |
* this method is called and the number of components successfully parsed |
| 329 |
* does not match the number of components of the base function. |
| 330 |
*/ |
| 331 |
void |
| 332 |
initialize(const std::string &vars, |
| 333 |
const std::string &expression, |
| 334 |
const ConstMap &constants, |
| 335 |
const bool time_dependent = false); |
| 336 |
|
| 337 |
/** |
| 338 |
* A function that returns default names for variables, to be used in the |
| 339 |
* first argument of the initialize() functions: it returns "x" in 1d, "x,y" |
| 340 |
* in 2d, and "x,y,z" in 3d. |
| 341 |
*/ |
| 342 |
static std::string |
| 343 |
default_variable_names(); |
| 344 |
|
| 345 |
/** |
| 346 |
* Return the value of the function at the given point. Unless there is only |
| 347 |
* one component (i.e., the function is scalar), you should state the |
| 348 |
* component you want to have evaluated; it defaults to zero, i.e., the first |
| 349 |
* component. |
| 350 |
*/ |
| 351 |
virtual double |
| 352 |
value(const Point<dim> &p, const unsigned int component = 0) const override; |
| 353 |
|
| 354 |
/** |
| 355 |
* Return an array of function expressions (one per component), used to |
| 356 |
* initialize this function. |
| 357 |
*/ |
| 358 |
const std::vector<std::string> & |
| 359 |
get_expressions() const; |
| 360 |
|
| 361 |
/** |
| 362 |
* @addtogroup Exceptions |
| 363 |
* @{ |
| 364 |
*/ |
| 365 |
DeclException2(ExcParseError, |
| 366 |
int, |
| 367 |
std::string, |
| 368 |
<< "Parsing Error at Column " << arg1 |
| 369 |
<< ". The parser said: " << arg2); |
| 370 |
|
| 371 |
DeclException2(ExcInvalidExpressionSize, |
| 372 |
int, |
| 373 |
int, |
| 374 |
<< "The number of components (" << arg1 |
| 375 |
<< ") is not equal to the number of expressions (" << arg2 |
| 376 |
<< ")."); |
| 377 |
|
| 378 |
/** @} */ |
| 379 |
}; |
| 380 |
|
| 381 |
|
| 382 |
template <int dim> |
| 383 |
std::string |
| 384 |
FunctionParser<dim>::default_variable_names() |
| 385 |
{ |
| 386 |
switch (dim) |
| 387 |
{ |
| 388 |
case 1: |
| 389 |
return "x"; |
| 390 |
case 2: |
| 391 |
return "x,y"; |
| 392 |
case 3: |
| 393 |
return "x,y,z"; |
| 394 |
default: |
| 395 |
DEAL_II_NOT_IMPLEMENTED(); |
| 396 |
} |
| 397 |
return ""; |
| 398 |
} |
| 399 |
|
| 400 |
|
| 401 |
|
| 402 |
DEAL_II_NAMESPACE_CLOSE |
| 403 |
|
| 404 |
#endif |