TMtxExpression Class

Source: MtxParseExpr.cs · Assembly: Dew.Math

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 to not and ~
  • remainder: %, identical to mod

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

csharp
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

NameTypeDescription
ConcatsAlwaysRealBooleanIf True, all [ ..] type of expression will be double type even, if all items are integer.
ConstantsAlwaysRealBooleanIf True, all constants will be double type even if number is integer.
EvaluatedLineInt32Returns the line (expression number) of the last evaluation, where a runtime error occured.
ExprCountInt32Number of expressions.
ExpressionsStringGets/sets several expressions separated by semicolon at once.
ExprResultTExprResultIndexerReturns expression result at specified index.
IsCompiledBooleanReturns True, if the expressions were already compiled.
ItemStringReturns expression by index.
LastResultTValueRecReturns result of the latest expression from the list.
OnPreprocessorTOnPreprocessorThe preprocessor event is called after the preprocessor has already applied any substitions and patched the parsed expression.
VarByNameTVarByNameIndexerReturns variable by name or nil, if variable does not exist.

Methods

NameDescription
AddExpr (2)Appends new expressions at the end of list.
ClearAllClears all expressions and all defined variables.
ClearExpressionsClears all expressions only.
ClearVariablesClears all defined variables only.
CompilePerforms compile of all the expressions in the list.
DefineBoolDefines new boolean variable.
DefineBoolConstantDefines new boolean constant.
DefineBoolMatrixUse internal matrix.
DefineBoolVectorUse internal vector.
DefineComplexDefines new complex variable.
DefineComplexConstantDefines new complex constant.
DefineCustomValue (2)Define type and initialize to nil.
DefineDoubleDefines new double variable.
DefineDoubleConstantDefines new double constant.
DefineFunctionDefines new function.
DefineIntegerDefines new integer variable.
DefineIntMatrixUse internal matrix.
DefineIntVectorUse internal vector.
DefineMatrix (2)Use internal matrix.
DefineOperatorDefines new operator.
DefineRangeDefines new range variable.
DefineStringDefines new string variable.
DefineVariable (2)Defines new variable.
DefineVaryingFunctionDefines new varying function.
DefineVector (2)Use internal vector.
DeleteExprDeletes expression at specified index.
Evaluate (2)Evaluates all expressions from the list.
EvaluateBool (2)Evaluates all expressions from the list.
EvaluateCompiledRuns the compiled script.
EvaluateComplex (2)Evaluates all expressions from the list.
EvaluateDouble (2)Evaluates all expressions from the list.
EvaluatedVarNameReturns the name of the result variable for expression at Index.
EvaluateMatrix (2)Evaluates all expressions from the list.
EvaluateRunEvaluates all lines of compiled script from specified Line forward.
EvaluateStepEvaluates one line of compiled script.
EvaluateVector (2)Evaluates all expressions from the list.
ExpandCharToWordReturns a word from Src string close to charIdx.
FindSymbolReturns TExprWord, if a symbol with aName already exists.
GetConstListRetrieves list of constants.
GetFuncListRetrieves list of functions.
GetOperListRetrieves list of operators.
GetVarListRetrieves list of variables.
InsertExprInserts new expression at specified index.
LoadContextSets new context (expressions and variable values).
NegativeTestSpecifies an expression, which must fail, underwise an exception is raised.
SaveContextRetrives current context (expressions and variable values).
SelfTestRuns 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.
TestMtxSpecifies a single expression, which must match ResultValue, underwise an exception is raised.
TestVecSpecifies a single expression, which must match ResultValue, underwise an exception is raised.
UndefineRemoves symbol from defined symbols.
VarPrintPrints the value "a" of variable with "aName" to Dst.
VarToolTipReturns Tool-Tip or the Hint string to be displayed for the variable with aName.

Events

NameDescription
OnPreprocessorEventThe preprocessor event is called after the preprocessor has already applied any substitions and patched the parsed expression.