> For the complete documentation index, see [llms.txt](https://docs.openbrim.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.openbrim.org/developers/llm-guides/ai-paramml-functions-reference.md).

# ParamML Functions Reference

## Overview

ParamML provides a comprehensive set of built-in functions that can be used within expressions to perform calculations, manipulate geometry, convert units, and query parametric models. This guide documents all available functions for AI agents creating ParamML expressions.

**Key Concepts:**

* Functions are called within ParamML expressions using standard syntax: `functionName(arg1, arg2, ... )`
* Functions are dispatched in three places: the math functions in `Eval._gFunc` (`Code/PML/Eval.ts`), the list/lambda functions (`map`, `filter`, `iif`, `atstation`, ...) in `JSParser.Parser.Execute` (`Code/Core/JsParser.ts`), and everything else in `Param.ExprProvFunctionCall` (`Code/PML/Param.ts`)
* Some functions are context-dependent (require specific modules like FEA, SEC, or OpenBrIM to be loaded)
* Write function names exactly as documented here. Most are matched case-sensitively; only the [math functions](#math-functions) are matched without regard to case (`Eval._gFunc` lowercases the name)

**ParamML Operators:** ParamML uses standard JavaScript-like operators for expressions:

* **Comparison Operators:** `<`, `>`, `<=`, `>=`, `==`, `!=` (`==` treats a null side as 0)
* **Logical Operators:** `&&` (AND), `||` (OR), `!` (NOT)
* **Fortran-style forms:** `.LT.`, `.GT.`, `.LE.`, `.GE.`, `.EQ.`, `.NE.`, `.AND.`, `.OR.`, `.NOT.` are rewritten to the operators above before parsing (outside string literals)
* **Arithmetic Operators:** `+`, `-`, `*`, `/`, `%`, `^` (power)
* **Ternary Operator:** `condition ? value1 : value2`
* **Unary Operators:** `-` (negation), `!` (logical NOT), `+` (positive)

**Inside XML attribute values, use the Fortran-style forms.** The library XML is parsed by a strict XML parser, and a raw `<` or `&` in an attribute value is malformed XML (the whole object fails to load). The library writes `.LT.`, `.AND.` and so on throughout; the symbolic operators are fine in expressions typed into the app, where there is no XML.

**Example:**

```xml
<P N="IsValid" V="Width .GT. 0 .AND. Height .GT. 0 ? 1 : 0"/>
<P N="NeedsReinforcement" V="Stress .GE. AllowableStress .OR. Depth .LT. MinDepth"/>
<P N="Power" V="Base ^ Exponent"/>
```

**Function Categories:**

1. [Array/List Operations](#arraylist-operations)
2. [Geometric Transformations](#geometric-transformations)
3. [Line/Curve Operations](#linecurve-operations)
4. [Surface/Volume Operations](#surfacevolume-operations)
5. [Unit Conversion](#unit-conversion)
6. [Advanced Geometry](#advanced-geometry)
7. [Mesh Generation](#mesh-generation)
8. [Object/Point Functions](#objectpoint-functions)
9. [Value/Expression Functions](#valueexpression-functions)
10. [String Manipulation](#string-manipulation)
11. [Functional Programming & Advanced Operations](#functional-programming--advanced-operations)
12. [External Module Functions](#external-module-functions)
13. [Math Functions and Constants](#math-functions)

***

## Array/List Operations

### `length(list)`

Returns the number of elements in an array or list.

**Parameters:**

* `list` (Array): The array to measure

**Returns:** Number - The count of elements

**Example:**

```xml
<P N="Count" V="length(Points)"/>
<!-- If Points has 5 elements, Count = 5 -->
```

**Related:** `first()`, `last()`

***

### `parent(obj)`

Returns the parent object of the given object in the hierarchical tree.

**Parameters:**

* `obj` (Object): The object whose parent to retrieve

**Returns:** Object - The parent object

**Example:**

```xml
<P N="ParentName" V="parent(self).Name"/>
```

***

### `project()`

Returns the root project object (top of the object hierarchy).

**Parameters:** None

**Returns:** Object - The root project object

**Example:**

```xml
<P N="ProjectName" V="project().Name"/>
```

***

### `getlistitem(list, index)` / `listitem(list, index)`

Accesses an element at a specific index in a list. Supports multi-dimensional indexing.

**Parameters:**

* `list` (Array): The array to access
* `index` (Number or multiple Numbers): The index/indices to retrieve

**Returns:** Any - The element at the specified index

**Example:**

```xml
<P N="FirstPoint" V="getlistitem(Points, 0)"/>
<P N="SecondPoint" V="listitem(Points, 1)"/>
<!-- Multi-dimensional: -->
<P N="Element" V="listitem(Matrix, 0, 2)"/>
```

**Related:** `first()`, `last()`

***

### `last(list)`

Returns the last element of an array.

**Parameters:**

* `list` (Array): The array to query

**Returns:** Any - The last element

**Example:**

```xml
<P N="LastStation" V="last(Stations)"/>
```

**Related:** `first()`, `length()`

***

### `first(list)`

Returns the first element of an array.

**Parameters:**

* `list` (Array): The array to query

**Returns:** Any - The first element

**Example:**

```xml
<P N="StartPoint" V="first(Points)"/>
```

**Related:** `last()`, `length()`

***

### `list(args...)`

Creates a new list from the provided arguments.

**Parameters:**

* `args...` (Any): Variable number of arguments to combine into a list

**Returns:** Array - A new list containing all arguments

**Example:**

```xml
<P N="MyList" V="list(1, 2, 3, 4, 5)"/>
<P N="Points" V="list(Pt1, Pt2, Pt3)"/>
```

***

### `sum(list, startIndex?, endIndex?)`

Calculates the sum of numeric elements in an array.

**Parameters:**

* `list` (Array): The array of numbers to sum
* `startIndex` (Number, optional): Starting index (default: 0)
* `endIndex` (Number, optional): Ending index (default: array length)

**Returns:** Number - The sum of elements

**Example:**

```xml
<P N="TotalLength" V="sum(SpanLengths)"/>
<P N="PartialSum" V="sum(Values, 2, 5)"/>
```

**Related:** `length()`

***

### `mergel(listOfLists)`

Merges nested lists into a single flat list.

**Parameters:**

* `listOfLists` (Array of Arrays): Nested array structure

**Returns:** Array - Flattened array

**Example:**

```xml
<P N="AllPoints" V="mergel(PointGroups)"/>
<!-- If PointGroups = [[P1,P2], [P3,P4]], result = [P1,P2,P3,P4] -->
```

**Related:** `concat()`

***

### `concat(list1, list2, ...)`

Concatenates multiple arrays into a single array. Can accept any number of arrays (not limited to two).

**Parameters:**

* `list1, list2, ...` (Arrays): Arrays to concatenate

**Returns:** Array - Combined array containing all elements in order

**Example:**

```xml
<P N="AllStations" V="concat(StartStations, MidStations, EndStations)"/>

<!-- Multiple arrays example -->
<O N="ConcatFunction" T="Group">
    <P N="list1" V="[1,2,3,4]" />
    <P N="list2" V="[3,4]" />
    <P N="list3" V="[5,6]" />
    <P N="concatParams1" V="concat(list1,list2,list3)" />
    <!-- concatParams1 = [1,2,3,4,3,4,5,6] -->
    <!-- The concat function can utilize multiple lists (or arrays); it is not strictly limited to just two -->
    <P N="concatParams2" V="concat(concat(list1,list2),list3)" />
    <!-- concatParams2 = [1,2,3,4,3,4,5,6] (same result) -->
</O>
```

**Notes:**

* Accepts unlimited number of array arguments
* Elements appear in order of arrays provided
* Duplicate values are preserved (not removed)

**Related:** `mergel()`

***

### `refine(list, refinement)`

Refines a list by interpolating additional points between existing elements. **Works only on simple number lists, not on point/coordinate lists.**

**Parameters:**

* `list` (Array of Numbers): The list to refine (must be simple number array, not point array)
* `refinement` (Number): Maximum spacing between refined values

**Returns:** Array - Refined list with interpolated values

**Example:**

```xml
<P N="RefinedPoints" V="refine(Points, 2)"/>
<!-- Detailed example -->
<O T="Group">
    <!-- ✅ CORRECT: Works with simple number list -->
    <P N="list1" V="[10,20,90,100]" />
    <P N="refine1" V="refine(list1,30)" />
    <!-- refine1 = [10,20,43.33,66.66,90,100] -->

    <!-- ❌ WRONG: Cannot refine point lists directly -->
    <P N="list2" V="[[0,0,0],[10,10,10],[90,90,90],[100,100,100]]" />
    <P N="refine2" V="refine(list2,30)" />
    <!-- refine2 = [[0,0,0],[10,10,10],[90,90,90],[100,100,100]] (unchanged) -->

    <!-- ✅ WORKAROUND: To refine point lists -->
    <P N="line1" V="[[10,0,0],[20,0,0],[90,0,0],[100,0,0]]" />
    <!-- Step 1: Extract X locations from points -->
    <P N="line1_xloc" V="map(line1,x[0])" />
    <!-- line1_xloc = [10,20,90,100] -->

    <!-- Step 2: Refine the X location list -->
    <P N="line1_xloc_refined" V="refine(line1_xloc,30)" />
    <!-- line1_xloc_refined = [10,20,43.33,66.66,90,100] -->

    <!-- Step 3: Use onlinex() to get refined points on line -->
    <P N="line1_locs_refined" V="map(line1_xloc_refined,onlinex(line1,x))" />
    <!-- line1_locs_refined = [[10,0,0],[20,0,0],[43.33,0,0],[66.66,0,0],[90,0,0],[100,0,0]] -->
</O>
```

**Notes:**

* **Important:** `refine()` only works on simple number arrays, not point/coordinate arrays
* For point lists, extract coordinates, refine them, then reconstruct points using `onlinex()` or similar
* Refinement value represents maximum spacing between output values

**Related:** `onlinex()`, `map()`

***

### `slice(list, start, end)`

Extracts a portion of an array from start to end index.

**Parameters:**

* `list` (Array): The source array
* `start` (Number): Starting index (inclusive)
* `end` (Number): Ending index (exclusive)

**Returns:** Array - Sliced portion of the array

**Example:**

```xml
<P N="MiddlePoints" V="slice(AllPoints, 2, 5)"/>
<!-- Extracts elements at indices 2, 3, 4 -->
```

***

## Geometric Transformations

### `translate(point, tx, ty, tz)`

Translates a point by the specified offset values.

**Parameters:**

* `point` (Point or Array): The point to translate
* `tx` (Number): Translation in X direction
* `ty` (Number): Translation in Y direction
* `tz` (Number): Translation in Z direction

**Returns:** Point - The translated point

**Example:**

```xml
<P N="ShiftedPoint" V="translate(OriginalPoint, 10, 0, 5)"/>
```

**Related:** `rotate()`

***

### `rotate(point, rx, ry, rz, origin?)`

Rotates a point (or array of points \[x,y,z]) around specified axes.

**Parameters:**

* `point` (Point or Array): The point(s) to rotate
* `rx` (Number): Rotation around X axis (degrees)
* `ry` (Number): Rotation around Y axis (degrees)
* `rz` (Number): Rotation around Z axis (degrees)
* `origin` (Point, optional): Origin point for rotation (default: \[0,0,0])

**Returns:** Point or Array - The rotated point(s)

**Example:**

```xml
<P N="RotatedPoint" V="rotate(Point, 0, 0, 45)"/>
<!-- Rotate 45 degrees around Z axis -->
<P N="RotatedAboutOrigin" V="rotate(Point, 30, 0, 0, CenterPoint)"/>
```

**Related:** `translate()`

***

## Line/Curve Operations

### `online(line, x, y)`

Returns a point on a line at specified local coordinates.

**Parameters:**

* `line` (Line3D): The line object
* `x` (Number): Local X coordinate along the line
* `y` (Number): Local Y coordinate (offset perpendicular to line)

**Returns:** Point - Point on the line

**Example:**

```xml
<O T="Point" N="MidPoint" X="online(CenterLine, 50, 0).X" Y="online(CenterLine, 50, 0).Y"/>
```

**Related:** `onlineg()`, `onliner()`, `onlinea()`

***

### `onlineg(line, x, y)`

Returns a point on a line in global coordinates.

**Parameters:**

* `line` (Line3D): The line object
* `x` (Number): Global X coordinate
* `y` (Number): Global Y coordinate

**Returns:** Point - Point on the line

**Example:**

```xml
<P N="GlobalPoint" V="onlineg(Baseline, 100, 50)"/>
```

**Related:** `online()`, `toglobal()`

***

### `onliner(line, n)`

Returns a point on a line at a relative position (0 to 1).

**Parameters:**

* `line` (Line3D): The line object
* `n` (Number): Relative position (0 = start, 1 = end, 0.5 = midpoint)

**Returns:** Point - Point on the line

**Example:**

```xml
<P N="QuarterPoint" V="onliner(Beam, 0.25)"/>
<P N="MidPoint" V="onliner(Beam, 0.5)"/>
```

**Related:** `onlinea()`, `online()`

***

### `onlinea(line, n)`

Returns a point on a line at an absolute distance from the start.

**Parameters:**

* `line` (Line3D): The line object
* `n` (Number): Absolute distance from start

**Returns:** Point - Point on the line

**Example:**

```xml
<P N="PointAt10ft" V="onlinea(Girder, 10)"/>
```

**Related:** `onliner()`, `linel()`

***

### `onlinerel(line, n)`

Returns a point on a line at a relative distance in the line's local direction.

**Parameters:**

* `line` (Line3D): The line object
* `n` (Number): Relative distance

**Returns:** Point - Point on the line

**Example:**

```xml
<P N="RelPoint" V="onlinerel(Edge, 0.3)"/>
```

**Related:** `onliner()`, `onlinea()`

***

### `onlinex(line, n)`

Returns a point on a line at a specific X coordinate.

**Parameters:**

* `line` (Line3D): The line object
* `n` (Number): X coordinate value

**Returns:** Point - Point on the line at the specified X

**Example:**

```xml
<P N="AtX100" V="onlinex(Baseline, 100)"/>
```

**Related:** `onliney()`, `onlinez()`

***

### `onliney(line, n)`

Returns a point on a line at a specific Y coordinate.

**Parameters:**

* `line` (Line3D): The line object
* `n` (Number): Y coordinate value

**Returns:** Point - Point on the line at the specified Y

**Example:**

```xml
<P N="AtY50" V="onliney(Baseline, 50)"/>
```

**Related:** `onlinex()`, `onlinez()`

***

### `onlinez(line, n)`

Returns a point on a line at a specific Z coordinate (elevation).

**Parameters:**

* `line` (Line3D): The line object
* `n` (Number): Z coordinate value

**Returns:** Point - Point on the line at the specified Z

**Example:**

```xml
<P N="AtElevation" V="onlinez(Profile, 120)"/>
```

**Related:** `onlinex()`, `onliney()`

***

### `oncircle(radius, x, y?, direction?)`

Returns a point on a circle at specified parameters.

**Parameters:**

* `radius` (Number): Circle radius
* `x` (Number): Angle in degrees or arc length
* `y` (Number, optional): Offset from circle (default: 0)
* `direction` (Number, optional): Direction modifier (default: 1)

**Returns:** Point - Point on the circle

**Example:**

```xml
<P N="CirclePoint" V="oncircle(10, 45)"/>
<!-- Point at 45 degrees on a circle of radius 10 -->
```

***

### `linel(line)`

Returns the length of a line.

**Parameters:**

* `line` (Line3D): The line object

**Returns:** Number - Length of the line

**Example:**

```xml
<P N="BeamLength" V="linel(Centerline)"/>
```

**Related:** `perimeter()`, `surfarea()`

***

### `closestPointOnLine(line, point)`

Finds the closest point on a line to a given point (projection).

**Parameters:**

* `line` (Line3D): The line object
* `point` (Point): The reference point

**Returns:** Point - Closest point on the line

**Example:**

```xml
<P N="Projection" V="closestPointOnLine(Edge, TargetPoint)"/>
```

**Related:** `intersect()`

***

### `closestLineIndex(lines, line)`

Finds the index of the closest line in a collection to a given line.

**Parameters:**

* `lines` (Array of Line3D): Collection of lines
* `line` (Line3D): Reference line

**Returns:** Number - Index of the closest line

**Example:**

```xml
<P N="NearestIndex" V="closestLineIndex(AllEdges, TargetEdge)"/>
```

***

### `toglobal(line)`

Converts a line from local to global coordinates.

**Parameters:**

* `line` (Line3D): The line in local coordinates

**Returns:** Line3D - Line in global coordinates

**Example:**

```xml
<P N="GlobalLine" V="toglobal(LocalLine)"/>
```

**Related:** `onlineg()`

***

### `nonlinearpoints(points)`

Removes collinear points from a point list, keeping only points that create non-linear segments.

**Parameters:**

* `points` (Array of Point): List of points

**Returns:** Array of Point - Filtered list with collinear points removed

**Example:**

```xml
<P N="SimplifiedPoints" V="nonlinearpoints(AllPoints)"/>
```

**Related:** `simplifypolyline()` (drops points that are only *nearly* collinear, within a tolerance)

***

### `simplifypolyline(line, tol, mode?, minDx?)`

Ramer-Douglas-Peucker simplification: returns the points of `line` that must be kept so that the polyline through them stays within `tol` of every candidate point -- in mode 0 every point. No new point is made; the first and last points are always kept.

**Parameters:**

* `line`: One polyline, a point list `[[x,y],...]` or `[[x,y,z],...]` (a missing z is 0), or a line object
* `tol` (Number): Largest allowed deviation, ≥ 0, in the coordinates' own length unit (the calling object's internal unit), not a display unit
* `mode` (Number, optional): `0` (default) = distance from a point to the segment joining its kept neighbours; `1` = the polyline is a function of x (a width or an elevation over a station): the y/z distance at the point's own x, and a point is a candidate only if its x lies strictly inside its kept neighbours' x range
* `minDx` (Number, optional): mode 1 only, how far inside that x range a candidate must lie (default 0), in the same unit as the coordinates

**Mode 1 bounds candidates only.** A point that is never a candidate is neither kept nor measured, however far it lies: one within `minDx` in x of a kept point, one at the same x as a kept neighbour (a width step at one station), one outside its kept neighbours' x range (x turning back). For the bound everywhere, give input whose x is strictly monotone and spaced more than `minDx`. The first and last points are kept as given, unchecked: the result is a function of x only when they are in x order.

**Returns:** Array of Point - the kept points, in order (a 2D list stays 2D)

**Example:**

```xml
<P N="EdgeForCADD" V="simplifypolyline(deck_left_line, 0.5)"/>
```

***

### `simplifypolylineidx(curves, tol, mode?, fixed?, minDx?)`

Same simplification, returning the kept **indices**. Several polylines of the same length can be simplified together: an index is kept when any of them needs it, so the result fits all of them at the same rows.

**Parameters:**

* `curves`: One polyline (as above), or a list of equal-length polylines / line objects
* `tol`, `mode`, `minDx`: as in `simplifypolyline()`
* `fixed` (Array of Number, optional): indices that are always kept

In mode 1 a point is a candidate only if it is one on every polyline, so a point one polyline needs can be left out because of another's x. The first, last and `fixed` points are kept as given, unchecked: the result is a function of x only when they are strictly monotone in x on every polyline.

**Returns:** Array of Number - sorted indices of the kept points

**Example:** keep the user rows and add only the refined rows both roadway edges need (OBPRoadway):

```xml
<P N="ll_keep" V="simplifypolylineidx([rightEdge,leftEdge],ll_tol,1,userRowIndices,0.01)"/>
```

**Cost:** about n × (kept points) on smooth input; O(n²) worst case (a 20,001-point zigzag at tol 0 takes seconds). Fine for the hundreds of points of a station list or an edge line.

***

### `linesplit(line, breakIndex)`

Splits a line at a specified index into two lines.

**Parameters:**

* `line` (Line3D): The line to split
* `breakIndex` (Number): Index at which to split

**Returns:** Array - Two lines \[line1, line2]

**Example:**

```xml
<P N="SplitLines" V="linesplit(OriginalLine, 3)"/>
```

***

### `intersect(line1, line2, plane?, rayMode?)`

Finds the intersection point between two lines.

**Parameters:**

* `line1` (Line3D): First line
* `line2` (Line3D): Second line
* `plane` (String, optional): Plane for 2D intersection ("XY", "XZ", "YZ")
* `rayMode` (Boolean, optional): If true, extends lines as rays

**Returns:** Point - Intersection point, or null if no intersection

**Example:**

```xml
<P N="CrossPoint" V="intersect(LineA, LineB, 'XY')"/>
```

**Related:** `intersectalong()`, `polygonLineIntersect()`

***

### `intersectalong(line1, line2, extLen?, plane?)`

Finds intersection between two lines with optional extension length.

**Parameters:**

* `line1` (Line3D): First line
* `line2` (Line3D): Second line
* `extLen` (Number, optional): Extension length for lines
* `plane` (String, optional): Intersection plane

**Returns:** Point - Intersection point

**Example:**

```xml
<P N="ExtendedIntersection" V="intersectalong(Edge1, Edge2, 5, 'XY')"/>
```

**Related:** `intersect()`

***

### `polygonLineIntersect(polygon, line, mode?)`

Finds intersection points between a polygon and a line.

**Parameters:**

* `polygon` (Surface3D): The polygon
* `line` (Line3D): The line
* `mode` (Number, optional): Intersection mode

**Returns:** Array of Point - Intersection points

**Example:**

```xml
<P N="CutPoints" V="polygonLineIntersect(Slab, CutLine)"/>
```

**Related:** `intersect()`

***

### `polygonunionall(polys[, close])`

Unions a whole list of plan polygons into one outer boundary. `polygonunion` takes two polygons; this one folds every polygon into the same union, so a group joins into one ring even when a piece connects only through a later piece in the list (L, T, U and Z layouts).

**Parameters:**

* `polys` (List): the polygons, each `[[x,y],...]` or `[[x,y,z],...]`
* `close` (Number, optional): grow every polygon by this distance, union, then shrink the result back by it. Default 0 (off).

**Returns:** List with one polygon (read it with `[0]`), or `[]` when no polygon is usable. When the pieces form several separate groups, the largest ring is the one returned.

**When to pass `close`:** when the pieces only touch. A plain union of pieces that share an edge, or of a hole that reaches the boundary, can return a ring that touches itself (a zero-width slit or spike), and the mesher refuses such a ring. Closing by a small distance makes the pieces overlap first. It fills gaps and notches narrower than `2 x close`, and moves the outline by at most `close`.

**Notes:**

* The direction a polygon is drawn in (clockwise or not) makes no difference.
* With `close`, a polygon holding a coordinate that is not a finite number is left out.

**Example:**

```xml
<P N="SlabOutline" V="polygonunionall(PiecePolys, 0.5)[0]"/>
```

**Related:** `polygonunion()`, `wallcut()`

***

### `wallcut(points, clips[, slotRatio[, minLen]])`

What is left of a straight wall's plan outline once the members standing in it are taken out: one outline per remaining piece, in order along the wall. It is how a wall is stopped at a column that occupies the same space, which an analysis cannot have.

**Parameters:**

* `points` (List): the wall outline, `[[x,y],...]`
* `clips` (List): the outlines to take out, each `[[x,y],...]`
* `slotRatio` (Number, optional): a clip covering at least this share of the wall's thickness takes the wall's FULL thickness over its length along the wall. Default 0.5. A shallower clip takes only its own outline (a notch in one face).
* `minLen` (Number, optional): pieces shorter than this along the wall are dropped. Default: the wall's thickness.

**Returns:** List of outlines, each `[[x,y],...]` (2D). `points` unchanged in a one-item list when no clip overlaps the wall; `[]` when nothing is left, or when `points` is not a polygon.

**Notes:**

* The wall's direction is its longest edge and its thickness is its extent across that edge, so this is for a STRAIGHT wall. On an L or T outline the other leg is measured as thickness; cut such a wall one leg at a time.
* Pieces stop 0.01 clear of every clip, so the result does not overlap the member it was cut for.
* The direction a clip is drawn in makes no difference. A clip that is not a polygon is ignored.

**Example:**

```xml
<P N="WallPieces" V="wallcut(WallOutline, ColumnFootprints)"/>
```

**Related:** `polygonunionall()`, `polygondifference()`

***

## Surface/Volume Operations

### `surfarea(surface)`

Calculates the area of a surface.

**Parameters:**

* `surface` (Surface3D): The surface object

**Returns:** Number - Surface area

**Example:**

```xml
<P N="DeckArea" V="surfarea(DeckSurface)"/>
```

**Related:** `volume()`, `perimeter()`

***

### `volumesurfareas(volume)`

Returns an array of areas for all surfaces of a volume.

**Parameters:**

* `volume` (Volume): The volume object

**Returns:** Array of Numbers - Areas of each surface

**Example:**

```xml
<P N="FaceAreas" V="volumesurfareas(BeamVolume)"/>
<P N="TopArea" V="volumesurfareas(BeamVolume)[0]"/>
```

**Related:** `volumesurfperimeters()`, `volume()`

***

### `volumesurfperimeters(volume)`

Returns an array of perimeters for all surfaces of a volume.

**Parameters:**

* `volume` (Volume): The volume object

**Returns:** Array of Numbers - Perimeters of each surface

**Example:**

```xml
<P N="EdgeLengths" V="volumesurfperimeters(Column)"/>
```

**Related:** `volumesurfareas()`, `perimeter()`

***

### `volumesideareas(volume, mode)`

Returns the side-face areas of a volume, as a **list** — one entry per edge of the volume's first cross-section. Sum it with `suml()` to get a single area.

**Parameters:**

* `volume` (Volume): The volume or line object
* `mode` (Number): which faces to include. Must be a number — a string matches nothing and yields zeros.
  * `0` all side faces (default)
  * `1` vertical faces only
  * `2` horizontal faces only
  * `3` horizontal faces in the top 1/3 (by elevation)
  * `4` horizontal faces in the bottom 1/3 (by elevation)

**Returns:** List of areas. Modes 2/3/4 append the volume's horizontal end caps after the per-edge values, so the list can be longer than the edge count — sum it rather than pairing it positionally with another per-edge list.

**Example:**

```xml
<!-- total side area of a footing -->
<P N="SideArea" V="suml(volumesideareas(Footing3D, 0))"/>

<!-- top surface of a vertically extruded column: the top cap -->
<P N="TopSurfaceArea" V="suml(volumesideareas(Column3D, 3))"/>
```

**Note:** modes 2/3/4 describe *horizontal* faces. A volume extruded horizontally (a deck, a pier cap) gets those from the sweep; a volume extruded vertically (a column, a stem wall) has none in the sweep, so its caps are what these modes report.

**Related:** `volumesurfareas()`

***

### `volumesurfdims(volume, algorithm?, side?)`

Returns dimensions of volume surfaces (width, height, etc.).

**Parameters:**

* `volume` (Volume): The volume object
* `algorithm` (Number, optional): Algorithm type for dimension calculation
* `side` (Number, optional): Specific side index

**Returns:** Object or Array - Surface dimensions

**Example:**

```xml
<P N="Dimensions" V="volumesurfdims(Beam)"/>
<P N="Width" V="volumesurfdims(Beam).Width"/>
```

**Related:** `volumesurfareas()`

***

### `volume(volume)`

Calculates the volume of a 3D solid.

**Parameters:**

* `volume` (Volume): The volume object

**Returns:** Number - Volume value

**Example:**

```xml
<P N="ConcreteVolume" V="volume(PierVolume)"/>
```

**Related:** `surfarea()`

***

### `volumeextvectorlength(volume, mode?)`

Returns the length of the extrusion vector for an extruded volume.

**Parameters:**

* `volume` (Volume): The extruded volume object
* `mode` (Number, optional): Calculation mode

**Returns:** Number - Extrusion vector length

**Example:**

```xml
<P N="ExtrusionLength" V="volumeextvectorlength(ExtrudedBeam)"/>
```

***

### `perimeter(surface, isOpen?)`

Calculates the perimeter of a surface or boundary.

**Parameters:**

* `surface` (Surface3D): The surface object
* `isOpen` (Boolean, optional): Whether the surface is open

**Returns:** Number - Perimeter length

**Example:**

```xml
<P N="SlabPerimeter" V="perimeter(DeckSurface, false)"/>
```

**Related:** `surfarea()`, `linel()`

***

### `punchingperimeter(surface, distance, boundary)`

Calculates the punching shear perimeter at a distance from a boundary.

**Parameters:**

* `surface` (Surface3D): The surface (usually a slab)
* `distance` (Number): Distance from the boundary
* `boundary` (Boundary): The loaded area boundary

**Returns:** Number - Punching perimeter length

**Example:**

```xml
<P N="ShearPerimeter" V="punchingperimeter(Slab, EffectiveDepth, ColumnFace)"/>
```

**Related:** `punchingperimeterlines()`

***

### `punchingperimeterlines(surface, distance, boundary)`

Returns the line segments forming the punching shear perimeter.

**Parameters:**

* `surface` (Surface3D): The surface
* `distance` (Number): Distance from the boundary
* `boundary` (Boundary): The loaded area boundary

**Returns:** Array of Line3D - Perimeter lines

**Example:**

```xml
<P N="PerimeterLines" V="punchingperimeterlines(Slab, d, Column)"/>
```

**Related:** `punchingperimeter()`

***

## Unit Conversion

### `withunits(num, primaryUnit, secondaryUnit?, unitType?, decimals?)`

Formats a number with unit labels.

**Parameters:**

* `num` (Number): The numeric value
* `primaryUnit` (String): Primary unit system ("ft", "m", etc.)
* `secondaryUnit` (String, optional): Secondary unit for dual display
* `unitType` (String, optional): Unit category ("Length", "Force", etc.)
* `decimals` (Number, optional): Decimal places

**Returns:** String - Formatted string with units

**Example:**

```xml
<P N="LengthLabel" V="withunits(120.5, 'ft', 'in', 'Length', 2)"/>
<!-- Result: "120.50 ft" or "120'-6\"" depending on format -->
```

**Related:** `convert()`, `unitlabel()`

***

### `unitlabel(unitCategory, unitType)`

Returns the unit label for a given category and type.

**Parameters:**

* `unitCategory` (String): Unit category ("Default", "Metric", "Imperial")
* `unitType` (String): Unit type ("Length", "Force", "Stress", etc.)

**Returns:** String - Unit label (e.g., "ft", "kN", "MPa")

**Example:**

```xml
<P N="LengthUnit" V="unitlabel('Default', 'Length')"/>
```

**Related:** `withunits()`, `convert()`

***

### `convert(num, unitType, fromUnit, toUnit)`

Converts a value from one unit to another.

**Parameters:**

* `num` (Number): The value to convert
* `unitType` (String): Type of unit ("Length", "Force", "Stress", etc.)
* `fromUnit` (String): Source unit ("ft", "m", "kip", "kN", etc.)
* `toUnit` (String): Target unit

**Returns:** Number - Converted value

**Example:**

```xml
<P N="LengthInMeters" V="convert(100, 'Length', 'ft', 'm')"/>
<!-- Converts 100 feet to meters -->
<P N="ForceInKN" V="convert(50, 'Force', 'kip', 'kN')"/>
```

**Related:** `withunits()`, `unitlabel()`

***

### `stationlabel(station, format?, decimals?)`

Formats a station value according to standard station notation.

**Parameters:**

* `station` (Number): Station value
* `format` (String, optional): Format string
* `decimals` (Number, optional): Decimal places

**Returns:** String - Formatted station label

**Example:**

```xml
<P N="StationText" V="stationlabel(1234.56)"/>
<!-- Result: "12+34.56" -->
```

**Related:** `withunits()`

***

## Advanced Geometry

### `crange(value, min, max)`

Maps a value to a color range (for visualization).

**Parameters:**

* `value` (Number): The value to map
* `min` (Number): Minimum value of range
* `max` (Number): Maximum value of range

**Returns:** Color - Color value based on range

**Example:**

```xml
<P N="StressColor" V="crange(Stress, 0, MaxStress)"/>
```

***

### `voronoi(surface, sitePoints, cutoutPoints?)`

Generates a Voronoi diagram on a surface.

**Parameters:**

* `surface` (Surface3D): The base surface
* `sitePoints` (Array of Point): Site points for Voronoi cells
* `cutoutPoints` (Array of Point, optional): Points to exclude

**Returns:** Array of Surface3D - Voronoi cells

**Example:**

```xml
<P N="VoronoiCells" V="voronoi(DeckSurface, ColumnLocations)"/>
```

**Related:** `voronoipts()`

***

### `voronoipts(surface, sitePoints, cutoutPoints?)`

Returns the vertices of Voronoi cells.

**Parameters:**

* `surface` (Surface3D): The base surface
* `sitePoints` (Array of Point): Site points
* `cutoutPoints` (Array of Point, optional): Points to exclude

**Returns:** Array of Point - Voronoi vertices

**Example:**

```xml
<P N="VoronoiVertices" V="voronoipts(Slab, Supports)"/>
```

**Related:** `voronoi()`

***

### `hittest(surface, point, local?)`

Tests if a point hits (is inside) a surface.

**Parameters:**

* `surface` (Surface3D): The surface to test
* `point` (Point): The point to test
* `local` (Boolean, optional): Use local coordinates

**Returns:** Boolean - True if point is inside surface

**Example:**

```xml
<P N="IsInside" V="hittest(DeckBoundary, TestPoint, false)"/>
```

***

## Mesh Generation

### `stripmesh(line1, x1, line2, x2)`

Generates a strip mesh between two lines.

**Parameters:**

* `line1` (Line3D): First boundary line
* `x1` (Number): Parameter on first line
* `line2` (Line3D): Second boundary line
* `x2` (Number): Parameter on second line

**Returns:** Mesh - Strip mesh object

**Example:**

```xml
<P N="DeckMesh" V="stripmesh(LeftEdge, 0, RightEdge, 0)"/>
```

**Related:** `gridmesh()`

***

### `gridmesh(arg0, arg1, arg2?, arg3?)`

Generates a grid mesh from parameters.

**Parameters:**

* `arg0`, `arg1`, `arg2`, `arg3`: Grid definition parameters (varies by use case)

**Returns:** Mesh - Grid mesh object

**Example:**

```xml
<P N="SlabMesh" V="gridmesh(Boundary, 12, 12)"/>
<!-- Creates 12x12 mesh within boundary -->
```

**Related:** `stripmesh()`

***

## Object/Point Functions

### `point(obj, index?)`

Retrieves a point from an object.

**Parameters:**

* `obj` (Object): The object containing points
* `index` (Number, optional): Point index

**Returns:** Point - The requested point

**Example:**

```xml
<P N="StartPoint" V="point(Line, 0)"/>
<P N="EndPoint" V="point(Line, 1)"/>
```

***

### `cog(obj)`

Calculates the center of gravity (centroid) of an object.

**Parameters:**

* `obj` (Object): The object (surface, volume, or line)

**Returns:** Point - Center of gravity

**Example:**

```xml
<O T="Point" N="Centroid" X="cog(Slab).X" Y="cog(Slab).Y" Z="cog(Slab).Z"/>
```

**Related:** `surfarea()`, `volume()`

***

## Value/Expression Functions

### `value(targetParam, sourceParam?, sourceValue?)`

Evaluates the value of a parameter in a different context.

**Parameters:**

* `targetParam` (String): Name of parameter to evaluate
* `sourceParam` (String, optional): Source parameter for context
* `sourceValue` (Any, optional): Value for source parameter

**Returns:** Any - Evaluated parameter value

**Example:**

```xml
<P N="BeamDepth" V="value('Depth', 'Station', 100)"/>
<!-- Gets the value of Depth parameter at Station=100 -->
```

**Note:** This is useful for evaluating station-dependent parameters at specific locations.

***

## String Manipulation

### `startswith(str, prefix)`

Tests if a string starts with a specified prefix.

**Parameters:**

* `str` (String): The string to test
* `prefix` (String): The prefix to check

**Returns:** Boolean - True if string starts with prefix

**Example:**

```xml
<P N="IsGirder" V="startswith(Name, 'Girder')"/>
```

**Related:** `endswith()`

***

### `endswith(str, suffix)`

Tests if a string ends with a specified suffix.

**Parameters:**

* `str` (String): The string to test
* `suffix` (String): The suffix to check

**Returns:** Boolean - True if string ends with suffix

**Example:**

```xml
<P N="IsSteel" V="endswith(MaterialName, 'Steel')"/>
```

**Related:** `startswith()`

***

### `lower(str)` / `upper(str)`

(All four functions in this block are matched by their lower-case names only, like `startswith`.)

Case-folds a string. A non-string subject returns `""` (so a rule probed with an unbound element variable does not error).

**Example:**

```xml
<P N="FamilyLc" V="lower(Family)"/>
```

**Related:** `contains()`

***

### `contains(str, substring)`

Tests whether `substring` occurs anywhere in `str`. An empty `substring` matches every string, which is what a blank "match anything" rule cell needs. Case-sensitive: wrap both sides in `lower()` for a case-insensitive match.

**Returns:** Boolean (1/0)

**Example:**

```xml
<P N="IsConcrete" V="contains(lower(Material), 'concrete')"/>
```

**Related:** `startswith()`, `endswith()`

***

### `proplookup(pairs, name[, default])`

Reads one value out of a list of `[name, value]` pairs by name (case-insensitive). Returns `default` (or `""`) when the name is absent. This is how a formula reads an authored property off an imported `BIMElement`'s `Props` list.

**Parameters:**

* `pairs` (List): `[['name','value'], ...]`
* `name` (String): the property to read
* `default` (Any, optional): returned when the name is not present

**Example:**

```xml
<P N="Mark" V="proplookup(Props, 'Mark', '')"/>
<P N="Camber" V="proplookup(Props, 'Camber Size', 0)"/>
```

***

### `substringcount(str, substring)`

Counts occurrences of a substring within a string.

**Parameters:**

* `str` (String): The string to search
* `substring` (String): The substring to count

**Returns:** Number - Count of occurrences

**Example:**

```xml
<P N="HyphenCount" V="substringcount(Label, '-')"/>
```

***

### `replaceall(str, find, replace)`

Replaces all occurrences of a substring with another string.

**Parameters:**

* `str` (String): The source string
* `find` (String): The substring to find
* `replace` (String): The replacement string

**Returns:** String - Modified string

**Example:**

```xml
<P N="CleanName" V="replaceall(RawName, '_', ' ')"/>
<!-- Replaces all underscores with spaces -->
```

**Related:** `removewhitespaces()`

***

### `removewhitespaces(str)`

Removes all whitespace characters from a string.

**Parameters:**

* `str` (String): The string to process

**Returns:** String - String without whitespace

**Example:**

```xml
<P N="CompactName" V="removewhitespaces(Name)"/>
```

**Related:** `replaceall()`

***

### `mergeLinePoints(targetLines, constraints?, tolerance?)`

Merges nearby points in a collection of lines based on tolerance.

**Parameters:**

* `targetLines` (Array of Line3D): Lines to process
* `constraints` (Object, optional): Merge constraints
* `tolerance` (Number, optional): Distance tolerance for merging

**Returns:** Array of Line3D - Lines with merged points

**Example:**

```xml
<P N="CleanedLines" V="mergeLinePoints(RawLines, null, 0.001)"/>
```

***

## Functional Programming & Advanced Operations

These advanced functions provide functional programming capabilities, station-dependent expressions, and conditional logic.

### `map(list, lambda)`

Applies a lambda function to each element of a list and returns a new list with the results.

**Parameters:**

* `list` (Array): The array to map over
* `lambda` (Lambda Expression): Function to apply to each element. Without an arrow the element is `x` and its index is `xi` (`map(L, x * 2)`, `map(L, xi)`). With an arrow you name the element, and the index is that name plus `i`: `map(L, k => k * ki)`. Name the element when nesting lambdas, so the inner one does not hide the outer `x` (`JSParser.Parser.MakeLambdaOperation` / `SetLambdaOperations`). The same rules hold for `filter`, `maxl`, `minl`, `suml`, `avg`, `sort` and the other lambda functions.

**Returns:** Array - New array with transformed elements

**Example:**

```xml
<P N="DoubledValues" V="map(Numbers, x => x * 2)"/>
<P N="Squares" V="map([1,2,3,4,5], x => x ^ 2)"/>
```

**⚠️ CRITICAL PERFORMANCE NOTE:**

**ALWAYS use `map()` for parameter loops—NEVER use `Repeat` for data transformations!**

Using `Repeat` to calculate parameter values creates unnecessary objects in the project tree, causing severe performance degradation (10-100x slower). Use `map()` for all data transformations.

**❌ WRONG - Using Repeat for calculations:**

```xml
<!-- Creates 100 objects - VERY SLOW! -->
<O T="Repeat" N="Loop" S="0" E="99" I="1" CTRL="i" i="0">
  <P N="Value" V="InputList[i] * 2"/>
</O>
<P N="Results" V="Loop.*.Value"/>
```

**✅ CORRECT - Using map():**

```xml
<!-- Single parameter - FAST! -->
<P N="Results" V="map(InputList, x => x * 2)"/>
```

**Common Use Cases for map():**

```xml
<!-- Extract property from objects -->
<P N="GirderLengths" V="map(Girders, x => x.Length)"/>

<!-- Multi-station FEA results -->
<P N="Moments" V="map(Stations, force(Element, 'LC1', 'My', x))"/>

<!-- Transform coordinates -->
<P N="ZeroElevPoints" V="map(Points, [x[0], x[1], 0])"/>

<!-- Extract nested properties -->
<P N="SupportStations" V="map(Supports, x.location.station)"/>
```

**When to Use Repeat vs map():**

* **Use Repeat:** Creating objects (Points, FENodes, Volumes, Beams, etc.)
* **Use map():** Transforming data, extracting properties, calculating values

See the Parametric Engine Guide section 4.1 for detailed explanation.

**Related:** `filter()`, `reduce()`

***

### `filter(list, lambda)`

Filters a list based on a condition, returning only elements that match.

**Parameters:**

* `list` (Array): The array to filter
* `lambda` (Lambda Expression): Condition to test each element (`x` for the element and `xi` for its index, or a named element `k => ...` with index `ki`; see `map()`)

**Returns:** Array - Filtered array containing only matching elements

**Example:**

```xml
<P N="PositiveValues" V="filter(Numbers, x => x > 0)"/>
<P N="EvenNumbers" V="filter([1,2,3,4,5,6], x => x % 2 == 0)"/>
```

**Related:** `map()`, `index()`

***

### `reduce(list, lambda)`

Reduces a list to a single value by applying a function cumulatively.

**Parameters:**

* `list` (Array): The array to reduce
* `lambda` (Lambda Expression): Reduction function (uses `x` for accumulator, `y` for current element)

**Returns:** Any - Single accumulated value

**Example:**

```xml
<P N="Sum" V="reduce([1,2,3,4,5], x + y)"/>
<P N="Product" V="reduce(Values, x * y)"/>
```

**Related:** `suml()`, `avg()`

***

### `maxl(list, lambda?)`

Finds the maximum value in a list based on an optional lambda function.

**Parameters:**

* `list` (Array): The array to search
* `lambda` (Lambda Expression, optional): Function to extract comparison value from each element. If omitted, compares the values directly.

**Returns:** Any - Maximum value

**Example:**

```xml
<!-- With lambda for object properties -->
<P N="MaxLength" V="maxl(Beams, x => x.Length)"/>
<P N="MaxAbsolute" V="maxl(Values, x => abs(x))"/>

<!-- Without lambda for simple numeric lists -->
<P N="MaxValue" V="maxl(NumberList)"/>
```

**Related:** `minl()`, `max()`

***

### `minl(list, lambda?)`

Finds the minimum value in a list based on an optional lambda function.

**Parameters:**

* `list` (Array): The array to search
* `lambda` (Lambda Expression, optional): Function to extract comparison value from each element. If omitted, compares the values directly.

**Returns:** Any - Minimum value

**Example:**

```xml
<!-- With lambda for object properties -->
<P N="MinWidth" V="minl(Columns, x => x.Width)"/>
<P N="MinAbsolute" V="minl(Values, x => abs(x))"/>

<!-- Without lambda for simple numeric lists -->
<P N="MinValue" V="minl(NumberList)"/>
```

**Related:** `maxl()`, `min()`

***

### `suml(list, lambda?)`

Calculates the sum of values extracted from a list using an optional lambda function.

**Parameters:**

* `list` (Array): The array to sum
* `lambda` (Lambda Expression, optional): Function to extract value from each element. If omitted, sums the values directly.

**Returns:** Number - Sum of extracted values

**Example:**

```xml
<!-- With lambda for object properties -->
<P N="TotalArea" V="suml(Surfaces, x => x.Area)"/>
<P N="WeightedSum" V="suml(Items, x => x.Value * x.Quantity)"/>

<!-- Without lambda for simple numeric lists -->
<P N="Total" V="suml(NumberList)"/>
```

**Related:** `avg()`, `reduce()`, `sum()`

***

### `avg(list, lambda?)`

Calculates the average of values extracted from a list using an optional lambda function.

**Parameters:**

* `list` (Array): The array to average
* `lambda` (Lambda Expression, optional): Function to extract value from each element. If omitted, averages the values directly.

**Returns:** Number - Average of extracted values

**Example:**

```xml
<!-- With lambda for object properties -->
<P N="AvgHeight" V="avg(Buildings, x => x.Height)"/>
<P N="MeanStress" V="avg(Elements, x => x.Stress)"/>

<!-- Without lambda for simple numeric lists -->
<P N="Average" V="avg(NumberList)"/>
```

**Related:** `suml()`

***

### `sort(list, lambda?, ascending?)`

Sorts a list based on a comparison function.

**Parameters:**

* `list` (Array): The array to sort
* `lambda` (Lambda Expression, optional): Function to extract sort key from each element
* `ascending` (Number, optional): 1 for ascending (default), 0 for descending

**Returns:** Array - Sorted array

**Example:**

```xml
<P N="SortedNumbers" V="sort([5,2,8,1,9])"/>
<P N="SortedByLength" V="sort(Beams, x => x.Length)"/>
<P N="DescendingOrder" V="sort(Values, x => x, 0)"/>
```

**Related:** `reverse()`

***

### `reverse(list)`

Reverses the order of elements in a list.

**Parameters:**

* `list` (Array): The array to reverse

**Returns:** Array - Reversed array

**Example:**

```xml
<P N="ReversedList" V="reverse([1,2,3,4,5])"/>
<!-- Result: [5,4,3,2,1] -->
```

**Related:** `sort()`

***

### `unique(list, lambda)` / `removedup(list, lambda)`

Removes duplicate elements from a list based on a lambda function.

**Parameters:**

* `list` (Array): The array to filter
* `lambda` (Lambda Expression): Function to extract comparison value from each element

**Returns:** Array - Array with duplicates removed

**Example:**

```xml
<P N="UniqueIDs" V="unique(Objects, x => x.ID)"/>
<P N="UniqueMaterials" V="removedup(Elements, x => x.Material)"/>
```

**Related:** `filter()`

***

### `index(list, lambda)`

Finds the index of the first element that matches a condition.

**Parameters:**

* `list` (Array): The array to search
* `lambda` (Lambda Expression): Condition to test each element

**Returns:** Number - Index of first matching element, or -1 if not found

**Example:**

```xml
<P N="FirstNegative" V="index(Values, x => x < 0)"/>
<P N="FoundIndex" V="index(Beams, x => x.Name == 'MainGirder')"/>
```

**Related:** `filter()`

***

### `iif(condition1, value1, condition2, value2, ..., elseValue?)`

Inline if-elseif-else function for conditional expressions.

**Parameters:**

* `condition1, condition2, ...` (Boolean): Conditions to test
* `value1, value2, ...` (Any): Values to return when conditions are true
* `elseValue` (Any, optional): Default value if no conditions match

**Returns:** Any - First matching value, or elseValue, or 0

**Example:**

```xml
<P N="Grade" V="iif(Score >= 90, 'A', Score >= 80, 'B', Score >= 70, 'C', 'F')"/>
<P N="Status" V="iif(Stress > Yield, 'Failed', Stress > AllowableStress, 'Warning', 'OK')"/>
```

**Note:** More flexible than ternary operator for multiple conditions

***

### `atstation(station, expression)`

Evaluates an expression at a specific station value, temporarily overriding the current station context.

**Parameters:**

* `station` (Number): Station value to evaluate at
* `expression` (Expression): Expression to evaluate

**Returns:** Any - Result of expression evaluated at the given station

**Example:**

```xml
<P N="DepthAtMidspan" V="atstation(60, Depth)"/>
<P N="ForceAt100" V="atstation(100, forceM('Girder', 'DeadLoad'))"/>
```

**Note:** Useful for evaluating station-dependent parameters at specific locations

***

### `makestadep(stations, values, variations?)`

Creates a station-dependent expression from discrete station/value pairs. The function returns a station-dependent parameter that can be evaluated at any station using `atstation()`.

**Parameters:**

* `stations` (Array of Numbers): Station values
* `values` (Array of Numbers or Arrays): Values at each station. **Note:** The `values` array should have one less element than `stations` (i.e., values.length = stations.length - 1), as shown in examples. Each element can be a single number or an array of numbers (for multiple values per station).
* `variations` (Array of Strings, optional): Variation types between stations ('linear', 'parabola', 'circle', 'polynomial'). Should match the number of gaps (stations.length - 1).

**Returns:** Number - Interpolated value at current station

**Example:**

```xml
<P N="VariableDepth" V="makestadep([0,50,100,150], [60,72,72,60], ['linear','linear','linear'])"/>
<!-- Depth varies from 60 at station 0 to 72 at stations 50-100, back to 60 at 150 -->
```

**Additional Example for Array Values (Multiple Values per Station):**

```xml
<P N="MultiValueParam" V="makestadep([0,100], [[10,20]], ['linear'])"/>
<!-- At station 0: 10, at station 100: 20, interpolated linearly (1 gap) -->
```

**Another Example (3 Stations, 2 Gaps):**

```xml
<P N="MultiValueParam2" V="makestadep([0,100,200], [[10,20], [15,25]], ['linear','linear'])"/>
<!-- At station 0: 10, at station 99: 19.9, at station 100: 20, at station 101: 15.1, at station 200: 25,interpolated linearly -->
```

**Related:** `variation()`, `makestadepexpr()` **Example:**

```xml
<O N="MakestadepFunction" T="Group">
    <P N="stationlist" V="[0,100,200]" />
    <P N="Valueslist" V="[10,20,30]" />
    <P N="varTextlist" V="['linear','linear']" />
    <P N="staDepParam" V="makestadep(stationlist,Valueslist,varTextlist)" />
    <P N="test1" V="atstation(50,staDepParam)" />
    <!-- test1 value = 15 (interpolated at station 50) -->
</O>
```

**Related:** `atstation()`, `variation()`, `makestadepexpr()`

***

### `makestadepexpr(stations, values, variations?)`

Creates a station-dependent expression string (not evaluated).

**Parameters:**

* `stations` (Array of Numbers): Station values
* `values` (Array of Numbers): Values at each station
* `variations` (Array of Strings, optional): Variation types

**Returns:** String - Station-dependent expression as text

**Example:**

```xml
<P N="DepthExpression" V="makestadepexpr([0,100,200], [60,72,60])"/>
```

**Related:** `makestadep()`

***

### `variation(type, fromValue, toValue, ...)`

Creates a variation between two values based on relative position (0 to 1).

**Parameters:**

* `type` (String): Variation type - 'linear', 'parabola', 'circle', 'polynomial', 'custom'
* `fromValue` (Number): Starting value
* `toValue` (Number): Ending value
* Additional parameters depend on type:
  * **parabola**: `parabolaType` ('concavedown' or 'concaveup')
  * **circle**: `radius`, `circleType`
  * **polynomial**: `startGrade`, `endGrade`
  * **custom**: `lambda` function

**Returns:** Number - Interpolated value

**Example:**

```xml
<P N="LinearVariation" V="variation('linear', 0, 100)"/>
<P N="ParabolicVariation" V="variation('parabola', 60, 72, 'concavedown')"/>
<P N="CustomVariation" V="variation('custom', x => sin(x * pi))"/>
```

**Note:** Requires context with station or relative position (x) set

***

### `variations(params...)`

Returns the list of variation types used in the given parameters.

**Parameters:**

* `params...` (Parameters): Parameters to check for variations

**Returns:** Array of Strings - List of variation types found

**Example:**

```xml
<P N="UsedVariations" V="variations(Depth, Width, Height)"/>
<!-- Might return ['parabola', 'linear'] -->
```

***

### `makelist(params...)` / `rangelist(params...)`

Creates a list from station-dependent range values.

**Parameters:**

* `params...` (Parameters): Parameters with range values

**Returns:** Array - Unique values from all ranges

**Example:**

```xml
<P N="AllStations" V="makelist(BeamStations, ColumnStations)"/>
<P N="CombinedRanges" V="rangelist(Range1, Range2, Range3)"/>
```

**Note:** Automatically extracts values from station-dependent ranges

***

### `exportval(paramName, object?, defaultReturn?)`

Exports a parameter value from an object, with optional default.

**Parameters:**

* `paramName` (String): Name of parameter to export
* `object` (Object, optional): Object to export from
* `defaultReturn` (Any, optional): Default value if parameter not found (default: 0)

**Returns:** Any - Parameter value or default

**Example:**

```xml
<P N="MaterialStrength" V="exportval('Fy', MaterialObject, 50)"/>
<P N="BeamLength" V="exportval('Length', Girder)"/>
```

***

### `paramlabel(param)`

Returns the display label of a parameter or object name.

**Parameters:**

* `param` (Parameter or Object): Parameter or object to get label from

**Returns:** String - Parameter label or object name

**Example:**

```xml
<P N="DepthLabel" V="paramlabel(Depth)"/>
```

**Note:** Returns the user-facing label, not the internal parameter name

***

## External Module Functions

These functions are available when specific modules are loaded in the context.

### Section Analysis Functions (SEC.Functions)

Available when section analysis module is loaded. Defined in [Functions.ts](https://github.com/openbrim/platform/tree/master/docs/developers/llm-guides/Code/SEC/Functions.ts).

#### `momentCapacity(section, orientation, strain, axial, ...)`

Calculates moment capacity of a cross-section.

**Parameters:**

* `section` (Section): The section object
* `orientation` (Number): Load orientation angle
* `strain` (Number): Maximum strain
* `axial` (Number): Axial force
* Additional parameters for analysis settings

**Returns:** Number - Moment capacity value

**Example:**

```xml
<P N="Capacity" V="momentCapacity(BeamSection, 0, 0.003, 0)"/>
```

**Related:** `momentCapacityNA()`, `interactionDiagram()`

***

#### `momentCapacityNA(section, orientation, strain, axial, ...)`

Returns neutral axis distance from section centroid for moment capacity calculation.

**Parameters:** Same as `momentCapacity()`

* `section`: Section object to analyze
* `orientation`: Rotation angle in radians (**clockwise positive**)
* `strain`: Concrete strain limit (typically 0.003)
* `axial`: Corresponding axial force (compression positive)

**Returns:** Number - Neutral axis distance from centroid (positive upward from origin)

**How It Works:**

1. **Rotates the section** (including all rebars and tendons) clockwise by the specified `orientation` angle about the $(0, 0)$ coordinate point.
2. **Applies compression** from top (positive Y direction) relative to origin (0,0)
3. **Returns NA distance** from centroid, positive upward:
   * **Positive value**: NA is above centroid (compression zone above)
   * **Negative value**: NA is below centroid (rare, large tension forces)

**Key Points:**

* Coordinate system origin at (0,0)
* Compression side is upward (positive Y)
* Result measured in the rotated coordinate system
* Section rotates **with all reinforcement** (rebars and tendons)

**Example Usage:**

```xml
<!-- Compression from top (0° rotation) -->
<P N="NA_distance" V="momentCapacityNA(mySection, 0, 0.003, 1000)" />
<!-- Returns positive distance (NA above centroid) -->

<!-- Compression from different angle (90° clockwise rotation) -->
<P N="NA_distance_rotated" V="momentCapacityNA(mySection, pi/2, 0.003, 1000)" />
<!-- Returns positive distance in rotated system -->
```

**Important:** When filtering rebars or calculating distances in the **original** coordinate system, you may need to adjust the sign of the returned NA value depending on the rotation angle and which side of the section you're working with.

**Related:** `momentCapacity()`, `interactionDiagram()`

***

#### `momentCapacityTension(section, orientation, strain, axial, ...)`

Returns tension force at moment capacity.

**Returns:** Number - Tension force

***

#### `momentCapacityCompression(section, orientation, strain, axial, ...)`

Returns compression force at moment capacity.

**Returns:** Number - Compression force

***

#### `momentCapacityCurvature(section, orientation, strain, axial, ...)`

Returns curvature at moment capacity.

**Returns:** Number - Curvature value

***

#### `momentCapacityLeverArm(section, orientation, strain, axial, ...)`

**Parameters:** Same as `momentCapacity()`

The distance between the resultant of the tensile forces and the resultant of the compressive forces at the flexural strength state, each force by its own sign: AASHTO 5.7.2.8's effective shear depth before its limits (0.9 d\_e, 0.72 h). `momentCapacityCompressionLoc - momentCapacityTensionLoc` is the same distance only when every force above the neutral axis compresses; a tendon in the compressed zone keeps its tension and moves that side's resultant (on a post-tensioned cap it read 146 in on a 108 in cap). Never negative: returns 0 where the state has no tension or no compression, where none exists, and where the tension resultant lies on the compressed side of the compression resultant (a heavy axial compression with tendons in the compressed zone).

```xml
<P N="d_v_raw" V="momentCapacityLeverArm(CapSection, pi, 0.003, Nu, 0.005, 0.75, 0.9, 400)" />
```

***

#### `sectionAgBottomRatio(section, orientation, ratio)`

The area of the section within `ratio` of its depth from its bottom, after the section is turned by `orientation` (radians, as `momentCapacity` takes it: 0 puts the bottom in tension under positive flexure, pi the top). The depth is the turned section's, extreme fibre to extreme fibre of its solid shapes: a cutout's points do not move it. `ratio` defaults to 0.5, AASHTO's half-depth containing the flexural tension zone (5.7.3.4.2, B5.2): the result is A\_ct. `ratio` is clamped to 0..1; 0 gives 0, and 1 gives the whole section: read without a station, the same area as `sectionAg` on a section with drawn shapes (one without any gives 0, where `sectionAg` falls back to the section's stored area).

Each shape is clipped to the band, so the area is exact on a non-convex shape such as an I-girder. Shapes are taken as drawn, as `sectionAg` takes them: a cutout subtracts all of itself that lies in the band, even a part drawn outside the solid; overlapping shapes count twice; bar and tendon layouts do not count, and every other shape does whatever its material, so a steel shape drawn in the section counts as area too.

**Returns:** Number - area; 0 when the call is refused (no section, an unresolved or NaN argument, an infinite orientation or ratio, a variation list in place of the section, a call while the project loads).

The function takes a section, not a variation list. A station-dependent section is taken at the caller's station. Called without one, it is read as it stands, as `sectionAg`, the section analysis and Engine3 (`pengine=2`, which has no caller station) read it. Either way the call records whether its value depends on the station, so a parameter computed from it is cached per station where the section varies and once where it does not, in any order of reads with and without a station. Recording that copies the section at the caller's station (none included) once per evaluation of the calling parameter.

#### `sectionRebarBottomRatio(section, orientation, ratio)`

The mild bars in the same band. **Returns:** `[A_s, d_s]`: their area, and the distance from the top of the turned section (the extreme compression fibre) to their centroid; `[0, 0]` when the band holds none or the call is refused. A bar on the band's line (within 1e-9 × the depth of it) counts at half its area, so the two halves of a section add up to the whole, and a ring of bars in diametrically opposite pairs (an even count), centred in a centrally symmetric outline such as a circle drawn with an even segment count, gets exactly half of them at every orientation (C5.7.2.8); an odd count gives one bar more on one side than the other, except where a bar lies on the line. At `ratio` 1 the band is the whole section and all its steel counts in full.

Two things the caller accounts for:

* Every bar counts at its full area. 5.7.3.4.2 reduces A\_s for a bar terminated less than its development length from the section, in proportion to its lack of development; this function does not.
* 5.7.2.8-2's d\_e takes the tension reinforcement. The half-depth set is that only on a circular member (C5.7.2.8). On a section with side bars the half-depth set holds them too, and d\_s comes out shallower than the main layer's, which is conservative.

#### `sectionTendonBottomRatio(section, orientation, ratio, mode, fpe, fps, memberDepth)`

The prestressing steel bonded to the concrete in the same band, with the same rule for steel on the line. A strand layout inside its debonded length does not count (the section analysis also leaves it out), and neither does an unbonded post-tensioning tendon (the section analysis keeps that one, at its prestrain). **Returns:** `[steel, d_p]`:

* `mode` 0 (default): steel = area.
* `mode` 1: area, each strand layout in proportion to its development, min(1, l\_px / l\_d) (5.7.3.4.2).
* `mode` 2: steel = force, each layout at f\_px: linear from 0 at the bonded end to `fpe` at 60 d\_b (5.9.4.3.2-2), then to `fps` at l\_d (5.9.4.3.2-3).

Modes 1 and 2 need finite stresses with `fps` > 0 and 0 ≤ `fpe` ≤ `fps`. Any other mode, or stresses outside that (a forgotten `fps`, or an infinite one, say), is refused with `[0, 0]`, as are a missing section, a NaN argument, an infinite orientation or ratio, and a bond distance that is not a finite number on a strand layout in the band (modes 1 and 2). Mode 0 reads neither stress, and an infinite `memberDepth` counts as not given, as a NaN one does.

`[0, 0]` means the band holds no bonded steel. Strands inside their debonded length (a `DebondingLength` that is not 0, a NULL one included, as in the section analysis) and unbonded tendons count as absent, so a band holding only those also gives d\_p 0. Where it holds bonded strands none of which counts, as at a bonded end in modes 1 and 2, the answer is `[0, d_p]`, with d\_p the depth of those strands, so a formula dividing by d\_p is not handed 0. A formula dividing by the steel must still guard it: on a girder without mild bars, 5.7.3.4.2's E\_s A\_s + E\_p A\_ps is 0 at a free end.

In modes 1 and 2, l\_d = κ (fps − 2/3 fpe) d\_b (5.9.4.3.2-1).

* κ is 1.0 for a pretensioned member up to 24 in deep and 1.6 deeper. The depth is `memberDepth` when given (pass the precast member's depth for a composite section) and the turned section's otherwise; a NULL, NaN, zero or negative `memberDepth` counts as not given.
* κ is 2.0 for a strand layout whose own `isDebonded` parameter is 1 (C5.7.2.8), whether or not the precompressed tensile zone is in tension, which is conservative. `isDebonded` is the layout's parameter, not the girder's: a section builder has to set it on each debonded strand layout. Without it a debonded strand takes 1.0 / 1.6, which overstates its development (unconservative).
* l\_px is the layout's distance to its nearer bonded end, the lesser of its `dToBondSt` and `dToBondEnd` parameters, which the library's section builder sets. A layout without either of them, or with a NULL one, or a post-tensioning tendon, counts in full (at `fps` in mode 2). A distance that is not a finite number refuses the call, even when the other one is missing or NULL, but only on a layout with a strand in the band: bond data elsewhere in the section does not take the band's steel away.
* The centroid is weighted the same way as the steel.
* The four bond parameters, `dToBondSt`, `dToBondEnd`, `isDebonded` and `DebondingLength`, are read at the caller's station, as the section's geometry is. Without one, the distances and `isDebonded` take each range's first value and `DebondingLength` is read at station 0, as the section analysis reads it. The layout's other parameters (strand count, tensioning) are read as the section analysis reads them.
* The development length uses the AASHTO equations as written: lengths in inches and stresses in ksi, the library's internal units.

For 5.7.3.4.2-4's A\_ps f\_po term, call mode 2 with `fpe` = `fps` = f\_po. That ramps f\_po over the transfer length only, as 5.7.3.4.2 says; mode 1 times f\_po would ramp it over l\_d, which is conservative.

```xml
<P N="shearAngle" V="iif(M_u .GE. 0, 0, pi)" />
<P N="A_ct" V="sectionAgBottomRatio(GirderSection, shearAngle, 0.5)" />
<P N="shearRebar" V="sectionRebarBottomRatio(GirderSection, shearAngle, 0.5)" />   <!-- [A_s, d_s] -->
<P N="shearTendon" V="sectionTendonBottomRatio(GirderSection, shearAngle, 0.5, 1, fpe, fps, GirderDepth)" />   <!-- [A_ps, d_p] -->
<P N="ApsFpo" V="sectionTendonBottomRatio(GirderSection, shearAngle, 0.5, 2, fpo, fpo, GirderDepth)" />   <!-- [A_ps f_po, d_p] -->
```

***

#### The section functions on a variation list: the section at a station

Every section function that reads a section's geometry or properties (`sectionA`, `sectionAg`, `sectionIy`, `sectionIz`, `sectionIzy`, `sectionCz`, `sectionCy`, `sectionRy`, `sectionRz`, `sectionQx`, `sectionQy`, `sectionDepth`, `sectionDepthMin`, `sectionDepthTypical`, `sectionWidth`, `sectionWidthMin`, `sectionWidthTypical`, `sectionExt`, `sectionShapeCoords`, `sectionPerimeter`, and the shape recognizer's `sectionShapeType`, `sectionShapeInfo`, `sectionPlateDims`, `sectionZy`, `sectionZz`) also takes a **variation list** in place of the section: the `[[Section, coordinate, variation, args...], ...]` list a station-dependent section is built from (`StaDepSectionData`; a girder exports its own as `staDepDataExported`), with the station as the second argument. The function then answers for the section the list defines **at that station**. For an in-range pair, gross-shape vertices use the FE station-dependent builder's vertex interpolation; endpoint/layout selection follows the rules and example below. That is exact on a `linear` stretch; on a `parabola` or `circle` stretch the vertex interpolation is origin-dependent (rows standing on their bottom follow the declared depth parabola, rows drawn about mid-depth run linearly, rows hung from their top bow the other way — the FE has the same quirk), so a load rating takes the list form on linear stretches only and interpolates its plate dimensions along the declared variation elsewhere.

* Without a station the first entry's section is answered; a station before the list's first coordinate or beyond its last answers that end entry's section (the FE itself keeps its last entry on both sides); a station that is not a number (NaN, a word) is refused. So `sectionA(list, sta) .GT. 0` does not tell an out-of-range station from one inside the list: find the entry at or before the station first, as the ratings do (`k = length(filter(list, x[1] .LE. sta)) - 1`, varying iff `0 <= k < length(list) - 1` and `list[k][2] .EQ. 'linear'`), and ask only then. A list that cannot be built (two entries whose sections have a different shape layout, an entry without drawn geometry) answers what a missing section gets: `0`, or the recognizer's not-recognised value.
* `sectionJ`, `sectionCw`, `sectionAy`, `sectionAz`, `sectionSCy` and `sectionSCz` answer `0` on a list: the local torsion solve under-reads a thin-walled section, and the others come from the section service for project sections only. Take J and Cw from the plate dimensions at the point (`sectionShapeInfo`) instead.
* The supported property calls default to `ignoreOption=1` (gross shapes only). An unreinforced list also supports `ignoreOption=0`. If any source row contains a rebar or tendon layout, requesting inclusive or reinforcement-only properties (`ignoreOption=0` or `2`) raises an unsupported-operation diagnostic: the geometric interpolation omits those layouts. This applies at exact rows, between rows, outside the list and to a single-row list, in both expression engines, including a reinforced/plain pair with different child structures. Malformed rows are still refused as missing sections. Query a section object for its reinforcement properties. This restriction does not change gross area, dimensions, coordinates or shape recognition. Explicit NULL/NaN property arguments after the station, including extra trailing arguments, return `0` in both engines.
* List clones evaluate the builder's numeric inputs at the requested station: X/Y/Z, RX/RY/RZ, rotation pivots AX/AY/AZ, corner R/C, point arc Segments, and circle radii/angles/resolution. Omitted transforms and corners default to zero; point arc Segments defaults to 6. Circle defaults follow its geometry getters (Radius 0.1, Radius2 falling back to Radius, StartAngle 0, EndAngle 2π, and the active resolution context). Equal Arc flags are retained. The memo distinguishes these inputs, material identity and yield properties, so an equal-elastic-modulus hybrid cannot reuse a uniform-material section's shape-recognition result.
* Plain Groups used only to collect a polygon's shallow Points do not apply their own frame; list keys and interpolation leave those unused frame expressions unread. Discovery Groups carrying independent Shapes retain their consumed frames. Retained endpoint/singleton rebar line layouts capture explicit `PositionFractions` in the source row's station context before clone writes; paired gross interpolation still omits those layouts.
* List interpolation supports materialized polygon points (including ordinary Group containers) and circles with matching child structures. Array-defined `Points` outlines consumed by the polygon geometry reader, changing consumed Arc/IsCutout flags or prototype inclusion between rows, and differing ancestor coordinate transforms raise explicit unsupported-operation diagnostics in both engines at all stations, including exact rows and outside clamps. Prototype outline points and Groups retain their exclusion. Use materialized point objects and matching ancestor frames for these lists. Ignored Circle children, display-only subtrees and metadata outside shape outlines do not participate in topology checks. Scalar section and FE builder behavior is unchanged.
* Rounded points (`R` nonzero and `Arc=false`) require positive integer `Segments`. A list request whose interpolation produces a fractional count raises a diagnostic; use constant integer resolution across rows when arbitrary query stations are needed. Arc points require finite positive `Segments`; positive fractions retain the existing geometry reader's ceil subdivision rule. Circles require a finite resolved `Segments` value, preserving their existing finite-count and omitted-default behavior. Source-row and frozen-result validation prevent these invalid counts from reaching geometry evaluation.
* Use section objects or lists in compiled formulas. Plain string section names are resolved by the interpreted engine's project lookup; existing compiled scalar getters and the newly added compiled getters accept section objects instead.
* A single-row list returns that row at every numeric station, including its exact coordinate. Outside a list with duplicate endpoint coordinates, clamping preserves the first/last input row order; exact-coordinate step selection still follows the first containing nonzero-length pair.
* The section at a station is memoised with at most 64 entries per pair's first row. Entries distinguish object identities, station-evaluated construction inputs, ancestor identities and actual frames, variation arguments and requested station. Repeated readings reuse the build but still compute that key without generating unfrozen source geometry. Active geometry filters bypass both memo lookup and insertion. Singleton, omitted-station and clamped-end clones retaining rebar/tendon layouts also rebuild on every call because their specialized geometry has additional inputs. Unfiltered simple numeric outlines, including strictly verified plain Group containers, keep their gross-only memo path; guarded or complex excluded subtrees rebuild prepared rows. Eviction is first-in, first-out: repeated sweeps over more than 64 distinct entries can rebuild every section. This bounds retained sections, not total computation time.
* Whole-list construction validation retains one snapshot per first-row Section, reused across equivalent fresh arrays only while the parameter-cache generation, full row references/stations, child identities/order and ancestor links match. Alternating distinct lists sharing that owner replace its snapshot and repeat admission. Active geometry filters bypass this reuse. Hits still inspect identities and compute the selected pair's construction/frame key; a build or invalidation can require full validation again. This is not a constant-time guarantee for long lists or dense outlines.

For example, let `S` contain a rectangle from `(0,0)` to `(4,10)` and a circular rebar layout with extents X `[-40,40]`, Y `[-30,30]`, and let `rows = [[S,100,'linear'],[S,200]]`:

| Station | Selection                      | `sectionExt(rows, station)` X/Y bounds |
| ------- | ------------------------------ | -------------------------------------- |
| 99      | first-row clone                | `[-40,40]` / `[-30,30]`                |
| 100     | in-range pair, exact first row | `[0,4]` / `[0,10]`                     |
| 150     | in-range pair                  | `[0,4]` / `[0,10]`                     |
| 200     | in-range pair, exact last row  | `[0,4]` / `[0,10]`                     |
| 201     | last-row clone                 | `[-40,40]` / `[-30,30]`                |

The endpoint clones retain layouts; paired interpolation omits them. `sectionDepth` and `sectionWidth` exclude these layouts throughout (10 and 4 here). Inclusive/reinforcement-only property options 0/2 are diagnosed throughout. The FE-at-point description refers to paired gross-shape vertices, and callers should use the documented selection rules for endpoint/layout extents.

**Example:**

```xml
<P N="ptList" V="sort(girder.staDepDataExported, x[1])"/>
<P N="ptK" V="length(filter(ptList, x[1] .LE. StationResolved)) - 1"/>
<P N="ptVary" V="iif(ptK .GE. 0 .AND. ptK .LT. length(ptList) - 1, iif(ptList[ptK][2] .EQ. 'linear', 1, 0), 0)"/>
<P N="ptA" V="iif(ptVary .EQ. 0, 0, sectionA(ptList, StationResolved))"/>
<P N="ptInfo" V="iif(ptA .GT. 0, sectionShapeInfo(ptList, StationResolved), [-1,0,0,0,0,0,0,0,0,0,0,0])"/>
```

***

#### `sectionDepth(section, station?)`

Returns the depth of a section at a given station.

**Parameters:**

* `section` (Section): The section object
* `station` (Number, optional): Station location

**Returns:** Number - Section depth

**Example:**

```xml
<P N="Depth" V="sectionDepth(GirderSection, 50)"/>
```

**Related:** `sectionWidth()`, `sectionExt()`

***

#### `sectionWidth(section, station?)`

Returns the width of a section.

**Parameters:**

* `section` (Section): The section object
* `station` (Number, optional): Station location

**Returns:** Number - Section width

***

#### `sectionExt(section, station?)`

Returns the extents (bounding box) of a section.

**Returns:** Object - {minX, maxX, minY, maxY}

***

#### `sectionPerimeter(section)`

Returns the length of the boundary reachable from outside a section. A cutout the section encloses is not included, so a pipe, HSS or box cell reports its outer boundary only; a cutout open to the outside (shear key, keyway, coped end) is part of the outer boundary and its exposed faces are counted. Touching or overlapping shapes are merged first, so only exposed edges count; separate parts each contribute their own outer boundary. A usable Perimeter property the section already carries (the section property calculation fills it, and a user can type one) is returned as is; otherwise the value is computed from the drawn shapes. A geometry edit clears the stored value so it is recomputed.

**Returns:** Number - Outer boundary length

**Arguments:** `sectionPerimeter(section, station, atCentroid, ignoreOption)` - only `section` is required. `ignoreOption` accepts the same values as the other `section*` functions; `IgnoreShapes` measures the reinforcement layout instead of the drawn shapes and never uses the stored value.

**Example:**

```xml
<P N="SkinPerimeter" V="sectionPerimeter(PileSection)"/>
```

**Related:** `sectionExt()`, `sectionDepth()`

***

#### `sectionShapeCoords(section)`

Returns coordinates defining the section shape.

**Returns:** Array of Point2D - Shape coordinates

***

#### `sectionShapeType(section, station?)`

Recognises the steel shape type from the section's drawn outline (the same geometry `sectionShapeCoords()` returns), for sections that carry geometry but no named dimensions, such as LARSA/B2K/IFC imports and hand-drawn shapes.

**Parameters:**

* `section` (Section): The section object. Pass a section **reference** (a parameter of type Section). A section **name** (a string) is looked up only by the interpreted engine; the compiled engine (Engine3) does not resolve names, the same as the other `section*` functions, so there a string returns the refusal (`-1`).
* `station` (Number, optional): Station location for a station-dependent section. If you leave it out, the interpreted engine uses the caller's station and the compiled engine (Engine3) uses the section's base geometry. Pass the station explicitly whenever the section varies along its length.

**Returns:** Number - a code from `OBPEnum_SteelSecShape`: `DoubSymISec=0`, `SingSymISec=1`, `ChannelSec=2`, `TubeSec=3`, `PipeSec=4`, `TeeSec=5`, `SingAngEqSec=6`, `SingAngUneqSec=7`, `DoubAngInContSec=8`, `DoubAngSepSec=9`, `SolidSec=10`. Returns **`-1`** when the shape is not recognised. It also returns `-1` for a null, unresolved or non-section argument, and for a station that is not a finite number. Never read `0` as a fallback, because `0` means a doubly symmetric I.

It refuses rather than guessing. These outlines return `-1`:

* filleted, sloped or tapered plates
* outlines made of several shapes. A mirrored back-to-back double angle is the only accepted exception.
* cover plates and stiffeners (they fail the area back-check)
* off-centre stems or webs that are not flush with a flange edge
* tube cells that are not a rectangle strictly inside a rectangle with equal side walls
* round outlines with fewer than 24 sides, so a 12- or 16-sided polygonal pile refuses rather than reading as a circle or pipe
* a round outline that crosses itself or winds more than once
* a pipe whose bore is not concentric, or is not strictly inside the outer ring with a positive wall
* any non-finite coordinate
* a section with no drawn Shape of its own (named dimensions only)

An outline of zero area (for example a cover plate drawn at thickness 0) is ignored.

`SolidSec` covers a rectangle, a trapezoid, a circle, a stadium and a symmetric chamfered rectangle. Other solid outlines refuse.

For outlines with chamfers or fillets, thin steps where two plates meet, turned a quarter turn, or boxes with overhanging flange plates, use `sectionShapeInfo()`.

***

#### `sectionPlateDims(section, station?)`

Reads the named plate dimensions a load rating needs from the section's outline. It uses the same analysis as `sectionShapeType()`, so the two never disagree. A plate-type code (I, channel, tee, angle, tube) is only returned when these dimensions also pass.

**Parameters:** as `sectionShapeType()`.

**Returns:** Array - `[conf, d, tw, bft, tft, bfb, tfb, numWeb]`, in the section's internal length units (the units `sectionShapeCoords()` uses).

* `conf` is **binary**: `1` means every check passed. `0` means do not use the values, and the whole vector is then `[0,0,0,0,0,0,0,0]`. This is also the result for a null, unresolved or non-section argument, and for a non-finite station.
* `d` is the **overall** depth for every type. Web depth is `d - tft - tfb`.
* `tw` is the thickness of **one** web or wall. A rectangular tube reports its side-wall thickness with `numWeb = 2`. Every other type reports `numWeb = 1`.
* `bft/tft` is the plate at the **top** of the outline and `bfb/tfb` the plate at the **bottom**:

| Type             | top (`bft`, `tft`)                               | bottom (`bfb`, `tfb`)                                                          |
| ---------------- | ------------------------------------------------ | ------------------------------------------------------------------------------ |
| I, channel       | top flange                                       | bottom flange                                                                  |
| Tee              | flange, if it is at the top; else `0, 0`         | flange, if it is at the bottom; else `0, 0`                                    |
| Angle            | horizontal leg, if it is at the top; else `0, 0` | horizontal leg, if it is at the bottom; else `0, 0` (`tw` is the vertical leg) |
| Rectangular tube | outer width, top wall                            | outer width, bottom wall                                                       |
| Solid rectangle  | width, `0`                                       | width, `0` (`tw` = width, `d` = height)                                        |

The following types get a type code from `sectionShapeType()` but return `conf = 0` here, because they have no named plates: pipe, double angle, and any solid that is not a rectangle (circle, trapezoid, stadium, chamfered rectangle).

**Example:**

```xml
<P N="pd" V="sectionPlateDims(fbSection)"/>
<P N="webDepth" V="iif(pd[0] .EQ. 1, pd[1] - pd[4] - pd[6], 0)"/>
```

**Related:** `sectionShapeType()`, `sectionShapeCoords()`, `sectionShapeInfo()`

***

#### `sectionShapeInfo(section, station?)`

The extended form of `sectionShapeType()` and `sectionPlateDims()` for outlines imported point by point. It recognises every outline those two recognise, and on top of that it:

* squares small corner chamfers and fillets back to the sharp corner, so an I, channel, tee, angle or tube drawn with its fillets or rounded corners reads as its nominal plates, however finely the curves are drawn. (A solid drawn with chamfered or rounded corners squares to `SolidSec` with `conf = 0`; see below.) A corner counts as small when each of its legs is at most half of the straight face it cuts into, and squaring changes the net area by at most 10%. Two limits follow for rounded tubes. With an outside corner radius of `2t`, a face must be at least about `8t` long, so thick rectangular HSS with a short side under about `8t` refuse (about 8% of the section database's rectangular HSS at design thickness). And a square HSS drawn at its nominal wall `t` exceeds the 10% up to about side/`t` = 8.1 (HSS 4x4x1/2 at nominal `t` is 8); it reads at the AISC design thickness;
* reads a thin step where two plates meet as part of the plate beside it, for example the extra corners a variable-section row is drawn with to match another row point for point (a rolled I drawn with 0.01 in legs at its web-to-flange corners to match a floor beam's flange-angle brackets). A step is a prismatic band between two others, no thicker than 5% of either, that spans the narrower one and lies within the wider one. It always joins the narrower one (the web or stem), so a flange keeps its drawn thickness and the web reads deeper, and the plates must still rebuild the outline's area within 2% (of the corner-squared outline when corners were squared). A band wider or narrower than both bands beside it (a fin, a groove) is not a step, nor is a band at the top or bottom of the outline or a thicker band; such outlines read as they did before. Two thin bands of like thickness in a row block each other (each is the other's neighbour); when one is at most 5% as thick as the other, the thinner merges first, into its narrower neighbour, and the other may then be a step. A thin plate on the inner face of a flange, between it and the web, is read as a step; a cover plate on the outer face is an end band and still refuses. Steps are merged only when nothing else reads the outline (an outline read without them, upright or turned, reads as before), and only on a single outline without a cut (an I, channel, tee or angle; a stepped tube or double angle still refuses). Because the limit is relative, 0.01 in legs need a flange at least 0.2 in thick (a W6X8.5 drawn that way still refuses); a step thinner than 1e-4 of the outline's height (its depth as drawn; its width for the quarter-turned reading) is below the level tolerance and is folded into the plate edges as before, so on a section about 100 in deep or more 0.01 in legs read as a web and a top flange about 0.01 in thicker;
* reads a rectangular tube whose top and/or bottom flange plate is wider than the webs, by any amount, when the overhang is centred and the plate is the tube's own wall;
* when the outline is not recognised upright, tries it turned a quarter turn, so an I-shape with its web horizontal (H orientation), a channel with its toes up or down, a tee with a horizontal stem or a stacked double angle is recognised. Only these four families are accepted turned; any other turned result refuses.

**Parameters:** as `sectionShapeType()`.

**Returns:** Array - `[type, conf, d, tw, bft, tft, bfb, tfb, numWeb, rot, bw, cornerR]`, refused `[-1,0,0,0,0,0,0,0,0,0,0,0]`.

* `type`, `conf` and `d` .. `numWeb` as `sectionShapeType()` and `sectionPlateDims()`, given in the shape's own upright frame. A tee turned a quarter turn reports its flange as `bft/tft` or as `bfb/tfb` depending on which way it was turned; read whichever pair is non-zero.
* **Squared plates are the circumscribing sharp-cornered plates.** Use them for width-to-thickness checks. Do not rebuild area, `S` or `Z` from them: for a rounded HSS they overstate the material by up to the 10% squaring limit (more in modulus). Take section properties from `sectionA()`, `sectionIy()` and `sectionZy()`. A squared solid returns `SolidSec` with `conf = 0`, as it does unsquared.
* `rot`: `1` when the shape is turned a quarter turn in the section, so bending about the section's horizontal axis is bending about the shape's y-axis (the axis of symmetry of a tee or double angle); `0` otherwise. That axis is usually, but not always, the minor principal axis: a double angle or a wide tee can be stiffer about it, so compare `sectionIy()` with `sectionIz()`.
* `bw`: for a tube, the outside width across the webs (equal to `bft` and `bfb` when no plate overhangs); `0` for other types. When a flange plate overhangs, `bft`/`bfb` is the full plate width: the flange between the webs is `bw - 2*tw` wide (stiffened), and each overhang, `(bft - bw)/2`, is an unstiffened projection.
* `cornerR`: for a tube whose four outer corners are drawn as curves, the mean corner size, which is the outside corner radius for circular corners; `0` for sharp or single-chamfer corners, for a tube whose flange plates overhang the webs, and for other types. A tube with rounded corners is normally a cold-formed HSS.

`sectionShapeType()` and `sectionPlateDims()` keep their own, narrower behaviour.

**Example:**

```xml
<P N="info" V="sectionShapeInfo(fbSection)"/>
<P N="weakAxis" V="info[9]"/>
```

**Related:** `sectionShapeType()`, `sectionPlateDims()`, `sectionZy()`

***

#### `sectionZy(section, station?)` / `sectionZz(section, station?)`

Plastic section modulus of the section's material region: `sectionZy` about the horizontal axis (the axis of `sectionIy`), `sectionZz` about the vertical axis. For a shape turned a quarter turn in the section (`sectionShapeInfo` `rot = 1`) the horizontal axis is the shape's own y-axis. The plastic neutral axis is found from the region itself, so singly symmetric shapes (tees, angles) are handled.

The region is built the way the section properties build it: the shapes are merged in the order they were drawn, each solid added and each cutout removed. Overlapping plates count once, a cutout removes only material that is there, and a cutout that a later shape fills again stays filled.

**Parameters:** as `sectionShapeType()`.

**Returns:** Number - in the section's internal length units cubed. **`0` means refused**; no real section has `Z = 0`. It is returned for:

* a section whose solid shapes differ in `E` or `Fy` (a girder with its deck drawn in, a concrete-filled tube, a hybrid girder), or where some shapes carry a material and others carry none. A shape without a material of its own takes its section's. Shapes of the same grade count as one material even when they reference different material objects. `Fy*Z` is an `Mp` only for one material; use the composite or transformed-section functions for these.
* a section without a drawn Shape of its own
* a null, unresolved or non-section argument, or a non-finite station
* a non-finite coordinate, or a region of no area

Guard every use: `iif(Zy .GT. 0, …, …)`. In particular, guard before dividing by it (`Sy/Zy`, `Mp/Myc`), where a `0` would give `Infinity` or `NaN` rather than a visible failure.

The value comes from the drawn geometry, including chamfers, fillets and rounded corners, so it differs from a rolled shape's tabulated `Z` exactly as far as the drawing differs from the rolled shape. For the outlines the section database draws, measured against the AISC tables:

* W shapes and WT: within about 4%. Equal angles: up to about 3% higher.
* M and HP shapes: up to about 10% and 5% **lower** (conservative).
* Rectangular tubes, drawn with sharp corners: up to about 16% **higher**, about both axes.
* Channels, S shapes and ST, drawn with flat (average-thickness) flanges: within about 2% about the horizontal axis, but up to about 16% (C, MC) and 11% (S, ST) **higher** about the vertical axis (`sectionZz`).
* Pipes: up to about 9% **higher**, because the outline uses the nominal wall and the AISC table uses the design wall.
* Round HSS: **do not use**. The database draws them from the rectangular-tube template without its dimensions, as a 44 x 44 box, so every function here returns a confident, wrong answer for them.
* Unequal angles: the database outline draws the long leg horizontal, while its tabulated values are about the axes of the long leg vertical, so compare them axis for axis with care.

The **higher** cases are unconservative for `Mp = Fy*Z`.

When the section has a tabulated `Z`, prefer it. The value from this function is for sections that have none.

**Example:**

```xml
<P N="Zh" V="sectionZy(fbSection)"/>
<P N="Mp" V="iif(Zh .GT. 0, Fy * Zh, 0)"/>
```

**Related:** `sectionShapeInfo()`, `sectionIy()`

***

#### `sectionHasTendon(section)`

Checks if section has post-tensioning tendons.

**Returns:** Boolean

***

#### `sectionHasRebar(section)`

Checks if section has reinforcing bars.

**Returns:** Boolean

***

#### `sectionIsComposite(section)`

Checks if section is composite.

**Returns:** Boolean

***

#### `interactionDiagram(section, ...)`

Generates interaction diagram data (P-M diagram): `interactionDiagram(section, orientation, εcu, εtl, φ compression, φ tension, refinement, useTendonInitStrain, axialCap, εcl)`.

**Returns:** Array - `[[M, P], ...]`, P compression positive, from the largest axial force down to P = 0. It is the compression part of the interaction surface's diagram at that orientation (the same states as `interactionCapacity` below: each integrated once, the moment signed about the centroid, steel bounded by its strain limit; where the concrete softens past its peak before εcu, the most nominal moment any admissible state carries at that nominal P, top fibre from the peak strain to εcu and the neutral axis below the section or in it, each point factored by φ of the εcu state at the same eccentricity; where φ turns the factored P back up the curve keeps the lower branch and steps out level). M is the capacity for moments that compress the side the orientation compresses and is never negative: where a state needs a moment the other way (a prestressed girder near pure compression in negative bending), the points run on the P axis. A non-zero `axialCap` (AASHTO 5.6.4.4) stops the diagram there: the first two points are `[0, cap]` and `[M at the cap, cap]` (one point when that M is 0 on the axis); a cap at or above the diagram's top caps it at the top.

**Example:**

```xml
<P N="PMDiagram" V="interactionDiagram(ColumnSection, 0, 100, 0.003)"/>
```

***

#### `interactionCapacity(section, P, My, Mz, ...)` and `interactionRatio(section, P, My, Mz, ...)`

Read off the section's interaction surface: diagrams every `step` degrees round the section. Unlike `interactionDiagram` at one orientation, they are right for a biaxial demand on a section that is not symmetric about the axis across the neutral axis, they tell the two faces apart, and they read tension too. P is compression positive; My and Mz are the frame element's (+My compresses the section's +y fibre, +Mz its +x fibre). Optional, in order: εcu (0.003), εtl (0.005), φ compression (0.75), φ tension (0.9), refinement (1000), εcl (0.002), step (10°).

* `interactionCapacity` returns the moment the section carries in the direction of (My, Mz) at **constant P**. It is **0** beyond the axial range, and where even a moment-free load fails at that P (an unsymmetric section near pure compression or pure tension, whose axial resultant there is off the centroid). Guard the division: demand/capacity at constant P is `sqrt(My^2 + Mz^2) / interactionCapacity(...)`.
* `interactionCurve(section, direction, ...)` returns the capacity to draw them against: `[[M, P], ...]`, the section of the surface by the vertical plane of `direction` (radians, the Orientation that compresses that side, as in `interactionDiagram`), M >= 0, a closed polygon whose edges on the P axis close it. Its optional arguments start at εcu.
* `interactionRatio` returns the **radial** ratio: |load| / |capacity along the ray from the origin through it|, the ratio the section editor's Interaction Diagram shows. 0 for no load. **-1** when there is no ratio: the section carries no load in that plane at all (no tensile capacity; the section editor then shows only whether the load is inside), the surface could not be built, an argument is missing or not a number, the section does not resolve, or the project is loading. **-1 is not a pass: guard it** (the example below reads it as 99).

Both: φ is applied as `interactionDiagram` applies it (only when φ compression and φ tension differ); no axial limit (apply AASHTO 5.6.4.4 yourself, as in the example); no axial-force or tendon-strain arguments. Every state of the surface is one the section can reach: concrete at most at εcu, every steel at most at its strain limit in tension (its material's failure strain in tension `esuTens` where given, else its stress-strain model's `esu`, else its material's, else 0.05; a tendon's total strain), so pure tension is the steel at that limit, whatever the refinement; moment curvature ends at the same limit, `momentCapacity` is not bounded by it (εcu, AASHTO 5.6.2.1); a bonded tendon is read at its total strain (prestrain + section strain) through its curve, so it keeps a reduced tension in the compressed zone (AASHTO 5.6.4.4-2) and never passes its curve's strength. The first call per section and set of inputs builds the surface (36 diagrams at the default step, about 0.2-6 s by refinement); later calls read its cache, which a section edit clears.

**Returns:** Number

**Example:**

```xml
<P N="Mcap" V="interactionCapacity(ColumnSection, Pu, Muy, Muz, 0.003, 0.005, 0.75, 0.9)"/>
<P N="ratio" V="interactionRatio(ColumnSection, Pu, Muy, Muz, 0.003, 0.005, 0.75, 0.9)"/>
<P N="DC" V="max(iif(ratio .GE. 0, ratio, 99), iif(P_r .GT. 0 .AND. Pu .GT. 0, Pu / P_r, 0))"/>
```

***

#### `crackedInertia(section, ...)`

Calculates cracked moment of inertia.

**Returns:** Number - Cracked inertia value

***

#### `maxRebarTensileStress(section, orientation, fx, moment, ecu, etl, phiComp, phiTens, refinement, useTendonInitStrain, ecl, prestressInLoads)`

Calculates maximum tensile stress in reinforcement under the axial force and moment. `prestressInLoads` = 1 when those forces already include the prestress (an FE service combination with the prestress load case): the tendons then carry no initial strain. Omit it for forces from the other loads only; omitting it for forces that include the prestress counts the prestress twice. With it, the moment is read about the centroid of the section's concrete outline (its shapes without the bar and tendon layouts: the axis a frame element whose section is that outline reports forces about) and moved onto the solver's axis, since the whole prestress is then in the axial force. That holds for every flagged call, sections without tendons included. `useTendonInitStrain` is ignored.

**Returns:** Number - Maximum stress

***

List guards are evaluated at each row's coordinate before selecting shapes and outline points. Matching selected topology can interpolate; changing guarded topology is diagnosed. Guard-bearing lists and complex excluded subtrees rebuild prepared rows per call and bypass result memoization. This includes containers outside the strict plain Group path, prototype/selection metadata and ignored child subtrees; simple numeric outlines retain memo reuse. Only live geometry consumers require container frames. Excluded clone branches are guarded out after required source reads so pair construction cannot evaluate their dormant expressions. The three retained endpoint layout types freeze the direct numeric inputs used by their geometry readers at the row coordinate; interpolated list reinforcement-inclusive properties remain unsupported. Layout detection for that diagnostic includes raw guarded layouts. Stock quantity-filter selection flags are retained, and incompatible consumed point/group selection in an interpolated pair is diagnosed. Arbitrary filters that rely on source object identity cannot be assumed to recognize a materialized clone.

For a list, `sectionPerimeter` always uses the materialized geometry under the requested ignore option, consistent with other list property reads. A stored source `Perimeter` constant or expression does not override it. Scalar section calls retain their stored-property shortcut.

### Alignment/Bridge Functions (OpenBrIM.Functions)

Available for bridge alignment operations. Defined in [Functions.ts](https://github.com/openbrim/platform/tree/master/docs/developers/llm-guides/Code/OBrIM/Functions.ts).

#### `alignHX(alignment, station, offset)`

Returns the global X coordinate on an alignment.

**Parameters:**

* `alignment` (Alignment): The alignment object
* `station` (Number): Station value
* `offset` (Number): Transverse offset from centerline

**Returns:** Number - X coordinate

**Example:**

```xml
<P N="PierX" V="alignHX(Centerline, 100, 0)"/>
```

**Related:** `alignHY()`, `alignHZ()`, `alignH()`

***

#### `alignHY(alignment, station, offset)`

Returns the global Y coordinate on an alignment.

**Parameters:** Same as `alignHX()`

**Returns:** Number - Y coordinate

***

#### `alignHZ(alignment, station, offset)`

Returns the global Z coordinate (elevation) on an alignment.

**Parameters:** Same as `alignHX()`

**Returns:** Number - Z coordinate

**Note:** This returns horizontal plane Z, use `alignV()` for vertical profile elevation.

***

#### `alignHA(alignment, station, offset)`

Returns the horizontal angle (bearing) of alignment at a station.

**Parameters:**

* `alignment` (Alignment): The alignment object
* `station` (Number): Station value
* `offset` (Number): Transverse offset

**Returns:** Number - Angle in degrees

**Example:**

```xml
<P N="BearingAngle" V="alignHA(Centerline, 50, 0)"/>
```

***

#### `alignH(alignment, station, offset)`

Returns all horizontal alignment data (X, Y, angle) at once.

**Parameters:** Same as `alignHX()`

**Returns:** Object - {X, Y, Angle}

**Example:**

```xml
<P N="HData" V="alignH(Centerline, 100, 5)"/>
<O T="Point" X="HData.X" Y="HData.Y"/>
```

***

#### `alignLocal(alignment, x, y, z)`

Converts global coordinates to local alignment coordinates (station, offset).

**Parameters:**

* `alignment` (Alignment): The alignment object
* `x`, `y`, `z` (Numbers): Global coordinates

**Returns:** Object - {Station, Offset}

**Example:**

```xml
<P N="LocalCoords" V="alignLocal(Centerline, 1000, 500, 0)"/>
<P N="Station" V="LocalCoords.Station"/>
```

**Related:** `alignH()`, `alignProjection()`

***

#### `alignProjection(sourceAlign, targetAlign, station, offset, ...)`

Projects a point from one alignment to another.

**Parameters:**

* `sourceAlign` (Alignment): Source alignment
* `targetAlign` (Alignment): Target alignment
* `station` (Number): Station on source
* `offset` (Number): Offset on source
* Additional parameters for projection method

**Returns:** Object - {Station, Offset} on target alignment

***

#### `alignT(alignment, station, offset)`

Returns transverse elevation at a station and offset.

**Parameters:**

* `alignment` (Alignment): The alignment object
* `station` (Number): Station value
* `offset` (Number): Transverse offset

**Returns:** Number - Elevation

***

#### `alignTA(alignment, station, offset)`

Returns transverse slope angle at a station and offset.

**Returns:** Number - Slope angle in degrees

***

#### `alignV(alignment, station)`

Returns vertical profile elevation at a station.

**Parameters:**

* `alignment` (Alignment): The alignment object
* `station` (Number): Station value

**Returns:** Number - Elevation from vertical profile

**Example:**

```xml
<P N="ProfileElev" V="alignV(Profile, 100)"/>
```

***

#### `alignvsag(alignment, startStation, endStation)`

Returns the stretches of the vertical profile between two stations that are sag curves (curving upward). A sag grade break, where two pieces meet with the grade rising, comes back as a range of almost no width around the break. With "Spans with a sag curve" chosen, Compute Linear Haunch straightens every span that holds part of one of these, from support to support, and also any span whose profile dips below its own chord by more than 1/16 in (1.5 mm) (a curve that reaches less than 1 ft, or 0.3 m in a metric project, into a span, or sits on a support, straightens a span only through that dip test). A profile that cannot be read (elevation points out of order), or a first argument that is not an alignment, returns an empty list.

**Parameters:**

* `alignment` (Alignment): The alignment object
* `startStation`, `endStation` (Number): The range to search

**Returns:** List - `[[from, to], ...]` station pairs, empty when there is no sag curve in the range

**Example:**

```xml
<P N="SagCurves" V="alignvsag(Centerline, 0, 1200)"/>
```

***

#### `alignA(alignment, station)`

Returns alignment angle (bearing) at a station.

**Parameters:**

* `alignment` (Alignment): The alignment object
* `station` (Number): Station value

**Returns:** Number - Bearing angle

***

#### `alignLength(alignment, ...)`

Returns the total length of an alignment.

**Returns:** Number - Alignment length

***

#### `alignRad(alignment, station, ...)`

Returns the horizontal radius at a station.

**Returns:** Number - Radius (positive for curves, very large for tangents)

***

#### `stationDifference(alignment, station1, station2, ...)`

Calculates the difference between two stations accounting for equations.

**Returns:** Number - Station difference

***

#### `verticalClearance(alignment, ...)`

Calculates vertical clearance at a location.

**Returns:** Number - Clearance value

***

#### `CutFillPolygon(surface1, surface2, ...)`

Generates cut/fill polygons between two surfaces.

**Returns:** Array - Cut and fill regions

***

#### `SplitPolygonByLine(polygon, line, ...)`

Splits a polygon by a line.

**Returns:** Array - Split polygon pieces

***

#### `mto(objects, ...)`

Performs material take-off calculations.

**Returns:** Object - Material quantities

***

#### `alignLine(alignment, startStation, endStation, ...)`

Extracts a line segment from an alignment between stations.

**Returns:** Line3D

***

#### `stressStrainCurvePoints(material, ...)`

Returns points on a material stress-strain curve.

**Returns:** Array - Curve points

***

#### `lineProjection(line, targetAlignment, ...)`

Projects a line onto an alignment.

**Returns:** Object - Projection data

***

#### `pointProjection(point, targetAlignment, ...)`

Projects a point onto an alignment.

**Returns:** Object - {Station, Offset}

***

#### `controlLocations(alignment, ...)`

Returns control point locations on an alignment.

**Returns:** Array - Control points

***

#### `alignHCenter(alignment, station, ...)`

Returns horizontal center point at a station.

**Returns:** Point

***

#### `convertToLocal(alignment, point, ...)`

Converts a point to local alignment coordinates.

**Returns:** Object - {Station, Offset, Elevation}

***

### Finite Element Analysis Functions (FEA.Functions)

Available when FEA analysis is performed. Defined in [Functions.ts](https://github.com/openbrim/platform/tree/master/docs/developers/llm-guides/Code/FEA/Functions.ts).

#### `feobj(objectName, paramName?, repeat?, index?)`

Retrieves a finite element object or its parameter value.

**Parameters:**

* `objectName` (String): Name of FEA object
* `paramName` (String, optional): Parameter name to retrieve
* `repeat` (Number, optional): Repeat index
* `index` (Number, optional): Sub-index

**Returns:** Object or Value - FEA object or parameter value

**Example:**

```xml
<P N="NodeDisp" V="feobj('Node1', 'UZ')"/>
```

***

#### `appliedmass(case)`

The one-line mass summary an eigen or time-history case shows in its **Applied Mass** cell, e.g. `Self mass × 1 + DC1 × 1` or `Self mass × 1 + STG_DW × 1 (loads of 4 of 5 stages)`. It reads the case's inputs only and needs no analysis results. A mass case a library object generates is named by that object (`DC1`, not `DC1.ACASE`). Defined in [AnalysisCaseEigen.ts](https://github.com/openbrim/platform/tree/master/docs/developers/llm-guides/Code/FEA/Loads/Eigen/AnalysisCaseEigen.ts) (`AppliedMassOf`). Library Verify gates compare this text word for word.

**Parameters:**

* `case` (AnalysisCaseEigen or AnalysisCaseTimeHistory). Pass the object: a name resolves to the first object of that name in the project, and every library RSA case names its core case `RSACASE`.

**Returns:** text; `""` when the argument is not an eigen or time-history case. A stage mass case reads `(loads of K of N stages)`: the loads of the K stages of its N-stage chain set to **Include Mass**, the chain cut at the stage the case runs in when it is attached to one stage. Evaluated in a compile, its nodal-mass count (`N nodal masses`) sees only the NodeMass objects compiled before the case, and the stage cut only the Construction Stage Loadings compiled before it: place the loading before the case.

**Example** (the library RSA case's read-only column):

```xml
<P N="o_AppliedMass" V="|appliedmass(RSACASE)|" T="Text" D="Applied Mass" Role="Input" Category="Modal Parameters" />
```

***

#### `activeelemscog(objects, stageOrCase, masses?)`

Center of gravity, weight and mass of the FE elements of model objects or FE groups that are present in a construction stage, plus optional additional masses from loads. It reads the **compiled** model and needs no analysis results. Defined in [GroupMass.ts](https://github.com/openbrim/platform/tree/master/docs/developers/llm-guides/Code/FEA/GroupMass.ts).

**Parameters:**

* `objects` (an object, an FEGroup, a list of them, or names): what is weighed.
  * **A model object** (a library object such as a girder, deck, truss member or pier, or any other object): the FE elements it created — the mesh the 3D view's Hide takes with the object. An element belongs to the object when its `Origin` (the path of names the compiler stamps on it) runs through the object's own path.
  * **An FEGroup:** the group's elements.
  * An element reached through several of the given objects or groups is counted once.
* `stageOrCase` (ConstructionStage, AnalysisCase, name, or `NULL`):
  * **A construction stage:** the elements present at the end of it. The stage chain is replayed from the root, as the solver replays it:
    * a stiffness state adds its elements;
    * a stiffness-less state with gravity self-weight adds them as weight only (wet concrete weighs before it is stiff);
    * any other stiffness-less state (a removal, or a deconstruction that reverses the weight) takes them out;
    * within one stage, a state that adds an element wins over one that takes it out, whatever their order, and a stage with an active group (`Group`) touches only the elements that group admits;
    * a state is read through its `Group`; the rare `Obj` form is not read.
  * **An analysis case:** weighed in the construction stage it runs in. A case that runs in no stage weighs the elements its `IsElementActive` admits.
  * **A combination:** refused, because it is not one structure.
  * **`NULL`:** every element of the objects and groups (the completed structure).
  * **Anything else** that does not resolve (`0`, `''`, an unknown name) returns zeros with a console warning. It never falls back to the completed structure.
  * A guarded-out member, such as the `STAGE` of a stage that is switched off, also reads `NULL`. Guard it in the caller (see the example).
* `masses` (optional: a load, a load object, a group of them, or a list): loads that are mass, such as a wearing surface, barriers, catwalks or a haunch modelled as loads.
  * A load object or a group gives the FE loads it created, found by `Origin` as elements are. FE loads of every kind count: surface, line and point loads, nodal loads, element line and surface loads. The nodal loads a compile makes of a point load (or of a load converted to nodal loads, or taken over by a stage's tributary transfer) carry no `Origin`, so a load counts once, as itself.
  * A load case gives no loads: its set holds those nodal loads beside the point load they were made of, and would count it twice. An FE group or a member gives none either. The Center of Gravity report's Additional Masses input takes static load objects only (`T="OBPBase_StaticLoad"`).
  * Each FE load counts as the net downward total of its global nodal forces, / g, spread over the nodes it pushes down: the load's own distribution, the one the LOADING view draws (where the solver moves a load, by a stage's tributary transfer or a staged surface load's erection mask, the mass stays where the load puts it). Eigen analysis turns a Mass Case into mass the same way (vertical force only); unlike a Mass Case, an upward force adds nothing, and the vertical forces of a moment's couple cancel.
  * How much of a load counts depends on the case: under `NULL`, every load that has a load case, at 1; for a construction stage (or a case run in one), the sum of the `Factor`s of the ConstructionStageLoadings that attach its case to that stage or one before it in its chain (a case removed later at -1 sums to 0 and drops out; one attached twice counts twice), leaving out the cases that run apart from the stage and generated weight-only rows, as the solver's stage sum does; for a case run in no stage, its own loads at 1; for a combination, none.
  * A load that pushes nothing down, or that cannot be distributed (no group, no element), adds nothing. Only an exception during the distribution logs a console warning; the CG report names the picked items that weigh nothing.
  * The additional masses add to `W`, `M`, the CG and the moments of inertia; `n` stays the number of elements.

**Returns:** `[Xcg, Ycg, Zcg, W, n, M, Ixx, Iyy, Izz, Ip]`, all in the calling object's internal units (for a library instance, those of the host project).

* The CG is in global coordinates; `W` is the weight.
* `n` is the number of elements that contributed weight, so "nothing found" (`n = 0`) is not mistaken for a CG at the origin.
* `M` is the mass, W / g, with the g eigen analysis uses, in force·time²/length (UT `Mass`).
* `Ixx`, `Iyy`, `Izz` are the mass moments of inertia about axes through the CG parallel to the global axes (UT `MassInertia`). Each element adds its own term as well as its parallel-axis term:
  * a line is a rod, (m/12)·d dᵀ, between its two ends' section mass centroids, plus its cross-section's own spread about that centroid, on the section's local axes. A single-material section uses its geometric properties, (m/A)·(Iz ŷŷᵀ + Iy ẑẑᵀ + Izy (ŷẑᵀ + ẑŷᵀ)), not analysis overrides. A composite section's stored properties are transformed by stiffness, so its mass properties are integrated over its shapes, each with its own density, and each end moves from the section's stored centroid (where the element is drawn) to its mass centroid;
  * a shell is one or two triangles, plus m·t²/12 across its thickness;
  * a solid is spread over its vertices (exact for a parallelepiped; approximate for other shapes).
* `Ip` is the polar mass moment of inertia about the bridge's longitudinal axis through the CG (UT `MassInertia`). That axis follows the alignment: every element is placed from its global position in one frame of the alignment carrying most of the weight, as its station, its offset, and its height above the profile grade line measured square to the grade. So on a curved bridge `Ip` is the sum of each section's polar moment about its own local axis, not the moment about one straight axis.
  * Objects authored with absolute elevations (`AlignV="Ignore"`: column bents, arches, hangers) or global coordinates (`AlignH="Ignore"`: precast intermediate diaphragms) land in the same frame as the deck.
  * Cross slope does not enter: offset and height are measured square to each other.
  * Without an alignment the frame is global and `Ip` equals `Ixx`, about global X whatever the structure's direction. With no element counted (only additional masses, say in a stage before the members exist), the alignment of the loads' nodes gives the frame.
  * The frame follows the alignment's profile: a structure that does not (a graded deck on a flat profile) gets its rise counted as height.
  * A selection spanning two alignments is measured on the heavier one.

Element weights are physical and unfactored:

* lines: offset-inclusive length × the area the solver's self-weight uses (`FELine.SectionArea`, which honours `PropSecAx`, `PropSecAxFac` and `PropSec`, so a member given a stiffened axial property weighs that way here as in the analysis) × unit weight;
* shells: area × thickness × unit weight (the real thickness, not the stiffness override);
* solids: volume × unit weight.

What is not counted:

* A construction state's self-weight factor (e.g. a girder `swFactor` allowance) is not applied.
* The solver's line self-weight uses the length without section offsets, so it can differ slightly for non-prismatic members.
* Nodes, springs, constraints and tendons carry no weight.
* Loads applied through load cases (haunch, SIP forms, wearing surface) are not included unless they are passed as `masses`.

Positions include end offsets and the section centroid offset. Before the first compile, and while a recompile runs, the function returns zeros (`n = 0`).

**Example** (from a library object: each picked object's own FE group, `ObjFEGroup`, when it has one, else the object itself):

```xml
<P N="cogObjects" V="[G1,G2,Deck1,TR1]" T="ExtObj" Role="Input" />
<P N="stg" V="NULL" T="OBPBaseConstructionStage" Role="Input" />
<O T="Export">
    <!-- a switched-off stage has no STAGE: pass a name of nothing so it reads zeros, not "all" -->
    <P N="cogCase" V="iif(stg .EQ. NULL,NULL,stg.STAGE .EQ. NULL,'inactive stage',stg.STAGE)" />
    <P N="cogSel" V="map(cogObjects,iif(x.ObjFEGroup .EQ. NULL,x,x.ObjFEGroup))" />
    <P N="DCG_Result" V="activeelemscog(cogSel,cogCase)" />
</O>
```

#### `activeelemsbreakdown(rows, stageOrCase, massRows?)`

`activeelemscog`'s polar mass moment of inertia, broken down member group by member group, for a report that shows the calculation (the Center of Gravity report's per-length table). Defined in [GroupMass.ts](https://github.com/openbrim/platform/tree/master/docs/developers/llm-guides/Code/FEA/GroupMass.ts).

**Parameters:**

* `rows`: `[[label, objects, tag?], ...]`. Each row's `objects` (an object, an FEGroup, or a list of them) are resolved as `activeelemscog` resolves them. An element that several rows reach counts in the first, so a hand-picked group placed before the rows by type keeps its elements. A label that names a library object type (`OBPFloorBeam`) reads as that type's label (`Floor Beam`), also when words follow it (`OBPTruss (left)` reads `Truss (left)`).
* `stageOrCase`: as for `activeelemscog`.
* `massRows` (optional): `[[label, loads, tag?], ...]`, rows of additional mass after the element rows. Each row's loads, load objects or groups are weighed as `activeelemscog`'s `masses`; a load that several rows reach counts in the first.

**Returns:** `[rows, total, alignment, sMin, sMax, structure]`, in the calling object's internal units:

* each row `[label, n, W, M, offset, height, J, offsetMin, offsetMax, tag, station, mass]`: elements counted (on a row of additional mass, its FE loads that weighed), weight, mass, the centroid's offset from the alignment (positive to the left) and height above the profile grade line, `J`, the row's polar mass moment of inertia about its own centroid, how far the row's elements reach to either side, by their nodes (a row crossing the alignment, a floor beam or the deck, has `offsetMin < 0 < offsetMax` however coarsely it is meshed; one beside it, a truss or an edge girder, does not), the input row's third value unchanged (a colour, say, which so stays with its row through a filter), the centroid's station, and `mass`, 1 on a row of additional mass and 0 on an element row;
* `total`: `[n, W, M, offset, height, Ip]` for all rows together, `n` counting the elements only;
* `alignment`: the name of the alignment the section is measured on;
* `sMin`, `sMax`: the stations the counted elements span;
* `structure`: `total` for the element rows alone, without the additional masses.

Every row is placed in ONE frame, that of the alignment carrying most of the elements' weight (with no element counted, only additional masses, the alignment of their loads' nodes), so the rows add up: `Ip = Σ (J + M·d²)`, with `d` the distance of a row's centroid from the whole centroid in the section. `Ip` equals `activeelemscog`'s for the same elements and masses to rounding (the rows sum in a different order: about 1e-15 relative).

**Example** (named rows first, then the picked objects by type):

```xml
<P N="named" V="[['Edge girders',[G1,G4]]]" />
<P N="types" V="map(unique(objs,o=>o.T),o=>o.T)" />
<P N="typeRows" V="map(types,ty=>[ty,filter(objs,o=>o.T .EQ. ty)])" />
<P N="BD" V="activeelemsbreakdown(concat(named,typeRows),NULL)" />
<P N="IpPerL" V="BD[1][5]/(BD[4]-BD[3])" />
```

#### `activeelemsbays(rows, stageOrCase, massRows, stations, tolerance?)`

The section's mass bay by bay: `activeelemsbreakdown`'s whole-length totals, between bay boundaries, for a report that gives the mass and polar mass moment of inertia per unit length per bay (the Center of Gravity report's Bay by Bay section). Defined in [GroupMass.ts](https://github.com/openbrim/platform/tree/master/docs/developers/llm-guides/Code/FEA/GroupMass.ts).

**Parameters:**

* `rows`, `stageOrCase`, `massRows`: as for `activeelemsbreakdown` (`massRows` may be `[]`).
* `stations`: the bay boundaries, in the caller's units: the floor beams' stations, the support lines', or any list. A station given twice counts once. Stations closer than a tenth of the gaps outside them are one boundary, at their mean: a double floor beam, three at one panel point, also when every floor beam is doubled (the end pairs included). A short end span stays a bay unless it is under a tenth of the span beside it. Such a merged boundary covers its stations from first to last.
* `tolerance` (default 0.01): how close a bay's mass and Ip per unit length must be to a group's first bay to join the group, as a fraction (0.01 is 1%).

Each element is cut at the boundaries: a line is split where it crosses one, a shell is clipped along it, a solid goes whole to the bay its centroid is in. A piece, or a load's node, on a boundary (a floor beam square to the alignment, or any floor beam of a merged boundary) goes half to each side; on the first or last boundary it goes wholly to the bay beside it, so such an end floor beam stays in the bays, and the first and last bays run to that boundary's outer station. A skewed floor beam is cut like any member, and its part before the first boundary is in the row before it. The sums are taken about a point of the section, not the frame's axis, so a model without an alignment (offsets in state-plane coordinates) keeps its digits.

**Returns:** `[bays, groups, stations]`, in the calling object's internal units, all three empty when fewer than two boundaries are left:

* `bays`: `[[from, to, W, M, offset, height, Ip, kind], ...]`. `kind` is 0 for a bay between two boundaries, -1 for what lies before the first boundary and 1 for what lies after the last (those two are listed only when they weigh something). Offset and height place the bay's centroid; `Ip` is about it. The bays' `W` add up to the breakdown's.
* `groups`: `[[first, last, from, to, W, M, offset, height, Ip], ...]`: runs of consecutive bays (kind 0, numbered from 1) within `tolerance` of the run's first bay, with the run's own totals.
* `stations`: the boundaries used.

**Example** (the floor beams' stations from a one-row-per-object breakdown, whose rows carry the object as their tag and the centroid's station at index 10):

```xml
<P N="objBD" V="activeelemsbreakdown(map(objs,o=>['',[o],o]),NULL)" />
<P N="fbSta" V="map(filter(objBD[0],r=>r[1] .GT. 0 .AND. r[9].T .EQ. 'OBPFloorBeam'),r=>r[10])" />
<P N="Bays" V="activeelemsbays(typeRows,NULL,[],fbSta,0.01)" />
<!-- the bays proper: rows of kind 0, not what lies before the first boundary or after the last -->
<P N="Inner" V="filter(Bays[0],b=>b[7] .EQ. 0)" />
<P N="FirstBayIpPerL" V="Inner[0][6]/(Inner[0][1]-Inner[0][0])" />
```

***

#### Dynamic Output Functions

FEA provides dynamic functions based on analysis results. Common patterns:

**Force Functions:**

* `force(element, loadCase, component)` - Element forces
* `forceN(element, loadCase)` - Axial force
* `forceV(element, loadCase)` - Shear force
* `forceM(element, loadCase)` - Moment

**Displacement Functions:**

* `disp(node, loadCase, component)` - Node displacements
* `dispX(node, loadCase)` - X displacement
* `dispY(node, loadCase)` - Y displacement
* `dispZ(node, loadCase)` - Z displacement

**Stress Functions:**

* `stress(element, loadCase, component)` - Element stresses
* `stressXX(element, loadCase)` - Normal stress XX
* `stressVM(element, loadCase)` - Von Mises stress

**Example:**

```xml
<P N="MaxDisp" V="dispZ('MidspanNode', 'LiveLoad')"/>
<P N="Moment" V="forceM('GirderElement', 'DeadLoad')"/>
```

***

#### `forceNeg(component, elementPath, loadCase, station?)`

Retrieves the negative (minimum) force/moment value from analysis results.

**Parameters:**

* `component` (String): Force component ('N', 'V', 'M', 'Mx', 'My', 'Mz', etc.)
* `elementPath` (String): Full path to the element (use `fullname()` for dynamic paths)
* `loadCase` (String): Load case or combination name
* `station` (Number, optional): Station location along element

**Returns:** Number - Negative (minimum) force value

**Example:**

```xml
<P N="MaxNegativeMoment" V="forceNeg('My', Girder.N + '.MainSpan', 'DeadLoad')"/>
<P N="MinShear" V="forceNeg('V', fullname(Beam) + '.Section', LoadCase, Station)"/>
```

**Use Cases:**

* Finding maximum negative moments for bottom flange design
* Determining compression forces for member design
* Envelope analysis across multiple load cases

**Related:** `forcePos()`, `forceM()`, `fullname()`

***

#### `forcePos(component, elementPath, loadCase, station?)`

Retrieves the positive (maximum) force/moment value from analysis results.

**Parameters:**

* `component` (String): Force component ('N', 'V', 'M', 'Mx', 'My', 'Mz', etc.)
* `elementPath` (String): Full path to the element
* `loadCase` (String): Load case or combination name
* `station` (Number, optional): Station location along element

**Returns:** Number - Positive (maximum) force value

**Example:**

```xml
<P N="MaxPositiveMoment" V="forcePos('My', Girder.N + '.MainSpan', 'LiveLoad')"/>
<P N="MaxTension" V="forcePos('N', fullname(Cable), Combination)"/>
```

**Use Cases:**

* Finding maximum positive moments for top flange design
* Determining tension forces for member design
* Strength envelope calculations

**Related:** `forceNeg()`, `forceM()`, `fullname()`

***

#### `fullname(object)`

Returns the full hierarchical path name of an object, including all parent object names.

**Parameters:**

* `object` (Object or Parameter): The object to get the full path for

**Returns:** String - Full dot-notation path (e.g., "Project.Bridge.Girder1")

**Example:**

```xml
<P N="ElementPath" V="fullname(Girder)"/>
<!-- Result: "BridgeModel.Superstructure.Girder1" -->

<P N="Forces" V="forceNeg('My', fullname(Beam) + '.Comb', LoadCase, Station)"/>
<!-- Dynamically constructs path like "Bridge.Beams.Beam1.Comb" -->
```

**Use Cases:**

* Dynamically constructing element paths for analysis queries
* Building unique identifiers for objects in repeats
* Debugging parameter resolution issues
* Creating reports with full object references

**Common Pattern - Force Queries in Repeats:**

```xml
<O T="Repeat" N="GirderChecks" S="0" E="length(Girders)-1" I="1" CTRL="i" i="0">
  <P N="CurrentGirder" V="Girders[i]"/>

  <!-- Use fullname to construct dynamic path -->
  <P N="MomentDL" V="forceM(fullname(CurrentGirder), 'DeadLoad')"/>
  <P N="MomentLL" V="forceM(fullname(CurrentGirder), 'LiveLoad')"/>
</O>
```

**Related:** `forceNeg()`, `forcePos()`, `feobj()`

***

#### `tshortTermLoss(tendon, point)`

Calculates short-term prestress losses in a tendon.

**Parameters:**

* `tendon` (Tendon): The tendon object
* `point` (Number or Point): Evaluation point

**Returns:** Number - Stress loss

***

#### `getPushoverSubStageNames(analysisCase, ...)`

Returns substage names from a pushover analysis.

**Returns:** Array of Strings - Substage names

***

#### `getPushoverLambda(analysisCase)`

Returns the converged load multiplier (λ) of each pushover step, in step order (parallel to `getPushoverSubStageNames`). Each value is the accumulated total load factor at that step, not a per-step increment. For displacement-controlled pushover this is the solver's converged load multiplier; for force-controlled pushover it is the applied load factor.

**Parameters:**

* `analysisCase` (String): Full name of the pushover analysis case, e.g. `pushoverCase.N+'.PUSHOVERCASE'` (object references are not resolved)

**Returns:** Array of Numbers - Load multiplier per step. Returns an empty array when no analysis results are available, and for displacement-controlled results saved by builds that predate this function (rerun the analysis to populate λ).

**Example:**

```xml
<P N="lambdaSteps" V="getPushoverLambda(pushoverCase.N+'.PUSHOVERCASE')"/>
```

**Related:** `getPushoverSubStageNames()`, `getPushoverHingeNames()`, `getPushoverHingeStatus()`

***

## Math Functions

Handled in `Eval._gFunc` (`Code/PML/Eval.ts`). These names are matched without regard to case (`ROUND` works like `round`). All return a number unless noted.

| Function                                                           | Returns                                                                                                                                                                                                                |
| ------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `abs(x)`, `exp(x)`, `log(x)`                                       | Absolute value; e^x; natural logarithm                                                                                                                                                                                 |
| `sqrt(x)`                                                          | Square root. A negative `x` stops the compile with an error naming the expression                                                                                                                                      |
| `pow(x, y)`                                                        | x^y (same as `x ^ y`)                                                                                                                                                                                                  |
| `mod(a, b)`                                                        | Remainder of a / b, same as `a % b` (takes the sign of `a`)                                                                                                                                                            |
| `round(x, decimals?)`, `ceil(x, decimals?)`, `floor(x, decimals?)` | Rounded to the nearest, next higher or next lower value. The optional second argument is the number of decimal places: `round(3.14159, 2)` = 3.14; a negative count rounds to tens, hundreds: `round(1234, -2)` = 1200 |
| `min(a, b, ...)`, `max(a, b, ...)`                                 | Smallest / largest of the arguments. For the smallest or largest item of a list use `minl` / `maxl`                                                                                                                    |
| `sin(a)`, `cos(a)`, `tan(a)`                                       | Trigonometric functions of an angle in radians                                                                                                                                                                         |
| `asin(x)`, `acos(x)`, `atan(x)`                                    | Inverse functions, in radians: asin and atan in -PI/2..PI/2, acos in 0..PI                                                                                                                                             |
| `atan2(y, x)`                                                      | Angle of the point (x, y) from the +X axis, in radians, -PI..PI. The first argument is y                                                                                                                               |
| `sinh`, `cosh`, `tanh`, `asinh`, `acosh`, `atanh`                  | Hyperbolic functions and their inverses                                                                                                                                                                                |
| `quad(a, b, c)`                                                    | The two roots `[x1, x2]` of a·x² + b·x + c = 0 (NaN when the roots are complex)                                                                                                                                        |
| `cubic(a, b, c, d)`, `quar(a, b, c, d, e)`                         | Roots of a cubic / quartic equation                                                                                                                                                                                    |
| `range(n)`                                                         | List `[0, 1, ..., n-1]`                                                                                                                                                                                                |
| `random()`                                                         | A pseudo-random number, 0 or more and less than 1. Never cached: anything computed from it is recomputed                                                                                                               |

### Constants

Constant names are matched without regard to case (`Param.Constants`, `Code/PML/Param.ts`). They are reserved: a parameter with one of these names can never be read by a formula.

* Math: `PI`, `euler` (e = 2.71828...; there is no `E` constant), `ln2`, `ln10`, `log2e`, `log10e`, `sqrt1_2`, `sqrt2`
* Yes/no: `yes` = 1, `no` = 0, `none` = 0
* Alignment rules: `orient` = 1, `warp` = 2, `ignore` = 3, `fixed` = 3; sides: `center` = 0, `left` = 1, `right` = 2, `top` = 1, `bottom` = 2
* Unit names, used by the Unit object: `inch`, `feet`, `yard`, `millimeter`, `centimeter`, `meter`, `mile`, `kilometer`, `pound`, `kip`, `newton`, `kilonewton`, `meganewton`, `kilogramforce`, `ton`, `metricton`, `uston`, `celsius`, `fahrenheit`, `second`, `minute`, `hour`, `degree`, `degrees`, `radian`
* Material kinds: `steel` = 1, `concrete` = 2, `rebar` = 3, `prestress` = 4
* `myself`: the object that holds the parameter; `self`: the nearest library-object instance that contains it (the project when there is none), as in `self.N` (`ParamFunc.MySelf`, `ParamFunc.Self`)

***

## Best Practices

### 1. Use Functions Directly

All ParamML functions can be called directly in expressions. The execution context is handled automatically by the evaluation engine, so you never need to provide it manually.

### 2. Check Array Lengths

Before accessing array elements, verify the array has sufficient length:

```xml
<P N="Value" V="length(Points) > 0 ? first(Points).X : 0"/>
```

### 3. Use Appropriate Units

Always specify unit types for physical quantities:

```xml
<P N="BeamLength" V="linel(Centerline)" UT="Length" UC="Default"/>
```

### 4. Handle Null Returns

Some functions may return null (e.g., `intersect()` if lines don't intersect). Use guards:

```xml
<P N="Guard" V="intersect(Line1, Line2) != NULL"/>
<P N="IntX" V="intersect(Line1, Line2).X"/>
```

### 5. Leverage Object Hierarchy

Use the parametric tree structure with `parent()` and `project()`:

```xml
<P N="ProjectWidth" V="project().Width"/>
<P N="ParentLength" V="parent(self).Length"/>
```

### 6. Optimize Performance

* Cache expensive calculations in parameters
* Use `value()` for station-dependent parameters instead of recalculating
* Prefer built-in functions over custom implementations

### 7. Document Complex Expressions

Use parameter descriptions to explain complex function usage:

```xml
<P N="Capacity" V="momentCapacity(Section, 0, 0.003, Axial)"
   D="Moment capacity at 0.003 strain with axial load"/>
```

***

## Common Usage Patterns

### Creating Points Along a Line

```xml
<O T="Repeat" N="StationPoints" S="0" E="NumStations - 1" I="1" CTRL="i" i="0">
  <O T="Point" N="Pt" X="onliner(Baseline, i/(NumStations-1)).X" Y="onliner(Baseline, i/(NumStations-1)).Y" Z="onliner(Baseline, i/(NumStations-1)).Z" />
</O>
```

### Alignment-Based Geometry

```xml
<O T="Point" N="BridgePoint" X="alignHX(Centerline, Station, Offset)" Y="alignHY(Centerline, Station, Offset)" Z="alignV(Centerline, Station)+alignT(Centerline, Station, Offset)">
  <P N="Station" V="100" Role="Input"/>
  <P N="Offset" V="10" Role="Input"/>
</O>
```

### Conditional Geometry Based on Analysis

```xml
<P N="RequireStiffener" V="forceM('Girder', 'Ultimate') > AllowableMoment ? 1 : 0"/>
<O T="Plate" N="Stiffener">
  <P N="Guard" V="RequireStiffener == 1"/>
  <!-- Stiffener geometry -->
</O>
```

### Section Property Queries

```xml
<P N="UseComposite" V="sectionIsComposite(BeamSection) ? 1 : 0"/>
<P N="Depth" V="sectionDepth(BeamSection, Station)"/>
<P N="Width" V="sectionWidth(BeamSection, Station)"/>
```

***

## Function Implementation Reference

For AI agents developing or debugging ParamML:

**Dispatchers** (search by method name; line numbers drift):

* `Code/PML/Eval.ts` - `_gFunc()`: math functions, `refs`, `objs`, `params`, `range`, `random`; anything it does not know goes on to `ExprProvFunctionCall`
* `Code/Core/JsParser.ts` - `Parser.Execute()`: `iif`, `atstation`, `exportval`, `makelist`, `variation(s)`, `makestadep`, and the lambda functions (`map`, `filter`, `reduce`, `maxl`, `minl`, `suml`, `avg`, `sort`, `reverse`, `removedup`, `unique`, `index`)
* `Code/PML/Param.ts` - `ExprProvFunctionCall()`: the list, geometry, string and unit functions

**Implementation Files:**

* [ParamFunc.ts](https://github.com/openbrim/platform/tree/master/docs/developers/llm-guides/Code/PML/ParamFunc.ts) - Core function implementations
* [SEC/Functions.ts](https://github.com/openbrim/platform/tree/master/docs/developers/llm-guides/Code/SEC/Functions.ts) - Section analysis functions
* [OBrIM/Functions.ts](https://github.com/openbrim/platform/tree/master/docs/developers/llm-guides/Code/OBrIM/Functions.ts) - Alignment/bridge functions
* [FEA/Functions.ts](https://github.com/openbrim/platform/tree/master/docs/developers/llm-guides/Code/FEA/Functions.ts) - Finite element analysis functions

**Error Handling:** All functions use `ParamML.Param.ThrowError(message)` for error reporting. Always validate:

* Parameter types (arrays, numbers, objects)
* Parameter count
* Null/undefined values
* Context requirements

***

## Summary

ParamML provides 90+ functions organized into categories:

* **Array/List**: Manipulation and queries of collections
* **Geometric**: Transformations and geometric calculations
* **Line/Curve**: Operations on linear geometry
* **Surface/Volume**: Area, volume, and perimeter calculations
* **Unit Conversion**: Formatting and converting physical units
* **Advanced Geometry**: Voronoi, intersection, mesh operations
* **String**: Text manipulation utilities
* **External Modules**: Context-specific functions for FEA, sections, and alignments

**Key Principles:**

1. Write function names as documented; only the math functions are matched without regard to case
2. Most geometric functions require execution context
3. External module functions are only available in appropriate contexts
4. Functions can be nested and combined in expressions
5. Always handle potential null returns from geometric operations
6. Use appropriate unit types for engineering calculations

This comprehensive function library enables AI agents to create sophisticated parametric bridge models with complex geometric relationships, engineering calculations, and analysis integrations.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.openbrim.org/developers/llm-guides/ai-paramml-functions-reference.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
