public class TMtxExpression
Expression evaluator.
The object is a compiler for mathematical expressions. It holds the lists of all compiled expression and all recognized symbols.
The user can define any number of user defined variables and functions. The functions can be overloaded by specifying different parameter count. Parameters to functions and result of functions can also be strings. User defined functions can be functions or methods (of object).
The math expressions can mix scalar, vector or matrix type. The following standard operators are supported:
- ', the transpose/adjungate operator for matrices
- power operator ^
- standard operators working on vector, matrix and scalar *, /, + , -
- The per element operators working on matrices and vectors *. , /. If you dont specify per element operation, linear algebra logic will be used for * and / when operands are matrices
- not operator !, identical to not and ~
- remainder operator %, identical to mod
- back division operator for matrices \ , A\B = A^(-1)*B, which comes from A*X = B and gives a solution to the system of linear equations. If matrices are not square LQR (minimum norm) solution is computed.
- div and mod for integer division
- comparison operators < , <= , > , >= , ==
- binary operators: and, not, or, xor
- assign operator, =
- colon operator (see below)
The "i" defines a complex number:
a = 2+3i;
All operations support complex numbers. When using expressions which can result in a complex number like: (-1)^(1/3), the result will be complex, only if arguments are complex. The expression will also not auto reduce to a real number, even if imaginary part of the complex number is 0. To reduce the result to the real number part only, you have to call function real(x). To explicitely form a complex number use the cplx(re, im) function. The iscomplex(x) function returns 1 if the variable is complex and 0 otherwise.
The type of variable is determined at compile time and may not change at run time. Vectors and matrices can be accessed by individual elements:
a(i)
m(r,c)
or in ranges by using the colon operator:
a(0:9), returns elements from index 0 to including 9.
m(1:2,2:3), returns sub matrix.
First element is referenced with index 0. The colon can also be used on the left side during assignment:
a(0:9) = b(1:10);
Optionally the colon operator also allows a step definition:
a = 20:-1:-20;
To return the matrix as a vector:
v = m(:);
Expressions with the colon operator are tightly optimized. The colon expression is only expanded to vector if needed. The variable returning result of colon expression uses Dew.Math.TVec.SetSubRange. Consequently:
b = a(1:10);
Translates to one single TVec.Copy(..) method call. In expressions there is also no "copy" overhead. The following expression requires one call to TVec.Mul(..) and one TVec.Copy(..):
c = a(1:10)*b(11:20);
Vectors and matrices can also return elements from conditions:
a = m(m > 4);
Despite the advanced vector/matrix syntax the single scalar syntax like:
c = Log(b) + d;
will still execute at top speed because type resolution is done at compile time. The constant expressions like 4*4 and 2^3 or even:
sin(3.2) - sqrt(cos(1.5))
are also evaluated at compile time.
It is of course possible to evaluate a list of expressions:
a = 1;
b = 2;
c = a + b;
where the variables will remain in the memory until cleared. Currently there is no support for "for" and "while" loops or in-script function definitions.
Other operands included:
- comparison:
> < <> = <= >= *., /., +., -. to indicate per element operation on vector matrix pairs- not:
!, identical tonotand~ - remainder:
%, identical tomod
Assignment operator is always required to be a simple " = " char, but in general the user can customize everything else.
The precedence of the operands is little different from Pascal (Delphi), giving a lower precedence to logical operands, as these only act on booleans (and not on integers like in Pascal) 1. (highest): ' ! ~ not -x +x 2. :
3. ^
4. * *. / /. \ div mod % 5. + +. - -.
6. << >> shl shr
7. < <= > >=
8. == != <> ~=
9. & and
10. | or xor
11. (lowest) =
This precedence order is easily customizable by overriding/changing InitSymbols
Optionally the operators can be redefined, but the assignment (equal) operator can not be overriden.
The following class properties:
MtxParseClass.TWordList.OnProbabilities
MtxParseClass.TWordList.OnStatistics
MtxParseClass.TWordList.OnSignal
MtxParseClass.TWordList.OnCustom
hold the callback functions to declare functions from the corresponding software packages. If you dont want for example the Probabilities functions to be avaialble when creating new TMtxExpression, set that property to nil.
The callbacks are of type MtxParseClass.TWordPopulate. You can assign your own callback to OnCustom event for custom defined function domains. The following units need to be included in your project for the first three callbacks to be populated: MtxParseProbabilities, MtxParseSignal, MtxParseStatistics.
A large set of functions and constants is already predefined.
Note:
Originally adapted from TExpressionParser written by Egbert van Nes ([Egbert.vanNes@Aqec.WKAO.WAU.NL](mailto:Egbert.vanNes@Aqec.WKAO.WAU.NL)) with permission.
Examples
using Dew.Math;
using Dew.Math.Units;
namespace Dew.Examples
{
void Example()
{
// 1. Define variables
TDoubleValue x = MyParser.DefineDouble("x");
TDoubleValue y = MyParser.DefineDouble("y");
// 2. Set values
x.DoubleValue = 3.0;
y.DoubleValue = 4.0;
// 3. Add formula and evaluate,
MyParser.AddExpr("Sqrt(x*x+y*y)");
double res = MyParser.EvaluateDouble();
// res = 5
}
}
Properties
| Name | Type | Description |
|---|---|---|
| ConcatsAlwaysReal | Boolean | If True, all [ ..] type of expression will be double type even, if all items are integer. |
| ConstantsAlwaysReal | Boolean | If True, all constants will be double type even if number is integer. |
| EvaluatedLine | Int32 | Returns the line (expression number) of the last evaluation, where a runtime error occured. |
| ExprCount | Int32 | Number of expressions. |
| Expressions | String | Gets/sets several expressions separated by semicolon at once. |
| ExprResult | TExprResultIndexer | Returns expression result at specified index. |
| IsCompiled | Boolean | Returns True, if the expressions were already compiled. |
| Item | String | Returns expression by index. |
| LastResult | TValueRec | Returns result of the latest expression from the list. |
| OnPreprocessor | TOnPreprocessor | The preprocessor event is called after the preprocessor has already applied any substitions and patched the parsed expression. |
| VarByName | TVarByNameIndexer | Returns variable by name or nil, if variable does not exist. |
Methods
| Name | Description |
|---|---|
| AddExpr (2) | Appends new expressions at the end of list. |
| ClearAll | Clears all expressions and all defined variables. |
| ClearExpressions | Clears all expressions only. |
| ClearVariables | Clears all defined variables only. |
| Compile | Performs compile of all the expressions in the list. |
| DefineBool | Defines new boolean variable. |
| DefineBoolConstant | Defines new boolean constant. |
| DefineBoolMatrix | Use internal matrix. |
| DefineBoolVector | Use internal vector. |
| DefineComplex | Defines new complex variable. |
| DefineComplexConstant | Defines new complex constant. |
| DefineCustomValue (2) | Define type and initialize to nil. |
| DefineDouble | Defines new double variable. |
| DefineDoubleConstant | Defines new double constant. |
| DefineFunction | Defines new function. |
| DefineInteger | Defines new integer variable. |
| DefineIntMatrix | Use internal matrix. |
| DefineIntVector | Use internal vector. |
| DefineMatrix (2) | Use internal matrix. |
| DefineOperator | Defines new operator. |
| DefineRange | Defines new range variable. |
| DefineString | Defines new string variable. |
| DefineVariable (2) | Defines new variable. |
| DefineVaryingFunction | Defines new varying function. |
| DefineVector (2) | Use internal vector. |
| DeleteExpr | Deletes expression at specified index. |
| Evaluate (2) | Evaluates all expressions from the list. |
| EvaluateBool (2) | Evaluates all expressions from the list. |
| EvaluateCompiled | Runs the compiled script. |
| EvaluateComplex (2) | Evaluates all expressions from the list. |
| EvaluateDouble (2) | Evaluates all expressions from the list. |
| EvaluatedVarName | Returns the name of the result variable for expression at Index. |
| EvaluateMatrix (2) | Evaluates all expressions from the list. |
| EvaluateRun | Evaluates all lines of compiled script from specified Line forward. |
| EvaluateStep | Evaluates one line of compiled script. |
| EvaluateVector (2) | Evaluates all expressions from the list. |
| ExpandCharToWord | Returns a word from Src string close to charIdx. |
| FindSymbol | Returns TExprWord, if a symbol with aName already exists. |
| GetConstList | Retrieves list of constants. |
| GetFuncList | Retrieves list of functions. |
| GetOperList | Retrieves list of operators. |
| GetVarList | Retrieves list of variables. |
| InsertExpr | Inserts new expression at specified index. |
| LoadContext | Sets new context (expressions and variable values). |
| NegativeTest | Specifies an expression, which must fail, underwise an exception is raised. |
| SaveContext | Retrives current context (expressions and variable values). |
| SelfTest | Runs all registered tests and raises an exception, if one fails. |
| Test (2) | Specifies a single expression, which must match ResultValue, underwise an exception is raised. |
| TestMtx | Specifies a single expression, which must match ResultValue, underwise an exception is raised. |
| TestVec | Specifies a single expression, which must match ResultValue, underwise an exception is raised. |
| Undefine | Removes symbol from defined symbols. |
| VarPrint | Prints the value "a" of variable with "aName" to Dst. |
| VarToolTip | Returns Tool-Tip or the Hint string to be displayed for the variable with aName. |
Events
| Name | Description |
|---|---|
| OnPreprocessorEvent | The preprocessor event is called after the preprocessor has already applied any substitions and patched the parsed expression. |