You are here: Start » Programming Reference » Formulas

# Formulas

## Introduction

A formula block enables to write down operations on basic arithmetic and logic types in a concise textual form. Its main advantage is the ability to simplify programs, in which calculations may require use of a big number of separate filters with simple mathematical functions.

Formula notations consist of a sequence of operators, arguments and functions and are founded on basic rules of mathematical algebra. Their objective in Adaptive Vision Studio is similar to formulas in spreadsheet programs or expressions in popular scripting languages.

A formula block can have any number of inputs and outputs defined by the user. These ports can be of any unrelated types, including various types in one block. Input values are used as arguments (identified by inputs names) in arithmetic formulas. There is a separate formula assigned to each output of a block, the role of such formula is to calculate the value held by given output. Once calculated, a value from output can be used many times in formulas of outputs which are located at a lower position in a block description.

Each of arguments used in formulas has a strictly defined data type, which is known and verified during formula initialization (so called static typing). Types of input arguments arise from explicitly defined block port types. These types are then propagated by operations performed on arguments. Finally, a formula value is converted to the explicitly defined type assigned to a formula output. Compatibility of these types is verified during program initialization (before the first execution of formula block), all incompatibilities are reported as errors.

Formula examples:

outValue = inValue + 10
outValue = inValue1 * 0.3 + inValue2 * 0.7
outValue = (inValue - 1) / 3
outValue = max(inValue1, inValue2) / min(inValue1, inValue2)
outRangePos = (inValue >= -5 and inValue <= 10) ? (inValue - -5) / 15 : Nil
outArea = inBox.Width * inBox.Height


## Data types

Blocks of arithmetic-logic formulas can pass any types from inputs to outputs. The data types mentioned below are recognized by operators and functions available in formulas and therefore they can take part in processing their values.

Data type Description
Integer

Arithmetic type of integral values in the range of -2,147,483,648...2,147,483,647, it can be used with arithmetic and comparison operators.

Integer?
Integer*

Conditional or optional arithmetic type of integral values, it can additionally take value of Nil (empty value).

It can be used everywhere, where the type of Integer is accepted. It (if an operator or a function doesn't assume different behavior) causes that the result of an operation performed on it is also a conditional value. It means that an occurrence of Nil value causes that operation execution is aborted and Nil value is returned as operation result.

Real

Real number (floating-point), it can be used with arithmetic and comparison operators.

Real?
Real*

Conditional or optional real value, it can additionally take value of Nil (empty value).

Similarly to Integer? it can be used everywhere, where the type of Real is accepted causing conditional execution of operators.

Long

Arithmetic type of integral values in the range of -9,223,372,036,854,775,808...9,223,372,036,854,775,807, it can be used with arithmetic and comparison operators.

Long?
Long*

Conditional or optional equivalent of Long type, it can additionally take value of Nil (empty value).

Similarly to Integer? it can be used everywhere, where the type of Long is accepted causing conditional execution of operators.

Double

Double precision floating-point number, it can be used with arithmetic and comparison operators.

Double?
Double*

Conditional or optional equivalent of Double type, it can additionally take value of Nil (empty value).

Similarly to Integer? it can be used everywhere, where the type of Double is accepted causing conditional execution of operators.

Bool

Logic type, takes one of the two values: true or false. It can be used with logic and comparison operators or as a condition argument. It's also a result of comparison operators.

Bool?
Bool*

Conditional or optional logic type, it can additionally take value of Nil (empty value).

It can be used everywhere, where the type of Bool is accepted. It (if an operator or a function doesn't assume different behavior) causes that the result of an operation performed on it is also a conditional value. It means that an occurrence of Nil value causes that operation execution is aborted and Nil value is returned as operation result.

String

Textual type accepting character strings of dynamic length.

Text length (in characters) can be determined using String type built-in .Length property.

String?
String*

Conditional or optional textual type, it can additionally take value of Nil (empty value).

It can be used everywhere, where the type of String is accepted. It (if an operator or a function doesn't assume different behavior) causes that the result of an operation performed on it is also a conditional value. It means that an occurrence of Nil value causes that operation execution is aborted and Nil value is returned as operation result.

enum

Any of the enumeration types declared in the type system. An enumeration type defines a limited group of items which can be assigned to a value of given type. Every one of these items (constants) is identified by a unique name among the given enumeration type (e.g. enumeration type SortingOrder has two possible values: Ascending and Descending).

As part of formulas it is possible to create a value of enumeration type and to compare two values of the same enumeration type.

enum?
enum*

Any conditional or optional enumeration type, instead of a constant, it can additionally take value of Nil (empty value).

structure

Any structure - a composition of a number of values of potentially different types in one object. Within formulas, it is possible to read separately structure elements and to perform further operations on them within their types.

structure?
structure*

Any conditional or optional structure, instead of field composition, it can additionally take value of Nil (empty value).

It is possible to get access to fields of conditional structures on the same basis as in the case of normal structures. However, a field to be read is also of conditional type. Reading fields of a conditional structure of value Nil returns as a result Nil value as well.

<T>Array

Any array of values. Within formulas, it is possible to determine array size, read and perform further operations on array elements.

Array size can be determined by .Length property which is built-in in array types.

<T>Array?
<T>Array*

Any conditional or optional array, instead of elements sequence it can additionally take value of Nil (empty value).

It is possible to read sizes and elements of conditional arrays on the same basis as in the case of normal arrays. In this case, values to be read are also of conditional type. Reading an element from a conditional array of Nil value returns as a result Nil value as well.

## Literal constants

You can place constant values in a formula by writing them down literally in the specified format.

Data type Example
Integer value in decimal notation Integer 0
150
-10000
Long 0L
150L
-10000L
Integer value in hexadecimal notation Integer 0xa1c
0x100
0xFFFF
Long 0xa1cL
0x100L
0xFFFFL
Real value in decimal notation Real 0.0
0.5
100.125
-2.75
Double 0.0d
0.5d
100.125d
-2.75d
Real value in scientific notation Real 1e10
1.5e-3
-5e7
Double 1e10d
1.5e-3d
-5e7d
Text String "Hello world!"
"First line\nSecond line"
"Text with \"quote\" inside."

### Textual constants

Textual constants are a way to insert data of type String into formula. They can be used for example in comparison with input data or in conditional generating of proper text to output of formula block. Textual constants are formatted by placing some text in quotation marks, e.g.: "This is text"; the inner text (without quotation marks) becomes value of a constant.

In case you wish to include in a constant characters unavailable in a formula or characters which are an active part of a formula (e.g. quotation marks), it is necessary to enter the desired character using escape sequence. It consists of backslash character (\) and proper character code (in this case backslash character becomes active and if you wish to enter it as a normal character it requires the use of escape sequence too). It is possible to use the following predefined special characters:

• \n - New line, ASCII: 10
• \r - Carriage return, ASCII: 13
• \t - Horizontal tabulation, ASCII: 9
• \' - Apostrophe, ASCII: 39
• \" - Quotation mark, ASCII: 34
• \\ - Backslash, ASCII: 34
• \v - Vertical tabulation, ASCII: 11
• \a - "Bell", ASCII: 7
• \b - "Backspace", ASCII: 8
• \f - "Form feed", ASCII: 12

Examples:

 "This text \"is quoted\"" "This text\nis in new line" "In Microsoft Windows this text:\r\nis in new line." "c:\\Users\\John\\" 

Other characters can be obtained by entering their ASCII code in hexadecimal format, by \x?? sequence, e.g.: "send \x06 ok" formats text containing a character of value 6 in ASCII code, and "\xce" formats a character of value 206 in ASCII code (hex: ce).

## Predefined constant values

As part of formula, it is possible to obtain access to one of the below-mentioned predefined constant values. In order to use a constant value as operation argument, it is required to enter the name of this constant value.

Name Data type Description
true Bool

Positive logic value.

false Bool

Negative logic value.

Nil Null

Special value of conditional and optional types, it represents an empty value (no value).

This constant doesn't has its own data type (it is represented by the special type of "Null"). Its type is automatically converted to conditional types as part of executed operations.

pi Real

Real value, it is the approximation of π mathematical constant.

e Real

Real value, it is the approximation of e mathematical constant.

### Enumeration constants

There are enumeration constants defined in the type system. They have their own types and among these types a given constant chooses one of a few possibilities. E.g. a filter for array sorting takes a parameter which defines the order of sorting. This parameter is of "SortingOrder" enumeration type. As part of this type, you can choose one of two possibilities identified by "Ascending" and "Descending" constants.

As part of formulas, it is possible to enter any enumeration constant into formula using the following syntax:

<enum name>.<item name>

Full name of a constant used in a formula consists of enumeration type name, of a dot and of name of one of the possible options available for a given type, e.g.:

 SortingOrder.Descending BayerType.BG GradientOperator.Gauss 

## Arithmetic conversions

Binary arithmetic operators are executed as part of one defined common type. In case when the types of both arguments are not identical, an attempt to convert them to one common type is performed, on this type the operation is then executed. Such conversion is called arithmetic conversion and when it's possible to carry it out, the types of arguments are called compatible.

Arithmetic conversion is performed as part of the following principles:

Conditions Performed conversions
Two different numeric types. The argument of type with smaller range or precision is converted to the type of second argument (with greater range or precision). Possible argument type conversions includes: Integer to Real, Integer to Long, Integer to Double and Real to Double. The same principle is used in case of conditional counterparts of mentioned types.
One of the types is conditional. The second type is converted to conditional type.
Two different conditional types. Arithmetic conversion is performed as part of types on which arguments conditional types are based. As the result, the types remain conditional.
One of the arguments is Nil. The second argument is converted to conditional type (if it's not already conditional), Nil value is converted to the conditional type of the second argument.

## Automatic implicit conversions

When some operation requires an argument of certain type and, instead of it, an argument of different type is used, implicit conversion of such argument type is attempted using the below-mentioned principles.

Conversion Description
Integer → Real
Integer → Double

Conversion of integer to floating-point value. As part of such conversion loss of precision may occur. As the result of it, instead of accurate number representation, an approximated floating-point value is returned.

Such conversion is also possible when it comes to conditional counterparts of given types.

Integer → Long
Real → Double

Conversion to equivalent type with greater range or precision. No data is lost as a result of such conversion.

Such conversion is also possible when it comes to conditional counterparts of given types.

T → T?

Assigning conditionality. Any non-conditional type can be converted to its conditional counterpart.

Nil → T?

Assigning type to a Nil value. Nil value can be converted to any conditional type. As the result of it, you get an empty value of given type.

T* → T?

As part of formulas, optional and conditional types are handled the same way (in formulas there is no defined reaction for automatic values, they only pass data). If given operation requires argument of conditional type, then it also can, basing on the same principles, take argument of optional type.

## Operators

As part of formulas, it is possible to use the following operators:

 Negation operator: - Identity operator: + Two's complement: ~ Logic negation: not Multiplicative operators: * / div mod Additive operators: + - Bit shift: >> << Bitwise operators: & | ^ Logic operators: and or xor Comparison operator: < <= > >= Equality testing: == <> Conditional operator: if-then-else  ?: Merge with default value: ?? Function call: function() Field read: . Array element read: [] Previous value of output: prev()

### Unary operators

##### Negation operator (-)
- expression

Data types: Integer, Real, Long, Double

Returns numeric value with negated sign.

##### Identity operator (+)
+ expression

Data types: Integer, Real, Long, Double

Returns numeric value without any changes.

##### Two's complement operator (~)
~ expression

Data types: Integer, Long

Returns integer value with negated bits (binary complement).

##### Logic negation operator (not)
not expression

Data types: Bool

Returns logic value of an opposite state.

### Binary operators

##### Multiplication operator (*)
expression * expression

Data types: Integer, Real, Long, Double

Returns product of two numeric arguments.

##### Real division operator (/)
expression / expression

Data types: Real, Double

Returns quotient of two real numbers.

##### Integer division operator (div)
expression div expression

Data types: Integer, Long

Returns quotient of two integer numbers without residue. A Domain Error appears during program runtime when second argument is equal to zero.

##### Modulo operator (mod)
expression mod expression

Data types: Integer, Long

Returns residue from division of two integer numbers. A Domain Error appears during program runtime when second argument is equal to zero.

##### Addition operator (+)
expression + expression

Data types: Integer, Real, Long, Double, String

Returns sum of two numeric values.

In case of using it with String type, it performs text concatenation and returns connected string.

##### Subtraction operator (-)
expression - expression

Data types: Integer, Real, Long, Double

Returns difference of two numeric values.

##### Bit right-shift (>>)
expression >> expression

Data types: Integer, Long

Returns value of the first argument, in which bits of its binary representation have been shifted right (in the direction of the less meaningful bits) by the number of positions defined by the second argument. After the shift, bits which exceed the type range on the right side are ignored. The lacking bits on the left side are filled in with zeros.

A Domain Error appears during program runtime when second argument is negative. In case of shift value larger than 31 for Integer type, or larger than 63 for Long type, the value of 0 will be returned.

##### Bit left-shift (<<)
expression << expression

Data types: Integer, Long

Returns value of the first argument, in which bits of its binary representation have been shifted left (in the direction of the more meaningful bits) by the number of positions defined by the second argument. After the shift, bits which exceed the type range on the left side are ignored. The lacking bits on the right side are filled in with zeros.

A Domain Error appears during program runtime when second argument is negative. In case of shift value larger than 31 for Integer type, or larger than 63 for Long type, the value of 0 will be returned.

##### Bitwise AND (&)
expression & expression

Data types: Integer, Long

Returns value of bitwise product of two integer numbers. This operator compares separately each pair of corresponding bits of two arguments. If values of both bits equal 1, then the result bit also equals 1. If value of at least one bit equals 0, then the result bit equals 0.

##### Bitwise OR (|)
expression | expression

Data types: Integer, Long

Returns value of bitwise sum of two integer numbers. This operator compares separately each pair of corresponding bits of two arguments. If value of at least one bit equals 1, the result bit also equals 1. If values of both bits equal 0, then the result bit equals 0.

##### Bitwise exclusive OR (^)
expression ^ expression

Data types: Integer, Long

Returns value of bitwise exclusive sum of two integer numbers. This operator compares separately each pair of corresponding bits of two arguments. If two bits are equal, the result bit equals 0. If two bits are not equal, then the result equals 1.

##### Logic AND (and)
expression and expression

Data types: Bool

This operator merges two logic arguments. If both arguments equal true, then the result also equals true. If at least one of the arguments equals false, then the result equals false.

##### Logic OR (or)
expression or expression

Data types: Bool

This operator merges two logic arguments. If at least one of the arguments equals true, then the result equals true. If both arguments equal false, then the result also equals false.

##### Logic exclusive OR (xor)
expression xor expression

Data types: Bool

This operator merges two logic arguments. If the arguments are unequal, then the result equals true. If the arguments are equal, then the result equals false.

##### Less than (<)
expression < expression

Data types: Integer, Real, Long, Double, String

Result type: Bool

This operator compares two values. It returns value of true only if value of the first argument is smaller than value of the second argument.

In case of using it with String type, the operator performs lexicographic text comparison.

##### Less than or equal to (<=)
expression <= expression

Data types: Integer, Real, Long, Double, String

Result type: Bool

This operator compares two values. It returns value of true only if value of the first argument is smaller than or equal to value of the second argument.

In case of using it with String type, the operator performs lexicographic text comparison.

##### Greater than (>)
expression > expression

Data types: Integer, Real, Long, Double, String

Result type: Bool

This operator compares two values. It returns value of true only if value of the first argument is larger than value of the second argument.

In case of using it with String type, the operator performs lexicographic text comparison.

##### Greater than or equal to (>=)
expression >= expression

Data types: Integer, Real, Long, Double, String

Result type: Bool

This operator compares two values. It returns value of true only if value of the first argument is larger than or equal to value of the second argument.

In case of using it with String type, the operator performs lexicographic text comparison.

##### Equality test (==)
expression == expression

Data types: any compatible types

Result type: Bool

This operator compares two arguments. If their values are equal, it returns value of true, otherwise it returns value of false. It's possible to determine the equality not only between compatible primitive types, but also between objects of any two same types (e.g. structures).

Please note that comparing values of type Real or Double (or structures with those types) may be tricky. It is caused by the fact that very small (unnoticeable) differences in values of such types may lead to unpredictable negative results of the comparison.

The operator treats conditional values in a special way. An occurrence of conditional type in one or both arguments doesn't cause that the whole operator is executed conditionally. Empty values of conditional types take part in comparisons too. It is also possible to determine if an argument carries a conditional empty value by comparing it to Nil constant.

This operator never returns conditional type.

##### Inequality test (<>)
expression <> expression

Data types: any compatible types

Result type: Bool

This operator performs an identical comparison to == operator, but it returns an opposite value (true, when arguments are not equal).

### Special operators

##### Conditional operator (if-then-else, ?:)
 if condition_expression then expression_1 else expression_2 if   condition_expression_1 then expression_1 elif condition_expression_2 then expression_2  (...) elif condition_expression_n then expression_n_minus_1 else expression_n condition_expression ? expression_1 : expression_2 

Data types:

• condition_expression_x: Bool
• expression_1, expression_2, ..., expression_n: any compatible types

This operator conditionally chooses and returns one of two or more values.

Condition value of type Bool is the first argument. If this argument equals true, then the first of values to choose from (the second argument of the operator) is returned as a result. If the first argument equals false, then the next from values to choose from is evaluated and returned as a result of the operation.

When connecting multiple conditions in a row (evaluating multiple conditions), next condition can be started with elif clause in place of else element. Conditions are then evaluated in order one-by-one.

The operator treats conditional values in a special way. An occurrence of conditional type only in case of the first argument (condition value) causes that the whole operator is executed conditionally. Conditional types in arguments of values to choose from don't make any changes in operator execution. Values of these arguments are always passed in the same way to operation result (also in case of empty value).

Operator result type is determined by combining types of values to choose from (by converting one type to another or by converting two types into yet another common result type), according to the principles of arithmetic conversions. Such type can be changed to a conditional type in case of operator conditional execution.

##### Merge with default (??)
expression ?? expression

Data types: any compatible types

This operator requires that the first argument is of conditional type. If the first argument returns a non-empty value, then this value becomes the result of the whole operation. If the first argument returns an empty value (Nil), then the value of the second argument becomes the result of the whole operation.

Operation result type is the type proceeding from combining types of two arguments, but with a modified conditionality. If the second argument is of non-conditional type, then the result of the whole operation is non-conditional too. If the second argument is of conditional type, then the result of the whole operation is conditional.

This operator can be used for choosing an alternative value basing on a condition of the empty first argument.

The operator is called merging with default value, because it allows removing conditionality from an argument and replacing its empty value with a default value. In order to do this, the second argument cannot be of conditional type.

This operator is intended to handle conditional types, it means that the operator itself is never executed conditionally.

##### Function call (function())
function(arg_1, arg_2, ..., arg_n)

Function call is performed by entering function name and a follow-up list of arguments in curly brackets. Required data types depend on called function.

##### Field read (.)
expression.name

This operator is used to read a single structure field or a property supported by an object. Operation result type is compatible with the type of the field which is read.

Any structure (from which a field of any type is read) can be passed as an argument.

name determines name of a field (or property), which should be read.

##### Object function call (.function())
expression.function(arg_1, arg_2, ..., arg_n)

This construction is intended to call a function provided by an object (defined by data type of expression object).

Access to this function is provided (similar to field read operator) by entering a dot sign and the function name after an argument. After the function name a list of function arguments should be entered in round brackets. The required data types depend on the function which is called.

##### Array element read ([])
expression[indexer]

This operator is used to read a single element from an array. Operator result type is equal to the array elements type. An indexer has to be an argument of type Integer, its value points to an element to be read (value of 0 indicates the first array element). If an indexer returns a value pointing out of 0...ArrayLength-1 range, then the operator causes that a Domain Error appears during program runtime.

##### Previous value of output (prev())
prev(outputName, defaultValue)prev(outputName)

This operator is used to read the value of a formula block output from the previous iteration of a task loop, inside which the formula block is instantiated. This operator takes an identifier as its first argument - the name of the formula block output. Any output of the parent formula block can be used, including the current formula output and outputs of formulas defined below the current one.

Second argument of the operator defines a default value and can accept any expression.

The purpose of this operator is to create an aggregate or sequence generating formula. In the first iteration of a task, this operator returns the default value (defined by the second argument). In each subsequent task iteration the operator returns the value previously computed by the referenced formula output (defined by the first argument).

Operator result type is determined by combining types of referenced output and default value argument, according to the principles of arithmetic conversions.

Second argument of the operator can be omitted. In such situation Nil is used as the default value and the result type is a conditional equivalent of the accessed output type. You can use the merge with default (??) operator to handle a Nil value.

## Operator precedence

In case of using more than one operator in the surrounding of the same argument, the precedence of executing these operators depends on their priorities. In the first instance, operators with the highest priority are executed. In case of binary operators with equal priorities, the operators are executed one after another from left to right, e.g.:

A + B * C / D

In the first instance, arguments B and C are multiplied (multiplication has higher priority than addition and, in this case, is located left from division operator which has the same priority). Multiplication result is divided by D (going from left to right), and then the quotient is added to A.

Unary operators, which are always in form of prefixes, are executed from the closest operator to an argument to the furthest one, that is from right to left.

Ternary conditional operators are executed in order from right to left. It enables nesting conditions as part of other conditional operators arguments.

Order of operators execution can be changed by placing nested parts of formulas in brackets, e.g.:

(A + B) * (C / D)

In this case, addition and division are executed in the first instance, then their results are multiplied.

#### Operator priorities

#OperatorDescription
1 []Array element read
()Function call
.Structure field read
.name()Object function call
2 +Identity
-Negation
~Bitwise negation
notLogic negation
3 * / div modMultiplicative operators
4 + -Additive operators
5 >> <<Bit shift
6& Bitwise operators
7^
8|
9 < <= > >=Values comparison
10 ==Equality test
<>Inequality tests
11and Logic operators
12xor
13or
14 ??Merge with default value
15 ?: Conditional operator
16 if-then-else

A lower number means higher priority and earlier execution of operator.

## Functions

As part of formulas, you can use one of the functions listed below by using a function call operator. Each function has its own requirements defined regarding the number and types of individual arguments. Functions with the same names can accept different sets of parameters types, on which the returned value type depends. Each of the functions listed below has its possible signatures defined in form of descriptions of parameters data types and returned value types resulting from them, e.g.:

Real foo( Integer, Real )

This signature describes the "foo" function, which requires two arguments, the first of type Integer and the second of type Real. The function returns a value of type Real. Such function can be used in a formula in the following way:

outValue = foo(10, inValue / 2) + 100

Arguments passed to a function don't have to exactly match a given signature. In such case, the best fitting function version is chosen. Then an attempt to convert arguments types to a form expected by a function is performed (according to the principles of implicit conversions). If choosing a proper function version for arguments types is not possible or, if it's not possible to convert one or more arguments to required types, then program initialization ends up with an error of incorrect function parameters set.

A conditional or optional type can be used as an argument of each function. In such case, if function signature doesn't assume some special use of conditional types, the entire function call is performed conditionally. A returned value is then also of a conditional type, an occurrence of an empty value among function arguments results in returning an empty value as function result.

### Built-in functions

##### sin
Real sin( Real )Double sin( Double )

Returns an approximation of the sine trigonometric function. It takes an angle measured in degrees as its argument.

##### cos
Real cos( Real )Double cos( Double )

Returns an approximation of the cosine trigonometric function. It takes an angle measured in degrees as its argument.

##### tan
Real tan( Real )Double tan( Double )

Returns an approximation of the tangent trigonometric function. It takes an angle measured in degrees as its argument.

##### asin
Real asin( Real )Double asin( Double )

Returns an approximation of the inverse sine trigonometric function. It returns an angle measured in degrees.

##### acos
Real acos( Real )Double acos( Double )

Returns an approximation of the inverse cosine trigonometric function. It returns an angle measured in degrees.

##### atan
Real atan( Real )Double atan( Double )

Returns an approximation of the inverse tangent trigonometric function. It returns an angle measured in degrees.

##### exp
Real exp( Real )Double exp( Double )

Returns an approximated value of the e mathematical constant raised to the power of function argument: exp(x) = ex

##### ln
Real ln( Real )Double ln( Double )

Returns an approximation of natural logarithm of its argument: ln(x) = loge(x)

##### log
Real log( Real )Double log( Double )

Returns an approximation of decimal logarithm of its argument: log(x) = log10(x)

##### sqrt
Real sqrt( Real )Double sqrt( Double )

Returns the square root of its argument: sqrt(x) = 2√x

##### floor
Real floor( Real )Double floor( Double )

Rounds an argument down, to an integer number not larger than the argument.

##### ceil
Real ceil( Real )Double ceil( Double )

Rounds an argument up, to an integer number not lesser than the argument.

##### round
Real round( Real, [Integer] )Double round( Double, [Integer] )

Rounds an argument to the closest value with a strictly defined number of decimal places. The first function argument is a real number to be rounded. The second argument is an optional integer number, defining to which decimal place the real number should be rounded. Skipping this argument effects in rounding the first argument to an integer number.

Examples:

 round(1.24873, 2) → 1.25 round(1.34991, 1) → 1.3 round(2.9812) → 3.0 
##### abs
Real abs( Real )Integer abs( Integer ) Double abs( Double )Long abs( Long )

Returns the absolute value of an argument (removes its sign).

##### pow
Real pow( Real, Integer )Real pow( Real, Real ) Double pow( Double, Integer )Double pow( Double, Double )

Raises the first argument to the power of the second argument. Returns the result as a real number: pow(x, y) = xy

##### integer
Integer integer( Real )Integer integer( Double ) Integer integer( Long )

Converts an argument to Integer type by cutting off its fractional part or ignoring most significant part of integer value.

##### real
Real real( Integer )Real real( Long ) Real real( Double )

Converts an argument to Real type.

##### long
Long long( Real )Long long( Double ) Long long( integer )

Converts an argument to Long type (cuts off fractional part of floating-point values).

##### double
Double double( Integer )Double double( Long ) Double double( Real )

Converts an argument to Double type.

##### toString
 String toString( Bool ) String toString( Integer ) String toString( Real ) String toString( Long ) String toString( Double ) 

Converts the argument to readable textual form.

##### min
 Integer min( Integer, Integer ) Real min( Real, Real ) Long min( Long, Long ) Double min( Double, Double ) Integer min( IntegerArray ) Real min( RealArray ) Long min( LongArray ) Double min( DoubleArray ) 

Returns the smallest of input values. This function can take two primitive numeric arguments, from which it chooses the smallest value or an array of primitive numeric values, in which the smallest value is searched for. In case of an attempt to search for a value in an empty array, an operation runtime error is reported.

##### max
 Integer max( Integer, Integer ) Real max( Real, Real ) Long max( Long, Long ) Double max( Double, Double ) Integer max( IntegerArray ) Real max( RealArray ) Long max( LongArray ) Double max( DoubleArray ) 

Returns the largest of input values. This function can take two primitive numeric arguments, from which it chooses the largest value or an array of primitive numeric values, in which the largest value is searched for. In case of an attempt to search for a value in an empty array, an operation runtime error is reported.

##### avg
 Integer avg( Integer, Integer ) Real avg( Real, Real ) Long avg( Long, Long ) Double avg( Double, Double ) Integer avg( IntegerArray ) Real avg( RealArray ) Long avg( LongArray ) Double avg( DoubleArray ) 

Computes the arithmetic mean of input values. This function can take two primitive numeric arguments, which are averaged or an array of primitive numeric values, which is averaged altogether. In case of an attempt to enter an empty array, an operation runtime error is reported.

##### lerp
 Integer lerp( Integer a, Integer b, Real lambda ) Real lerp( Real a, Real b, Real lambda ) Long lerp( Long a, Long b, Real lambda ) Double lerp( Double a, Double b, Double lambda ) 

Computes a linear interpolation between two numeric values. Point of interpolation is defined by the third argument of type Real in range from 0.0 to 1.0 (0.0 for value equal to a, 1.0 for value equal to b).

##### sum
 Integer sum( IntegerArray ) Real sum( RealArray ) Long sum( LongArray ) Double sum( DoubleArray ) 

Returns the sum of input values. This function can take an array of primitive numeric values, which will be summed altogether. In case of entering an empty array, the value of 0 will be returned.

Note: in case of summing large values or a big number of real arguments, it's possible to partially lose the result precision and, due to this, to mangle the final result. In case of summing integer numbers of too large values, the result may not fit in the allowed data type range.

##### product
 Integer product( IntegerArray ) Real product( RealArray ) Long product( LongArray ) Double product( DoubleArray ) 

Returns the product of entered values. This function can take an array of primitive numeric values, which all will be multiplied. In case of entering an empty array, the value of 1 will be returned.

Note: in case of multiplying large values or a big number of real arguments, it's possible to partially lose the result precision and, due to this, to mangle the final result. In case of multiplying integer numbers of too large values, the result may not fit in the allowed data type range.

##### variance
 Real variance( RealArray ) Double variance( DoubleArray ) 

Computes statistic variance from a set of numbers provided as an array in the argument. Result is computed using the formula: 1n∑(x - xi)2. In case of an attempt to enter an empty array, a domain error is reported.

##### stdDev
 Real stdDev( RealArray ) Double stdDev( DoubleArray ) 

Computes statistic standard deviation from a set of numbers provided as an array in the argument. Result is equal to a square root of variance described above. In case of an attempt to enter an empty array, a domain error is reported.

##### median
 Integer median( IntegerArray ) Real median( RealArray ) Long median( LongArray ) Double median( DoubleArray ) 

Returns the median value from a set of numbers provided as an array in the argument. In case of an attempt to enter an empty array, a domain error is reported.

##### nthValue
 Integer nthValue( IntegerArray, Integer n ) Real nthValue( RealArray, Integer n ) Long nthValue( LongArray, Integer n ) Double nthValue( DoubleArray , Integer n) 

Returns the n-th value in sorted order from a set of numbers provided as an array in the argument. The zero-based index n, of type Integer, is provided as the second argument. In case of an attempt to enter an empty array, a domain error is reported.

##### quantile
 Integer quantile( IntegerArray, Real point ) Real quantile( RealArray, Real point ) Long quantile( LongArray, Real point ) Double quantile( DoubleArray , Real point ) 

Returns the specified quantile from a set of numbers provided as an array in the argument. In case of an attempt to enter an empty array, a domain error is reported.

##### all
Bool all( BoolArray )

This function takes an array of logical values and returns True when all elements in the array are equal to True. In case of entering an empty array, the value of True will be returned.

##### any
Bool any( BoolArray )

This function takes an array of logical values and returns True when at least one element in the array equals True. In case of entering an empty array, the value of False will be returned.

### Functions of type String

On text arguments it is possible to call functions (according to object function call operator) processing or inspecting a text string, e.g.:

outText = inText.Replace( "to-find", inNewText.ToLower() )


The type of String provides the following object functions:

##### Substring
 String arg.Substring( Integer position ) String arg.Substring( Integer position, Integer length ) 

This function returns the specified part of text. The first argument defines the position (starting from zero) on which the desired part starts in text. The second argument defines the desired length of returned part of text (this length can be automatically shortened when it exceeds the text length). Leaving out the second argument results in returning the part of text from the specified position to the end of text.

##### Trim
String arg.Trim()

Returns argument value, from which the whitespace characters have been removed from the beginning and the end.

##### ToLower
String arg.ToLower()

Returns argument value, in which all the upper case letters have been changed to their lower case equivalents.

##### ToUpper
String arg.ToUpper()

Returns argument value, in which all the lower case letters have been changed to their upper case equivalents.

##### Replace
String arg.Replace( String find, String insert )

Searches text for all occurrences of the value entered as the first argument and replaces such occurrences with the value entered as the second argument. Text search is case sensitive.

This function searches the source text consecutively from left to right and leaps the occurrences immediately after finding them. If the sought-after parts overlap in the text, only the complete occurrences found this way will be replaced.

##### StartsWith
Bool arg.StartsWith( String )

This function returns True only if text contains at its beginning (on the left side) the value entered as the argument (or if it is equal to it). Text search is case sensitive.

##### EndsWith
Bool arg.EndsWith( String )

This function returns True only if text contains at its end (from the right side) the value entered as the argument (or if it is equal to it). Text search is case sensitive.

##### Contains
Bool arg.Contains( String )

This function returns True only if text contains (as a part at any position) the value entered as the argument (or if it is equal to it). Text search is case sensitive.

##### Find
 Integer arg.Find( String ) Integer arg.Find( String, Integer ) 

This function searches in text for the first occurrence of the part entered as the argument (it performs searching from left to right) and returns the position, at which an occurrence has been found. It returns -1 when the sought-after substring doesn't occur in text. Text search is case sensitive.

Optionally, as the second function argument, one can enter the starting position from which the search should be performed.

##### FindLast
 Integer arg.FindLast( String ) Integer arg.FindLast( String, Integer ) 

This function searches in text for the last occurrence of the part entered as the argument (it performs search starting from right) and returns the position, at which an occurrence has been found. It returns -1 when the sought-after substring doesn't occur in text. Text search is case sensitive.

Optionally, as the second function argument, one can enter the starting position from which the search should be performed (and proceed in the direction of text beginning).

##### IsEmpty
Bool arg.IsEmpty()

This function returns True if text is empty (its length equals 0).

### Structure constructors

As part of formulas, you can pass and access fields of any structures. It's also possible to generate a new structure value, which is passed to further program operations.

In order to generate a structure value, a structure constructor (with syntax identical to the function with the name of the structure type) is used. As part of structure parameters, structure fields values should be entered consecutively. E.g. the constructor below generates a structure of type Box, starting in point 5, 7, with width equal to 100 and height equal to 200:

Box(5, 7, 100, 200)

Not all structure types are available through constructors in formulas. Only structures consisting of fields of primitive data types and not requiring specific dependencies between them are available. E.g. types such as Box, Circle2D or Segment2D consist of arithmetic types and due to this creating them in formulas is possible. Types such as Image, Region or Path have complex data blocks describing primitives and therefore it's not possible to create them in formulas.

Some structures have additional requirements on field values (e.g. Box requires that width and height be non-negative). When such a requirement is not met a Domain Error appears during program runtime.

## Examples

#### Summing two integer values

 Filter inputs: inA of type Integer inB of type Integer Filter outputs: outSum of type Integer
 outSum = inA + inB 

#### Linear interpolation of two integer values

Having given two integer values and the position between them in form of a real number 0...1, the task is to compute the interpolated value in this position.

 Filter inputs: inA of type Integer inB of type Integer inPos of type Real Filter outputs: outValue of type Integer
 outValue = integer(round( inA * (1 - inPos) + inB * inPos )) 

A simple weighted averaging of two given values is performed here. Due to the multiplication by real values, the intermediate averaging result is also a real value. It's necessary then to round and convert the final result back to integer value.

#### Computing a center of Box primitive

Box is a data structure consisting of four fields of type Integer: X, Y, Width and Height. Having given an object of such primitive, the task is to compute its center in form of two integer coordinates X and Y.

 Filter inputs: inBox of type Box Filter outputs: outX of type Integer outY of type Integer
 outX = inBox.X + inBox.Width div 2 outY = inBox.Y + inBox.Height div 2 

#### Generating a structure

In the previous example, data used in a formula is read from a primitive of type Box. Such primitive can also be generated inside of a formula and passed to an output. In this example, we'd like to enlarge a Box primitive by a frame of given width.

 Filter inputs: inBox of type Box inFrame of type Integer Filter outputs: outBox of type Box
 outBox = Box( inBox.X - inFrame, inBox.Y - inFrame, inBox.Width + inFrame*2, inBox.Height + inFrame*2 ) 

#### Partial conditional execution

In case of working with conditional types, it's possible, as part of formula blocks, to use primitive types and to use conditional filters execution, including conditional execution of entire formula blocks. It's also possible to pass conditional execution inside formulas. This way, only a part of formulas of a block, or even only a part of a single formula, is executed conditionally.

In the simple summing shown below, parameter B is of a conditional type and this conditionality is passed to output.

 Filter inputs: inA of type Real inB of type Real? inC of type Integer Filter outputs: outValue of type Real?
 outValue = inA + inB + inC 

Formula content itself doesn't contain any specific elements related to a conditional parameter. Only formula output is marked with a conditional type. An occurrence of an empty value in input causes aborting execution of further operators and moving an empty value to output, in a similar way to operations on filters.

#### Replacing an empty value with a default object

If the conditional output type and thereby the conditional execution mode of following filters were not desired in the example above, it's possible to resolve the conditional type still in the same formula by creating a connection with a non-conditional default value.

 Filter inputs: inA of type Real inB of type Real? inC of type Integer Filter outputs: outValue of type Real
 outValue = (inA + inB + inC) ?? 0 

Addition operators still work on conditional types, the entirety of their calculations can be aborted when an empty value occurs. The result is however merged with a default value of 0. If summing doesn't return a non-empty result, then the result value is replaced with such non-empty value. In such case, an output doesn't have to be of conditional type.

#### Empty array response

In order to find the maximal value in an array of numbers, you can use the max function, it requires although a non-empty array. If an explicit reaction to such case is possible, we can define it by a condition and thereby avoid an error by passing an empty sequence to input.

 Filter inputs: inElements of type IntegerArray Filter outputs: outValue of type Integer
 outValue = (inElements.Length > 0) ? max(inElements) : 0 

In the example above a value of zero is entered instead of maximum of an empty array.

#### Range testing

Let's assume that we test a position of some parameter, which varies in the range of -5...10 and we'd like to normalize its value to the range of 0...1. What's more, the reaction to an error and to range overrun by a parameter is returning an empty value (which means conditional execution of further operations).

 Filter inputs: inParameter of type Real Filter outputs: outRangePos of type Real?
 outRangePos = (inValue >= -5 and inValue <= 10) ? (inValue + 5) / 15 : Nil 

#### Choosing a constant enumeration value

If block results should control operations which take enumeration types as parameters, then it's possible to generate values of such types as part of formulas. In the example below we'd like to determine the sorting direction, having given a flag of type Bool, which determines, if the direction should be opposite to the default one.

 Filter inputs: inReverse of type Bool Filter outputs: outOrder of type SortingOrder
 outOrder = inReverse ? SortingOrder.Descending : SortingOrder.Ascending 

#### Adding integer values of the loop

This example works in a loop, in each iteration there is some value passed to the inValue input and the goal is to sum these values. The prev operator returns 0 in the first iteration (as defined by its second argument). In each iteration the value of inValue input is added to the sum from the previous iteration.

 Filter inputs: inValue of type Integer Filter outputs: outSum of type Integer
 outSum = prev(outSum, 0) + inValue 
 Previous: Macrofilters Next: Error Handling