A number of custom functions are written to assist in equation writing and to refer to outputs of other widgets above. These functions are used IN ADDITION to those available through math.js.

MathJS Foundation

Calcs.com builds upon the MathJS library to provide additional engineering-specific functions.

Pulling Data from Other Widgets

These functions allow you to pull unedited data from another widget or part of a widget.

L() - Lookup Reference Function

The lookup reference function is a specific reference function for lookup widgets only. The widgets that can be referenced by the lookup reference function are:
  • lookup widgets
  • shared lookup widgets
Syntax and rulesIf the function is referencing a widget with an integer reference ID:
L(integer_referenceId, columnIndex)
If the function is referencing a widget with a string reference ID:
L("string_refrenceId", columnIndex)
The lookup reference function calls for the value at the specified column index, starting at index = 0 for the left-most column of the tableData comprising the lookup widget, increasing by 1 as we go right in the tableData columns. Example usage The example below is from steelComplexBeam.json:
{
    "type": "sheetTemplateWidgets",
    "attributes": {
        "type": "computed",
        "label": "Axial Stiffness",
        "symbol": "EA",
        "units": "kN",
        "description": "E [MPa] *  Ag [mm ^ 2] * 10 ^ (-3)",
        "equation": [
            {
                "condition": "@default",
                "result": "x(\"E\") * L(\"member\", 7) * 10 ^ (-3)"
            }
        ],
        "referenceId": "EA"
    }
}
Here, the lookup reference in attributes.equation[0].result is referencing the 7th Index (8th countable column) of the "member" shared table lookup widget.

T() - Internal Table Reference Function

The table reference function is a special reference function used to reference specific cells, rows or columns only from within the table. This is a reference function used when writing computed fields in a computed column of a table widget.
Syntax and rulesColumn and Row indices start at 0 when being used in the table reference function. Each row of the table has an inherent rowIndex() and each column of the table has an inherent colIndex().If we are referring to rows as they are created for the first column in the table:
T(rowIndex(),0)
If we are referring to a specific cell (the cell on the first row, second column from the left):
T(0,1)
Example usage The following code is taken from steelComplexBeam.json to calculate deflection limits in a table:
{
    "type": "sheetTemplateWidgets",
    "attributes": {
        "type": "table",
        "referenceId": "Delta_{allow}",
        "label": "Deflection Limit",
        "symbol": "\\Delta_{allow}",
        "defaultValue": [[250, 8, 8]],
        "description": "The minimum of either the span ratio denominator (i.e. L/x) or the specified mm deflection limit",
        "dataColumns": [
            {
                "label": "Span Ratio Denominator",
                "shortLabel": "Span/L",
                "units": "",
                "type": "input"
            },
            {
                "label": "Deflection Limit",
                "shortLabel": "Limit",
                "units": "mm",
                "type": "input"
            },
            {
                "label": "Allowable Deflection Limit",
                "shortLabel": "Limit",
                "units": "mm",
                "type": "computed",
                "equation": [
                    {
                        "condition": "@default",
                        "result": "min(L / T(rowIndex(), 0), T(rowIndex(), 1))"
                    }
                ]
            }
        ]
    }
}
Under the Allowable Deflection Limit column, the computed values are dependent on the input values from the user at T(rowIndex(), 0) and T(rowIndex(), 1).

matrixSubset() - Matrix Subset Function

The matrix subset function is a method of extracting individual elements or array of elements of a matrix while providing a user-friendly output.
Syntax and rulesThe basic syntax of the matrix subset function is:
matrixSubset(target_matrix, rowIndex, columnIndex)
  • target_matrix is the field reference function that calls a matrix by its reference ID
  • rowIndex is an integer or array that describes the row for extraction. This, unlike the other index types, start at index=1
  • columnIndex is an integer or array that describes the column for extraction. This, unlike the other index types, start at index=1
Example usage
{
    "type": "sheetTemplateWidgets",
    "attributes": {
        "type": "computed",
        "label": "Max Moment at Permanent and Imposed Strength Limit State",
        "symbol": "M^*_{m,pi}",
        "units": "kNm",
        "description": "AS4100-1998 Cl 5.6.1.",
        "equation": [
            {
                "condition": "@default",
                "result": "abs(matrixSubset(LC_str,1,3))"
            }
        ],
        "referenceId": "M*mpi"
    }
}

vectorSubset() - Vector Subset Function

The vector subset function is a method of extracting individual elements of a single vector while providing a user-friendly output.
Syntax and rulesThe basic syntax of the vector subset function is:
vectorSubset(vector, elementIndex)
  • vector is the vector as a result of a field reference function call
  • elementIndex is an integer index of the element required for extraction (starting at index=0)
I believe this is an error and elementIndex is actually 1-based.

col() - Extract a Column (as a row matrix)

The column extract function is used to extract the whole specific column of a matrix and returns it as a row matrix. This is most commonly used when accessing large data sets returned by the server.
MathJS also has a similar built-in function column(), with the same syntax. The only functional difference between the two is that col() returns a row matrix ([[a, b]]) while column() returns a column matrix ([[a], [b]]).
Syntax and rules The basic syntax is: col(matrix, columnIndex)
  • matrix is the matrix called by the field reference function
  • columnIndex is the index of the column required for extraction. Unlike most indexing, this starts at index=1

interpolate() - Interpolate a value from 2D or 3D data

This function interpolates a value from either 2D or 3D data.

Built-in MathJS Functions

column() - Extract a Column (as a column matrix)

column(matrix, colNum)

row() - Extract a Row (as a row matrix)

row(matrix, rowNum)

Iterating Over a Set of Data

setSum() - Σ (Cumulative Sum of a Set) Function

The SetSum function is a function that allows the sum of a numeric function over a pre-defined range, much like the sum function in mathematics.
Syntax and rulesThe basic syntax for the SetSum function is:
setSum(from,to,math,"variable")
  • from is an integer value that describes the lower bound of the sum function. Note that for sums, the from is included in the sum
  • to is an integer value that describes the upper bound of the sum function. Note that for sums, the to is included in the sum
  • math is the mathematical expression that will be summed in the setSum operation. The key variable is exchanged in this equation to be equal to the variable declared in the last argument of setSum
  • "variable" is the variable that goes from from to to in the summation.

iterate() - Iterate Function

The iterate function is a general iteration much in the same way as the setSum function, however the step of the iterated variable can be controlled to a greater detail and the output of the iteration is not a single summed value, but an array of values as a result of the iteration.
Syntax and rulesThe basic syntax for the iterate function is:
iterate(from,to,step,expression,variable)
  • from is an integer value that describes the lower bound of the iteration. Note that this value is included in the iteration
  • to is an integer value that describes the upper bound of the iteration. Note that this value is included in the iteration
  • step is a float value that describes the step size for the iteration.
  • expression is any mathematical expression used for the iterative process
  • variable is the variable that is iterated that must exist in the expression
The equivalent in Python would be:
results = []
for variable in range(from, to + 1, step): # python stop is not inclusive so +1
    results.append(expression) # e.g. "small" if variable < 5 else "big"
Conditional String Example:
{
    "condition": "@default",
    "result": "iterate(1, 10, 1, num <= 5 ? \"small number\" : \"big number\", num)"
}

deepReplace() - Replace deeply within a structure

Preforms a string find-replace deep within a structure - including object/dictionary values, matrix values, etc. This is particularly useful for some upgrade mappings!
Syntax and rulesThe basic syntax for the function is:
deepReplace(dataStructure, findString, replaceString)
  • dataStructure is any type of data structure - a matrix, object/dictionary, etc
  • findString is a string to find anywhere in the structure
  • replaceString is the string to replace it with

mapObject() - Map keys and values in an object

Functions exactly the same as MathJS’s map() function, except it iterates over all entries in an object, rather than all rows in a matrix.
Syntax and rulesThe basic syntax for the function is:
mapObject(object, function)
  • object is any object/dictionary
  • function is a function of the key AND the value for each entry, equal to an object with the new key and value. For example: f(key, value) = {key: concat(key, "_2"), value: 2 * value}

Solvers

solveSecant() - Secant Method Function

The solveSecant function is a solver to find the root of an arbitrary single-variable equation. It uses the Secant Method to iterate toward a root, based upon two initial guesses provided as inputs.
Syntax and rulesThe basic syntax for the solveSecant() function is:
solveSecant(guess0, guess1, convergenceCriterion, maxIters, fnEquation)
  • guess0 is the first guess for the value of fnEquation’s independent variable (must use the same unit too)
  • guess1 is the second guess for the value of fnEquation’s independent variable (must use the same unit too)
  • convergenceCriterion is a value, in the same unit as fnEquation’s independent variable, which defines when the result has been found to have sufficient accuracy (i.e. [iteration n] - [iteration n-1] < convergenceCriterion)
  • maxIters is a unitless integer setting the maximum number of iterations to perform in searching for the result
  • fnEquation is any mathematical equation, written as a function of a single variable (e.g. f(n) = n^2), for which a root will be found
It will iterate until it either (a) reaches the root to within the given accuracy, or (b) exceeds the maximum number of iterations, in which case it will throw an error.
Example Usage 1:
{
    "type": "sheetTemplateWidgets",
    "attributes": {
        "type": "computed",
        "label": "Neutral Axis Location",
        "symbol": "k_{upx} d_{ox}",
        "units2": "mm",
        "equation": [
            {
                "result": "solveSecant(k_ub*d_x, d_x, 0.0001 mm, 100, f(kd) = B*gamma*alpha2_fc * kd + setSum(1, n_lr, matrixSubset(reo_x, i, 4) * max(-f_sy, min(f_sy, e_cu * (kd - matrixSubset(reo_x, i, 2)) / kd * E_s)), \"i\"))",
                "condition": "@default"
            }
        ],
        "referenceId": "kupx_dx"
    }
}

Sheet State

presetCode() - Preset Used to Create the Sheet

This function simply returns the code for the preset used to open the template, as a string. Syntax: presetCode()

unitSystem() - Unit System Used to Create the Sheet

This function simply returns the current unit system, as a string (currently either “FPS” or “MKS”) Syntax: unitSystem()

Formatting Strings

defaultFormat() - Calcs.com Number Format

This function applies the Calcs.com standard number format used throughout the platform. This is on the philosophy that we don’t want different templates to round differently! Basic usage: defaultFormat(number)
Advanced options (use with caution):
defaultFormat(number, sigFigs, intRange)
  • number is whatever number you want to display in a string
  • sigFigs (default = 3) is an integer that defines the number of significant figures to round to
  • intRange (default = [0, 1000]) is a 1x2 array of integers or null that defines a range within which to display the exact (unrounded) integer value
Please make sure that any use of these advanced options is VERY, VERY well justified, as they do mean deviating from our normal Calcs.com rules.

Built-in MathJS Functions

Allow concatenating a string together. Useful for “Members Schedule” export widgets or labels for diagrams.
print('Vert: $v_t x $v_w x $v_y MPa', 
      {v_t: matrixSubset(T,1,2), 
       v_w: matrixSubset(T,1,3),
       v_y: matrixSubset(T,1,4)})

// Output: "Vert:10x200x250MPa"

Miscellaneous

maxIndex() / minIndex() - Array Max/Min Index Function

The array max/min index function is used to find the index of the maximum or minimum value in an array. This is also based on index starting at 1. Syntax:
  • maxIndex(array)
  • minIndex(array)

ln() - Natural Logarithm (base e)

For some bizarre reason, MathJS doesn’t have ln() as a function even though it renders a base e logarithm as “ln()”. So we created the function.
WARNING: Because of its ambiguity, you should NEVER use the built-in function log(x) without EXPLICITLY specifying the base as log(x, base). A class 3 bug previously resulted due to confusion about the default base.
If you want to use the natural log, you can safely (and equally) write it as either ln(x) or log(x, e).

isIncluded() - Check for existence of an element

Using this function, you can check whether an element exists in an array or not. For example, if vec = [1, 2, 3, 4, 5], then isIncluded(1, vec) will return true.

Checks

I() - Indicator Function (true = 1, false = 0)

The indicator function is a programmatic equivalent of the Heaviside or Dirac delta function. It returns a value of 0 or 1 conditional on achieving a TRUE condition.
Syntax and rulesThe basic syntax is:
I(condition)
  • condition is a mathematical equality or inequality that must return a TRUE or FALSE output. If a TRUE output is observed, the function resolves to a value of 1. If a FALSE output is observed, the function resolves to a value of 0.
Example usage
{
    "type": "sheetTemplateWidgets",
    "attributes": {
        "type": "input",
        "label": "Offset of Angle from Bottom of PFC",
        "symbol": "d_b",
        "units": "mm",
        "description": "Distance from the bottom of the PFC beam to the bottom of the angle section. 0mm implies the bottom of the angle is flush with the bottom of the PFC",
        "defaultValue": "0",
        "checks": [
            {
                "condition": "x(\"d_b\") <= L(\"memberPFC\", 2) - (I(L(\"Angle Vertical Leg\", 1) == 0) * L(\"memberAngle\", 1) + I(L(\"Angle Vertical Leg\", 1) == 1) * L(\"memberAngle\", 2)) and x(\"d_b\") >= -15",
                "result": "Invalid entry, offset must be between -15mm and such that the top of the angle doesn't protrude over the the top of the PFC beam"
            }
        ],
        "referenceId": "d_b"
    }
}
This example is from the pfcAngle.json. The indicator functions when multiplied by a certain value given the condition acts like on and off switches for parts of the equation.

Deprecated Functions

The following functions are deprecated and should not be used in new templates:

x() - Field Reference Function

This function used to be required any time we referred to a referenceId of another widget. It has since been replaced by just directly using the referenceId (e.g. M_u) or using it within backticks (e.g. `M*`).

x(,true) - Special Field Reference Function

In the special occasion where a target table widget has both input and computed fields with a high chance of circular references, a modified reference function was required. This has been replaced by better reference patterns.

isNumber() - Number Check Function

This function checks if a widget produces a number or a null value. The inherent math.js isNumeric() function works better for most use cases.