Functions, Operators and Built-ins

<< Click to Display Table of Contents >>

Navigation:  Defining Entity Types > Create a New Entity Type >

Functions, Operators and Built-ins

Previous pageReturn to chapter overviewNext page

Ventity offers a number of operators, functions, and built-in variables and values that you can use.

 

Date and Time

 

Every Ventity model automatically includes a single Model entity called Model. Defined in that entity are four variables:

 

Initial Time

The model time at the start of the simulation.

Final Time

The model time at which the simulation ends.

Time

The time variable for the model.

Time Step

The duration of one time slice. The amount by which time advances during each calculation round.

 

The values of the four variables are determined by the Run Configuration. Other entities can access these variables through the model entity. So, to use Time in an equation, you would enter "Model.Time". To use Final Time, enter "Model.Final Time."

 

CurrentTimeSlice()

Dimensionless <- ()

The sequential index number of the current time slice. The first time slice in the simulation is 0, and the number increments each Time Step.

 

SimulationDay(), 

SimulationMonth(), 

SimulationYear()

Dimensionless <- ()

Extract date components from the simulation time when using calendar time.

 

Logic

See also: Reference Functions below.

 

==, !=, <>, <, <=, >, 
>=

 

Comparison operators. Comparisons between two quantities return true or false. "!=" and "<>" both mean "not equal".

 

!, not, &&  

Boolean operators. "!" and "not" both mean "not", "&&" means "and". "=" and "==" are equivalent in Ventity.

 

If (C) {X} Else {Y}

 

Returns X if condition C is true, and Y if false. Example: if (mood=="indigo") {x} else {2*z}

 

If (C1) {X1} 

   Else If (C2) {X2} 

   ...
   Else {Y}

Returns X1 if condition C1 is true, X2 if condition C2 is true and so on.  If none of the conditions are true, returns Y. If more than one condition is true, returns the first one in the sequence. As many "Else If (condition) {results}" as you wish may be added between the initial "If" and the final "Else {result}".

 

True, False

Special values that can be used in place of a logical test.

 

FPEquals(value1, value2, tolerance)

 

Tests for equality with a tolerance; useful for preventing tiny differences in double-precision numbers from defeating an equality test.

 

IsValid(value)

 

Tests whether a number is valid (invalid numbers are NaN or infinity). Returns a boolean true/false value, and therefore is usable only in conditions like an "if" statement. Another way to test for NaN is to check if (x == x), which can only fail if x is NaN. See also: ValidOrX, ValidOrZero.

 

Math

 

+, -, *,  /, ^

Arithmetic operators: add, subtract, multiply, divide, exponentiate.

 

Pi()

Dimensionless <- ()

 

π (Ratio of circumference to diameter for a circle). Pi is dimensionless.

 

Min(a,b[,c,d,e]), 

Max(a,b[,c,d,e]), 

Bound(x,a,b)

Min and Max return the minimum or maximum of up to five supplied arguments.  All arguments must have the same units, and the result will be in those units.

Bound returns a if x<a, x if a≤x≤b, and b if x>b and is equivalent to min(max(a,x),b). Result will be in units of x, a, and b, which must be the same.

 

Modulo(a,b)

Remainder when a is divided by b. a and b must be in the same units, and result will be in those units.

 

Sin(a), Cos(a), Tan(a)

Sine, cosine or tangent of radian angle a, which must be dimensionless.

 

Asin(x), Acos(x), Atan(x)

Inverse sine, cosine or tangent of x, in radians. Both x and the result are dimensionless.

 

Sinh(x), Cosh(x), Tanh(x)

Hyperbolic sine, cosine or tangent of x. Result is dimensionless.

 

Abs(x), Sign(x)

Absolute value of x, Signum (sign) function of x. ABS will return units of x, sign will return dimensionless units.

 

Exp(x), Pow(b,x)

Exp raises e to the argument, Pow raises base b to power x. b^x is the equivalent of pow(b,x). Power must be dimensionless. Base must usually be dimensionless, but in simple cases units are accepted. For example, if b has units of meters, the result of b^2 will have units of meters*meters.

 

GammaLn(x)

Computes the logarithm of the gamma function. The gamma function can be thought of as a generalized factorial that interpolates non-integer inputs. Gamma(n) = (n-1)!, so x! = Exp(GammaLn(x+1)). Computing factorials directly should be done with caution, as Exp(GammaLn(.)) becomes large very quickly.

 

Sqrt(x)

SquareRoot(x)

Returns the positive square root of x. Normally, x must be dimensionless, as will be the result. When x has a simple squared unit (such as meters*meters), the result will have the appropriate units (meters).

 

Log(x), Log10(x)

Natural (base e) logarithm, or base 10 logarithm of x. Input and result must be dimensionless.

 

Xidz(a,b,x)

Zidz(a,b)

Xidz ("x if divide by zero") returns x if b=0, or a/b otherwise. Zidz ("zero if divide by zero") is equivalent to Xidz(a,b,0). Returns units of a/b.

 

ValidOrX(value,x), 

ValidOrZero(value)

Return the input value, or a specified value if the input is invalid. See also: IsValid.

 

Random Numbers

 

The seed value for the random number generator is set in Run Control. Generally these functions wrap their Math.net equivalents, so if you see a distribution function you need, please make a feature request via email. Where distributions are turncated by min and max values, draws are made by rejection sampling. If more than 10 rejections occur, the function falls back to a uniform distribution between the min and max bounds. Available distributions:

 

RandomUniform(min,max)

Random()

RandomUniform returns a random number uniformly distributed between min and max. Random() is shorthand for RandomUniform(0,1).

 

RandomNormal(mean,stdev[,min,max])

Returns a random number normally distributed around mean with standard deviation stdev. With four arguments, output is restricted to fall between min and max.

 

RandomBinomial(p,n)

RandomBinomal returns a number from a binomial distribution with success probability p and n trials. Equivalent to the sum of n calls to RandomBernoulli with probability p.

 

RandomBernoulli(p)

RandomBernoulli is equivalent to RandomBinomial(p,1) - i.e. a single trial with probability p.

 

RandomPoisson(mean[,min,max])

Returns a random number from a Poisson distribution with mean rate mean. With three arguments, output is restricted to fall between min and max.

 

RandomBeta(a,b)

A draw from the Beta distribution with parameters (a,b)

 

RandomExponential(x)

The Exponential distribution with rate parameter x

 

RandomGamma(shape, rate)

The Gamma distribution with specified shape and rate. Integer shapes yield the Erlang distribution, and Erlang(1) is Exponential.

 

RandomNegativeBinomial(p,n)

The Negative Binomial distribution with trial probability = p and trial failures = n.

 

RandomTriangular(lower,upper,peak)

A triangular distribution. Ordering should be lower < peak < upper.

 

RandomWeibull(shape, scale)

The Weibull distribution with specified shape and scale.

 

Random Distributions

 

See also

 

NormalCDF(value, mean, standardDeviation [, minrange, maxrange] )

The Cumulative Distribution Function of the Normal (Gaussian) distribution. If minrange and maxrange are supplied, the truncated normal is computed.

 

NormalLikelihood(value, mean, standardDeviation [, minrange, maxrange])

The density function or PDF of the Normal distribution, optionally truncated by [minrange, maxrange].

 

 

Rounding

Ceiling(x), 

Floor(x), 

Round(x), 

Truncate(x)

Floor rounds x down to the next integer, Ceiling rounds up, Truncate rounds toward zero, Round rounds to the nearest integer (choosing the even one if x is midway between). Result is in units of x.

 

 

Test Inputs

 

Step(height,time)

Returns 0 until time, then height thereafter. Step function returns units of height, but requires time to be in units of time.

 

Ramp(slope,start,stop)

Returns 0 until time start, then increases at rate slope until time stop, then constant thereafter. Ramp function requires slope to be in units, and the both start and stop in the same units of time. It will return slope * time units.

 

Pulse(start,duration)

Returns 0 until time start, then returns 1 for duration time units, then 0 thereafter. start and duration must both be in units of time with the result being dimensionless.

 

PulseTrain(start,duration,interval,stop)

Returns 0 until time start, then an alternating pattern of 1 for duration time units followed by 0 for interval-duration time units, until time stop, then 0 thereafter. Pulse Train function requires units of time for start, duration, interval and stop, with the result being dimensionless.

 

 

Aggregates

 

Aggregate variables (statistics) can be computed for any collection of entities in the model:

 

Count

The number of entities in a collection at the beginning of each time slice. (Built-in variable in all collections)

 

For minimum, maximum, average, median, standard deviation, sum, or product of x, where x is any variable defined for the members of the collection, see aggregate variables.

 

 

Allocation

 

Allocation is performed by Allocate and Market actions. A variable that is going to receive the results of an allocation must be set equal to the special function, Allocation:

 

Allocation()

Indicates to Ventity that the value of the variable will be set by an allocation. Returns zero if no allocation to this variable is active. Allocation() is used with no arguments.

 

 

Delay

 

DelayInformation(variable,

timedelay[,early value]) 

Returns value of the input variable with a delay based on the variable timedelay. DelayInformation can only be used to look backward, with only positive whole numbers being accepted in the variable timedelay. The optional early value specifies a value to be used prior to the availability of computed values; if omitted, the initial value of the input variable will be used.

 

Built-in Dynamic Macros

These are dynamic functions common in SD practice, and corresponding with their equivalents in Vensim. They are implemented as macros, so their internal variables may be seen if Model>Preferences permits it.

 

SMOOTH (input, delay time)

 

Returns exponential smooth of input over delay time.

 

SMOOTHI (input, delay time, initial value)

 

Returns exponential smooth of input over delay time with initial value.

 

DELAY1 (input, delay time)

 

Returns exponential delay of input.

DELAY1I (input, delay time, initial value)

 

Returns exponential delay of input with initial value.

 

DELAY3 (input, delay time)

 

Returns third order exponential delay of input.

DELAY3I (input, delay time, initial value)

 

Returns third order exponential delay of input with initial value.

 

TREND (input, average time, initial value)

 

 

Returns average fractional rate of growth or decline in the input. Initial value indicates initial trend of the growth/decline.

 

FORECAST (input, average time, horizon)

 

Returns forecast of the value of the input at given time and horizon.

 

NPV (input stream, discount rate, initial value, factor)

 

 

Returns net present value of input stream using discount rate, using initial value as starting value and all multiplied by factor.

 

NPVE (input stream, discount rate, initial value, factor)

Returns net present value of input stream using discount rate, using initial value as starting value and all multiplied by factor. Calculates value of input stream at end of period and discount rate in discrete period. Same calculation sequence as in Excel.

 

Custom Macros
 

Custom Macros can be designed and called as functions within an equation.This can be useful to construct structures that will need to be replicated multiple times within a model.

 

Initialization

 

ActiveInitial(main expression, initial expression) 

Uses the initial expression for computations during an entity's initialization phase (i.e. upon creation of the entity), and the main expression thereafter.

 

Initial(expression)

Freezes the initial value of an expression.

 

Categorizing Values for Attributes

 

GetCategory(collection reference, variable) 

Sorts collection by variable. Generates a list of the collection, then looks up those that match the parameters set by the variable. Returns all of these values.

 

GetCategory is the most efficient method for processing a list of variables. This function can only be used in an Action, and to use it you'll need to have a collection already created which you reference via the collection entity name (as it appears in the Model Overview), and the variable by which you're assigning categorical values.

 

The collection reference should point to a special entitytype containing the desired categorization. This entity must contain an attribute, "Category Name" and a numerical variable, "Category Level":

getCategoryVariables1

 

You can make the Category Name the key to the entitytype to reduce clutter, though this is not required, and may be an obstacle if you'd like to assign different values to the same category.

 

Once you have defined the entitytype, you can use initialization data to set the category levels. The Category Level is the lower bound for each Category Name:

 

getCategoryData1

 

Once you have created the entitytype containing the categories, you can use it in a GetCategory call in an action. Here, a Process List action iterates over the Person[] collection and assigns a level from the Quintile entitytype to each:

 

getCategoryAction1

 

Lookup Table

 

You may provide your own table of values for Ventity to use as a lookup function. In Ventity, such functions are called "table functions" or "lookup functions" interchangeably.

 

Creating a table function

 

Drag a Lookup icon lookup from the palette onto a diagram and name the lookup. If you right-click to edit the function, you will be presented with an x-y table and graph. The x-axis represents input values, and the y-axis shows the corresponding output. Fill in the table directly, or by clicking on the graph to add points. Once added, points may be dragged to new locations. To delete points, switch to "Delete Mode", and click on any points you wish to delete. The graph window will automatically expand to include all points on the table. You can make the window larger with the min and max fields near each graph axes. Use the units fields to indicate the units of the inputs and outputs of the function.

 

lookup02

 

Note: If input values are below or above the domain of the table, Ventity will extrapolate the function as needed using the slopes defined by the first two points for inputs less than the defined domain, and the last two points for values greater than the defined domain.

 

Once created, a lookup table can be edited in the built-in data, and will follow the same rules as other built-in data. This uses the same interface as when you edit the tables in the Model Workspace, but alternatively will accept a pasted input in (x1, y1), (x2, y2)... etc. format. This can be especially helpful if copying in data from a outside spreadsheet source.

 

For more information on built-in data and its handling, click here.

 

 

List of lookup table functions

 

All of the table functions require a linked table. To link a table, simply create an auxiliary to house the function and draw a line from the table to the auxiliary, or in the arguments for the table function, write in the name for the table, right-click the underlined name and select "Draw arrow from (table name)".

 

Note: Ventity will automatically check for units mismatch in table functions and display an error message to console if one is found on model run.

 

LookupArea (table)

 

Returns area under the line of the table function.

LookupAreaByRange (table,x,time)

 

Starting at x value, returns area under the line of the table function.

 

LookupExtrapolate (table,x)

 

Calculates slope of the line, then returns expected y value for given value of x using that slope.

 

LookupForward (table,time)

 

Next y value is used between x values instead of being interpolated.

 

LookupBackward (table,time)

 

Previous y value is held between x values instead of being interpolated.

 

LookupInvert (table, time)

 

Inverts lookup for x and y values, returning y for x.

LookupSlope (table,time)

 

Returns the change in y divided by the change in x from one point to the next point.

 

LookupMaxValue (table)

 

Returns highest value of y the table.

LookupMaxValueByRange(table,x1,x2)

 

Returns highest value of y for the table between the two given x values (x1, x2).

 

LookupMinValue (table)

 

Returns the lowest value of y for the table.

LookupMinValueByRange (table,x1,x2)

 

Returns lowest value for y of the table between the two given x values (x1, x2)

 

 

Individual table functions for individual entities

 

The table function you provide in the entity type definition is the default, but an individual entity can have its own values for the table function. Individual overrides for table function values are provided during initialization.

 

 

String functions for attribute initialization

 

These functions may be used to construct attribute string values.

 

RoundToString(value) 

Rounds a value to an integer and converts to a string; useful for initializing an attribute with a sequence number.

 

Concatenate(value1,value2)

Concatenate two strings without a space. The string may be "quoted text," another attribute, or RoundToString. The value list may contain up to four arguments.

 

Combine(value1,value2)

Combine two strings with a separating space.

 

CombineWithDelimiter("delimiter",value1,value2)

Combine two strings with a delimiting character or string.

 

 

Reference functions

 

These functions may be used to construct attribute string values.

 

EntityExists(collection,entitykey)

Tests whether an entity with the given key exists in a collection. Useful for determining whether a relationship entity linking two other entities already exists, for example.

 

IsActive(entity reference)

Tests whether a reference points to an entity that is "alive" (not deleted).

 

IsNull(entity reference)

Tests whether an entity reference is defined (points to a valid entity).