> ## Documentation Index
> Fetch the complete documentation index at: https://docs.nexalis.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Nexalis Macros

# Nexalis Macros

Nexalis Cloud provides built-in functions for advanced time-series data processing. These functions simplify complex operations and ensure accurate calculations.

***

## @nexalis/scale

Applies scaling transformations to dataPoints values using `multiplier` and `adder` attributes. This is useful for unit conversions, calibration adjustments, or normalization.

### Use Cases

The primary purpose of `@nexalis/scale` is to transform raw industrial values into standardized units defined by the **Nexalis data model**. Values are stored "raw" (as sent from the data sources), and the `multiplier` and `adder` attributes bring them into the **correct units**.

**Example**: A site sends active power measurements in Watts (W), but the Nexalis data model specifies kilowatts (kW). The dataPoint would have:

* `multiplier: 0.001` (converts W → kW)
* `adder: 0`

When you fetch this data and apply `@nexalis/scale`, a raw value of 5000 W becomes 5 kW.

### Common Transformations

1. **Power Units**: W → kW (`multiplier: 0.001`, `adder: 0`)
2. **Temperature Scales**: Celsius → Fahrenheit (`multiplier: 1.8`, `adder: 32`)
3. **Sensor Offsets**: Apply zero-point corrections using `adder`

### Attributes Used

The function reads these attributes from each dataPoint:

* **multiplier**: Multiplies each value (e.g., for unit conversion)
* **adder**: Adds to each value (e.g., for offset correction)

If one of 'multiplier' or 'adder' is missing or null, that transformation is skipped (you get raw values).

### Formula

For each dataPoint:

```
scaled_value = original_value × multiplier + adder
```

### Parameters

| Parameter | Type             | Description                                         |
| --------- | ---------------- | --------------------------------------------------- |
| `DATA`    | LIST\<dataPoint> | List of dataPoints to apply scaling transformations |

### Returns

A list of dataPoints with scaled values. The original `multiplier` and `adder` attributes remain in the dataPoint metadata.

### Example: Power Standardization

```warpscript theme={null}
// Fetch raw active power data (stored in Watts from SCADA)
{
  'token' $read_token
  'class' 'nx.value'
  'labels' { 'assetType' 'INV' 'dataObject' 'TotW' }
  'start' '2026-01-15T00:00:00Z'    // the trailing "Z" means "UTC timezone"
  'end' '2026-01-18T23:59:59Z' 
} FETCH

// Apply scaling to convert W → kW per Nexalis data model
// dataPoint has attributes: multiplier=0.001, adder=0

@nexalis/scale
```

> ⚠️ **Warning:** This function is not idempotent. If you call it twice, it will scale the data twice.

***

## @nexalis/fetch\_trapezoidal\_averages

Fetches time-series data from Nexalis Cloud and computes time-weighted (trapezoidal) averages over fixed-width time buckets. This is ideal for accurate aggregation of non-uniformly sampled data. This macro calls @nexalis/scale macro by default (the values returned are scaled).

### Why Trapezoidal Averages?

Unlike simple arithmetic means, trapezoidal averaging accounts for the time duration between data points, providing more accurate averages when:

* Data points are irregularly spaced
* Sampling rates vary over time
* You need true time-weighted calculations

### Parameters

| Parameter     | Type           | Required | Description                                                                      |
| ------------- | -------------- | -------- | -------------------------------------------------------------------------------- |
| `read_token`  | STRING         | Yes      | Nexalis API read token with fetch permissions                                    |
| `start`       | STRING or LONG | Yes      | Start timestamp (ISO8601 string or microseconds)                                 |
| `end`         | STRING or LONG | Yes      | End timestamp (ISO8601 string or microseconds)                                   |
| `bucket_size` | LONG           | Yes      | Bucket width in minutes                                                          |
| `labels`      | MAP            | Yes      | Labels **and attributes** to filter dataPoints (supports regexp with `~` prefix) |
| `scaling`     | BOOLEAN        | No       | Boolean to apply scaling using @nexalis/scale macro (default: true)              |
| `class`       | STRING         | No       | Selector for the dataPoints classes (default: "nx.value")                        |

### Returns

A list of dataPoints containing trapezoidal averages for each bucket. Only LONG and DOUBLE value types are processed; discrete measurements (STRING/BOOLEAN) are automatically filtered out.

<Note>
  **NaN values**: The macro returns `NaN` (Not a Number) for buckets where no values were recorded during the interval and no anterior values exist for trapezoidal interpolation. This will only occur at the start of a time series.
</Note>

### Example Usage

```warpscript theme={null}
// Fetch 15-minute trapezoidal averages over 1 day

{ 'token' $read_token
  'start' '2026-01-01T00:00:00Z'
  'end' '2026-01-02T00:00:00Z'
  'bucket_size' 15    //minutes
  'labels' { 'assetType' 'INV' 'dataObject' 'TotW' }
  }
  @nexalis/fetch_trapezoidal_averages
```

### Example with regular expression

```warpscript theme={null}
// Fetch dataPoints containing "INV" or "METER"

{ 'token' $read_token
  'start' '2026-01-01T00:00:00Z'
  'end' '2026-01-02T00:00:00Z'
  'bucket_size' 15    //minutes
  'labels' { 'dataPoint' '~(.*INV.*|.*METER.*)' }  // Regexp pattern
  }
```

### How It Works

1. **Retrieves** dataPoints data according to labels selection and extends time windows with boundary points (1 pre and post) for accurate edge calculations
2. **Filters** to keep only analog measurements (gets rid of strings/booleans)
3. **Averages** values by applying trapezoidal averaging to compute time-weighted means per bucket

***

## @nexalis/fetch\_bucketized

Fetches time-series data from Nexalis Cloud and bucketizes it into fixed-width time intervals using a timeseries bucketizer such as `last`, `first`, `max` or `mean`. This macro calls `@nexalis/scale` by default, so returned values are scaled unless disabled.

### Why use `@nexalis/fetch_bucketized`?

Use this macro when you want to:

* Resample raw time series into regular time buckets
* Keep the latest, first, mean, or another bucketized value per interval
* Query multiple dataPoints with label or attribute filters
* Optionally return raw values without Nexalis scaling

### Parameters

| Parameter     | Type           | Required | Description                                                                       |
| ------------- | -------------- | -------- | --------------------------------------------------------------------------------- |
| `token`       | STRING         | Yes      | Nexalis API read token with fetch permissions                                     |
| `start`       | STRING or LONG | Yes      | Start timestamp (ISO8601 string or microseconds)                                  |
| `end`         | STRING or LONG | Yes      | End timestamp (ISO8601 string or microseconds)                                    |
| `bucket_size` | LONG           | Yes      | Bucket width in minutes                                                           |
| `bucketizer`  | STRING         | Yes      | Bucketizer to apply, for example `last`, `first`, or `mean`                       |
| `labels`      | MAP            | Yes      | Labels and attributes used to filter dataPoints (supports regexp with `~` prefix) |
| `scaling`     | BOOLEAN        | No       | Applies `@nexalis/scale` to the result (default: `true`)                          |
| `class`       | STRING         | No       | Selector for the dataPoints classes (default: `"nx.value"`)                       |

### Returns

A list of bucketized dataPoints over the requested time range.

<Note>
  The macro aligns the requested start and end timestamps to bucket boundaries, prevents future timestamps from being queried, and fills bucket gaps using previous values before clipping back to the requested interval.
</Note>

### Example Usage

```warpscript theme={null}
// Fetch 5-minute bucketized values using the last value in each bucket

{ 'token' $read_token
  'start' '2026-01-01T00:00:00Z'
  'end' '2026-01-02T00:00:00Z'
  'bucket_size' 5    // minutes
  'bucketizer' 'last'
  'labels' { 'siteName' 'stationA' 'description' '~(.*power.*|.*speed.*)' }
} @nexalis/fetch_bucketized
```

### How It Works

1. Fetches dataPoints matching the requested class, labels, and attributes, with one boundary value before and after the interval.
2. Normalizes timestamps and aligns them to the requested bucket size.
3. Applies the selected timeseries bucketizer over fixed-width buckets.
4. Fills missing buckets using previous values, shifts timestamps to bucket starts, and clips to the requested interval.
5. Applies `@nexalis/scale` unless `scaling` is set to `false`.
