# Built-in Functions

In addition to standard algebraic and logical operators, Insight Maker has many powerful built-in functions. The following is a list of these functions along with descriptions and sample usages.

- Mathematical Functions (27)
- Time Functions (13)
- Historical Functions (14)
- Random Number Functions (13)
- Agent Functions (25)
- Vector Functions (20)
- General Functions (6)
- String Functions (10)
- Programming (9)
- User Input Functions (3)
- Statistical Distributions (20)

## Mathematical Functions

Rounds a number to the nearest integer.

**Basic Structure:**

Round(Value)

**Description:**

The **Round** function rounds a given numerical value to the nearest integer.

Use cases include rounding values where only a whole number is needed. For example, if a stock contains a population size, you might round the value to the nearest whole number in the output, as you cannot have a fraction of a person. Similarly, in financial calculations, you might round the result to the nearest dollar or cent.

**Examples:**

Round(3.6)→4

Round(3.5)→4

Round(-1.4)→-1

Round(2.1)→2

Rounds a number up to the nearest integer.

**Basic Structure:**

Ceiling(Value)

**Description:**

The **Ceiling** function rounds a number up to the nearest integer, regardless of the fractional part.

For example, in construction, when calculating the number of tiles needed to cover a floor, one would round up to ensure there are enough tiles, even if only a fraction of the last tile is needed.

**Examples:**

Ceiling(3.01)→4

Ceiling(-1.99)→-1

Ceiling(5.0)→5

Ceiling(7.1)→8

Rounds a number down to the nearest integer.

**Basic Structure:**

Floor(Value)

**Description:**

The **Floor** function rounds a number down to the nearest integer. This function may be used when allocating resources that cannot be fractioned. For example, it could used in manufacturing for determining the maximum number of products that can be created from a given set of raw materials.

**Examples:**

Floor(3.99)→3

Floor(-1.01)→-2

Floor(5.0)→5

Floor(7.9)→7

Finds the cosine of an angle.

**Basic Structure:**

Cos(Angle)

**Description:**

The **Cos** function calculates the cosine of a given angle, which must be specified in radians. The cosine of an angle in a right triangle is the ratio of the length of the adjacent side to the length of the hypotenuse. This function is widely used in trigonometry, physics, and engineering to determine the orientation or alignment of objects in space.

**Examples:**

Cos(0)→1

Cos(Pi/3)→0.5

Cos(Pi)→-1

Cos(2*Pi)→1

Finds the arc-cosine of a value. The result includes units.

**Basic Structure:**

ArcCos(Value)

**Description:**

The **ArcCos** function, or inverse cosine, calculates the angle (in radians) whose cosine is the given value. This function is useful for deriving an angle from the cosine ratio, playing a key role in trigonometry, geometry, and physics. It's often used in calculating angles for design and analysis in engineering, determining the orientation of objects, and converting between coordinate systems.

**Examples:**

ArcCos(1)→0

ArcCos(0)→Pi/2

ArcCos(-1)→Pi

ArcCos(0.5)→Pi/3

Finds the sine of an angle.

**Basic Structure:**

Sin(Angle)

**Description:**

The **Sin** function calculates the sine of a specified angle, provided in radians. The sine of an angle in a right triangle is the ratio of the length of the opposite side to the hypotenuse. This function is used in various fields like trigonometry, physics, and engineering for understanding wave patterns, oscillations, and circular motion.

**Examples:**

Sin(0)→0

Sin(Pi/2)→1

Sin(Pi)→0

Sin(3*Pi/2)→-1

Finds the arc-sine of a value. The result includes units.

**Basic Structure:**

ArcSin(Value)

**Description:**

The **ArcSin** function, or inverse sine, finds the angle (in radians) whose sine is the given value. It's pivotal in trigonometry for solving triangles, in physics for calculating angles of incidence and reflection, and in engineering for design and analysis that involves angular measurements.

**Examples:**

ArcSin(0)→0

ArcSin(1)→Pi/2

ArcSin(-1)→-Pi/2

ArcSin(0.5)→Pi/6

Finds the tangent of an angle.

**Basic Structure:**

Tan(Angle)

**Description:**

The **Tan** function computes the tangent of a given angle, expressed in radians. The tangent of an angle in a right triangle is the ratio of the length of the opposite side to the adjacent side. This function is used for applications involving slopes, angles, and curves in fields such as trigonometry, calculus, and physics.

**Examples:**

Tan(0)→0

Tan(Pi/4)→1

Tan(Pi)→0

Tan(3*Pi/4)→-1

Finds the arc-tangent of a value. The result includes units.

**Basic Structure:**

ArcTan(Value)

**Description:**

The **ArcTan** function, or inverse tangent, calculates the angle (in radians) whose tangent is the given value. It's particularly useful in trigonometry for determining the angle of a line, in physics for calculating angles of trajectories, and in engineering for angle measurements in design and construction.

**Examples:**

ArcTan(1)→Pi/4

ArcTan(0)→0

ArcTan(-1)→-Pi/4

Returns the base-10 logarithm of a number.

**Basic Structure:**

Log(Value)

**Description:**

The **Log** function returns the base-10 logarithm of a number, a fundamental operation in mathematics that determines how many times one number should be multiplied by itself to reach another number. It can be used to model exponential growth or decay, sound intensity, and in financial calculations involving interest rates.

**Examples:**

Log(10)→1

Log(100)→2

Log(1)→0

Log(1000)→3

Returns the natural logarithm of a number.

**Basic Structure:**

Ln(Value)

**Description:**

The **Ln** function computes the natural logarithm (logarithm to the base *e*) of a given number. It is the inverse of the **Exp** function.

Understanding the natural logarithm is used for solving equations involving exponential growth or decay, and it plays a significant role in differential equations and calculus.

**Examples:**

Ln(e)→1

Ln(e^3)→3

Ln(1)→0

Ln(e^0.5)→0.5Ln and e are inverses

Returns e taken to a power.

**Basic Structure:**

Exp(Value)

**Description:**

The **Exp** function calculates the value of *e* (approximately 2.71828), the base of natural logarithms, raised to a given power. It is the inverse of the **Ln** function.

It is used for understanding continuous growth processes, like population growth, radioactive decay, and continuously compounded interest.

**Examples:**

Exp(2)→e^2

Exp(0)→1Exp of 0 is always 1

Exp(-1)→1/eExp of -1 gives the reciprocal of e

Exp(1)→eExp of 1 is e itself

Returns the sum of a vector or list of numbers.

**Basic Structure:**

Sum(Values)

**Description:**

The **Sum** function calculates the total sum of a series of numbers provided as arguments. You may also use this function to sum the elements of a vector.

**Examples:**

Sum(1, 2, 3, 4)→10A list of numbers

Sum({-1, 5, -2, 8})→10Works with vectors

Sum({0.5, 2.5, 4})→7.0

Sum(10)→10Single value is simply returned

Returns the product of a vector or list of numbers.

**Basic Structure:**

Product(Values)

**Description:**

The **Product** function multiplies together all the numbers provided as arguments. You may also use this function to find the product of the elements in a vector.

This function is particularly useful in scenarios where the total product of a series of factors is needed, such as compound interest calculations, production output estimations, and in determining the likelihood of independent events occurring in sequence.

**Examples:**

Product(1, 2, 3, 4)→24A list of numbers

Product({-1, 4, -3})→-12Works with vectors

Product(0.5, 2, 8)→8

Product({2, 2, 2, 2})→16

Returns the largest of a vector or list of numbers.

**Basic Structure:**

Max(Values)

**Description:**

The **Max** function identifies and returns the largest number from a given list or vector of numerical values. It is used to find the highest value in a dataset, such as the maximum temperature recorded in a day, the highest stock price in a given period, or the maximum capacity of a system.

**Examples:**

Max(2, 4, -1)→4

Max(100, 54, 89, 3)→100

Max({1, 3, 5, 7, 9})→9Finding the maximum value in a vector

Max(-5, -2, -9, -4)→-2Maximum of negative numbers

Returns the smallest of a vector or list of numbers.

**Basic Structure:**

Min(Values)

**Description:**

The **Min** function finds and returns the smallest number from a list or vector of numerical values. It can be used to find the minimum required resources, the lowest temperature, or the least cost in optimizations.

**Examples:**

Min(2, 4, -1, 3)→-1

Min({10, 5, 15, 2})→2

Min(-8, -3, -10)→-10

Returns the mean (average) of a vector or list of numbers.

**Basic Structure:**

Mean(Values)

**Description:**

The **Mean** function calculates the arithmetic average of a set of numbers by summing all the numbers and then dividing by the count of numbers. You may also use this function to find the mean of the elements in a vector.

This function can help analyze average income in demographics studies, average temperature for climate analysis, or overall performance in academic assessments.

**Examples:**

Mean(2, 7, 3)→4

Mean(1, 3, 5, 7)→4Average of a simple numeric sequence

Mean({10, 20, 30, 40, 50})→30Calculating the mean of a vector

Mean(-2, -4, -6)→-4Average of negative numbers

Returns the median of a vector or list of numbers.

**Basic Structure:**

Median(Values)

**Description:**

The **Median** function calculates the middle value of a sorted list of numbers, dividing the data set into two halves. If the list has an even number of observations, the median is the average of the two middle numbers. You may also use this function to find the median of the elements in a vector. It's a critical measure in statistics to identify the central tendency without being skewed by outliers.

**Examples:**

Median(2, 7, 3)→3

Median(1, 3, 3, 6, 7)→3Median with an odd number of elements

Median({1, 2, 3, 4})→2.5Median of an even number of elements in a vector

Returns the standard deviation of a vector or list of numbers.

**Basic Structure:**

StdDev(Values)

**Description:**

The **StdDev** function calculates the standard deviation, a measure of the amount of variation or dispersion in a set of numbers. A low standard deviation indicates that the values tend to be close to the mean, whereas a high standard deviation indicates that the values are spread out over a wider range.

To calculate the standard deviation of a list of numbers, first calculate the mean (average) of the numbers, then subtract the mean from each number to find the deviations, square each deviation, calculate the mean of these squared deviations, and finally take the square root of this mean.

It's widely used to measure volatility, in quality control to assess variability of manufacturing outputs, and in research to quantify the variance in experimental data.

**Examples:**

StdDev(1, 2, 3)→1

StdDev({10, 20, 30})→10

StdDev(100, 100, 100)→0No variation from the mean

Returns the absolute value of a number.

**Basic Structure:**

Abs(Value)

**Description:**

The **Abs** function calculates the absolute value of a number, which is the number's distance from zero on the number line without considering direction.

Applications include calculating the absolute difference between two numbers, adjusting negative values to positive for analyses that do not consider direction, and to represent absolute changes in values.

**Examples:**

Abs(-23)→23

Abs(17)→17Positive numbers remain unchanged

Abs(-0.5)→0.5

Abs(0)→0Absolute value of zero is zero

Returns the remainder of the division of two numbers.

**Basic Structure:**

(Value One) mod (Value Two)

**Description:**

The **Mod** operator calculates the remainder of the division of two numbers. It is used in programming, mathematics, and cryptography for operations such as determining even or odd numbers, distributing items evenly across groups, and cyclic processes. The **%** operator is a synonym for **mod**.

This function is useful for algorithms that require periodicity, loop iterations with a fixed step size, and in scenarios where the exact division ratio is crucial.

**Examples:**

13 mod 5→3

13 % 5→3Using the % operator instead of mod

10 mod 2→0Checking for even numbers

9 mod 3→0Perfectly divisible numbers

Returns the square root of a number.

**Basic Structure:**

Sqrt(Value)

**Description:**

The **Sqrt** function calculates the square root of a given number, which is the value that, when multiplied by itself, gives the original number.

Common use cases include determining the length of the side of a square given its area, scaling data, and in quadratic equations to find the distance between two points.

**Examples:**

Sqrt(9)→3

Sqrt(16)→4

Sqrt(2)→1.41

1 if the value is greater than 0, -1 if it is less than 0, and 0 if it is 0.

**Basic Structure:**

Sign(Value)

**Description:**

The **Sign** function determines the sign of a number, returning 1 for positive numbers, -1 for negative numbers, and 0 for zero.

This function aids in categorizing numerical data based on its sign, simplifying the handling of conditional operations that vary with the positive or negative nature of inputs.

**Examples:**

Sign(-12)→-1

Sign(20)→1Positive number sign

Sign(0)→0Zero sign

Sign(-0.01)→-1Sign of a small negative number

The value 3.14159265.

**Basic Structure:**

pi

**Description:**

The constant **pi** represents the ratio of the circumference of a circle to its diameter, approximately equal to 3.14159265. It's a fundamental element in geometry, trigonometry, and calculus, involved in calculations of areas, volumes, and trigonometric functions.

**Examples:**

pi→3.14159265

2*pi→6.28318531Circumference of a unit circle

The value 2.71828183.

**Basic Structure:**

e

**Description:**

The constant **e** is the base of the natural logarithm, approximately equal to 2.71828183. It plays an important role in calculus, particularly in the context of exponential growth and decay, compounding interest calculations, and in the solution of differential equations.

**Examples:**

e→2.71828183

1/e→0.367879441

Returns the logit transformation of the value. Converts values on a 0 to 1 scale to a -Infinity to Infinity scale.

**Basic Structure:**

Logit(Value)

**Description:**

The **Logit** function applies the logit transformation to a value, converting probabilities (values between 0 and 1) into log-odds (values from -Infinity to Infinity). It's a key function in logistic regression and other statistical models dealing with probabilities and odds. It is the inverse of the **Expit** function.

**Examples:**

Logit(0.5)→0Logit transformation of a probability of 0.5

Logit(0.75)→1.0986Higher probabilities result in positive log-odds

Logit(0.25)→-1.0986Lower probabilities result in negative log-odds

Logit(0.9)→2.197Logit of a high probability

Returns the expit transformation of the value. Converts values on a -Infinity to Infinity scale to a 0 to 1 scale.

**Basic Structure:**

Expit(Value)

**Description:**

The **Expit** function, also known as the logistic function, converts log-odds (values ranging from -Infinity to Infinity) back into probabilities (values between 0 and 1). It's widely used in logistic regression, artificial neural networks, and in contexts requiring the interpretation of odds as probabilities. It is the inverse of the **Logit** function.

**Examples:**

Expit(0)→0.5Expit transformation returning a probability of 0.5

Expit(1)→0.73106Positive values result in probabilities greater than 0.5

Expit(-1)→0.26894Negative values yield probabilities less than 0.5

Expit(2)→0.88079Higher input gives higher probabilities

## Time Functions

The current time in seconds.

**Basic Structure:**

Seconds()

**Description:**

The **Seconds** function returns the current simulation time in seconds. It is useful for tracking and controlling simulation events over time, such as scheduling tasks, monitoring progress, and modeling time-dependent processes.

**Examples:**

Seconds()*1000The time in milliseconds

Seconds()/60Converts seconds to minutes

IfThenElse(Seconds() > 3600, 'More than an hour has passed.', 'Less than an hour has passed.')Checks if more than an hour has passed in the simulation

The current time in minutes.

**Basic Structure:**

Minutes()

**Description:**

The **Minutes** function returns the current simulation time in minutes. It is useful for tracking and controlling simulation events over time, such as scheduling tasks, monitoring progress, and modeling time-dependent processes.

**Examples:**

Seconds() = Minutes()*60→True

Minutes()*60Converts minutes back to seconds

IfThenElse(Minutes() > 120, 'More than 2 hours have passed.', 'Less than 2 hours have passed.')Uses minutes to determine how long the simulation has run

The current time in hours.

**Basic Structure:**

Hours()

**Description:**

The **Hours** function returns the current simulation time in hours. It is useful for tracking and controlling simulation events over time, such as scheduling tasks, monitoring progress, and modeling time-dependent processes.

**Examples:**

Hours()*60Converts hours to minutes

IfThenElse(Hours() >= 24, 'A day or more has passed.', 'Less than a day has passed.')Determines if a day has passed in the simulation

Hours()/24Converts hours to days

The current time in days.

**Basic Structure:**

Days()

**Description:**

The **Days** function returns the current simulation time in days. It is useful for tracking and controlling simulation events over time, such as scheduling tasks, monitoring progress, and modeling time-dependent processes.

**Examples:**

Days()*24Converts days to hours

IfThenElse(Days() > 7, 'More than a week has passed.', 'Less than a week has passed.')Checks if more than a week has passed

Days()/7Converts days to weeks

The current time in weeks.

**Basic Structure:**

Weeks()

**Description:**

The **Weeks** function returns the current simulation time in weeks. It is useful for tracking and controlling simulation events over time, such as scheduling tasks, monitoring progress, and modeling time-dependent processes.

**Examples:**

Weeks()*7Converts weeks to days

IfThenElse(Weeks() > 4, 'More than a month has passed.', 'Less than a month has passed.')Determines if more than a month has passed based on the number of weeks

Weeks()*4Approximates weeks to months for quick calculations

The current time in months.

**Basic Structure:**

Months()

**Description:**

The **Months** function returns the current simulation time in months. It is useful for tracking and controlling simulation events over time, such as scheduling tasks, monitoring progress, and modeling time-dependent processes.

**Examples:**

Months()*30Approximates months to days

IfThenElse(Months() >= 12, 'A year or more has passed.', 'Less than a year has passed.')Checks if a year has passed in simulation time

Months()/12Converts months to years for long-term tracking

The current time in years.

**Basic Structure:**

Years()

**Description:**

The **Years** function returns the current simulation time in years. It is useful for tracking and controlling simulation events over time, such as scheduling tasks, monitoring progress, and modeling time-dependent processes.

**Examples:**

IfThenElse(Years() > 10, 15, 0)Implements a condition based on the simulation time exceeding 10 years

Years()*12Converts years to months for detailed time analysis

Years()*365Converts years to days for precise time calculations

The current time including units.

**Basic Structure:**

Time()

**Description:**

The **Time** function returns the current simulation time with its associated units. It is useful for tracking and controlling simulation events over time, such as scheduling tasks, monitoring progress, and modeling time-dependent processes.

**Examples:**

IfThenElse(Time() > {10 Years}, 15, 0)Determines actions based on the simulation time surpassing 10 years

Time() - TimeStart()Calculates the elapsed time since the start of the simulation

TimeEnd() - Time()Determines the remaining time until the simulation ends

The simulation start time including units.

**Basic Structure:**

TimeStart()

**Description:**

The **TimeStart** function provides the start time of the simulation including its units. This can be used to calculate elapsed time.

**Examples:**

Time() - TimeStart()Calculates the elapsed time since the simulation started

The simulation time step including units.

**Basic Structure:**

TimeStep()

**Description:**

The **TimeStep** function indicates the time step of the simulation including units, allowing for adjustments based on the simulation's granularity and ensuring smooth progression of time-dependent processes.

**Examples:**

IfThenElse(TimeStep() < {1 Day}, 'High resolution simulation.', 'Low resolution simulation.')Determines the resolution of the simulation based on the time step

TimeLength() / TimeStep()Calculates the number of time steps in the simulation

The total length of the simulation including units.

**Basic Structure:**

TimeLength()

**Description:**

The **TimeLength** function returns the total duration of the simulation from start to end, including units. You can use it to track how long is left in the simulation.

**Examples:**

IfThenElse(TimeLength() > {365 Days}, 'Simulation spans more than a year.', 'Simulation spans less than a year.')

(Time() - TimeStart()) / TimeLength()Calculates the percentage of time elapsed in the simulation

The time at which the simulation ends including units.

**Basic Structure:**

TimeEnd()

**Description:**

The **TimeEnd** function returns the end time of the simulation including units. You can use it to track how long is left in the simulation.

**Examples:**

TimeStart() + TimeLength() = TimeEnd()→True

IfThenElse(Time() > TimeEnd(), 'Simulation has ended (you should never see this).', 'Simulation still in progress.')

Model of seasonality influences. Sine wave with a period of one year, a peak amplitude of one, and a peak at the specified time.

**Basic Structure:**

Seasonal(Peak=0)

**Description:**

The **Seasonal** function models seasonality effects using a sine wave with a period of one year. The *Peak* parameter specifies the time of year at which the peak occurs. This function is particularly useful for simulating seasonal variations in processes such as sales, temperature, or agricultural production.

**Examples:**

Seasonal()

Seasonal({9 Months})*0.5+1A wave that oscillates from 0 to 1 and peaks in September

Seasonal({6 Months})Models a sine wave peaking in June, useful for simulating summer peak

Seasonal({3 Months}) + Seasonal({9 Months})Combines two seasonal patterns, peaking in March and September

## Historical Functions

Returns the value of a primitive for a specified length of time ago. Default Value stands in for the primitive value in the case of negative times.

**Basic Structure:**

Delay([Primitive], Delay Length, Default Value)

**Description:**

The **Delay** function retrieves the value of a primitive from a specified length of time in the past. This is useful for modeling delays in systems, such as the lag between decision-making and observing the effects of those decisions. The *Default Value* is used for simulation times before the *Delay Length* has elapsed, ensuring the model behaves reasonably when data from the past is not yet available.

**Examples:**

Delay([Population], {5 Years}, 100000)The population value from 5 years ago or 100000 if less than 5 years have passed.

Delay([Interest Rate], {1 Year}, 0.05)Retrieves the interest rate from one year ago, using 0.05 as the default if the simulation is in its first year.

Delay([Revenue], {3 Months}, 50000)Accesses the revenue value from three months prior, defaulting to 50000 if the simulation is within the first three months.

Delay([Temperature], {2 Years}, 20)Fetches the temperature from two years ago, with a default value of 20 if the simulation has not yet reached two years.

Returns a smoothed, first-order exponential delay of a value. The Initial Value is optional.

**Basic Structure:**

Delay1([Value], Delay Length, Initial Value)

**Description:**

The **Delay1** function applies a first-order exponential smoothing to a value over a specified delay length. It models processes where changes occur gradually over time, such as the accumulation of experience or the slow adjustment of market prices to new information. The optional *Initial Value* parameter provides a starting value for the delay.

**Examples:**

Delay1([Sales], {1 year}, 200)→A smoothed sales figure over the past year, starting from 200.

Delay1([Pollution], {6 month})Applies a six-month smoothed delay to pollution data.

Delay1([Customer Satisfaction], {3 month})Models a smoothed three-month delay in customer satisfaction.

Delay1([Water Level], {2 years}, 100)Smooths the water level changes over two years, with an initial water level of 100.

Returns a smoothed, third-order exponential delay of a value. The Initial Value is optional.

**Basic Structure:**

Delay3([Value], Delay Length, Initial Value)

**Description:**

The **Delay3** function implements a third-order exponential smoothing, offering a more gradual response than Delay1. It is particularly effective for modeling systems with significant inertia or delay, such as the gradual adaptation of an ecosystem to climate change or the slow response of economic indicators to policy shifts. The optional *Initial Value* parameter provides a starting value for the delay.

**Examples:**

Delay3([Investment], {5 Years}, 100000)Models a third-order delay on investment impacts over five years, starting from an initial investment of 100000.

Delay3([Technology Adoption], 24)Applies a two-year, third-order delay to the adoption of new technology.

Delay3([Population Growth], 48)Simulates a third-order delay in population growth over four years.

Delay3([Carbon Emission], 12, 1000)Implements a third-order smoothing delay on carbon emission data over one year, starting from 1000 units.

Returns a smoothed, exponential delay of a value with the specified order. The Initial Value is optional.

**Basic Structure:**

DelayN([Value], Delay Length, Order, Initial Value)

**Description:**

The **DelayN** function applies an nth order exponential smoothing to delay a value over a specified length of time. The order determines the degree of smoothing, with higher orders resulting in a smoother delay. This function is useful for modeling delays in systems where the effect of a change is spread out over time rather than occurring instantly. Common use cases include modeling the delayed impact of policy changes, environmental regulations, or marketing campaigns. The optional *Initial Value* provides a starting value for the delay.

**Examples:**

DelayN([Population Growth], {5 Years}, 3, 100)Models a three-order delayed response in population growth over five years, starting at 100.

DelayN([Investment], {2 Years}, 2)Applies a second-order delay to investment returns over two years.

DelayN([CO2 Emissions], {10 Years}, 1)Models the delayed impact of CO2 emissions on climate change over ten years.

DelayN([Sales], {6 Months}, 4, 200)Uses a fourth-order delay.

Returns a smoothing of a value. Results in an averaged curve fit. Length affects the weight of past values. The Initial Value is optional.

**Basic Structure:**

Smooth([Value], Length, Initial Value)

**Description:**

The **Smooth** function smooths a value over a specified length of time with first order exponential smoothing, effectively smoothing out fluctuations to reveal underlying trends. This is particularly useful in data analysis and modeling to reduce noise and make patterns more apparent. Applications range from smoothing economic indicators to analyzing trends in environmental data. The *Length* parameter determines how far back in time the smoothing considers, with longer lengths resulting in more significant smoothing. The optional *Initial Value* parameter provides a starting value.

**Examples:**

Smooth([Interest Rate], {12 Months}, 0.05)Smooths interest rate fluctuations over the past year, starting with an initial rate of 0.05.

Smooth([Temperature], {30 Days})Averages daily temperature data over the past month.

Smooth([Stock Price], {6 Months})Applies smoothing to stock price movements over six months.

Smooth([Traffic Flow], {1 Week}, 500)Smooths weekly fluctuations in traffic flow, starting with an initial count of 500 vehicles.

Returns a smoothing of a value with a specified order. Length affects the weight of past values. The Initial Value is optional.

**Basic Structure:**

SmoothN([Value], Length, Order, Initial Value)

**Description:**

The **SmoothN** function extends the Smooth function by applying nth order exponential smoothing, allowing for more sophisticated smoothing of data over time. This method is particularly useful for dealing with volatile data series, where a higher order of smoothing can help identify long-term trends and patterns. The *Length* parameter controls the temporal scope of the smoothing, and the *Order* parameter adjusts the degree of smoothing applied. The optional *Initial Value* parameter provides a starting value.

**Examples:**

SmoothN([Revenue], {1 Year}, 3, 100000)Applies a third-order smoothing to revenue data over one year, starting from 100000.

SmoothN([Pollution], {2 Years}, 2)Uses second-order smoothing on pollution levels over two years.

SmoothN([Customer Satisfaction], {3 Months}, 4)Fourth-order smoothing of customer satisfaction scores over three months.

SmoothN([Rainfall], {6 Months}, 5, 200)Applies fifth-order smoothing to rainfall data over six months, with an initial value of 200mm.

Returns the values a primitive has taken on over the course of the simulation as a vector. The second optional argument is a time window to limit the depth of the history.

**Basic Structure:**

PastValues([Primitive], Period = All Time)

**Description:**

The **PastValues** function captures and returns a vector of all the values a specified primitive has assumed throughout the simulation or within a defined time window. This feature is particularly valuable for analyzing historical data within a model, such as tracking changes in a variable over time. It enables modelers to perform retrospective analyses, compare past and present values, and identify trends or patterns. The optional *Period* argument allows focusing on a specific timeframe.

**Examples:**

Sum(PastValues([Income]))Total past income

Mean(PastValues([Stock Price], {5 Years}))Computes the average stock price over the last 5 years.

Max(PastValues([Temperature], {1 Year}))Finds the highest temperature value in the past year.

Min(PastValues([Water Level], {2 Years}))Determines the lowest water level recorded in the past two years.

Returns the maximum of the values a primitive has taken on over the course of the simulation. The second optional argument is a time window to limit the calculation.

**Basic Structure:**

PastMax([Primitive], Period = All Time)

**Description:**

The **PastMax** function calculates the highest value that a specified primitive has reached during the simulation or within a given timeframe. It can be used to monitor maximum loads, peak performances, or the highest levels of resource utilization. The optional *Period* parameter allows for the analysis of peak values within a specific interval.

**Examples:**

PastMax([Income], {10 Years})The maximum income in the past 10 years

PastMax([Pollution Level], {5 Years})Determines the maximum pollution level recorded in the last 5 years.

PastMax([Customer Satisfaction])Finds the highest customer satisfaction score throughout the simulation.

PastMax([Sales], {1 Year})Calculates the peak sales volume within the past year.

Returns the minimum of the values a primitive has taken on over the course of the simulation. The second optional argument is a time window to limit the calculation.

**Basic Structure:**

PastMin([Primitive], Period = All Time)

**Description:**

The **PastMin** function computes the smallest value that a specified primitive (such as a variable or constant) has assumed during the simulation or within a specified time window specified by *Period*.

**Examples:**

PastMin([Income], 10)→The minimum income in the past 10 units of timeFinds the lowest income value over the last 10 time units.

PastMin([Water Level], {2 Years})Determines the lowest water level recorded in the past two years.

PastMin([Stock Price])Calculates the lowest stock price during the entire simulation.

Returns the median of the values a primitive has taken on over the course of the simulation. The second optional argument is a time window to limit the calculation.

**Basic Structure:**

PastMedian([Primitive], Period = All Time)

**Description:**

The **PastMedian** function calculates the median value that a specified primitive has reached during the simulation or within a given time window specified by *Period*.

It provides a robust measure of central tendency, especially in skewed distributions.

**Examples:**

PastMedian([Product Sales], {1 Year})Finds the median sales number for a product over the past year.

PastMedian([Temperature], {3 Months})Calculates the median temperature recorded over the last three months.

PastMedian([Pollution Level])Determines the median level of pollution throughout the simulation.

Returns the mean of the values a primitive has taken on over the course of the simulation. The second optional argument is a time window to limit the calculation.

**Basic Structure:**

PastMean([Primitive], Period = All Time)

**Description:**

The **PastMean** function computes the average value that a specified primitive has assumed during the simulation or within a specified *Period*.

Use cases include calculating the average growth rate of a population, the mean temperature for climatological studies, or the average revenue generated in a fiscal period.

**Examples:**

PastMean([Rainfall], {1 Year})Calculates the average rainfall over the past year.

PastMean([Stock Value], {3 Months})The mean stock value in the last quarter.

PastMean([Energy Consumption])The mean energy consumption throughout the simulation.

Returns the standard deviation of the values a primitive has taken on over the course of the simulation. The second optional argument is a time window to limit the calculation.

**Basic Structure:**

PastStdDev([Primitive], Period = All Time)

**Description:**

The **PastStdDev** function calculates the standard deviation of the values a specified primitive has taken on during the simulation or within a defined *Period*. This measure shows how much variation exists from the average or mean value.

A higher standard deviation indicates greater variability, whereas a lower standard deviation indicates that the values are closer to the mean.

**Examples:**

PastStdDev([Market Demand], {1 Year})Evaluates the volatility in market demand over the past year.

PastStdDev([Temperature], {6 Months})The standard deviation in temperature during the last six months.

PastStdDev([Production Output])Calculates the standard deviation of production output throughout the simulation.

Returns the correlation between the values that two primitives have taken on over the course of the simulation. The third optional argument is an optional time window to limit the calculation.

**Basic Structure:**

PastCorrelation([Primitive], [Primitive], Period = All Time)

**Description:**

The **PastCorrelation** function calculates the statistical correlation between the values of two specified primitives over the course of the simulation or within a given *Period*. This is used for identifying relationships between variables, such as the correlation between advertising spend and sales revenue, or temperature changes and ice cream sales.

A positive correlation indicates that as one primitive increases, the other tends to increase, while a negative correlation indicates that as one increases, the other tends to decrease.

**Examples:**

PastCorrelation([Income], [Expenditures], {10 Years})The correlation between income and expenditures over the past 10 years.

PastCorrelation([Temperature], [Ice Cream Sales], {1 Year})The correlation between temperature and ice cream sales over the last year.

PastCorrelation([Social Media Spend], [Website Traffic])The correlation between social media marketing spend and website traffic throughout the simulation.

Takes the dynamic value and forces it to be fixed over the course of the period. If period is ommitted, the value is held constant over the course of the whole simulation.

**Basic Structure:**

Fix(Value, Period = All Time)

**Description:**

The **Fix** function locks the value of a dynamic variable, making it constant for a specified period or throughout the entire simulation if the *Period* is ommitted. This is especially useful for things like sensitivity testing where you want to choose a random value at the start of the simulation and then hold it constant for the duration of the simulation.

**Examples:**

Fix(Rand(), {5 Years})Chooses a new random value every five years

Fix([Initial Stock Price])Sets the initial stock price to remain constant throughout the simulation.

Fix([Annual Rainfall], {10 Years})Keeps the annual rainfall amount constant for a decade.

Fix([Technology Efficiency], {2 Years})Assumes technology efficiency remains unchanged for two years.

## Random Number Functions

Generates a uniformly distributed random number between the minimum and maximum. The minimum and maximum are optional and default to 0 and 1 respectively.

**Basic Structure:**

Rand(Minimum, Maximum)

**Description:**

The **Rand** function generates a random number that follows a uniform distribution between specified minimum and maximum values. If no parameters are provided, it defaults to a range between 0 and 1.

The uniform distribution is characterized by its equal probability for all values within the range.

**Examples:**

Rand()Generates a random number between 0 and 1

Rand(1, 10)Generates a random number between 1 and 10

Rand(-5, 5)Generates a random number between -5 and 5

Rand(0, 100)Generates a random number between 0 and 100

Generates a normally distributed random number with a mean and a standard deviation. The mean and standard deviation are optional and default to 0 and 1 respectively.

**Basic Structure:**

RandNormal(Mean, Standard Deviation)

**Description:**

The **RandNormal** function generates a random number that follows a normal (Gaussian) distribution, defined by a specific *Mean* and *Standard Deviation*. By default, it produces a standard normal distribution with a mean of 0 and a standard deviation of 1.

**Examples:**

RandNormal()Generates a standard normal distributed random number

RandNormal(10, 2)Generates a random number with mean 10 and standard deviation 2

RandNormal(100, 15)Generates a random number with mean 100 and standard deviation 15

RandNormal(50, 5)Generates a random number with mean 50 and standard deviation 5

Generates a log-normally distributed random number with a mean and a standard deviation.

**Basic Structure:**

RandLognormal(Mean, Standard Deviation)

**Description:**

The **RandLognormal** function generates a random number with a distribution that is log-normally distributed, defined by its *Mean* and *Standard Deviation* in the log-space. This distribution is used to model variables whose log-transform is normally distributed, such as certain financial assets, life spans of technical products, and other skewed distributions.

Lognormal distribution values are always greater than 0, with a long tail to the right, making them suitable for representing quantities that cannot be negative.

**Examples:**

RandLognormal(1, 0.25)Generates a log-normally distributed number with a log-space mean of 1 and standard deviation of 0.25

RandLognormal(0, 0.5)Generates a log-normally distributed number with a log-space mean of 0 and standard deviation of 0.5

RandLognormal(2, 1)Generates a log-normally distributed number with a log-space mean of 2 and standard deviation of 1

Returns true with the specified probability, otherwise false. The probability is optional and defaults to 0.5: a coin flip.

**Basic Structure:**

RandBoolean(Probability)

**Description:**

The **RandBoolean** function generates a binary outcome (true or false) based on a specified *Probability*. By default, with a probability of 0.5, it simulates a fair coin flip. This function is useful for modeling binary outcomes in simulations, such as success/failure, yes/no, or on/off scenarios, where each event has a certain probability of occurring.

**Examples:**

RandBoolean(0.1)Returns false with 90% probability and true with 10% probability

RandBoolean(0.9)Returns true with 90% probability and false with 10% probability

RandBoolean()A 50% chance to return either false or true, simulating a coin flip

Generates a binomially distributed random number. The number of successes in Count random events each with Probability of success.

**Basic Structure:**

RandBinomial(Count, Probability)

**Description:**

The **RandBinomial** function generates a random number representing the number of successes in a given *Count* number of trials, each with the same *Probability* of success. This function is used to model scenarios where an event has a binary outcome (success or failure) repeated multiple times, such as flipping a coin or quality control tests.

**Examples:**

RandBinomial(10, 0.5)The number of successes in 10 trials with a 50% success rate

RandBinomial(20, 0.3)The number of successes in 20 trials with a 30% success rate

RandBinomial(5, 0.8)The number of successes in 5 trials with an 80% success rate

Generates a negative binomially distributed random number. The number of random events each with Probability of success required to generate the specified Successes.

**Basic Structure:**

RandNegativeBinomial(Successes, Probability)

**Description:**

The **RandNegativeBinomial** function generates a random number representing the number of trials needed to achieve a specified number of *Successes*, where each trial has the same *Probability* of success. This function is useful in scenarios where the focus is on reaching a predetermined number of successes, such as the number of sales calls needed to achieve a set number of sales or the number of patients to treat before a certain number of recoveries is observed.

The negative binomial distribution is an extension of the binomial distribution, handling cases where the number of trials is not fixed in advance.

**Examples:**

RandNegativeBinomial(3, 0.5)The number of trials to achieve 3 successes with a 50% success rate

RandNegativeBinomial(5, 0.3)The number of trials to achieve 5 successes with a 30% success rate

RandNegativeBinomial(2, 0.7)The number of trials to achieve 2 successes with a 70% success rate

Generates a Poisson distributed random number.

**Basic Structure:**

RandPoisson(Lambda)

**Description:**

The **RandPoisson** function generates a random number following the Poisson distribution with a mean (*Lambda*) rate of occurrence. The Poisson distribution is used to model the number of times an event occurs within a fixed interval of time or space. This function is particularly useful in scenarios where events happen independently at a constant rate, such as the number of customers arriving at a store in an hour or the number of emails received per day.

**Examples:**

RandPoisson(5)Generates a Poisson distributed number with Lambda=5

RandPoisson(10)Simulates the number of events (Lambda=10) occurring in a fixed interval

RandPoisson(2)Models a low-rate event occurrence scenario with Lambda=2

Generates a triangularly distributed random number.

**Basic Structure:**

RandTriangular(Minimum, Maximum, Peak)

**Description:**

The **RandTriangular** function generates a random number following a triangular distribution defined by a *minimum*, *maximum*, and *peak* (most likely value). This distribution is used for simulations where precise data is unavailable, but the limits and the most likely outcome are known.

**Examples:**

RandTriangular(1, 10, 5)Generates a triangular distributed number with a minimum of 1, maximum of 10, and peak at 5

RandTriangular(0, 100, 20)Models a scenario with wide range but a more likely lower value

RandTriangular(3, 6, 4)Useful for more precise estimations with narrower ranges

Generates an exponentially distributed random number with the specified rate parameter.

**Basic Structure:**

RandExp(Lambda)

**Description:**

The **RandExp** function generates a random number following the exponential distribution with rate parameter (*Lambda*), representing the time between events in a Poisson process. This distribution is widely used to model waiting times, such as the time until the next phone call at a call center or the time to failure of mechanical components.

Common applications include modeling the time between arrivals in queue systems, reliability testing for time to failure of products, and other processes where events occur continuously and independently at a constant average rate.

**Examples:**

RandExp(1)Generates an exponentially distributed time between events with Lambda=1

RandExp(0.5)Simulates longer expected time between events with Lambda=0.5

RandExp(5)Models a high rate of event occurrence with short expected times between them with Lambda=5

Generates a Gamma distributed random number.

**Basic Structure:**

RandGamma(Alpha, Beta)

**Description:**

The **RandGamma** function generates a random number following the Gamma distribution, characterized by shape (*alpha*) and rate (*beta*) parameters. The Gamma distribution is used for modeling waiting times for multiple events, such as the total rainfall accumulated in a year, or the load on web servers over time. It's useful when the event rate varies or when events occur in sequence.

**Examples:**

RandGamma(2, 2)Generates a Gamma distributed number with Alpha=2, Beta=2

RandGamma(5, 1)Models a scenario with a longer tail, indicating possible high-value outcomes

RandGamma(1, 0.5)Simulates an exponential distribution with Alpha=1 and Beta=0.5

Generates a Beta distributed random number.

**Basic Structure:**

RandBeta(Alpha, Beta)

**Description:**

The **RandBeta** function generates a random number following the Beta distribution with shape parameters *alpha* and *beta*. This distribution is used to model events that have a limited range, such as probabilities that vary between 0 and 1. It's especially useful in Bayesian statistics, project management for task completion rates, and modeling proportions.

**Examples:**

RandBeta(2, 5)Generates a Beta distributed number leaning towards lower values

RandBeta(5, 2)Models a distribution with a tendency towards higher values

RandBeta(1, 1)Represents a uniform distribution between 0 and 1

Generates a random number according to a custom distribution.

**Basic Structure:**

RandDist(X, Y)

**Description:**

The **RandDist** function generates a random number based on a custom distribution defined by vectors of *x* (values) and *y* (likelihood). This function allows for the modeling of complex, non-standard distributions that cannot be captured by pre-defined distribution functions. It's particularly useful for empirical distributions derived from data

**Examples:**

RandDist({1, 2, 3}, {0.2, 0.5, 0.3})Generates a number from a custom distribution with three discrete outcomes

RandDist({0, 10, 20}, {0, 0.5, 0})Models a triangular distribution manually

RandDist({-1, 0, 1}, {0.25, 0.5, 0.25})Simulates outcomes with a higher likelihood of occurring at 0

Sets the seed for the random number generator.

**Basic Structure:**

SetRandSeed(Seed)

**Description:**

The **SetRandSeed** function sets the seed for the random number generator, ensuring reproducibility of random number sequences. This is useful for debugging simulations and for scientific research where replicating results is necessary. By setting the same seed, you guarantee that the sequence of random numbers generated will be the same across different simulation runs.

Use cases include initializing simulations to ensure consistent results for comparison, teaching scenarios where specific outcomes are expected, and research studies requiring reproducibility.

Note that changes to the simulation algorithm or model structure can affect the sequence of random numbers, even with the same seed.

**Examples:**

SetRandSeed(123)Initializes the random number generator with a seed of 123

SetRandSeed(83940)Ensures a different sequence of random numbers with seed 83940

## Agent Functions

Returns a vector of all the agents in the agent population.

**Basic Structure:**

[Agent Population].FindAll()

**Description:**

The **Find All** function is used to retrieve every agent within a specified agent population. It's particularly useful for performing operations or analyses on the entire group of agents at once, without any need to filter based on conditions or states.

Use cases include calculating aggregate statistics (such as average health in a population), applying global changes (like an environmental factor affecting all agents), or initializing properties across all agents at the start of a simulation.

**Examples:**

[Fish].FindAll()Retrieves all fish agents in the simulation.

[People].FindAll().Count()Counts the total number of people agents.

Mean([Trees].FindAll().Map(x.Value([Height])))Calculates the average height of all tree agents.

Returns a vector of agents in the specified state.

**Basic Structure:**

[Agent Population].FindState([State])

**Description:**

The **Find State** function identifies all agents within a given population that are in a specific state. It's an important tool for segmenting agent populations based on their current conditions or behaviors. The matching agents are returned as a vector.

Common use cases include identifying all agents with a disease in epidemiological models, categorizing agents based on decision-making states in social simulations, or segregating resources by availability in logistics models.

**Examples:**

[Students].FindState([Studying])Finds all students currently in the studying state.

[Cells].FindState([Infected])Selects all cells that are in the infected state.

Mean([Trees].FindState([Burned]).Map(x.Value([Height])))Calculates the average height of all burned tree agents.

Returns a vector of agents not in the specified state.

**Basic Structure:**

[Agent Population].FindNotState([State])

**Description:**

The **Find Not State** function filters out agents within a population that are not in a given state, allowing for the exclusion of specific conditions or behaviors. The matching agents are returned as a vector.

Use cases include identifying susceptible individuals in a disease model or excluding specific roles in a workplace simulation.

**Examples:**

[Patients].FindNotState([Recovered])Finds all patients who have not recovered.

[Machines].FindNotState([Operational])Identifies all machines that are not operational.

[Students].FindNotState([Graduated])Selects all students who have not yet graduated.

Mean([Trees].FindNotState([Burned]).Map(x.Value([Height])))Calculates the average height of all trees that are not in the burned state.

Returns an agent with the specified index. Agent indexes start at 1.

**Basic Structure:**

[Agent Population].FindIndex(Index)

**Description:**

The **FindIndex** function retrieves a specific agent from a population based on its index. Indexes start at 1 and increase sequentially.

Example applications include tracking the first or last agent in a system, selecting specific agents for detailed analysis, or initiating events for particular individuals in a population model.

**Examples:**

[Fish].FindIndex(1)Selects the first fish agent created in the simulation.

[People].FindIndex([People].Count())Retrieves the most recently added person to the population.

[Books].FindIndex(5)Accesses the fifth book agent in the library simulation.

Returns a vector of agents that are within the specified distance of a target agent or location.

**Basic Structure:**

[Agent Population].FindNearby(Target, Distance)

**Description:**

The **FindNearby** function identifies agents within a certain distance from a target agent or location, facilitating the modeling of local interactions or influence zones. Matching agents are returned as a vector. It's particularly useful in spatially explicit simulations where proximity affects agent interactions, such as disease transmission, social influence, or resource competition.

**Examples:**

[Trees].FindNearby(PollutedArea, 50)Selects trees within 50 units of a polluted area.

[Fish].FindNearby(FoodSource, 20)Retrieves fish within 20 units of a food source.

[Population].FindState([Infected]).FindNearby(Self, 25)All infected people who are near the agent.

Returns the nearest agents to the target agent or location. The number of agents returned is specified by the optional Count.

**Basic Structure:**

[Agent Population].FindNearest(Target, Count=1)

**Description:**

The **FindNearest** function identifies the closest agent(s) to a specified target, either an agent or a location, with an optional *Count* parameter to specify the number of agents to return. If *Count* is ommitted, only the closest agent is returned. The matching agents are returned as a vector.

**Examples:**

[Customers].FindNearest(Store)Finds the nearest customer to the store.

[Prey].FindNearest(Predator, 3)Identifies the three nearest prey to the predator.

[EmergencyVehicles].FindNearest(AccidentSite, 5)Selects the five nearest emergency vehicles to an accident site.

Returns the agent farthest from the target agent or location. The number of agents returned is specified by the optional Count.

**Basic Structure:**

[Agent Population].FindFurthest(Target, Count=1)

**Description:**

The **Find Furthest** function identifies the agent(s) that are furthest away from a specified target, either another agent or a specific location. This function is useful in scenarios where distance or separation is a key factor, such as in spatial analysis, competition models, or emergency response planning. The optional *Count* parameter allows you to specify the number of farthest agents to return. If *Count* is ommitted, only the furthest agent is returned.

**Examples:**

[Population].FindFurthest(Target, 4)Identifies the four agents furthest from the target, useful for evacuation or resource distribution planning.

[RetailStores].FindFurthest(Mall)Finds the retail store furthest from the mall to analyze competition or customer reach.

[FireStations].FindFurthest(Fire, 3)Selects the three fire stations furthest from a fire, potentially to remain on standby or cover other areas.

Returns the values of the specified primitive for each agent in the population as a vector.

**Basic Structure:**

[Agent Population].Value([Primitive])

**Description:**

The **Value** function retrieves the values of a specified primitive for each agent within an agent population, returning these values as a vector. This is particularly useful for aggregate analysis, statistical calculations, or when comparing or contrasting agents based on specific attributes.

Common use cases include analyzing the distribution of a particular trait within a population, such as age or income in demographic studies, or health status in epidemiological models.

**Examples:**

[University].Value([GPA]).Mean()Calculates the average GPA of all students in the University population.

[Employees].Value([Salary]).Max()Finds the highest salary among all employees.

[Cars].Value([Mileage]).Min()Identifies the car with the lowest mileage.

Sets the value of the specified primitive for each agent in the population to the given value. Can also be applied directly to an agent.

**Basic Structure:**

[Agent Population].SetValue([Primitive], Value)

**Description:**

The **SetValue** function allows for the direct modification of a primitive's value for each agent within a population or for a specific agent. This is used in scenarios where an attribute needs to be updated based on simulation conditions or decisions, such as changing an agent's status, modifying resource levels, or adjusting positional data.

**Examples:**

[University].SetValue([Smoker], false)Updates the smoker status to non-smoker for all individuals in the University population.

car.SetValue([FuelLevel], 100)Refills the fuel tank of the car full capacity.

Returns the location of an agent as the vector {x, y}.

**Basic Structure:**

[Agent].Location()

**Description:**

The **Location** function retrieves the current spatial position of an agent, represented as an *{x, y}() vector. This function is useful for spatially explicit models where the position, movement, or distribution of agents plays a significant role in the system's dynamics.

Applications include tracking the movement of animals in ecological studies, monitoring the spread of individuals in epidemiological models, or analyzing traffic flow in urban planning simulations.

**Examples:**

Self.Location().xRetrieves the x-coordinate of the agents.

Self.Location().yGets the y-coordinate of the agent.

Predator.Location().Distance(Prey.Location())Calculates the distance between a predator and its prey.

Sets the location of the agent.

**Basic Structure:**

[Agent].SetLocation(New Location)

**Description:**

The **SetLocation** function assigns a new spatial position to an agent, specified by an *{x, y}* vector. This function is useful for simulating movement, migration, or any form of spatial redistribution of agents within a model.

It can be used to simulate animals moving towards resources in ecological models, people relocating in demographic simulations, or vehicles navigating in transportation systems. This direct manipulation of agent position supports dynamic spatial interactions and the modeling of complex behaviors based on geographical context.

**Examples:**

Student.SetLocation({x: 60, y: 40})Moves the student to a new position on the map, simulating spatial dynamics in a campus model.

Taxi.SetLocation(Customer.Location())Positions the taxi at the customer's location.

Bird.SetLocation(Bird.location() + {x: -10, y: 0})Simulates the eastward movement of a bird by 10 units.

Gets the numeric index of an agent within an agent population. Indexes are sequential within a population and start at 1.

**Basic Structure:**

[Agent].Index()

**Description:**

The **Index** function returns the position of an agent within its population, starting with 1. This sequential numbering is useful for identifying agents uniquely within a population..

**Examples:**

Self.Index()Obtains the agent's own index within its population, useful for self-referencing in complex interactions.

IfThenElse(agent.Index() Mod 2 = 0, agent.SetValue([Is Even], true), agent.SetValue([Is Even], false))Assigns [Is Even] state values to agents based on their index.

Returns the distance between two agents or locations.

**Basic Structure:**

Distance(Location One, Location Two)

**Description:**

The **Distance** function calculates the straight-line (Euclidean) distance between two points, defined by their *{x, y}* coordinates. This function is useful for spatial analysis, measuring proximity, or triggering interactions based on spatial separation in models.

**Distance** can also be passed agents in place of location vectors, in which case it will calculate the distance between the two agents.

**Examples:**

Distance({x: 10, y: 5}, {x: 20, y: 15})Calculates the distance between two points.

Distance(Self.Location(), FoodSource.Location())Measures the distance from an agent to a food source.

Distance(patient, hospital)Determines the distance from a patient to the hospital.

Moves an agent the amount specified.

**Basic Structure:**

[Agent].Move({x, y})

**Description:**

The **Move** function changes an agent's position by a specified vector *{x, y}*, enabling the simulation of mobility, migration, and other forms of spatial dynamics.

**Examples:**

Self.Move({x: Rand(-1, 1), y: Rand(-1, 1)})Executes a random walk, moving the agent in a random direction by up to 1 unit in both the x and y dimensions.

Self.Move({x: 0, y: -5})Moves the agent 5 units north, simulating straightforward linear movement.

Car.Move({x: 10, y: 0})Advances the car 10 units east, useful for simulating traffic flow or vehicle navigation.

Moves an agent towards a target agent or location by the distance specified.

**Basic Structure:**

[Agent].MoveTowards(Target, Distance)

**Description:**

The **MoveTowards** function directs an agent towards a specified target agent or location by a given *Distance*. The target can be a set of coordinates or another agent, and the distance specifies how far the agent should move in the direction of the target on each invocation.

**Examples:**

Self.MoveTowards({0, 100}, 10)Moves towards the point {0, 100} by 10 units.

Self.MoveTowards([Food Sources].FindNearest(Self), 5)Moves towards the nearest food source by 5 units.

Returns the agents connected to an agent in the network.

**Basic Structure:**

[Agent].Connected()

**Description:**

The **Connected** function retrieves a list of agents that are directly connected to a specified agent within a network. This function is used to analyze network structures, including social networks, supply chains, or ecological food webs. By understanding the connections between agents, modelers can simulate the spread of information, diseases, or resources through a network.

**Examples:**

Self.Connected().Length()The number of connections an agent has.

Self.Connected().Map(Self.Unconnect(x))→Removes all connections from the agent

Connects two agents in the network. The second agent can also be a vector of agents. Optionally, you can specify a connection weight which will be stored with the connection.

**Basic Structure:**

[Agent 1].Connect([Agent 2], Weight=1)

**Description:**

The **Connect** function establishes a connection between two agents within a network, optionally assigning a *Weight* to the connection. This is useful for simulations that involve network dynamics, such as social networks, ecosystems, or infrastructure systems. Connection weights can represent the strength or capacity of the connection, influencing the interaction between agents, such as the amount of resource flow or the intensity of communication.

**Examples:**

Self.Connect([Population].FindNearest(Self), 5)Connects an agent to the nearest agent with a weight of 5.

Self.Connect(Self.FindNearest([Food Source]), 10)→Connects to the nearest food source with a weight of 10, indicating high priority.

Unconnects two agents in the network. The second agent can also be a vector of agents.

**Basic Structure:**

[Agent 1].Unconnect([Agent 2])

**Description:**

The **Unconnect** function removes the connection between two agents in a network, or between an agent and a group of agents if the second argument is a vector. This function is used to simulate changes in network structure over time, such as the dissolution of social ties, the disruption of supply chains, or the loss of habitat connectivity.

Use cases include modeling the effects of social distancing on disease spread, analyzing the impact of infrastructure failure on logistics networks, or simulating habitat fragmentation in ecological systems.

**Examples:**

Self.Unconnect(Self.Connected())Removes all of an agent's connections.

Self.Unconnect(SpecificAgent)Targeted disconnection from a particular agent.

Returns the connection weight between two agents.

**Basic Structure:**

[Agent 1].ConnectionWeight([Agent 2])

**Description:**

The **ConnectionWeight** function retrieves the weight of the connection between two agents in a network. This weight can represent various aspects of the connection, such as its strength, frequency, or capacity, depending on the model's context. It's used for simulations that require detailed analysis of the interactions within a network, enabling the quantification of relationships and flows between agents.

**Examples:**

Self.ConnectionWeight(agent)Retrieves the weight of the connection to a specific agent.

Max(Self.Connected().Map(Self.ConnectionWeight(x)))Identifies the strongest connection weight an agent has.

Sets the connection weight between two agents.

**Basic Structure:**

[Agent 1].SetConnectionWeight([Agent 2], Weight)

**Description:**

The **SetConnectionWeight** function adjusts the weight of the connection between two agents in a network. Connection weights can represent the strength, influence, or capacity of the connection, impacting the dynamics of interactions within the network. For example, in a social network model, the weight might represent the closeness of a relationship; in a transportation model, it could represent the capacity of a route.

**Examples:**

Self.SetConnectionWeight(Other, 10)Sets the weight of the connection to Other agent as 10.

Self.SetConnectionWeight(BestBFriend, 100)Increases the connection weight with the Best Friend agent, indicating a very strong bond.

The total number of agents in a population.

**Basic Structure:**

[Agent Population].PopulationSize()

**Description:**

The **PopulationSize** function returns the total number of agents within a specified population. It can be used to trigger actions when the population reaches a certain size, to calculate per capita metrics, or to adjust resources based on population size.

**Examples:**

[Fish].PopulationSize()Returns the total number of fish agents in the simulation.

IfThenElse([Rabbits].PopulationSize() > 1000, 'Overpopulated', 'Stable')Checks if the rabbit population exceeds 1000 to label it 'Overpopulated'.

[Employees].PopulationSize()Fetches the current number of employee agents.

Adds a new agent to the population. If Base is set, the new agent will be a clone of Base Agent. Otherwise, the agent will be like a newly created agent at the start of the simulation.

**Basic Structure:**

[Agent Population].Add(Base Agent=Initial Agent)

**Description:**

The **Add** function introduces a new agent into the population. Optionally, *Base Agent* may be set to have the new agent can be a clone of an existing agent, inheriting its properties and state, or it can start with default properties.

**Examples:**

[University].Add()Adds a new student agent with default properties to the University.

[Trees].Add(Tree)Clones the Tree agent, simulating the planting of a new tree with similar characteristics.

Repeat([Company].Add(NewHire), 10)Hires 10 new employees, each a clone of the NewHire agent.

Removes an agent from the population. The agent will no longer be simulated. Can be used to "Kill" an agent.

**Basic Structure:**

[Agent].Remove()

**Description:**

The **Remove** function eliminates an agent from the simulation, ceasing its simulation activities. This is used to simulate death in biological models, the exit of individuals or entities in social or economic models, or the discontinuation of products in market models.

**Examples:**

[University].FindState([Smoker]).Map(x.Remove())Expel all the smokers from the Universit.

prey.Remove()Removes a specific prey agent from the simulation.

The width of the geographic region an agent is within.

**Basic Structure:**

Width(Agent)

**Description:**

The **Width** function returns the width of the geographic region that an agent is within. This can be useful to calibrate behavior based on the size of the region.

**Examples:**

Width(Self)The width of the geographic region the agent is within.

The height of the geographic region an agent is within.

**Basic Structure:**

Height(Agent)

**Description:**

The **Height** function provides the height of the geographic region an agent is within. This can be useful to calibrate behavior based on the size of the region.

**Examples:**

Height(Self)The height of the geographic region the agent is within.

## Vector Functions

Creates a vector with a range of sequential values going from start to end.

**Basic Structure:**

Start:End

**Description:**

The **Range** operator creates a vector of sequential numbers starting from a specified *Start* value and ending at a specified *End* value. By default, it increments by 1. For custom step sizes, place the step size between the start and the end values, such as "0:0.5:10".

**Examples:**

1:5→{1, 2, 3, 4, 5}

0:2:10→{0, 2, 4, 6, 8, 10}Creates a vector from 0 to 10 in steps of 2

-5:1:5→{-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5}Creates a vector from -5 to 5 in steps of 1

10:-2:2→{10, 8, 6, 4, 2}Creates a descending vector from 10 to 2 in steps of -2

The number of elements in a vector.

**Basic Structure:**

Vector.Length()

**Description:**

The **Length** function returns the number of elements in a vector. It's used to determine the size of a vector, which is important for looping over elements, analyzing data size, and managing dynamic vectors in models.

**Examples:**

{1, 1, 2, 3}.Length()→4

{10, 20, 30, 40, 50}.Length()→5

{}.Length()→0

{ 'a', 'b', 'c', 'd', 'e', 'f' }.Length()→6

Selects one or more elements from a vector.

**Basic Structure:**

Vector{Selector}

**Description:**

The **Select** function retrieves one or more elements from a vector based on the provided *Selector*. Selectors can be integers (to select by position), vectors of integers (for multiple positions), strings (for named vectors), or vectors of booleans (to select by condition). It's useful for extracting specific data points, subsetting vectors, or applying conditions to filter elements.

**Examples:**

{1,3,7}{2}→3

{4, 5, 6, 7}{ {1, 3} }→{4, 6}Selects elements at positions 1 and 3

{ 'a': 1, 'b': 2, 'c': 3 }{'b'}→2Selects element with name 'b'

{10, 20, 30, 40, 50}{ {true, false, true, false, true} }→{10, 30, 50}Selects elements at positions where selector is true

vector{ vector > 10 }Selects elements that are greater then 10

Merges items together into a single vector.

**Basic Structure:**

Join(Item 1, Item 2, Item N)

**Description:**

The **Join** function combines multiple items into a single vector. Items can be numbers, strings, or other vectors. This function is useful for concatenating data from different sources or aggregating results.

**Examples:**

Join(0, {1, 1, 2})→{0, 1, 1, 2}

Join({1, 2}, {3, 4}, {5, 6})→{1, 2, 3, 4, 5, 6}Joins three vectors into one

Join('a', {'b', 'c'}, 'd')→{'a', 'b', 'c', 'd'}Combines strings and a vector into a single vector

Join()→{}Returns an empty vector when no arguments are provided

Flattens a vector removing and expanding all nested vectors.

**Basic Structure:**

Vector.Flatten()

**Description:**

The **Flatten** function converts a vector containing nested vectors into a single, flat vector. This operation is useful for simplifying data structures, preparing data for analysis, and ensuring compatibility with functions that require non-nested input.

**Examples:**

{ {0}, {1, 1, 2} }.Flatten()→{0, 1, 1, 2}

{ {1, 2}, {3, {4, 5}} }.Flatten()→{1, 2, 3, 4, 5}Flattens a vector with nested vectors

{ {}, {0}, {}, {1, 2} }.Flatten()→{0, 1, 2}Ignores empty vectors and flattens the rest

{ { { {1} } } }.Flatten()→{1}Flattens deeply nested vectors into a single level

Returns a vector with duplicates removed.

**Basic Structure:**

Vector.Unique()

**Description:**

The **Unique** function removes duplicate elements from a vector, returning a vector in which each element appears only once. It's useful for data cleaning, generating lists of distinct values, and preparing datasets for analysis.

**Examples:**

{1, 1, 2, 3}.Unique()→{1, 2, 3}

{'a', 'b', 'a', 'c', 'b'}.Unique()→{'a', 'b', 'c'}Removes duplicates from a vector of strings

{10, 20, 20, 10, 30}.Unique()→{10, 20, 30}Identifies and removes duplicate numbers

{}.Unique()→{}Returns an empty vector when applied to an empty vector

Returns the combined elements of two vectors (with duplicates removed).

**Basic Structure:**

Vector.Union(Vector 2)

**Description:**

The **Union** function merges two vectors, eliminating duplicate elements. This operation is useful for combining data sets, ensuring no repetition of elements.

**Examples:**

{1, 2}.Union({2, 3})→{1, 2, 3}

{'apple', 'banana'}.Union({'banana', 'cherry'})→{'apple', 'banana', 'cherry'}

{1, 4, 5}.Union({6, 7})→{1, 4, 5, 6, 7}Union of distinct numerical vectors.

{}.Union({2, 3})→{2, 3}Union with an empty vector returns the non-empty vector.

Returns the elements that exist in both vectors.

**Basic Structure:**

Vector.Intersection(Second Vector)

**Description:**

The **Intersection** function identifies and returns the elements common to both vectors.

**Examples:**

{1, 2}.Intersection({2, 3})→{2}

{'apple', 'banana'}.Intersection({'banana', 'cherry'})→{'banana'}

{1, 2, 3}.Intersection({4, 5, 6})→{}Intersection of disjoint vectors results in an empty vector.

{1, 2, 3}.Intersection({3, 2, 1})→{1, 2, 3}Intersection of vectors with the same elements in different order.

Returns the elements that exist in only one of the two vectors.

**Basic Structure:**

Vector.Difference(Vector 2)

**Description:**

The **Difference** function computes the set of elements that are unique to each vector when comparing two vectors.

**Examples:**

{1, 2}.Difference({2, 3})→{1, 3}

{'apple', 'banana'}.Difference({'banana', 'cherry'})→{'apple', 'cherry'}

{1, 2, 3}.Difference({})→{1, 2, 3}Difference with an empty vector retains all elements.

{1, 2, 3}.Difference({4, 5, 6})→{1, 2, 3, 4, 5, 6}Completely unique vectors result in a combination of both.

Sorts a vector from smallest value to largest value.

**Basic Structure:**

Vector.Sort()

**Description:**

The **Sort** function arranges the elements of a vector in ascending order, from the smallest to the largest value. **Sort** is used with vectors of numeric elements.

**Examples:**

{1, 3, 2, -1}.Sort()→{-1, 1, 2, 3}

{10, 20, 5, 30}.Sort()→{5, 10, 20, 30}

{1, 2, 3}.Sort()→{1, 2, 3}Already sorted vectors remain unchanged.

Reverses the ordering of elements in a vector.

**Basic Structure:**

Vector.Reverse()

**Description:**

The **Reverse** function inverts the order of elements within a vector, making the last element become the first and vice versa.

**Examples:**

{1, 2, 3}.Reverse()→{3, 2, 1}

{'apple', 'banana', 'cherry'}.Reverse()→{'cherry', 'banana', 'apple'}Reversing the order of strings.

Takes a random sample from a vector. Allow Repeats determines whether the same index can be sampled multiple times and is false by default.

**Basic Structure:**

Vector.Sample(Sample Size, Allow Repeats=False)

**Description:**

The **Sample** function randomly selects a specified number of elements from a vector. The option to allow repeats determines if elements can be chosen multiple times. It's used for simulations, bootstrapping statistical methods, and creating randomized subsets of data for analysis.

**Examples:**

{1, 4, 9}.Sample(2)→{9, 1}Randomly sampling two elements without repeats.

{1, 2, 3, 4, 5}.Sample(3, true)Sampling with replacement allows the same element to be selected more than once.

{1, 2, 3}.Sample(1)Randomly sampling a single element.

{1, 2, 3, 4, 5, 6}.Sample(4, false)Sampling four unique elements from the vector.

Returns the position of the needle within the vector (starting with index 1). If the needle is not found, 0 is returned.

**Basic Structure:**

Vector.IndexOf(Needle)

**Description:**

The **IndexOf** function searches for a specific element (*needle*) in a vector and returns its position, with indexing starting at 1. If the element is not found, it returns 0.

**Examples:**

{1, 4, 9}.IndexOf(9)→3

{'apple', 'banana', 'cherry'}.IndexOf('banana')→2Finding the position of a string within a vector of strings.

{1, 2, 3}.IndexOf(4)→0Searching for a non-existing element returns 0.

{2, 4, 2}.IndexOf(2)→1Returns the position of the first occurrence of the element.

Returns true if the needle is in the vector. Otherwise returns false.

**Basic Structure:**

Vector.Contains(Needle)

**Description:**

The **Contains** function checks whether a vector includes a specified element (*needle*), returning true if the element is found and false otherwise.

**Examples:**

{1, 4, 9}.Contains(9)→true

{'apple', 'banana', 'cherry'}.Contains('mango')→falseChecking for an element not present in the vector.

{}.Contains(1)→falseChecking an empty vector for any element returns false.

Creates a new vector by repeating an expression a specified number of times. 'x' in the expression refers to the current index. Times may also be a vector of strings in which case a named vector is created.

**Basic Structure:**

Repeat(Expression, Times)

**Description:**

The **Repeat** function generates a vector by evaluating an expression multiple times, where each evaluation's result is determined by its current index (*x*). This is particularly useful for initializing vectors with calculated values or creating custom sequences. For example, generating a series of numbers squared, or setting up initial states in a model where each state's value depends on its position.

When used with a vector of strings, it produces a named vector, enabling the creation of more readable and structured data sets. In this case, *key* can be used to access the current element's key.

**Examples:**

Repeat(x^2, 3)→{1, 4, 9}

Repeat(x*10, 5)→{10, 20, 30, 40, 50}Creates a vector {10, 20, 30, 40, 50} by multiplying index by 10

Repeat(2^x, 4)→{2, 4, 8, 16}Generates a vector with powers of 2

Repeat('Group ' + key, {'a', 'b', 'c'})→{a: 'Group a', b: 'Group b', c:'Group c'}

Applies a function to each element of a vector and returns the result. The function may also be an expression where 'x' in the expression represents the current element and, for named vectors, 'key' represents the current element's key.

**Basic Structure:**

Vector.Map(Function)

**Description:**

The **Map** function applies a specified function or expression to each element in a vector, transforming the original elements based on the function's logic.

The *x* variable represents the current element being processed, making it easy for operations that require element-wise manipulation, such as doubling values, converting units, or applying a mathematical formula. In the context of named vectors, *key* allows access to the current element's key.

**Examples:**

{1, 2, 3}.Map(x*2)→{2, 4, 6}

{1, 2, 3}.Map(x^2)→{1, 4, 9}Squares each element in the vector

{'a': 2, 'b': 4, 'c': 6}.Map(x/2)→{'a': 1, 'b': 2, 'c': 3}Halves each element in a named vector

{'a': 2, 'b': 4, 'c': 6}.Map(key + '-' + x)→{'a': 'a-2', 'b': 'b-4', 'c': 'c-6'}Adds the key to each element in a named vector

Tests each element of a vector using a function and returns the elements which evaluate to true. The function may also be an expression where 'x' in the expression represents the current element.

**Basic Structure:**

Vector.Filter(Function)

**Description:**

The **Filter** function screens each element of a vector through a given condition, returning a new vector composed only of elements for which the condition holds true. This is particularly useful for extracting subsets of data that meet specific criteria, such as filtering for values above a threshold, selecting specific items based on characteristics, or cleaning data.

The *x* variable represents the current element being processed, making it easy for operations that require element-wise filtering. In the context of named vectors, *key* allows access to the current element's key.

**Examples:**

{1, 2, 3}.Filter(x >= 2)→{2, 3}

{-2, 2, 4}.Filter(x > 0)→{2, 4}Filters for positive numbers only

{5, 10, 15}.Filter(x mod 5 == 0)→{5, 10, 15}Selects elements divisible by 5

{'a': 1, 'b': 2, 'c': 3}.Filter(x > 1)→{'b': 2, 'c': 3}Filters a named vector for values greater than 1

{'a': 1, 'b': 2, 'c': 3}.Filter(key = 'a')→{'a': 1}Filters a named vector based on the key

Returns the keys for a named vector as a vector. Any element without a key will be omitted.

**Basic Structure:**

Vector.Keys()

**Description:**

The **Keys** function extracts the keys from a named vector and returns them as a new vector.

**Examples:**

{'a': 1, 'b': 2, 'c': 3}.Keys()→{'a', 'b', 'c'}

{'first': 100, 'second': 200}.Keys()→{'first', 'second'}

Returns the values of a vector (stripping away any keys if it is a named vector).

**Basic Structure:**

Vector.Values()

**Description:**

The **Values** function retrieves all the values from a vector, discarding any associated keys in the case of named vectors.

**Examples:**

{'a': 1, 'b': 4, 'c': 9}.Values()→{1, 4, 9}

{'height': 180, 'weight': 75}.Values()→{180, 75}

Finds the Value in the Values Vector and returns the corresponding item in the Results Vector. If the exact Value is not found in the Values Vector, linear interpolation of the nearby values will be used.

**Basic Structure:**

Lookup(Value, Values Vector, Results Vector)

**Description:**

The **Lookup** function matches a given value against a series of values and returns a corresponding result from a parallel vector of results. If the exact value is not found, the function interpolates linearly between the two closest values. This function is used for modeling non-linear relationships or when discrete data points need to be transformed into a continuous curve.

Examples include interpolating temperature effects on growth rates or calculating tax based on income brackets.

**Examples:**

Lookup(6, {5, 7}, {10, 15})→12.5Interpolates between points for a value of 6.

Lookup(8, {5, 10}, {100, 200})→160Interpolates to find a result for 8.

Lookup(10, {0, 5, 10}, {0, 50, 100})→100Finds an exact match without needing to interpolate.

## General Functions

Tests a condition and returns one value if the condition is true and another value if the condition is false.

**Basic Structure:**

IfThenElse(Test Condition, Value if True, Value if False)

**Description:**

The **IfThenElse** function evaluates a condition and returns a specified value if the condition is true, and another value if the condition is false. It is a fundamental control structure used to branch execution flow within a model, allowing for dynamic responses based on varying conditions.

Common use cases include decision-making within a simulation, such as changing parameters based on thresholds or switching between different states in a state-based model.

**Examples:**

IfThenElse(20 > 10, 'High', 'Low')→HighReturns 'High' because the condition (20 > 10) is true.

IfThenElse(CurrentTime() > 5, 100, 0)→100Returns 100 if the current simulation time is greater than 5.

IfThenElse([Population] > 1000, 'Overpopulated', 'Sustainable')Evaluates population levels to return 'Overpopulated' or 'Sustainable'.

IfThenElse(Sum([Incomes]) > 50000, 'Wealthy', 'Average')Determines wealth status based on the sum of incomes.

Creates a pulse input at the specified time with the specified Height and Width. Height defaults to 1 and Width defaults to 0. Repeat is optional and will create a pulse train with the specified time if positive.

**Basic Structure:**

Pulse(Time, Height, Width=0, Repeat=-1)

**Description:**

The **Pulse** function generates a discrete or continuous series of pulses in a simulation, useful for modeling events that happen instantaneously or over a set period. The pulse can be configured to repeat at regular intervals by setting *Repeat*. This function is commonly used to simulate periodic inputs like seasonal sales spikes, annual resource allocations, or irregular events like natural disasters.

The pulse is defined by its start *time*, *height* (magnitude), *width* (duration), and *repeat* interval. A *width* of 0 indicates an instantaneous pulse.

**Examples:**

Pulse({10 Years}, 5, 2)→5Generates a pulse with height 5 and width 2 years, starting at year 10.

Pulse({5 Years}, 10, 1, {10 Years})Creates a pulse of height 10 starting at year 5, repeating every 10 years.

Pulse({1 Year}, 3, 0.5, {2 Years})A pulse of height 3 and width 0.5 years starting at year 1, repeating every 2 years.

Pulse({0 Years}, 1, 1, {1 Year})An annual pulse starting immediately, with height 1 and width 1 year.

Creates an input that is initially set to 0 and after the time of Start is set to Height. Height defaults to 1.

**Basic Structure:**

Step(Start, Height=1)

**Description:**

The **Step** function models a sudden change in a system's input at a specified *Start* time, where the input remains at the new *Height* indefinitely. It is useful for simulating scenarios like policy changes, investment injections, or environmental shifts. The function provides a simple way to model before-and-after effects of a single change within a system.

Typical use cases include step changes in funding, the introduction of new regulations, or sudden shifts in market demand.

**Examples:**

Step({10 Years}, 5)→5Introduces a step change to 5 after 10 years.

Step({2 Years}, 100)Implements a step change to 100 starting at year 2.

Step({5 Years})Default step to 1 starting at year 5.

Creates a ramp input which moves linearly from 0 to Height between the Start and Finish times. Before Start, the value is 0; after Finish, the value is Height. Height defaults to 1.

**Basic Structure:**

Ramp(Start, Finish, Height=1)

**Description:**

The **Ramp** function linearly increases an input from 0 to a specified *Height* over a defined period (from *Start* to *Finish*). After the *Finish* time, the function remains at *Height*. This function is particularly useful for modeling transitions or growth patterns that do not happen instantaneously.

It is often used to simulate gradual policy implementations, phased project developments, or resource depletion over time.

**Examples:**

Ramp({10 Year}, {20 Years}, 5)→5Linearly increases from 0 to 5 over 10 years, reaching full height at 20 years.

Ramp({0 Year}, {5 Years}, 100)A ramp from 0 to 100 starting immediately and completing over 5 years.

Ramp({3 Years}, {8 Years}, -50)Decreases from 0 to -50, starting at year 3 and ending at year 8.

Ramp({1 Year}, {10 Years})Gradual increase from 0 to 1, starting at year 1 through year 10.

Pauses the simulation and allows sliders to be adjusted.

**Basic Structure:**

Pause()

**Description:**

The **Pause** function temporarily halts the simulation, providing an opportunity to adjust parameters or examine the model's state more closely. This can be particularly useful during interactive sessions or presentations where real-time feedback is desired. It is often used in combination with **IfThenElse** function condition logic to pause the simulation at critical points or when specific conditions are met.

Common applications include educational settings, interactive games, or during stakeholder demonstrations to explore different scenarios.

**Examples:**

IfThenElse(Years() = 20, Pause(), 0)Pauses simulation at year 20 to allow for adjustments.

IfThenElse([Population] > 500, Pause(), 0)Pauses simulation when population exceeds 500.

Pause()Direct invocation to pause simulation, typically used within a conditional statement.

Immediately terminates the simulation.

**Basic Structure:**

Stop()

**Description:**

The **Stop** function immediately ends the simulation, which is useful for stopping a model once a certain condition is met or an objective is achieved. This function is often used in conjuction with the **IfThenElse** function.

Use cases include ending a simulation upon reaching a target value, exceeding safe operational thresholds, or concluding a scenario analysis.

**Examples:**

IfThenElse(Rand() < 0.01, Stop(), 0)Stops the simulation randomly with a 1% probability.

IfThenElse([Pollution] > 100, Stop(), 0)Terminates simulation if pollution exceeds a threshold.

Stop()Direct command to stop the simulation, typically used within a conditional statement.

## String Functions

The length of a string in characters.

**Basic Structure:**

String.Length()

**Description:**

The **Length** function returns the number of characters in a string. This includes all letters, numbers, spaces, and punctuation marks.

Use cases for **Length** include validating input data and processing user inputs or data fields where the length of the string may affect the outcome (e.g., formatting a display).

**Examples:**

"Hello, world!".Length()→13

"".Length()→0An empty string has a length of 0.

"1234567890".Length()→10Counts numbers as characters.

"This is a test.".Length()→15Includes spaces in the count.

Obtains a certain character or set of characters.

**Basic Structure:**

String.Range(Characters)

**Description:**

The **Range** function extracts a substring from a string, given a range of character positions. The first character of the string is at position 1. This function is useful for parsing strings, extracting specific data from formatted text, or processing parts of user input.

**Examples:**

"abcdef".Range(2:4)→"bcd"Extracts characters 2 through 4.

"Hello, world!".Range({1, 2, 3, 4, 5})→"Hello"Extracts the first 5 characters.

"InsightMaker".Range({1, 3})→"Is"Extracts disjoint characters.

Splits a string into a vector at the locations of the Delimiter.

**Basic Structure:**

String.Split(Delimiter)

**Description:**

The **Split** function divides a string into a vector of substrings, based on the specified *Delimiter*. It's particularly useful for parsing CSV data, breaking down complex strings into manageable parts, or extracting specific information from formatted text.

For example, splitting a list of names separated by commas, breaking a sentence into words using spaces as delimiters, or parsing a date string into year, month, and day components.

**Examples:**

"apple,banana,cherry".Split(",")→{"apple", "banana", "cherry"}Splits a comma-separated list.

"2024-02-22".Split("-")→{"2024", "02", "22"}Splits a date string into components.

"one two three".Split(" ")→{"one", "two", "three"}Splits a space-separated string.

Finds the location of the first occurrence of the needle in the string.

**Basic Structure:**

String.IndexOf(Needle)

**Description:**

The **IndexOf** function returns the position of the first occurrence of a specified substring (*Needle*) within a string. If the substring is not found, it returns -1. This function is useful for searching strings for specific data, verifying if and where a substring appears, or processing and analyzing text data.

Common use cases include finding the position of a character or phrase within a user input, validating formatting by checking for the presence of required characters, or parsing structured strings.

**Examples:**

"Hello, world!".IndexOf("world")→8Finds the start of 'world'.

"abcdef".IndexOf("d")→4Finds the position of 'd'.

"Repeat, repeat, repeat".IndexOf("repeat")→9Case-sensitive search.

"This does not contain it".IndexOf("xyz")→0Returns 0 if not found.

Returns true if the needle is in the string. Otherwise returns false.

**Basic Structure:**

String.Contains(Needle)

**Description:**

The **Contains** function checks if a string contains a specified substring (*Needle*) and returns true if it does, and false otherwise. This is particularly useful for validating input (e.g., checking for forbidden words or required terms), analyzing text for specific content, or filtering data based on text content.

**Examples:**

"Hello, world!".Contains("world")→trueChecks if 'world' is present.

"abcdef".Contains("g")→falseChecks if 'g' is not present.

"Case matters".Contains("case")→falseCase-sensitive check.

"Look for a substring".Contains("sub")→trueFinds a substring within the string.

Uppercases all letters in a string.

**Basic Structure:**

String.UpperCase()

**Description:**

The **UpperCase** function converts all the letters in a given string to uppercase. This function can be useful for normalizing text input, ensuring consistent case for string comparisons, or formatting text output for readability.

**Examples:**

"hello world".UpperCase()→"HELLO WORLD"

"InsightMaker".UpperCase()→"INSIGHTMAKER"

"123abc!".UpperCase()→"123ABC!"Non-letter characters remain unchanged

Lowercases all letters in a string.

**Basic Structure:**

String.LowerCase()

**Description:**

The **LowerCase** function converts all the letters in a given string to lowercase. It is often used to standardize text input, facilitate case-insensitive string comparisons, or achieve a uniform text format across documents or datasets.

**Examples:**

"HELLO WORLD".LowerCase()→"hello world"

"InsightMaker".LowerCase()→"insightmaker"

"123ABC!".LowerCase()→"123abc!"Non-letter characters remain unchanged

Combines the elements in a vector into a single string using the specified separator.

**Basic Structure:**

Vector.Join(String)

**Description:**

The **Join** function combines the elements of a vector into a single string, inserting a specified separator *String* between each element. This function is useful for concatenating a list of values into a readable format, generating comma-separated values (CSV) for data export, or creating compound keys from multiple attributes.

**Examples:**

{"John", "Paul", "George", "Ringo"}.Join(", ")→"John, Paul, George, Ringo"Join names with a comma and space

{2024, 02, 22}.Join("/")→"2024/02/22"Create a date string from year, month, and day

{"apple", "banana", "cherry"}.Join("-")→"apple-banana-cherry"Join words with a hyphen

Removes whitespace from both ends of a string.

**Basic Structure:**

String.Trim()

**Description:**

The **Trim** function removes any leading and trailing whitespace from a given string. This is particularly useful for cleaning input data, preparing text for processing, or ensuring that comparisons and searches are not affected by extraneous spaces.

**Examples:**

" hello world ".Trim()→"hello world"Trim spaces around text

"

InsightMaker

".Trim()→"InsightMaker"Trim tab and newline characters as well as spaces

"NoExtraSpaces".Trim()→"NoExtraSpaces"String without extra spaces is unchanged

Converts a string representation of a number to its numerical form.

**Basic Structure:**

String.Parse()

**Description:**

The **Parse** function converts a string that represents a number into its numerical form. This is used for processing textual data that includes numerical information, such as user input, data imported from text files, or strings extracted from web sources.

Use cases include converting strings to numbers for mathematical operations, processing numerical data encoded as strings in imported datasets, and validating user input as part of data entry forms.

**Examples:**

"123".Parse()→123Convert a string to an integer

"3.14159".Parse()→3.14159Convert a string to a floating-point number

"-456".Parse()→-456Convert a negative number string to its numerical form

"1e3".Parse()→1000Convert exponential notation string to a number

## Programming

Assigns a value to a reusable variable.

**Basic Structure:**

Variable <- Value

**Description:**

The **Variables** function allows for the declaration and assignment of a value to a variable within Insight Maker models. Variables are fundamental in creating dynamic models, enabling the storage and manipulation of values throughout the simulation. They can represent parameters, constants, or any other data type that may change or be referenced over time.

Variables are particularly useful for holding state information, intermediate calculations, or controlling the flow of execution within the model. By using variables, modelers can write more modular, readable, and reusable code.

**Examples:**

x <- 10

x^2→100Assigns 10 to x and then squares x

y <- 5

z <- y * 2

z→10Assigns 5 to y, calculates z as twice y, and returns z

a <- 100

b <- a / 10

c <- b + 5

c→15Demonstrates chaining of variables: assigns 100 to a, divides a by 10 for b, and adds 5 to b for c

counter <- 1

While counter <= 5

counter <- counter + 1

End Loop

counter→6Uses a variable as a counter in a loop, demonstrating variable modification and reuse

Test one or more conditions and selectively execute code based on these tests.

**Basic Structure:**

If Condition Then

Expression

Else If Condition Then

Expression

Else

Expression

End If

**Description:**

The **If-Then-Else** structure is a conditional statement that allows models to execute different sections of code based on whether a condition (or set of conditions) is true or false. This control structure is used for incorporating decision-making into models, enabling the simulation of complex, dynamic behaviors that depend on variable states and conditions.

Use cases include toggling between different equations based on threshold values, implementing policy changes in response to changing indicators, or simulating decision-making processes within agent-based models.

**Examples:**

x <- 5

If x > 10 Then

'Big'

Else

'Small'

End If→'Small'Checks if x is greater than 10, returns 'Small' since x is 5

temperature <- 22

If temperature > 25 Then

'Hot'

Else If temperature < 15 Then

'Cold'

Else

'Moderate'

End If→'Moderate'Classifies the temperature into Hot, Moderate, or Cold

score <- 85

If score >= 90 Then

'A'

Else If score >= 80 Then

'B'

Else If score >= 70 Then

'C'

Else

'F'

End If→'B'Determines a grade based on score ranges

If [Value] > 100 Then

Terminate()

End IfStops the simulation if a value exceeds 100

Repeats an action until a condition is no longer true.

**Basic Structure:**

While Condition

Expression

End Loop

**Description:**

The **While Loop** executes a block of code repeatedly as long as a given condition is true. This structure is used for performing iterative calculations, simulating processes over time, or executing an action multiple times until a specific condition is met.

**Examples:**

x <- 1

While x < 10

x <- x*2

End Loop

x→16Doubles x until it is no longer less than 10

counter <- 0

sum <- 0

While counter < 5

sum <- sum + counter

counter <- counter + 1

End Loop

sum→10Sums numbers from 0 to 4 using a while loop

balance <- 100

year <- 0

While balance < 200

balance <- balance * 1.05

year <- year + 1

End Loop

year→15Calculates how many years it takes for an investment to double with an annual return of 5%

n <- 1

factorial <- 1

While n <= 5

factorial <- factorial * n

n <- n + 1

End Loop

factorial→120Calculates the factorial of 5 using a while loop

Repeats an action for each element in a vector.

**Basic Structure:**

For Variable in Vector

Expression

End Loop

**Description:**

The **For-In Loop** iterates over each element in a vector, allowing for repeated operations on each element. This structure is used for processing collections of data where an operation needs to be applied to each item individually. Common use cases include summing the elements of a vector, applying transformations to data points, and aggregating results.

**Examples:**

sum <- 0

For x in {1, 10, 27}

sum <- sum + x

End Loop

sum→38

product <- 1

For x in {1, 2, 3, 4}

product <- product * x

End Loop

product→24Multiplies each element, starting with 1

For i in {5, 6, 7}

Print(i)

End LoopPrints each number in the vector to the console

count <- 0

For item in {10, 20, 30, 40}

If item > 15 Then

count <- count + 1

End If

End Loop

count→3Counts the number of items greater than 15

Creates a reusable function.

**Basic Structure:**

Function Name()

Expression

End Function

**Description:**

The **Functions** feature allows users to define reusable code blocks. These blocks can be named and parameterized to perform specific tasks, such as calculations or data manipulations, with varying inputs. This promotes code reuse and modularity. Functions are fundamental in complex modeling, enabling the encapsulation of logic for tasks like mathematical operations, data processing, or custom simulation logic.

**Examples:**

Function Square(x)

x^2

End Function

Square(5)→25

Function Add(x, y)

x + y

End Function

Add(5, 3)→8Adds two numbers

Function IsPositive(x)

If x > 0 Then

Return True

Else

Return False

End If

End Function

IsPositive(-2)→FalseChecks if a number is positive

Function Max(x, y)

If x > y Then

return x

Else

return y

End If

End Function

Max(10, 20)→20Returns the maximum of two numbers

Creates an anonymous function.

**Basic Structure:**

Variable <- Function()

Expression

End Function

**Description:**

An **Anonymous Function** is a function without a name, directly assigned to a variable. These are particularly useful for short, one-off operations, or as arguments to higher-order functions like map, filter, or reduce.

**Examples:**

square <- Function(x)

x^2

End Function

square(5)→25

increment <- Function(x)

x + 1

End Function

increment(5)→6Increments the input value by 1

isEven <- Function(x)

x mod 2 = 0

End Function

isEven(4)→TrueChecks if a number is even

greet <- Function(name)

'Hello, ' + name

End Function

greet('World')→Hello, WorldCreates a greeting message

**Anonymous Functions Single Line**

Creates a single-line anonymous function.

**Basic Structure:**

Function() Expression

**Description:**

Single-line **Anonymous Functions** offer a compact way to define a function inline without the need for explicit start and end indicators. Ideal for simple operations, these functions can be used directly in expressions or passed as arguments to other functions. They're particularly useful for transformations within map, filter, or similar functions.

**Examples:**

{1, 2, 3}.Map(Function(value) value^2 - value)→{0, 2, 6}

{1, 2, 3}.Filter(Function(x) x > 1)→{2, 3}Filters values greater than 1

{-1, 0, 1}.Map(Function(x) IfThenElse(x < 0, -x, x))→{1, 0, 1}Applies absolute value operation

Passes an error message up to the nearest Try-Catch block or aborts the simulation with the error message.

**Basic Structure:**

throw 'Message'

**Description:**

The **throw** statement allows for explicit error generation within a model. When an error condition is met, **throw** can be used to halt execution and signal an error, optionally passing the error up to a Try-Catch block for handling. This is useful for validating inputs, enforcing constraints, or notifying when assumptions are violated. Proper error handling is useful for debugging and for creating robust, reliable models.

**Examples:**

If x < 0 Then

throw 'Value cannot be negative.'

End IfThrows an error for negative values

If z == 0 Then

throw 'Division by zero error.'

End IfPrevents division by zero

Attempts to execute some code. If an error occurs, the error is passed as a string variable to the catch block which will then be executed. The catch block will not be executed unless an error occurs.

**Basic Structure:**

Try

Expression

Catch ErrorString

Expression // Handle the error

End Try

**Description:**

The Error Handling structure uses **Try-Catch** blocks to manage exceptions gracefully. When an error is thrown within the Try block, execution moves to the Catch block, allowing for custom error handling. The error message is available as a variable with the name specified immediately after the *Catch* statement. This structure is useful for robust models, enabling error management without halting the simulation. It's particularly useful for processing external data, complex calculations, and where operations may fail under certain conditions.

**Examples:**

Try

1 / 0

Catch err

'Error caught: ' + err

End Try→Error caught: Division by zero.Handles division by zero error

Try

sqrt(-1)

Catch err

'Math error: ' + err

End Try→Math error: Cannot take square root of negative number.Catches math errors

Try

accessElement(vector, 10)

Catch err

'Vector access error: ' + err

End Try→Vector access error: Index out of range.Handles vector access errors

## User Input Functions

Show an alert dialog with the message.

**Basic Structure:**

Alert(Message)

**Description:**

The **Alert** function displays a pop-up alert dialog box with a custom *Message* provided by the user.

This function is useful for making models interactive. This is particularly useful for simulation games or interactive scenario analysis.

**Examples:**

Alert("Simulation Started.")Notifies that the simulation has begun.

Alert("Threshold exceeded for population growth.")Warns when a population exceeds a predefined threshold.

Prompts the user for an input and returns it. Can optionally provide a default value for the input.

**Basic Structure:**

Prompt(Message, Default='')

**Description:**

The **Prompt** function requests input from the user through a dialog box, displaying a message and optionally providing a *Default* value that the user can accept or overwrite.

This function is useful for making models interactive, allowing users to input parameters or make choices during a simulation run. This is particularly useful for simulation games or interactive scenario analysis.

**Examples:**

timeScale <- Prompt("What time scale should we use?.", 10).Parse()Asks for a time scale with a default of 10.

initialPopulation <- Prompt("Initial population size:", 100)Requests an initial population size, defaulting to 100.

modelName <- Prompt("What is the name of your model?")Queries for the model's name without providing a default value.

Prompts the user to confirm a statement and returns a boolean based on whether they confirmed it or not.

**Basic Structure:**

Confirm(Message)

**Description:**

The **Confirm** function presents the user with a dialog box that asks them to confirm or deny a statement, returning a boolean value based on their choice.

This function is useful for making models interactive, allowing users to make choices during a simulation run. This is particularly useful for simulation games or interactive scenario analysis

**Examples:**

advanced <- Confirm("Use advanced mode?")Asks the user if they want to use advanced settings.

continueSimulation <- Confirm("Continue the simulation after 100 steps?")Queries whether to continue the simulation after a certain number of steps.

## Statistical Distributions

Returns the value of x in the CDF of the Normal Distribution.

**Basic Structure:**

CDFNormal(x, Mean=0, Standard Deviation=1)

**Description:**

The **CDFNormal** function calculates the Cumulative Distribution Function (CDF) for a normal distribution at a given point *x*. The function uses the *Mean* and *Standard Deviation* of the distribution, which are set to 0 and 1 by default, respectively. This function is useful for calculating the probability that a random variable from a normal distribution is less than or equal to *x*.

**Examples:**

CDFNormal(1.96)→0.975

CDFNormal(0)→0.5CDF at the mean of the distribution

CDFNormal(-1.96)→0.025Calculating the lower tail probability

CDFNormal(2, 1, 2)→0.691With a non-standard mean and deviation

Returns the value of x in the PDF of the Normal Distribution.

**Basic Structure:**

PDFNormal(x, Mean=0, Standard Deviation=1)

**Description:**

The **PDFNormal** function computes the Probability Density Function (PDF) value of a given point *x* for a normal distribution characterized by a specific *Mean* and *Standard Deviation*. The PDF represents the likelihood of *x* occurring within this distribution. This function is used for statistical analyses, including hypothesis testing, and for modeling phenomena with normal (Gaussian) distributions.

**Examples:**

PDFNormal(1.5, 0, 1)→0.13

PDFNormal(0)→0.399Density at the mean of the distribution

PDFNormal(-1, 0, 1)→0.242Density in the left tail of the distribution

PDFNormal(2, 0, 2)→0.121With a non-standard deviation

Returns the value of p in the inverse CDF of the Normal Distribution.

**Basic Structure:**

InvNormal(p, Mean=0, Standard Deviation=1)

**Description:**

The **InvNormal** function calculates the inverse Cumulative Distribution Function (CDF) for a normal distribution. It returns the *x* value for which the area under the normal distribution curve to the left of *x* is equal to *p*. This function is useful for finding critical values in statistical tests and confidence interval calculations.

Use cases include determining z-scores for confidence levels in statistics, and calculating thresholds for hypothesis testing in research.

**Examples:**

InvNormal(0.975)→1.96

InvNormal(0.5)→0Value at the median of the distribution

InvNormal(0.025)→-1.96Value in the left tail for 95% confidence

InvNormal(0.95, 0, 2)→3.29With a non-standard deviation

Returns the value of x in the CDF of the Lognormal Distribution.

**Basic Structure:**

CDFLognormal(x, Mean=0, Standard Deviation=1)

**Description:**

The **CDFLognormal** function computes the Cumulative Distribution Function (CDF) for a lognormal distribution at a specific point *x*. This distribution results when the logarithm of a variable is normally distributed, making it ideal for representing variables that are bound to be positive, such as stock prices or lifetimes of components.

**Examples:**

CDFLognormal(10, 1, 0.5)→0.995Probability of a value in a positively skewed distribution

CDFLognormal(3)→0.864Default mean and deviation for a basic lognormal CDF calculation

CDFLognormal(5, 2, 1)→0.348Adjusted mean and deviation for specific use case

Returns the value of x in the PDF of the Lognormal Distribution.

**Basic Structure:**

PDFLognormal(x, Mean=0, Standard Deviation=1)

**Description:**

The **PDFLognormal** function calculates the Probability Density Function (PDF) for a lognormal distribution at a specific point *x*. This function is useful for determining how likely a specific value is within a distribution that's positively skewed, such as population sizes or the size of organisms.

**Examples:**

PDFLognormal(10, 1, 0.5)→0.003Density of a value in a lognormal distribution

PDFLognormal(3)→0.073Density with default parameters

PDFLognormal(5, 2, 1)→0.074Custom mean and deviation for a specific case

Returns the value of p in the inverse CDF of the Lognormal Distribution.

**Basic Structure:**

InvLognormal(p, Mean=0, Standard Deviation=1)

**Description:**

The **InvLognormal** function calculates the inverse Cumulative Distribution Function (CDF) for a lognormal distribution. It finds the *x* value for which a given portion *p* of the distribution lies to the left.

**Examples:**

InvLognormal(0.95, 1, 0.5)→6.19Finding a high percentile in a positively skewed distribution

InvLognormal(0.5)→1Median value in a lognormal distribution

InvLognormal(0.1, 2, 1)→2.05Low percentile for custom parameters

Returns the value of x in the CDF of Student's t Distribution.

**Basic Structure:**

CDFt(x, Degrees Of Freedom)

**Description:**

The **CDFt** function computes the Cumulative Distribution Function (CDF) for Student's t-distribution at a given point *x*, with a specified number of *Degrees Of Freedom*.

**Examples:**

CDFt(2.2, 10)→0.974Probability of a t-value with 10 degrees of freedom

CDFt(0, 30)→0.5CDF at the mean of the t-distribution

CDFt(-1.5, 5)→0.097Lower tail probability with 5 degrees of freedom

Returns the value of x in the PDF of Student's t Distribution.

**Basic Structure:**

PDFt(x, Degrees Of Freedom)

**Description:**

The **PDFt** function calculates the Probability Density Function (PDF) for Student's t-distribution at a specific value *x*, given a number of *Degrees Of Freedom*. This distribution allows for the analysis of small sample sizes and is particularly useful when the population variance is unknown.

**Examples:**

PDFt(2.2, 10)→0.044Density of a t-value with 10 degrees of freedom

PDFt(0, 30)→0.396Density at the mean of the t-distribution

PDFt(-1.5, 5)→0.125Density in the lower tail with 5 degrees of freedom

Returns the value of p in the inverse CDF of Student's t Distribution.

**Basic Structure:**

Invt(p, Degrees Of Freedom)

**Description:**

The **Invt** function calculates the inverse Cumulative Distribution Function (CDF) for Student's t-distribution, returning the *x* value associated with a given probability *p* and a specific number of *Degrees Of Freedom*. This is useful for critical value calculations in statistical tests.

Use cases include determining the cutoff values for t-tests when comparing sample means or calculating confidence intervals for mean differences.

**Examples:**

Invt(0.975, 10)→2.23Critical t-value for 95% confidence with 10 degrees of freedom

Invt(0.5, 30)→0Median of the t-distribution

Invt(0.025, 5)→-2.57Critical value in the lower tail for 95% confidence with 5 degrees of freedom

Returns the value of x in the CDF of the F Distribution.

**Basic Structure:**

CDFF(x, Degrees Of Freedom1, Degrees Of Freedom2)

**Description:**

The **CDFF** function calculates the Cumulative Distribution Function (CDF) for an F distribution at a given point *x*, using specified degrees of freedom for the numerator (*Degrees Of Freedom1*) and the denominator (*Degrees Of Freedom2*).

This function is used for statistical modeling, especially in variance analysis (ANOVA) where it helps determine if the variances between two populations are significantly different.

**Examples:**

CDFF(3.84, 1, 5)→0.893Calculating the CDF value for x=3.84 with 1 and 5 degrees of freedom in the numerator and denominator, respectively.

CDFF(5, 10, 20)→0.999Understanding the tail probability for more complex ANOVA scenarios.

CDFF(2.5, 3, 30)→0.921Assessing variance differences in smaller sample sizes.

Returns the value of x in the PDF of the F Distribution.

**Basic Structure:**

PDFF(x, Degrees Of Freedom1, Degrees Of Freedom2)

**Description:**

The **PDFF** function computes the Probability Density Function (PDF) for an F distribution at a specific point *x*, using *Degrees Of Freedom1* for the numerator and *Degrees Of Freedom2* for the denominator.

**Examples:**

PDFF(3, 5, 10)→0.056Evaluating the likelihood of a variance ratio of 3 given 5 and 10 degrees of freedom in the numerator and denominator.

PDFF(4.5, 2, 20)→0.017Determining the density for a more extreme variance ratio.

PDFF(1, 10, 10)→0.615Assessing the density at the mean of the distribution.

Returns the value of p in the inverse CDF of the F Distribution.

**Basic Structure:**

InvF(p, Degrees Of Freedom1, Degrees Of Freedom2)

**Description:**

The **InvF** function finds the inverse Cumulative Distribution Function (inverse CDF) value for a given probability *p*, within an F distribution characterized by *Degrees Of Freedom1* and *Degrees Of Freedom2*. This function is used for statistical analysis, particularly in determining critical values for hypothesis tests involving ANOVA.

**Examples:**

InvF(0.95, 5, 2)→19.3Finding the critical value for a 95% confidence level in an ANOVA test.

InvF(0.99, 3, 30)→4.51Determining a more stringent critical value for a hypothesis test.

InvF(0.975, 2, 20)→4.46Calculating critical values for two-tailed tests in research.

Returns the value of x in the CDF of the Chi-Squared Distribution.

**Basic Structure:**

CDFChiSquared(x, Degrees Of Freedom)

**Description:**

The **CDFChiSquared** function computes the Cumulative Distribution Function (CDF) for a chi-squared distribution at a specified point *x*, with a given *Degrees Of Freedom*. This function is instrumental in statistical tests, especially for goodness-of-fit tests and in chi-squared tests for independence.

**Examples:**

CDFChiSquared(10, 5)→0.925Calculating the CDF value for a chi-squared statistic of 10 with 5 degrees of freedom.

0.949→CDF valueDetermining the significance level for a common threshold in chi-squared tests.

CDFChiSquared(5.991, 2)→CDF valueAssessing the probability for a chi-squared value in bivariate analysis.

Returns the value of x in the PDF of the Chi-Squared Distribution.

**Basic Structure:**

PDFChiSquared(x, Degrees Of Freedom)

**Description:**

The **PDFChiSquared** function calculates the Probability Density Function (PDF) for a chi-squared distribution at a specific point *x*, given *Degrees Of Freedom*. Used for statistical analysis, it aids in understanding the distribution of chi-squared statistics across different degrees of freedom.

**Examples:**

PDFChiSquared(2, 5)→0.138Evaluating the density for a chi-squared value of 2 with 5 degrees of freedom.

PDFChiSquared(7.8, 3)→0.023Understanding the likelihood of a chi-squared statistic in a smaller sample.

PDFChiSquared(0.5, 1)→0.439Analyzing the density for low chi-squared values in simple hypotheses.

Returns the value of p in the inverse CDF of the Chi-Squared Distribution.

**Basic Structure:**

InvChiSquared(p, Degrees Of Freedom)

**Description:**

The **InvChiSquared** function retrieves the inverse Cumulative Distribution Function (inverse CDF) value for a given probability *p* in a chi-squared distribution, specified by *Degrees Of Freedom*. It's vital for determining critical values in hypothesis testing, particularly in chi-squared tests.

**Examples:**

InvChiSquared(0.95, 3)→7.81Identifying the critical chi-squared value for a 95% confidence level.

InvChiSquared(0.99, 1)→6.63Calculating a critical value for a higher confidence level in a simple test.

InvChiSquared(0.975, 2)→7.378Determining critical values for a two-tailed chi-squared test.

Returns the value of x in the CDF of the Exponential Distribution.

**Basic Structure:**

CDFExponential(x, Rate)

**Description:**

The **CDFExponential** function calculates the Cumulative Distribution Function (CDF) for an exponential distribution at a given value of *x*. This distribution is characterized by its *Rate* parameter, which represents the rate of events per unit time. The function is useful for modeling time until the next event in processes that are memoryless, such as the time between arrivals in a queue.

**Examples:**

CDFExponential(10, 0.5)→0.9933Probability that the time until the next event is less than or equal to 10 units, given a rate of 0.5 events per unit time.

CDFExponential(5, 1)→0.9933Probability that the time until the next event is less than or equal to 5 units, with a rate of 1 event per unit time.

CDFExponential(3, 2)→0.9975Probability that the time until the next event is less than or equal to 3 units, given a rate of 2 events per unit time.

Returns the value of x in the PDF of the Exponential Distribution.

**Basic Structure:**

PDFExponential(x, Rate)

**Description:**

The **PDFExponential** function calculates the Probability Density Function (PDF) for an exponential distribution at a given value of *x*. This function helps in understanding the likelihood of a particular time between events for processes that have a constant rate, represented by the *Rate* parameter.

**Examples:**

PDFExponential(1, 0.5)→0.303Likelihood of time 1 unit between events, with a rate of 0.5.

PDFExponential(2, 1)→0.135Likelihood of time 2 units between events, with a rate of 1.

PDFExponential(4, 2)→0.00067Likelihood of time 4 units between events, with a rate of 2.

Returns the value of p in the inverse CDF of the Exponential Distribution.

**Basic Structure:**

InvExponential(p, Rate)

**Description:**

The **InvExponential** function calculates the inverse Cumulative Distribution Function (CDF) of an exponential distribution for a given probability *p*. This function is useful for determining the time until an event occurs with a certain probability, given the constant rate of occurrence. It's particularly useful in simulations and probabilistic models to determine thresholds or critical values.

**Examples:**

InvExponential(0.5, 1)→0.6931Time until next event with 50% probability, at a rate of 1 event per unit time.

InvExponential(0.8, 0.5)→3.2189Time until next event with 80% probability, at a rate of 0.5 events per unit time.

InvExponential(0.95, 2)→1.4979Time until next event with 95% probability, at a rate of 2 events per unit time.

Returns the value of x in the CDF of the Poisson Distribution.

**Basic Structure:**

CDFPoisson(x, Lambda)

**Description:**

The **CDFPoisson** function calculates the Cumulative Distribution Function (CDF) for a Poisson distribution at a given value of *x*. The Poisson distribution is characterized by its *Lambda* parameter, which represents the average rate of events per interval.

**Examples:**

CDFPoisson(5, 3)→0.916Probability of observing up to 5 events when the average rate is 3 per interval.

CDFPoisson(10, 7)→0.901Probability of observing up to 10 events with an average rate of 7 per interval.

CDFPoisson(2, 5)→0.124Probability of observing up to 2 events when the average rate is 5 per interval.

Returns the value of x in the PMF of the Poisson Distribution.

**Basic Structure:**

PMFPoisson(x, Lambda)

**Description:**

The **PMFPoisson** function calculates the Probability Mass Function (PMF) for a Poisson distribution at a given value of *x*. This function is useful for modeling the probability of observing exactly *x* events in a fixed interval, given the average rate (*Lambda*) of these events. It's particularly valuable in scenarios where events occur independently and at a constant average rate over time.

**Examples:**

PMFPoisson(4, 2)→0.09Probability of observing exactly 4 events when the average rate is 2 per interval.

PMFPoisson(0, 5)→0.0067Probability of observing no events when the average rate is 5 per interval.

PMFPoisson(8, 3)→0.0081Probability of observing exactly 8 events with an average rate of 3 per interval.