# List of functions in Envision

Home » Resources » Here

This page lists the functions supported by Envision. The primary purpose of functions is to extend the capabilities of Envision whenever the basic language syntax would not be sufficient.

## Function syntax

The general syntax for functions is:
x = fun(arg1, arg2, arg3)

With fun replaced by the name of the function, and the argN, the comma-delimited list of arguments passed to the function. All functions operate on vectors.

## Mathematical functions

• abs(number): similar to the ABS function in Excel.
• ceiling(number): similar to the CEILING function in Excel.
• exp(number): similar to the EXP function in Excel.
• floor(number): similar to the FLOOR function in Excel.
• log(number, base): similar to the LOG function in Excel. The base argument is optional, when it is omitted, it is assumed to be 10.
• max(num1, num2, num3, ..., numN): similar to the MAX function in Excel.
• min(num1, num2, num3, ..., numN): similar to the MIN function in Excel.
• norminv(number): similar to the NORMINV function in Excel with a mean at 0 and a standard deviation at 1.
• pow(number, exponent): similar to the POWER function in Excel. Envision also support the power operator number ^ exponent which performs the same calculation.
• round(number, digits): similar to the ROUND function in Excel. Second argument is optional, and represents the number of digits that intended to be kept.
• sqrt(number): similar to the SQRT function in Excel.

## Text functions

• concat(text1, text2, ..., textN): concatenate text values from text1 to textN.
• contains(text, pattern): Returns true if the text contains an occurrence of the pattern.
• endswith(text, pattern): Returns true if the text ends with an occurrence of the pattern.
• field(text, separator, index): Returns the nth field (zero-indexed) in a text value that contains multiple sub-strings separated by a specified separator. Ex: field("a-b-c-d-", "-", 2) == "c". This function is intended to facilitate parsing values that have been concatenated within a single table column.
• indexof(text, pattern): Returns the index of the first occurrence of the pattern within the text, or -1, if not such occurrence is found.
• lowercase(text): Returns the lowercase variant of the text.
• parsedate(text, format): Converts the text into a date using the specified format. The format is optional. When the format is omitted, the date is parsed based on the date format auto-detection behavior of Envision. When the format is provided, the date is parsed against the format expectation. See custom date format string for the detail for the format syntax. If a date cannot be parsed, the date 2001-01-01 is returned instead.
• parsenumber(text): Converts the text into a number. The parser leverages the number format auto-detection behavior of Envision. If the number cannot be parsed, zero is returned instead.
• parsetime(text, format): Converts a time of the day into a fraction between 0 and 1, representing a fractional day. The format is optional. When the format is not specified, the default value yyyy-MM-dd HH:mm:ss is used. Envision is using the .NET Custom Time Format.
• replace(text, pattern, replacement): Returns the text where all occurrences of the pattern have been replaced by the replacement. This function is similar to the SUBSTITUTE function of Excel, omitting the instance_num argument.
• startswith(text, pattern): Return true if the text starts with an occurrence of the pattern.
• strlen(text): Returns the length of the text argument.
• substr(text, start, count): The start position is defined by start. If negative, it's an offset from the end of the string, otherwise it's an offset from the start of the string. The length of the returned substring is defined by count, treated as 0 if count < 0. If the segment start or length place it partially or completely outside the string, e.g. substr("A", 2, 1), then the segment is clipped to fit. Function substr(text, start) is defined as substr(text, start, <infinity>).
• uppercase(text): Returns the uppercase variant of the text.

## Calendar functions

• "\{myDate:yyyy-MM-dd}": custom date formatting through string interpolation. The date format is specified by the token found after the semi-colon. More details about date format strings.
• chineseYear(date): Returns the current year in the Chinese calendar.
• chineseYearEnd(date): Returns the last day of the current Chinese Year.
• chineseYearStart(date): Returns the first day of the current Chinese year.
• date(y, m, d): Returns a date built from the year, month and day passed as arguments. The arguments y, m and d are expected to be numbers.
• monday(date): Returns the first Monday that precedes the date (inclusive).
• month(date): Returns the index of the month associated to the date, counting the number of months since January 1st 2001.
• monthnum(date): Returns the applicable month (1-12) for the date passed as argument.
• today(timezone): Return the current wall-time date with the time-zone passed as argument and expressed as the difference in hours to UTC.
• year(date): Returns the applicable year for the date passed as argument. Similar to the YEAR function in Excel.
• yearStart(date): Returns the first day of the year for the current year.
• yearEnd(date): Returns the last day of the year for the current year.
• weeknum(date): Similar to the WEEKNUM (System 2) function in Excel.

## Ranking functions

• argfirst(ordering, group): Returns true for one first value of the group according to the ordered values (the ordering). The group is optional. When the group is provided, the function returns true once per group. An overload argfirst(ordering, group) where condition is also provided for convenience. When the where option is used, it may result in groups where no true value is present, because the condition was false for the entire group.
• arglast(ordering, group): Same as argfirst(), but returning true for the one last value.
• cumsum(number, rank, group): Returns the cumulative sum of the numbers according to the increasing ranks. The group is optional. When the group is specified, it is used to perform a local cumulative sum for each group.
• fifo(V, T.D, T.Q): Helper for FIFO inventory analysis. Returns the unsold inventory quantity as a vector of T. The vector V contains the total stock. The table T contains the purchase orders. T.D contains the dates, and T.Q contains the purchase quantities. The function computes the unsold quantities by playing the purchase orders backward in time. See also FIFO inventory method.
• rank(number, group): Returns the ranks of the numbers with no tie. Similar to the RANK.EQ function in Excel, except that all numbers get a distinct rank (tie-breaks are arbitrary). The group is optional. When the group is provided, it is used to perform local ranks for each group.
• rankd(number): Returns the ranks of the numbers; identical numbers get identical ranks. Similar to the RANK.EQ function in Excel.

## Graph functions

• canonical(A, B): returns the canonical representative for each A value. From a practical perspective, this function is used to deal with code replacement (ex: SKU code replacement). For example, canonical(OldSku, NewSku) would return the latest SKUs available for each item, recursively performing the replacements. See also nonCanonical().
• nonCanonical(A, B): returns true whenever a canonical representative cannot be computed for the A. This happens when circular paths or branching paths get detected.
• connected(A, B, group) : considers the undirected graph described by all edges (A,B), then returns for each node A the name of the smallest node in A's connected component. Here, "smallest" means having the smallest name, in terms of string comparison. The group is optional. When the group is specified, the dataset is first partitioned against the specified groups.

## Distribution functions

### Parametric distributions

Parametric distributions can be generated, that is, functions which take a number as an argument - the parameter - and return a distribution.

• dirac(n) returns a function zero valued everywhere except for n where the function is valued at 1.
• identity(n) returns the function $\text{id}: k \to k$ but limited to the segment [0;n] and 0 elsewhere.
• uniform(n) returns the function $\text{unif}: k \to 1$ but limited to the segment [0;n] and 0 elsewhere.
• uniform(m, n) returns the function $\text{unif}: k \to 1$ but limited to the segment [m;n] and 0 elsewhere. If $m - 1 = n$, the uniform() returns a zero distribution.
• uniform(D) returns the function $\text{unif}: k \to 1$ but limited to the positive support of the distribution D and 0 elsewhere.
• poisson(a) returns the Poisson distribution of parameter a ($\lambda$ in literature).
• exponential(a) returns the exponential distribution of parameter a ($\lambda$ in literature).

### Non-parametric distributions

• distrib(Id, G.Probability, G.Min, G.Max) is a function that returns distribution defined by a list of buckets; where each bucket has left and right inclusive boundaries and a value for the bucket.
• ranvar(T.X) is an aggregator that returns the empirical distribution resulting from the observations obtained from the vector T.X.

### Indicators on distributions

Numeric indicators can also be obtained from distributions.

• crps(X, A) where A are integral numbers, returns the Continuous Ranked Probability Score (CRPS).
• mean(X) returns the statistical mean.
• variance(X) returns the statistical variance.
• mass(X) returns to mass of distribution, that is, $\sum_{k=-\infty}^{\infty}f(k)$
• isranvar(X) returns a Boolean that is true if the distribution is a random variable.
• int(X, A, B) where A and B are integral numbers returns the integral of X over the inclusive segment [A;B].
• quantile(X, tau) returns the quantile of the distribution; the smallest $x$ such as $\mathbf{P}[X \leq x] \geq \tau$.
• spark(X) returns a text value that contains compact ascii-art representation of the distribution.

### Transformations of distributions

A distribution can be transformed into another distribution.

• reflect(X) returns the reflected distribution $k \to f(-k)$.
• transform(X,a) returns a distribution that approximates through interpolation $k \to f(k / a)$.
• fillrate(X) returns the marginal fill rate. Expects a random variable as input and returns a random variable.
• truncate(X, a, b) returns the truncated distribution $k \to f(k) \text{ if } k \in [a; b] \text{ else } 0$. The boundaries A and B are inclusive.
• maxr(X, a) returns the distribution $k \to f(k) \text{ if } k \in ]-\infty; a - 1] \text{ or } \sum_{i=a}^\infty f(i) \text{ if } k = a \text{ else } 0$.
• minr(X, a) returns the distribution $k \to f(k) \text{ if } k \in [a + 1; \infty[ \text{ or } \sum_{i=-\infty}^a f(i) \text{ if } k = a \text{ else } 0$.
• zoz(X) (zero on zero) returns the distribution where $k \to f(k) \text{ if } k \neq 0 \text{ else } 0$.

## Table creation functions

See creating tables for more details.

• extend.range(N): Create N lines for each line from the table passed as argument where N is expected to be an integer.
• extend.distrib(distribution, gap, multiplier, reach): Extends a distribution into a table.
• extend.billOfMaterials(...): Translates a demand history for items into the demand history for the parts.

• forex(value, Origin, Destination, date): Returns the amount expressed in the currency Origin into the equivalent amount in the currency Destination according to the historical rates at the specified date. The currencies should be encoded with their canonical three-letter codes. Lokad supports about 30 currencies leveraging the data provided by the European Central Bank. Rates are updated on a daily basis. See also isCurrency() to test the validity of your currency code.
• hash(value): Returns a pseudo-injective hash value between 0 and 2^24-1. This function is typically used randomly shuffle a dataset by hashing the content of a column, and then sorting against the hashed values.
• isCurrency(currencyCode): returns true if the text entry passed as argument is a currency code recognized by the forex() function.
• mkuid(X, offset): returns a unique number, with unicity maintained across Envision runs. This function is intended to uniquely identify results calculated by Lokad. For example, it can be used to generate a unique purchase order number to be incremented whenever the Envision script is re-executed. The vector X is ignored, but the UID (unique identifier) is generated as a scalar in the table associated to X. The offset is an optional scalar that represents the starting suffix for for the UID. The generated strings are numbers in format PPPPPPPAAA, with P a page number (does not start with 0) that is always strictly increasing, and A an incremented counter that starts at offset (or 0 if no offset parameter is provided). P has at least 7 digits, A has at least 3. The UIDs offer three properties. (1) All UIDs can be parsed as numbers, and those numbers will be different. Keep in mind, however, that UIDs have at least 10 digits, and likely more if each call needs to generate more than 1000. (2) An UID generated at time T is strictly inferior (in alphabetical order) to an UID generated at time T' > T. (3) If all calls generate similar numbers of UIDs (less than 999, or between 1000 and 9999, etc.) then the previous property is also true for the numeric order between UIDs.
• solve.moq(...): an advance numeric solver for the general MOQ problem (minimal order quantities).
• priopack(R, V, S, C, J[, B]): a simple variant of the bin packing algorithm intended to be used with purchase prioritization list. Unlike the classic bin packing algorithm, not only, we seek to optimize the bin capacities, but the ordering of the units should also preserved as much as possible. R contains the ranks of the lines to be packed. V is the volume of each line. S is the equivalence class of the suppliers, with bin packing computed per supplier. C is the max volume capacity, its value is homogeneous to V, and it is assumed to be a constant value across the equivalent class C. J is the jumping threshold, its values is homogeneous to V, it is typically expected to a small multiple of the C value. B is an optional argument interpreted as the barrier; when this value is provided, the bin-packing process is not allowed to reorder lines that below to the same equivalence class as defined by B.
• stockrwd(Id, G.Proba, G.Min, G.Max, M, S, C, A): the stock reward function. This function is used to build prioritized ordering policy out of the probabilistic forecasts produced by Lokad.