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

# Query Guide

> How to query ModMS API with date ranges, variables, and mathematical expressions

## Query Endpoint

**Base URL:** `http://modms.devops.arabiaweather.com/q`

## Query Parameters

### Fields

Specify which variables to retrieve using the `fields` parameter:

```
fields=time | location | MODEL.VAR
```

* **`time`**: Timestamp for each data point
* **`location`**: Geographic coordinates (latitude, longitude)
* **`MODEL.VAR`**: Model variable in format `MODEL.LEVEL.VARIABLE`

**Multiple fields:** Separate with `|` (pipe with spaces)

### Time Range

Specify time range using the `time` parameter:

```
time=[start TO end]
time=[now TO timestamp]
time=[start TO end STEP interval]
```

**Formats:**

* **Unix timestamp**: `1762355295`
* **`now`**: Current time
* **STEP**: Time interval for interpolation (e.g., `60 minutes`)

### Location

Specify geographic location using the `location` parameter:

```
location=(latitude, longitude)
```

**Format:** `(lat, lon)` with decimal degrees

## Variable Format

Variables follow the pattern: `MODEL.LEVEL.VARIABLE`

**Examples:**

* `GFS.ATM.TCDC` - GFS total cloud cover
* `GEM.GND2M.TMP` - GEM 2m temperature
* `UK10.GND10M.UGRD` - UK10 10m U-wind component
* `ICON.SFC.APCP.HR` - ICON hourly precipitation

**Common Models:**

* `GFS` - Global Forecast System
* `GEM` - Global Environmental Multiscale
* `UK10` - UK Met Office
* `ICON` - ICOsahedral Nonhydrostatic
* `WRFME` - WRF Middle East
* `EC25` - ECMWF
* `AIFS` - AIFS model

## Model Run Specification

You can specify a particular model run using the `@` syntax:

**ModMS (Main Server):**

* `MODEL.LEVEL.VARIABLE` - Uses the latest available run
* `MODEL@model-run.LEVEL.VARIABLE` - Specifies a specific model run (e.g., `GFS@2218`)

**MAMS (Archive Server):**

* `MODEL@timestamp.LEVEL.VARIABLE` - **Must** use Unix timestamp format (e.g., `GFS@1766577600`)

<Warning>
  **Important:** MAMS requires timestamp format (`MODEL@timestamp`), while ModMS supports both model-run format (`MODEL@model-run`) and timestamp format.
</Warning>

**Examples:**

* ModMS: `GFS@2218.ISO200HPA.UGRD` (model run format)
* MAMS: `GFS@1766577600.ISO200HPA.UGRD` (timestamp format)
* ModMS: `GFS.ISO200HPA.UGRD` (uses latest available run)

## Mathematical Expressions

ModMS supports complex mathematical expressions in queries using the **muparser** library and custom functions.

### Basic Math Operations

Standard arithmetic operations:

* `+` - Addition
* `-` - Subtraction
* `*` - Multiplication
* `/` - Division
* `%` - Modulo (via `mod()` function)
* `^` - Power

### Comparison Operators

* `==` - Equal
* `!=` - Not equal
* `>` - Greater than
* `<` - Less than
* `>=` - Greater than or equal
* `<=` - Less than or equal
* `&&` - Logical AND
* `||` - Logical OR (via `or()` function)

### Conditional Expressions

Ternary operator for conditional logic:

```
condition ? value_if_true : value_if_false
```

**Example:**

```
(LSM.LSM == 0 && speed(GFS.GND10M.UGRD, GFS.GND10M.VGRD) > 7) ? 100 : 0
```

## Built-in Functions

### Aggregation Functions

**`min(value1, value2, ...)`**

* Returns minimum value, ignoring NaN

**`max(value1, value2, ...)`**

* Returns maximum value, ignoring NaN

**`avg(value1, value2, ...)`**

* Returns average of values, ignoring NaN

**`median(value1, value2, ...)`**

* Returns median value (up to 15 values), ignoring NaN

### Model Merging Functions

**`merge(value1, value2, ...)`**

* Returns first non-NaN value from left to right
* Used to combine multiple model sources with fallback

**`cmerge(time, value1, lastTime1, value2, lastTime2, ...)`**

* Time-weighted merge based on model freshness
* First parameter is current time
* Then pairs of (value, last\_available\_time)
* Weights models by how recent their data is

### Wind Functions

**`speed(u, v)`**

* Calculates wind speed from U and V components
* Formula: `sqrt(u² + v²)`

**`dir(u, v)`**

* Calculates wind direction from U and V components
* Returns direction from north in degrees (0-360)

### Meteorological Functions

**`rh(temp, dewpoint)`**

* Calculates relative humidity from temperature and dewpoint
* Both parameters in Kelvin

**`dpt(temp, rh)`**

* Calculates dewpoint from temperature and relative humidity

### Consensus Functions

**`consensus(value1, value2, ...)`**

* Finds longest chain of similar values and returns average
* Used for model ensemble consensus

**`consensusT(threshold, value1, value2, ...)`**

* Consensus with threshold - groups values above/below threshold
* First parameter is threshold value

**`consensusL(maxDiff, value1, value2, ...)`**

* Linear consensus with maximum difference parameter
* First parameter is maximum allowed difference

**`confidenceGT(threshold, value1, value2, ...)`**

* Returns confidence (0-1) that values are above threshold

**`confidenceBT(threshold, value1, value2, ...)`**

* Returns confidence (0-1) based on threshold comparison

### Filter Functions

**`filter(value, currentTime, maxTime)`**

* Returns value only if currentTime is less than maxTime, else NaN

**`filter(value, currentTime, minTime, maxTime)`**

* Returns value only if minTime is less than or equal to currentTime and currentTime is less than maxTime, else NaN

### Utility Functions

**`nearest(target, value1, value2, ...)`**

* Returns value closest to target

**`nearestxy(target, x1, y1, x2, y2, ...)`**

* Returns y-value whose x-value is closest to target

**`or(value1, value2, ...)`**

* Logical OR - returns first truthy value

**`fzero(x1, y1, x2, y2, ...)`**

* Finds zero crossing point between data points

**`mod(value, divisor)`**

* Modulo operation

### Unit Conversion

**`conv("unit1>unit2", value)`**

* Converts between units using UDUNITS library
* Example: `conv("kelvin>celsius", GFS.GND2M.TMP)`

## Query Capabilities

### 1. Single Model Queries

Query data from a single model:

```
GFS.GND2M.TMP - 273.15
```

### 2. Multi-Model Merging

Combine multiple models with fallback:

```
merge(WRFME.ISO850HPA.TMP, GFS.ISO850HPA.TMP) - 273.15
```

### 3. Model Averaging

Average values from multiple models:

```
avg(GFS.ISO500HPA.TMP, UK10.ISO500HPA.TMP) - 273.15
```

### 4. Model Median

Get median from multiple models:

```
median(speed(EC25.GND10M.UGRD, EC25.GND10M.VGRD), 
       speed(GFS.GND10M.UGRD, GFS.GND10M.VGRD), 
       speed(ICON.GND10M.UGRD, ICON.GND10M.VGRD))
```

### 5. Conditional Calculations

Use conditional logic based on conditions:

```
(LSM.LSM == 0 && speed(GFS.GND10M.UGRD, GFS.GND10M.VGRD) > 7 && 
 GFS.GND2M.RH < 60 && GFS.SFC.APCP.HR <= 0) ? 
 (min(speed(GFS.GND10M.UGRD, GFS.GND10M.VGRD) / 7 * 0.5, 1.0) * 
  GFS.GND2M.RH < 40 ? 100 : (GFS.GND2M.RH * -2.5 + 200)) : 0
```

### 6. Derived Variables

Calculate derived meteorological variables:

```
speed(GFS.GND10M.UGRD, GFS.GND10M.VGRD)
dir(GFS.GND10M.UGRD, GFS.GND10M.VGRD)
rh(GEM.GND2M.TMP, GEM.GND2M.DPT)
```

### 7. Time-Based Filtering

Filter values based on time constraints:

```
filter(GFS.SFC.APCP.HR, time, GFS.RUNTIME + 72)
```

### 8. Time-Weighted Merging

Merge models based on data freshness:

```
cmerge(time, EC25.GND10M.UGRD, EC25.LASTTIME, 
       ICON.GND10M.UGRD, ICON.LASTTIME, 
       GFS.GND10M.UGRD, GFS.LASTTIME)
```

### 9. Ensemble Consensus

Get consensus from multiple model runs:

```
consensus(EC25.SFC.APCP.HR*1000, UK10.SFC.TPRATE.HR, 
          GFS.SFC.APCP.HR, ICON.SFC.TPRATE.HR)
```

### 10. Unit Conversions

Convert between units:

```
GFS.GND2M.TMP - 273.15  // Kelvin to Celsius
GFS.MSL.PRMSL / 100     // Pascal to Hectopascal
```

## Time Step Interpolation

The `STEP` parameter enables time interpolation to get data at regular intervals:

**Syntax:**

```
time=[start TO end STEP interval]
```

**Interval Units:**

* `minutes` - Minutes (e.g., `60 minutes` for hourly)
* `hours` - Hours
* `days` - Days

**Example:**

```
time=[now TO 1766620800 STEP 60 minutes]
```

This returns data points every 60 minutes between `now` and the end timestamp, interpolating values from available model timesteps.

<Info>
  Use STEP when you need regular time intervals (e.g., hourly data) but the model only provides data at irregular timesteps.
</Info>

## URL Encoding

When constructing URLs manually, remember to URL-encode special characters:

* **Space**: `%20`
* **Pipe**: `%7C` or `|` (usually works)
* **Comma**: `%2C` or `,` (usually works)
* **Parentheses**: `%28` `(` and `%29` `)`

## Related Documentation

* [API Examples](/data-ai/modms/api-examples) - Practical query examples
* [ModMS Overview](/data-ai/modms) - System overview
* [ModMS Architecture](/data-ai/modms/architecture) - System architecture
