Skip to content

API Reference Overview

The Monet Stats API provides a comprehensive collection of statistical metrics and utilities for atmospheric sciences applications. This reference covers all available functions, their parameters, return values, and use cases.

API Structure

Monet Stats is organized into several functional modules:

Core Modules

Import Conventions

Standard Imports

# Import entire library
import monet_stats as ms

# Import specific modules
from monet_stats import contingency_metrics, correlation_metrics

# Import specific functions
from monet_stats import R2, RMSE, POD, FAR
import monet_stats as ms
import numpy as np
import xarray as xr

Data Format Support

NumPy Arrays

import numpy as np

obs = np.array([1, 2, 3, 4, 5])
mod = np.array([1.1, 2.1, 2.9, 4.1, 4.8])

r2 = ms.R2(obs, mod)  # Works with 1D arrays
rmse = ms.RMSE(obs, mod)

Multi-dimensional Arrays

# 2D arrays (e.g., spatial fields)
obs_2d = np.random.normal(20, 2, (50, 50))
mod_2d = obs_2d + np.random.normal(0, 1, (50, 50))

fss = ms.FSS(obs_2d, mod_2d, window=5)

Pandas DataFrames

import pandas as pd

df = pd.DataFrame({
    'observed': np.random.normal(20, 2, 100),
    'modeled': np.random.normal(20.5, 2.5, 100),
    'station': ['A'] * 50 + ['B'] * 50
})

# Apply metrics by group
results = df.groupby('station').apply(
    lambda x: pd.Series({
        'RMSE': ms.RMSE(x['observed'], x['modeled']),
        'R2': ms.R2(x['observed'], x['modeled'])
    })
)

XArray DataArrays

import xarray as xr

obs_da = xr.DataArray(
    np.random.normal(20, 2, (10, 10, 365)),
    dims=['lat', 'lon', 'time'],
    coords={
        'lat': range(10),
        'lon': range(10),
        'time': pd.date_range('2020-01-01', periods=365, freq='D')
    }
)

mod_da = obs_da + xr.DataArray(
    np.random.normal(0, 1, (10, 10, 365)),
    dims=['lat', 'lon', 'time'],
    coords=obs_da.coords
)

# Metrics preserve coordinates and dimensions
skill = ms.R2(obs_da, mod_da)  # Returns DataArray with same coordinates

Common Parameters

Core Parameters

Most metrics accept these common parameters:

  • obs: Observed values (array-like)
  • mod: Modeled/predicted values (array-like)
  • axis: Axis along which to compute metrics (int, optional)
  • nan_policy: How to handle NaN values ('omit', 'propagate', 'raise')

Threshold Parameters

Many metrics use threshold parameters for categorical analysis:

  • minval: Minimum threshold for event definition
  • maxval: Maximum threshold for event definition (optional)

Spatial Parameters

Spatial metrics often include:

  • window: Size of spatial window (int)
  • threshold: Event threshold for spatial analysis

Return Value Types

Scalar Values

Most metrics return single scalar values:

r2 = ms.R2(obs, mod)  # float
rmse = ms.RMSE(obs, mod)  # float

Arrays

Some metrics return arrays for multi-dimensional input:

# For 2D spatial data
fss = ms.FSS(obs_2d, mod_2d)  # float

DataArrays (xarray)

When using xarray inputs, metrics return DataArrays:

skill = ms.R2(obs_da, mod_da)  # DataArray with coordinates

Error Handling

Data Shape Validation

try:
    result = ms.R2(obs_1d, mod_2d)  # Will raise ValueError
except ValueError as e:
    print(f"Shape mismatch: {e}")

NaN Handling

# Data with NaN values
obs_with_nan = np.array([1, 2, np.nan, 4])
mod_with_nan = np.array([1.1, 2.1, 3.1, 4.1])

# Functions automatically handle NaN by default
rmse = ms.RMSE(obs_with_nan, mod_with_nan)  # Uses valid pairs only

Type Validation

# Invalid types will raise TypeError
try:
    result = ms.R2("invalid", "data")  # TypeError
except TypeError as e:
    print(f"Invalid data type: {e}")

Performance Considerations

Vectorized Operations

All metrics use NumPy and Xarray vectorized operations for optimal performance. Loop-free implementations ensure maximum speed on modern hardware.

Out-of-Core Processing with Dask

For datasets larger than RAM, monet-stats is fully compatible with Dask. Most metrics are "lazy-aware" and will preserve the Dask computation graph.

# Open large dataset with chunks (Aero Protocol recommended)
ds = xr.open_dataset("large_data.nc", chunks={"time": "auto", "lat": 100, "lon": 100})
obs = xr.open_dataset("obs_data.nc", chunks={"time": "auto", "lat": 100, "lon": 100})

# Metrics stay lazy and don't trigger loading
skill = ms.RMSE(obs.var, ds.var, axis="time")

# Execution only happens on compute() or plotting
result = skill.compute()

Scientific Provenance

When using Xarray DataArrays, monet-stats automatically updates the attrs['history'] to track which statistical operations were applied to the data, ensuring scientific reproducibility.

Example Usage Patterns

Basic Error Analysis

import monet_stats as ms
import numpy as np

# Sample data
obs = np.array([1.0, 2.5, 3.2, 4.8, 5.0])
mod = np.array([1.2, 2.3, 3.5, 4.6, 5.2])

# Error metrics
error_analysis = {
    'RMSE': ms.RMSE(obs, mod),
    'MAE': ms.MAE(obs, mod),
    'MB': ms.MB(obs, mod),
    'NMB': ms.NMB(obs, mod),
    'NME': ms.NME(obs, mod)
}

Comprehensive Model Evaluation

def evaluate_model(observed, modeled):
    """Comprehensive model evaluation suite"""

    metrics = {
        # Error measures
        'RMSE': ms.RMSE(observed, modeled),
        'MAE': ms.MAE(observed, modeled),
        'MB': ms.MB(observed, modeled),
        'NMB': ms.NMB(observed, modeled),

        # Skill scores
        'R2': ms.R2(observed, modeled),
        'NSE': ms.NSE(observed, modeled),
        'KGE': ms.KGE(observed, modeled),
        'IOA': ms.IOA(observed, modeled),

        # Relative measures
        'MPE': ms.MPE(observed, modeled),
        'NME': ms.NME(observed, modeled)
    }

    return metrics

# Usage
results = evaluate_model(obs, mod)
for metric, value in results.items():
    print(f"{metric}: {value:.4f}")

Categorical Event Analysis

# Binary event analysis
obs_events = np.array([0, 1, 1, 0, 1, 0, 1, 1, 0, 0])
mod_events = np.array([0, 1, 0, 0, 1, 1, 1, 0, 0, 1])

# Contingency table metrics
contingency_metrics = {
    'POD': ms.POD(obs_events, mod_events, threshold=0.5),
    'FAR': ms.FAR(obs_events, mod_events, threshold=0.5),
    'CSI': ms.CSI(obs_events, mod_events, threshold=0.5),
    'HSS': ms.HSS(obs_events, mod_events, threshold=0.5),
    'ETS': ms.ETS(obs_events, mod_events, threshold=0.5)
}

API Reference

The following sections provide auto-generated documentation for each core module based on docstrings.

Contingency Metrics

BSS_binary(obs, mod, threshold, axis=None)

Binary Brier Skill Score for deterministic forecasts.

Typical Use Cases

  • Evaluating the accuracy of deterministic binary forecasts (e.g., precipitation yes/no).
  • Used in meteorology and environmental modeling to assess forecast skill relative to a reference.

Typical Values and Range

  • Range: -∞ to 1
  • 1: Perfect forecast
  • 0: Same skill as reference forecast
  • Negative: Worse than reference forecast

Parameters

obs : numpy.ndarray or xarray.DataArray Observed binary outcomes or continuous values. mod : numpy.ndarray or xarray.DataArray Forecast binary outcomes or continuous values. threshold : float Threshold value to convert continuous forecasts to binary. axis : int, str, or iterable of such, optional Axis along which to compute the score.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Binary Brier Skill Score.

Examples

import numpy as np from monet_stats.contingency_metrics import BSS_binary obs = np.array([0, 1, 1, 0]) mod = np.array([0, 1, 0, 0]) BSS_binary(obs, mod, threshold=0.5) 0.5

Source code in src/monet_stats/contingency_metrics.py
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
def BSS_binary(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    threshold: float,
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Binary Brier Skill Score for deterministic forecasts.

    Typical Use Cases
    -----------------
    - Evaluating the accuracy of deterministic binary forecasts (e.g.,
      precipitation yes/no).
    - Used in meteorology and environmental modeling to assess forecast skill
      relative to a reference.

    Typical Values and Range
    ------------------------
    - Range: -∞ to 1
    - 1: Perfect forecast
    - 0: Same skill as reference forecast
    - Negative: Worse than reference forecast

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed binary outcomes or continuous values.
    mod : numpy.ndarray or xarray.DataArray
        Forecast binary outcomes or continuous values.
    threshold : float
        Threshold value to convert continuous forecasts to binary.
    axis : int, str, or iterable of such, optional
        Axis along which to compute the score.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Binary Brier Skill Score.

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.contingency_metrics import BSS_binary
    >>> obs = np.array([0, 1, 1, 0])
    >>> mod = np.array([0, 1, 0, 0])
    >>> BSS_binary(obs, mod, threshold=0.5)
    0.5
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis

        obs_binary = (obs >= threshold).astype(float)
        mod_binary = (mod >= threshold).astype(float)

        bs = ((mod_binary - obs_binary) ** 2).mean(dim=dim)
        obs_clim = obs_binary.mean(dim=dim)
        bs_ref = ((obs_clim - obs_binary) ** 2).mean(dim=dim)

        result = xr.where(bs_ref > 0, 1.0 - (bs / bs_ref), 0.0)
        history = f"BSS_binary computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        obs_binary = (np.asarray(obs) >= threshold).astype(float)
        mod_binary = (np.asarray(mod) >= threshold).astype(float)

        bs = np.nanmean((mod_binary - obs_binary) ** 2, axis=axis)
        obs_clim = np.nanmean(obs_binary, axis=axis)
        if axis is not None:
            # Need to keep dims for subtraction
            obs_clim_kd = np.nanmean(obs_binary, axis=axis, keepdims=True)
        else:
            obs_clim_kd = obs_clim
        bs_ref = np.nanmean((obs_clim_kd - obs_binary) ** 2, axis=axis)

        with np.errstate(divide="ignore", invalid="ignore"):
            result = np.where(bs_ref > 0, 1.0 - (bs / bs_ref), 0.0)
            return result.item() if np.ndim(result) == 0 else result

CSI(obs, mod, minval, maxval=None, axis=None)

Critical Success Index (CSI).

Typical Use Cases

  • Evaluating forecast skill for rare or binary events (e.g., precipitation, air quality exceedances).
  • Used in meteorology and environmental modeling to assess event prediction accuracy.

Typical Values and Range

  • Range: 0 to 1
  • 1: Perfect forecast
  • 0: No skill (no correct predictions)

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Modeled values. minval : float Minimum threshold value for event detection. maxval : float, optional Maximum threshold value for event detection. axis : int, str, or iterable of such, optional Axis along which to compute the metric.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray CSI value for the given threshold.

Examples

import numpy as np from monet_stats.contingency_metrics import CSI obs = np.array([1, 0, 1, 0]) mod = np.array([1, 1, 0, 0]) CSI(obs, mod, minval=0.5) 0.3333333333333333

Source code in src/monet_stats/contingency_metrics.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
def CSI(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    minval: float,
    maxval: Optional[float] = None,
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Critical Success Index (CSI).

    Typical Use Cases
    -----------------
    - Evaluating forecast skill for rare or binary events (e.g., precipitation,
      air quality exceedances).
    - Used in meteorology and environmental modeling to assess event prediction
      accuracy.

    Typical Values and Range
    ------------------------
    - Range: 0 to 1
    - 1: Perfect forecast
    - 0: No skill (no correct predictions)

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Modeled values.
    minval : float
        Minimum threshold value for event detection.
    maxval : float, optional
        Maximum threshold value for event detection.
    axis : int, str, or iterable of such, optional
        Axis along which to compute the metric.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        CSI value for the given threshold.

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.contingency_metrics import CSI
    >>> obs = np.array([1, 0, 1, 0])
    >>> mod = np.array([1, 1, 0, 0])
    >>> CSI(obs, mod, minval=0.5)
    0.3333333333333333
    """
    a, b, c, d = _contingency_table(obs, mod, minval, maxval, axis=axis)
    denom = a + b + c
    if isinstance(denom, xr.DataArray):
        result = xr.where(denom > 0, a / denom, np.nan)
        history = f"CSI computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        with np.errstate(divide="ignore", invalid="ignore"):
            result = np.where(denom > 0, a / denom, np.nan)
            return result.item() if np.ndim(result) == 0 else result

ETS(obs, mod, minval, maxval=None, axis=None)

Equitable Threat Score (ETS).

Typical Use Cases

  • Evaluating forecast skill for rare events (e.g., precipitation, air quality exceedances).
  • Used in meteorology and environmental modeling to assess binary event prediction accuracy.

Typical Values and Range

  • Range: -1/3 to 1
  • 1: Perfect forecast
  • 0: No skill (random forecast)
  • Negative values: Worse than random

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Modeled values. minval : float Minimum threshold value for event detection. maxval : float, optional Maximum threshold value for event detection. axis : int, str, or iterable of such, optional Axis along which to compute the metric.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray ETS value for the given threshold.

Examples

import numpy as np from monet_stats.contingency_metrics import ETS obs = np.array([1, 0, 1, 0]) mod = np.array([1, 1, 0, 0]) ETS(obs, mod, minval=0.5) -0.2

Source code in src/monet_stats/contingency_metrics.py
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
def ETS(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    minval: float,
    maxval: Optional[float] = None,
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Equitable Threat Score (ETS).

    Typical Use Cases
    -----------------
    - Evaluating forecast skill for rare events (e.g., precipitation, air quality
      exceedances).
    - Used in meteorology and environmental modeling to assess binary event
      prediction accuracy.

    Typical Values and Range
    ------------------------
    - Range: -1/3 to 1
    - 1: Perfect forecast
    - 0: No skill (random forecast)
    - Negative values: Worse than random

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Modeled values.
    minval : float
        Minimum threshold value for event detection.
    maxval : float, optional
        Maximum threshold value for event detection.
    axis : int, str, or iterable of such, optional
        Axis along which to compute the metric.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        ETS value for the given threshold.

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.contingency_metrics import ETS
    >>> obs = np.array([1, 0, 1, 0])
    >>> mod = np.array([1, 1, 0, 0])
    >>> ETS(obs, mod, minval=0.5)
    -0.2
    """
    a, b, c, d = _contingency_table(obs, mod, minval, maxval, axis=axis)
    total = a + b + c + d
    random_hits = ((a + b) * (a + c)) / total
    denom = a + b + c - random_hits
    if isinstance(denom, xr.DataArray):
        result = xr.where(denom > 0, (a - random_hits) / denom, np.nan)
        history = f"ETS computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        with np.errstate(divide="ignore", invalid="ignore"):
            result = np.where(denom > 0, (a - random_hits) / denom, np.nan)
            return result.item() if np.ndim(result) == 0 else result

ETS_max_threshold(obs, mod, minval_range, maxval_range, step_size=1.0)

Find the threshold that maximizes the Equitable Threat Score (ETS) over a range.

Typical Use Cases

  • Finding the optimal threshold for binary classification in meteorological or environmental modeling.
  • Used to optimize event detection thresholds in forecast systems.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. minval_range : float Minimum value of threshold range to test. maxval_range : float Maximum value of threshold range to test. step_size : float, optional Step size for testing thresholds. Default is 1.0.

Returns

optimal_threshold : float Threshold value that maximizes ETS. max_ets : float Maximum ETS value achieved.

Examples

import numpy as np obs = np.array([1, 2, 3, 4, 5]) mod = np.array([1.5, 2.5, 3.5, 4.5, 5.5]) ETS_max_threshold(obs, mod, 1, 5, 0.5) (2.5, 1.0)

Source code in src/monet_stats/contingency_metrics.py
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
def ETS_max_threshold(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    minval_range: float,
    maxval_range: float,
    step_size: float = 1.0,
) -> Tuple[float, float]:
    """
    Find the threshold that maximizes the Equitable Threat Score (ETS) over a range.

    Typical Use Cases
    -----------------
    - Finding the optimal threshold for binary classification in meteorological
      or environmental modeling.
    - Used to optimize event detection thresholds in forecast systems.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    minval_range : float
        Minimum value of threshold range to test.
    maxval_range : float
        Maximum value of threshold range to test.
    step_size : float, optional
        Step size for testing thresholds. Default is 1.0.

    Returns
    -------
    optimal_threshold : float
        Threshold value that maximizes ETS.
    max_ets : float
        Maximum ETS value achieved.

    Examples
    --------
    >>> import numpy as np
    >>> obs = np.array([1, 2, 3, 4, 5])
    >>> mod = np.array([1.5, 2.5, 3.5, 4.5, 5.5])
    >>> ETS_max_threshold(obs, mod, 1, 5, 0.5)
    (2.5, 1.0)
    """
    thresholds = np.arange(minval_range, maxval_range, step_size)
    ets_values = []

    for threshold in thresholds:
        ets_val = ETS(obs, mod, threshold)
        if isinstance(ets_val, xr.DataArray):
            ets_val = ets_val.values.item()
        ets_values.append(ets_val)

    # Find the threshold that gives the maximum ETS
    max_idx = np.nanargmax(ets_values)
    optimal_threshold = thresholds[max_idx]
    max_ets = ets_values[max_idx]

    return float(optimal_threshold), float(max_ets)

FAR(obs, mod, minval, maxval=None, axis=None)

False Alarm Rate (FAR) for a given event threshold.

Typical Use Cases

  • Evaluating the frequency of false alarms in categorical forecasts (e.g., precipitation, air quality events).
  • Used in meteorology and environmental modeling to assess forecast reliability.

Typical Values and Range

  • Range: 0 to 1
  • 0: No false alarms (perfect reliability)
  • 1: All alarms are false (no reliability)

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. minval : float Minimum event threshold. maxval : float, optional Maximum event threshold. axis : int, str, or iterable of such, optional Axis along which to compute the metric.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray False alarm rate.

Examples

import numpy as np from monet_stats.contingency_metrics import FAR obs = np.array([0, 1, 1, 0]) mod = np.array([1, 1, 0, 0]) FAR(obs, mod, minval=0.5) 0.5

Source code in src/monet_stats/contingency_metrics.py
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
def FAR(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    minval: float,
    maxval: Optional[float] = None,
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    False Alarm Rate (FAR) for a given event threshold.

    Typical Use Cases
    -----------------
    - Evaluating the frequency of false alarms in categorical forecasts (e.g.,
      precipitation, air quality events).
    - Used in meteorology and environmental modeling to assess forecast
      reliability.

    Typical Values and Range
    ------------------------
    - Range: 0 to 1
    - 0: No false alarms (perfect reliability)
    - 1: All alarms are false (no reliability)

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    minval : float
        Minimum event threshold.
    maxval : float, optional
        Maximum event threshold.
    axis : int, str, or iterable of such, optional
        Axis along which to compute the metric.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        False alarm rate.

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.contingency_metrics import FAR
    >>> obs = np.array([0, 1, 1, 0])
    >>> mod = np.array([1, 1, 0, 0])
    >>> FAR(obs, mod, minval=0.5)
    0.5
    """
    a, b, c, d = _contingency_table(obs, mod, minval, maxval, axis=axis)
    denom = a + c
    if isinstance(denom, xr.DataArray):
        result = xr.where(denom > 0, c / denom, np.nan)
        history = f"FAR computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        with np.errstate(divide="ignore", invalid="ignore"):
            result = np.where(denom > 0, c / denom, np.nan)
            return result.item() if np.ndim(result) == 0 else result

FAR_min_threshold(obs, mod, minval_range, maxval_range, step_size=1.0)

Find the threshold that minimizes the False Alarm Rate (FAR) over a range.

Typical Use Cases

  • Finding the optimal threshold for minimizing false alarms in meteorological or environmental modeling.
  • Used to optimize event detection thresholds in forecast systems.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. minval_range : float Minimum value of threshold range to test. maxval_range : float Maximum value of threshold range to test. step_size : float, optional Step size for testing thresholds. Default is 1.0.

Returns

optimal_threshold : float Threshold value that minimizes FAR. min_far : float Minimum FAR value achieved.

Examples

import numpy as np obs = np.array([1, 2, 3, 4, 5]) mod = np.array([1.5, 2.5, 3.5, 4.5, 5.5]) FAR_min_threshold(obs, mod, 1, 5, 0.5) (2.5, 0.0)

Source code in src/monet_stats/contingency_metrics.py
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
def FAR_min_threshold(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    minval_range: float,
    maxval_range: float,
    step_size: float = 1.0,
) -> Tuple[float, float]:
    """
    Find the threshold that minimizes the False Alarm Rate (FAR) over a range.

    Typical Use Cases
    -----------------
    - Finding the optimal threshold for minimizing false alarms in meteorological
      or environmental modeling.
    - Used to optimize event detection thresholds in forecast systems.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    minval_range : float
        Minimum value of threshold range to test.
    maxval_range : float
        Maximum value of threshold range to test.
    step_size : float, optional
        Step size for testing thresholds. Default is 1.0.

    Returns
    -------
    optimal_threshold : float
        Threshold value that minimizes FAR.
    min_far : float
        Minimum FAR value achieved.

    Examples
    --------
    >>> import numpy as np
    >>> obs = np.array([1, 2, 3, 4, 5])
    >>> mod = np.array([1.5, 2.5, 3.5, 4.5, 5.5])
    >>> FAR_min_threshold(obs, mod, 1, 5, 0.5)
    (2.5, 0.0)
    """
    thresholds = np.arange(minval_range, maxval_range, step_size)
    far_values = []

    for threshold in thresholds:
        far_val = FAR(obs, mod, threshold)
        if isinstance(far_val, xr.DataArray):
            far_val = far_val.values.item()
        far_values.append(far_val)

    # Find the threshold that gives the minimum FAR
    min_idx = np.nanargmin(far_values)
    optimal_threshold = thresholds[min_idx]
    min_far = far_values[min_idx]

    return float(optimal_threshold), float(min_far)

FBI(obs, mod, minval, maxval=None, axis=None)

Frequency Bias Index (FBI) for a given event threshold.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. minval : float Minimum event threshold. maxval : float, optional Maximum event threshold. axis : int, str, or iterable of such, optional Axis along which to compute the metric.

Returns

fbi : numpy.number, numpy.ndarray, or xarray.DataArray Frequency bias index.

Examples

import numpy as np from monet_stats.contingency_metrics import FBI obs = np.array([0, 1, 1, 0]) mod = np.array([1, 1, 0, 0]) FBI(obs, mod, minval=0.5) 1.0

Source code in src/monet_stats/contingency_metrics.py
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
def FBI(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    minval: float,
    maxval: Optional[float] = None,
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Frequency Bias Index (FBI) for a given event threshold.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    minval : float
        Minimum event threshold.
    maxval : float, optional
        Maximum event threshold.
    axis : int, str, or iterable of such, optional
        Axis along which to compute the metric.

    Returns
    -------
    fbi : numpy.number, numpy.ndarray, or xarray.DataArray
        Frequency bias index.

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.contingency_metrics import FBI
    >>> obs = np.array([0, 1, 1, 0])
    >>> mod = np.array([1, 1, 0, 0])
    >>> FBI(obs, mod, minval=0.5)
    1.0
    """
    a, b, c, d = _contingency_table(obs, mod, minval, maxval, axis=axis)
    denom = a + b
    if isinstance(denom, xr.DataArray):
        result = xr.where(denom > 0, (a + c) / denom, np.nan)
        history = f"FBI computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        with np.errstate(divide="ignore", invalid="ignore"):
            result = np.where(denom > 0, (a + c) / denom, np.nan)
            return result.item() if np.ndim(result) == 0 else result

HSS(obs, mod, minval, maxval=None, axis=None)

Heidke Skill Score (HSS).

Typical Use Cases

  • Evaluating categorical forecast skill (e.g., precipitation, air quality events).
  • Used in meteorology and environmental modeling to assess binary event prediction accuracy.

Typical Values and Range

  • Range: -∞ to 1
  • 1: Perfect forecast
  • 0: No skill (random forecast)
  • Negative values: Worse than random

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Modeled values. minval : float Minimum threshold value for event detection. maxval : float, optional Maximum threshold value for event detection. axis : int, str, or iterable of such, optional Axis along which to compute the metric.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray HSS value for the given threshold.

Examples

import numpy as np from monet_stats.contingency_metrics import HSS obs = np.array([1, 0, 1, 0]) mod = np.array([1, 1, 0, 0]) HSS(obs, mod, minval=0.5) -0.3333333333333333

Source code in src/monet_stats/contingency_metrics.py
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
def HSS(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    minval: float,
    maxval: Optional[float] = None,
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Heidke Skill Score (HSS).

    Typical Use Cases
    -----------------
    - Evaluating categorical forecast skill (e.g., precipitation, air quality
      events).
    - Used in meteorology and environmental modeling to assess binary event
      prediction accuracy.

    Typical Values and Range
    ------------------------
    - Range: -∞ to 1
    - 1: Perfect forecast
    - 0: No skill (random forecast)
    - Negative values: Worse than random

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Modeled values.
    minval : float
        Minimum threshold value for event detection.
    maxval : float, optional
        Maximum threshold value for event detection.
    axis : int, str, or iterable of such, optional
        Axis along which to compute the metric.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        HSS value for the given threshold.

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.contingency_metrics import HSS
    >>> obs = np.array([1, 0, 1, 0])
    >>> mod = np.array([1, 1, 0, 0])
    >>> HSS(obs, mod, minval=0.5)
    -0.3333333333333333
    """
    a, b, c, d = _contingency_table(obs, mod, minval, maxval, axis=axis)
    denom = (a + c) * (c + d) + (a + b) * (b + d)
    if isinstance(denom, xr.DataArray):
        result = xr.where(denom > 0, 2 * (a * d - b * c) / denom, np.nan)
        history = f"HSS computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        with np.errstate(divide="ignore", invalid="ignore"):
            result = np.where(denom > 0, 2 * (a * d - b * c) / denom, np.nan)
            return result.item() if np.ndim(result) == 0 else result

HSS_max_threshold(obs, mod, minval_range, maxval_range, step_size=1.0)

Find the threshold that maximizes the Heidke Skill Score (HSS) over a range.

Typical Use Cases

  • Finding the optimal threshold for binary classification in meteorological or environmental modeling.
  • Used to optimize event detection thresholds in forecast systems.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. minval_range : float Minimum value of threshold range to test. maxval_range : float Maximum value of threshold range to test. step_size : float, optional Step size for testing thresholds. Default is 1.0.

Returns

optimal_threshold : float Threshold value that maximizes HSS. max_hss : float Maximum HSS value achieved.

Examples

import numpy as np obs = np.array([1, 2, 3, 4, 5]) mod = np.array([1.5, 2.5, 3.5, 4.5, 5.5]) HSS_max_threshold(obs, mod, 1, 5, 0.5) (2.5, 1.0)

Source code in src/monet_stats/contingency_metrics.py
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
def HSS_max_threshold(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    minval_range: float,
    maxval_range: float,
    step_size: float = 1.0,
) -> Tuple[float, float]:
    """
    Find the threshold that maximizes the Heidke Skill Score (HSS) over a range.

    Typical Use Cases
    -----------------
    - Finding the optimal threshold for binary classification in meteorological
      or environmental modeling.
    - Used to optimize event detection thresholds in forecast systems.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    minval_range : float
        Minimum value of threshold range to test.
    maxval_range : float
        Maximum value of threshold range to test.
    step_size : float, optional
        Step size for testing thresholds. Default is 1.0.

    Returns
    -------
    optimal_threshold : float
        Threshold value that maximizes HSS.
    max_hss : float
        Maximum HSS value achieved.

    Examples
    --------
    >>> import numpy as np
    >>> obs = np.array([1, 2, 3, 4, 5])
    >>> mod = np.array([1.5, 2.5, 3.5, 4.5, 5.5])
    >>> HSS_max_threshold(obs, mod, 1, 5, 0.5)
    (2.5, 1.0)
    """
    thresholds = np.arange(minval_range, maxval_range, step_size)
    hss_values = []

    for threshold in thresholds:
        hss_val = HSS(obs, mod, threshold)
        if isinstance(hss_val, xr.DataArray):
            hss_val = hss_val.values.item()
        hss_values.append(hss_val)

    # Find the threshold that gives the maximum HSS
    max_idx = np.nanargmax(hss_values)
    optimal_threshold = thresholds[max_idx]
    max_hss = hss_values[max_idx]

    return float(optimal_threshold), float(max_hss)

POD(obs, mod, minval, maxval=None, axis=None)

Probability of Detection (POD) for a given event threshold.

Typical Use Cases

  • Evaluating how well a model detects events above a critical threshold (e.g., pollution exceedances, precipitation events).
  • Used in contingency table analysis for categorical forecast verification.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. minval : float Minimum event threshold. maxval : float, optional Maximum event threshold. axis : int, str, or iterable of such, optional Axis along which to compute the metric.

Returns

pod : numpy.number, numpy.ndarray, or xarray.DataArray Probability of detection.

Examples

import numpy as np from monet_stats.contingency_metrics import POD obs = np.array([0, 1, 1, 0]) mod = np.array([1, 1, 0, 0]) POD(obs, mod, minval=0.5) 0.5

Source code in src/monet_stats/contingency_metrics.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
def POD(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    minval: float,
    maxval: Optional[float] = None,
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Probability of Detection (POD) for a given event threshold.

    Typical Use Cases
    -----------------
    - Evaluating how well a model detects events above a critical threshold
      (e.g., pollution exceedances, precipitation events).
    - Used in contingency table analysis for categorical forecast verification.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    minval : float
        Minimum event threshold.
    maxval : float, optional
        Maximum event threshold.
    axis : int, str, or iterable of such, optional
        Axis along which to compute the metric.

    Returns
    -------
    pod : numpy.number, numpy.ndarray, or xarray.DataArray
        Probability of detection.

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.contingency_metrics import POD
    >>> obs = np.array([0, 1, 1, 0])
    >>> mod = np.array([1, 1, 0, 0])
    >>> POD(obs, mod, minval=0.5)
    0.5
    """
    a, b, c, d = _contingency_table(obs, mod, minval, maxval, axis=axis)
    denom = a + b
    if isinstance(denom, xr.DataArray):
        result = xr.where(denom > 0, a / denom, np.nan)
        history = f"POD computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        with np.errstate(divide="ignore", invalid="ignore"):
            result = np.where(denom > 0, a / denom, np.nan)
            return result.item() if np.ndim(result) == 0 else result

POD_max_threshold(obs, mod, minval_range, maxval_range, step_size=1.0)

Find the threshold that maximizes the Probability of Detection (POD) over a range.

Typical Use Cases

  • Finding the optimal threshold for maximizing detection rates in meteorological or environmental modeling.
  • Used to optimize event detection thresholds in forecast systems.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. minval_range : float Minimum value of threshold range to test. maxval_range : float Maximum value of threshold range to test. step_size : float, optional Step size for testing thresholds. Default is 1.0.

Returns

optimal_threshold : float Threshold value that maximizes POD. max_pod : float Maximum POD value achieved.

Examples

import numpy as np obs = np.array([1, 2, 3, 4, 5]) mod = np.array([1.5, 2.5, 3.5, 4.5, 5.5]) POD_max_threshold(obs, mod, 1, 5, 0.5) (2.5, 1.0)

Source code in src/monet_stats/contingency_metrics.py
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
def POD_max_threshold(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    minval_range: float,
    maxval_range: float,
    step_size: float = 1.0,
) -> Tuple[float, float]:
    """
    Find the threshold that maximizes the Probability of Detection (POD) over a range.

    Typical Use Cases
    -----------------
    - Finding the optimal threshold for maximizing detection rates in
      meteorological or environmental modeling.
    - Used to optimize event detection thresholds in forecast systems.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    minval_range : float
        Minimum value of threshold range to test.
    maxval_range : float
        Maximum value of threshold range to test.
    step_size : float, optional
        Step size for testing thresholds. Default is 1.0.

    Returns
    -------
    optimal_threshold : float
        Threshold value that maximizes POD.
    max_pod : float
        Maximum POD value achieved.

    Examples
    --------
    >>> import numpy as np
    >>> obs = np.array([1, 2, 3, 4, 5])
    >>> mod = np.array([1.5, 2.5, 3.5, 4.5, 5.5])
    >>> POD_max_threshold(obs, mod, 1, 5, 0.5)
    (2.5, 1.0)
    """
    thresholds = np.arange(minval_range, maxval_range, step_size)
    pod_values = []

    for threshold in thresholds:
        pod_val = POD(obs, mod, threshold)
        if isinstance(pod_val, xr.DataArray):
            pod_val = pod_val.values.item()
        pod_values.append(pod_val)

    # Find the threshold that gives the maximum POD
    max_idx = np.nanargmax(pod_values)
    optimal_threshold = thresholds[max_idx]
    max_pod = pod_values[max_idx]

    return float(optimal_threshold), float(max_pod)

TSS(obs, mod, minval, maxval=None, axis=None)

Hanssen-Kuipers Discriminant (True Skill Statistic, TSS).

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. minval : float Minimum event threshold. maxval : float, optional Maximum event threshold. axis : int, str, or iterable of such, optional Axis along which to compute the metric.

Returns

tss : numpy.number, numpy.ndarray, or xarray.DataArray True skill statistic.

Examples

import numpy as np from monet_stats.contingency_metrics import TSS obs = np.array([0, 1, 1, 0]) mod = np.array([1, 1, 0, 0]) TSS(obs, mod, minval=0.5) 0.0

Source code in src/monet_stats/contingency_metrics.py
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
def TSS(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    minval: float,
    maxval: Optional[float] = None,
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Hanssen-Kuipers Discriminant (True Skill Statistic, TSS).

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    minval : float
        Minimum event threshold.
    maxval : float, optional
        Maximum event threshold.
    axis : int, str, or iterable of such, optional
        Axis along which to compute the metric.

    Returns
    -------
    tss : numpy.number, numpy.ndarray, or xarray.DataArray
        True skill statistic.

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.contingency_metrics import TSS
    >>> obs = np.array([0, 1, 1, 0])
    >>> mod = np.array([1, 1, 0, 0])
    >>> TSS(obs, mod, minval=0.5)
    0.0
    """
    a, b, c, d = _contingency_table(obs, mod, minval, maxval, axis=axis)
    pod_denom = a + b
    pofd_denom = c + d

    if isinstance(pod_denom, xr.DataArray):
        pod = xr.where(pod_denom > 0, a / pod_denom, np.nan)
        pofd = xr.where(pofd_denom > 0, c / pofd_denom, np.nan)
        result = pod - pofd
        history = f"TSS computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        with np.errstate(divide="ignore", invalid="ignore"):
            pod = np.where(pod_denom > 0, a / pod_denom, np.nan)
            pofd = np.where(pofd_denom > 0, c / pofd_denom, np.nan)
            result = pod - pofd
            return result.item() if np.ndim(result) == 0 else result

scores(obs, mod, minval, maxval=None, axis=None)

Calculate scores using the _contingency_table.

Parameters

obs : numpy.ndarray or xarray.DataArray Observation values ("truth"). mod : numpy.ndarray or xarray.DataArray Model values ("prediction"). minval : float Minimum threshold for event. maxval : float, optional Maximum threshold for event. axis : int, str, or iterable of such, optional Axis along which to compute the scores.

Returns

a, b, c, d Counts of hits, misses, false alarms, and correct negatives.

Examples

import numpy as np obs = np.array([1, 2, 3, 4]) mod = np.array([1.5, 1.8, 3.2, 3.8]) a, b, c, d = scores(obs, mod, minval=2.5)

Source code in src/monet_stats/contingency_metrics.py
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
def scores(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    minval: float,
    maxval: Optional[float] = None,
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Tuple[
    Union[np.number, np.ndarray, xr.DataArray],
    Union[np.number, np.ndarray, xr.DataArray],
    Union[np.number, np.ndarray, xr.DataArray],
    Union[np.number, np.ndarray, xr.DataArray],
]:
    """
    Calculate scores using the _contingency_table.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observation values ("truth").
    mod : numpy.ndarray or xarray.DataArray
        Model values ("prediction").
    minval : float
        Minimum threshold for event.
    maxval : float, optional
        Maximum threshold for event.
    axis : int, str, or iterable of such, optional
        Axis along which to compute the scores.

    Returns
    -------
    a, b, c, d
        Counts of hits, misses, false alarms, and correct negatives.

    Examples
    --------
    >>> import numpy as np
    >>> obs = np.array([1, 2, 3, 4])
    >>> mod = np.array([1.5, 1.8, 3.2, 3.8])
    >>> a, b, c, d = scores(obs, mod, minval=2.5)
    """
    return _contingency_table(obs, mod, minval, maxval, axis=axis)

Correlation Metrics

Correlation and Agreement Metrics for Model Evaluation

AC(obs, mod, axis=None)

Anomaly Correlation (AC).

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model predicted values. axis : int, str, or iterable of such, optional Axis along which to compute the statistic.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Anomaly correlation coefficient (unitless, -1 to 1).

Examples

import numpy as np from monet_stats.correlation_metrics import AC obs = np.array([1, 2, 3, 4]) mod = np.array([1.1, 2.1, 2.9, 4.1]) AC(obs, mod) 0.9922778767136677

Source code in src/monet_stats/correlation_metrics.py
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
def AC(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Anomaly Correlation (AC).

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model predicted values.
    axis : int, str, or iterable of such, optional
        Axis along which to compute the statistic.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Anomaly correlation coefficient (unitless, -1 to 1).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.correlation_metrics import AC
    >>> obs = np.array([1, 2, 3, 4])
    >>> mod = np.array([1.1, 2.1, 2.9, 4.1])
    >>> AC(obs, mod)
    0.9922778767136677
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis

        obs_bar = obs.mean(dim=dim)
        mod_bar = mod.mean(dim=dim)
        obs_anom = obs - obs_bar
        mod_anom = mod - mod_bar
        p1 = (mod_anom * obs_anom).sum(dim=dim)
        p2 = ((mod_anom**2).sum(dim=dim) * (obs_anom**2).sum(dim=dim)) ** 0.5
        result = p1 / p2
        # Update history
        history = f"AC computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        obs_bar = np.ma.mean(obs, axis=axis)
        mod_bar = np.ma.mean(mod, axis=axis)
        if axis is not None:
            # Need to keep dims for subtraction if axis is not None
            obs_bar_kd = np.ma.mean(obs, axis=axis, keepdims=True)
            mod_bar_kd = np.ma.mean(mod, axis=axis, keepdims=True)
        else:
            obs_bar_kd = obs_bar
            mod_bar_kd = mod_bar
        obs_anom = np.subtract(obs, obs_bar_kd)
        mod_anom = np.subtract(mod, mod_bar_kd)
        p1 = np.ma.sum(np.ma.multiply(mod_anom, obs_anom), axis=axis)
        p2 = np.ma.sqrt(np.ma.multiply(np.ma.sum(obs_anom**2, axis=axis), np.ma.sum(mod_anom**2, axis=axis)))
        return p1 / p2

CCC(obs, mod, axis=None)

Concordance Correlation Coefficient (CCC).

Typical Use Cases

  • Quantifying the agreement between model and observations, accounting for precision and accuracy.
  • Used in model evaluation to assess how well model predictions agree with observations.
  • Measures how far the values deviate from the line of perfect concordance (slope=1, intercept=0).

Typical Values and Range

  • Range: -1 to 1
  • 1: Perfect agreement between model and observations
  • 0: No agreement
  • -1: Perfect negative agreement

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable of such, optional Axis along which to compute the coefficient.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Concordance correlation coefficient (unitless, -1 to 1).

Examples

import numpy as np from monet_stats.correlation_metrics import CCC obs = np.array([1, 2, 3, 4]) mod = np.array([1.1, 2.1, 2.9, 4.1]) CCC(obs, mod) 0.9984779299847792

Source code in src/monet_stats/correlation_metrics.py
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
def CCC(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Concordance Correlation Coefficient (CCC).

    Typical Use Cases
    -----------------
    - Quantifying the agreement between model and observations, accounting for
      precision and accuracy.
    - Used in model evaluation to assess how well model predictions agree with
      observations.
    - Measures how far the values deviate from the line of perfect concordance
      (slope=1, intercept=0).

    Typical Values and Range
    ------------------------
    - Range: -1 to 1
    - 1: Perfect agreement between model and observations
    - 0: No agreement
    - -1: Perfect negative agreement

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable of such, optional
        Axis along which to compute the coefficient.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Concordance correlation coefficient (unitless, -1 to 1).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.correlation_metrics import CCC
    >>> obs = np.array([1, 2, 3, 4])
    >>> mod = np.array([1.1, 2.1, 2.9, 4.1])
    >>> CCC(obs, mod)
    0.9984779299847792
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis

        # Calculate means
        obs_mean = obs.mean(dim=dim)
        mod_mean = mod.mean(dim=dim)

        # Calculate variances and covariance
        obs_var = obs.var(dim=dim)
        mod_var = mod.var(dim=dim)
        covar = ((obs - obs_mean) * (mod - mod_mean)).mean(dim=dim)

        # Calculate CCC
        numerator = 2 * covar
        denominator = obs_var + mod_var + (obs_mean - mod_mean) ** 2
        result = numerator / denominator
        # Update history
        history = f"CCC computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        # Calculate means
        obs_mean = np.nanmean(obs, axis=axis)
        mod_mean = np.nanmean(mod, axis=axis)

        # Calculate variances and covariance
        obs_var = np.nanvar(obs, axis=axis)
        mod_var = np.nanvar(mod, axis=axis)
        if axis is not None:
            obs_mean_kd = np.nanmean(obs, axis=axis, keepdims=True)
            mod_mean_kd = np.nanmean(mod, axis=axis, keepdims=True)
        else:
            obs_mean_kd = obs_mean
            mod_mean_kd = mod_mean
        covar = np.nanmean((obs - obs_mean_kd) * (mod - mod_mean_kd), axis=axis)

        # Calculate CCC
        numerator = 2 * covar
        denominator = obs_var + mod_var + (obs_mean - mod_mean) ** 2
        return numerator / denominator

E1(obs, mod, axis=None)

Modified Coefficient of Efficiency (E1).

Typical Use Cases

  • Quantifying the efficiency of model predictions relative to observed mean, robust to outliers.
  • Used in hydrology, meteorology, and model skill assessment.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model predicted values. axis : int, str, or iterable of such, optional Axis along which to compute the statistic.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Modified coefficient of efficiency (unitless, -inf to 1).

Examples

import numpy as np from monet_stats.correlation_metrics import E1 obs = np.array([1, 2, 3]) mod = np.array([2, 2, 4]) E1(obs, mod) 0.0

Source code in src/monet_stats/correlation_metrics.py
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
def E1(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Modified Coefficient of Efficiency (E1).

    Typical Use Cases
    -----------------
    - Quantifying the efficiency of model predictions relative to observed mean,
      robust to outliers.
    - Used in hydrology, meteorology, and model skill assessment.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model predicted values.
    axis : int, str, or iterable of such, optional
        Axis along which to compute the statistic.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Modified coefficient of efficiency (unitless, -inf to 1).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.correlation_metrics import E1
    >>> obs = np.array([1, 2, 3])
    >>> mod = np.array([2, 2, 4])
    >>> E1(obs, mod)
    0.0
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis

        num = abs(obs - mod).sum(dim=dim)
        denom = abs(obs - obs.mean(dim=dim)).sum(dim=dim)
        result = 1.0 - (num / denom)
        result = xr.where((num == 0) & (denom == 0), 1.0, result)
        result = xr.where((num != 0) & (denom == 0), -np.inf, result)

        # Update history
        history = f"E1 computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        num = np.ma.abs(np.subtract(obs, mod)).sum(axis=axis)
        mean_obs = np.ma.mean(obs, axis=axis, keepdims=True)
        denom = np.ma.abs(np.subtract(obs, mean_obs)).sum(axis=axis)
        with np.errstate(divide="ignore", invalid="ignore"):
            result = 1.0 - (num / denom)
            result = np.where((num == 0) & (denom == 0), 1.0, result)
            result = np.where((num != 0) & (denom == 0), -np.inf, result)
        return result.item() if np.ndim(result) == 0 else result

E1_prime(obs, mod, axis=None)

Modified Coefficient of Efficiency (E1') - Alternative formulation.

Typical Use Cases

  • Quantifying the efficiency of model predictions relative to observed mean, robust to outliers.
  • Used in hydrology, meteorology, and model skill assessment as an alternative to E1.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model predicted values. axis : int, str, or iterable of such, optional Axis along which to compute the statistic.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Modified coefficient of efficiency (unitless, -inf to 1).

Examples

import numpy as np from monet_stats.correlation_metrics import E1_prime obs = np.array([1, 2, 3]) mod = np.array([2, 2, 4]) E1_prime(obs, mod) 0.0

Source code in src/monet_stats/correlation_metrics.py
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
def E1_prime(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Modified Coefficient of Efficiency (E1') - Alternative formulation.

    Typical Use Cases
    -----------------
    - Quantifying the efficiency of model predictions relative to observed mean,
      robust to outliers.
    - Used in hydrology, meteorology, and model skill assessment as an
      alternative to E1.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model predicted values.
    axis : int, str, or iterable of such, optional
        Axis along which to compute the statistic.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Modified coefficient of efficiency (unitless, -inf to 1).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.correlation_metrics import E1_prime
    >>> obs = np.array([1, 2, 3])
    >>> mod = np.array([2, 2, 4])
    >>> E1_prime(obs, mod)
    0.0
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis

        obs_mean = obs.mean(dim=dim)
        num = abs(obs - mod).sum(dim=dim)
        denom = abs(obs - obs_mean).sum(dim=dim)
        # Handle case where denominator is 0
        result = 1.0 - (num / denom)
        result = xr.where((num == 0) & (denom == 0), 1.0, result)
        result = xr.where((num != 0) & (denom == 0), -np.inf, result)

        # Update history
        history = f"E1_prime computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        if axis is None:
            obs_c, mod_c = matchedcompressed(obs, mod)
            obs_mean_kd = np.nanmean(obs_c)
        else:
            obs_c, mod_c = obs, mod
            obs_mean_kd = np.nanmean(obs_c, axis=axis, keepdims=True)

        num = np.nansum(np.abs(obs_c - mod_c), axis=axis)
        denom = np.nansum(np.abs(obs_c - obs_mean_kd), axis=axis)
        with np.errstate(divide="ignore", invalid="ignore"):
            result = 1.0 - (num / denom)
            if np.ndim(result) == 0:
                if num == 0 and denom == 0:
                    result = np.array(1.0)
                elif denom == 0:
                    result = np.array(-np.inf)
            else:
                result = np.where((num == 0) & (denom == 0), 1.0, result)
                result = np.where((num != 0) & (denom == 0), -np.inf, result)
        return result.item() if np.ndim(result) == 0 else result

IOA(obs, mod, axis=None)

Index of Agreement (IOA).

Typical Use Cases

  • Quantifying the agreement between model and observations, normalized by total deviation.
  • Used in model evaluation for skill assessment.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model predicted values. axis : int, str, or iterable of such, optional Axis along which to compute the statistic.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Index of agreement (unitless, 0-1).

Examples

import numpy as np from monet_stats.correlation_metrics import IOA obs = np.array([1, 2, 3]) mod = np.array([2, 2, 4]) IOA(obs, mod) 0.8

Source code in src/monet_stats/correlation_metrics.py
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
def IOA(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Index of Agreement (IOA).

    Typical Use Cases
    -----------------
    - Quantifying the agreement between model and observations, normalized by
      total deviation.
    - Used in model evaluation for skill assessment.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model predicted values.
    axis : int, str, or iterable of such, optional
        Axis along which to compute the statistic.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Index of agreement (unitless, 0-1).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.correlation_metrics import IOA
    >>> obs = np.array([1, 2, 3])
    >>> mod = np.array([2, 2, 4])
    >>> IOA(obs, mod)
    0.8
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis

        obsmean = obs.mean(dim=dim)
        num = ((obs - mod) ** 2).sum(dim=dim)
        denom = ((abs(mod - obsmean) + abs(obs - obsmean)) ** 2).sum(dim=dim)
        result = 1.0 - (num / denom)
        result = xr.where((num == 0) & (denom == 0), 1.0, result)
        result = xr.where((num != 0) & (denom == 0), -np.inf, result)

        # Update history
        history = f"IOA computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        obsmean = np.ma.mean(obs, axis=axis, keepdims=True)
        num = (np.ma.abs(np.subtract(obs, mod)) ** 2).sum(axis=axis)
        denom = ((np.ma.abs(np.subtract(mod, obsmean)) + np.ma.abs(np.subtract(obs, obsmean))) ** 2).sum(axis=axis)
        with np.errstate(divide="ignore", invalid="ignore"):
            result = 1.0 - (num / denom)
            result = np.where((num == 0) & (denom == 0), 1.0, result)
            result = np.where((num != 0) & (denom == 0), -np.inf, result)
        return result.item() if np.ndim(result) == 0 else result

IOA_m(obs, mod, axis=None)

Index of Agreement (IOA), robust to masked arrays.

Typical Use Cases

  • Quantifying the agreement between model and observations, normalized by total deviation.
  • Used in model evaluation for skill assessment, robust to masked arrays.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model predicted values. axis : int, str, or iterable of such, optional Axis along which to compute the statistic.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Index of agreement (unitless, 0-1).

Examples

import numpy as np from monet_stats.correlation_metrics import IOA_m obs = np.array([1, 2, 3]) mod = np.array([2, 2, 4]) IOA_m(obs, mod) 0.8

Source code in src/monet_stats/correlation_metrics.py
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
def IOA_m(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Index of Agreement (IOA), robust to masked arrays.

    Typical Use Cases
    -----------------
    - Quantifying the agreement between model and observations, normalized by
      total deviation.
    - Used in model evaluation for skill assessment, robust to masked arrays.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model predicted values.
    axis : int, str, or iterable of such, optional
        Axis along which to compute the statistic.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Index of agreement (unitless, 0-1).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.correlation_metrics import IOA_m
    >>> obs = np.array([1, 2, 3])
    >>> mod = np.array([2, 2, 4])
    >>> IOA_m(obs, mod)
    0.8
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis

        obsmean = obs.mean(dim=dim)
        num = ((obs - mod) ** 2).sum(dim=dim)
        denom = ((abs(mod - obsmean) + abs(obs - obsmean)) ** 2).sum(dim=dim)
        result = 1.0 - (num / denom)
        result = xr.where((num == 0) & (denom == 0), 1.0, result)
        result = xr.where((num != 0) & (denom == 0), -np.inf, result)

        # Update history
        history = f"IOA_m computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        obsmean = np.ma.mean(obs, axis=axis, keepdims=True)
        num = (np.ma.abs(np.subtract(obs, mod)) ** 2).sum(axis=axis)
        denom = ((np.ma.abs(np.subtract(mod, obsmean)) + np.ma.abs(np.subtract(obs, obsmean))) ** 2).sum(axis=axis)
        with np.errstate(divide="ignore", invalid="ignore"):
            result = 1.0 - (num / denom)
            result = np.where((num == 0) & (denom == 0), 1.0, result)
            result = np.where((num != 0) & (denom == 0), -np.inf, result)
        return result.item() if np.ndim(result) == 0 else result

IOA_prime(obs, mod, axis=None)

Index of Agreement (IOA') - Alternative formulation.

Typical Use Cases

  • Quantifying the agreement between model and observations, normalized by total deviation.
  • Used in model evaluation for skill assessment as an alternative to IOA.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model predicted values. axis : int, str, or iterable of such, optional Axis along which to compute the statistic.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Index of agreement (unitless, 0-1).

Examples

import numpy as np from monet_stats.correlation_metrics import IOA_prime obs = np.array([1, 2, 3]) mod = np.array([2, 2, 4]) IOA_prime(obs, mod) 0.8

Source code in src/monet_stats/correlation_metrics.py
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
def IOA_prime(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Index of Agreement (IOA') - Alternative formulation.

    Typical Use Cases
    -----------------
    - Quantifying the agreement between model and observations, normalized by
      total deviation.
    - Used in model evaluation for skill assessment as an alternative to IOA.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model predicted values.
    axis : int, str, or iterable of such, optional
        Axis along which to compute the statistic.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Index of agreement (unitless, 0-1).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.correlation_metrics import IOA_prime
    >>> obs = np.array([1, 2, 3])
    >>> mod = np.array([2, 2, 4])
    >>> IOA_prime(obs, mod)
    0.8
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis

        obsmean = obs.mean(dim=dim)
        num = ((obs - mod) ** 2).sum(dim=dim)
        denom = ((abs(mod - obsmean) + abs(obs - obsmean)) ** 2).sum(dim=dim)
        # Handle case where denominator is 0
        result = 1.0 - (num / denom)
        result = xr.where((num == 0) & (denom == 0), 1.0, result)
        result = xr.where((num != 0) & (denom == 0), -np.inf, result)

        # Update history
        history = f"IOA_prime computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        if axis is None:
            obs_c, mod_c = matchedcompressed(obs, mod)
            obsmean_kd = np.nanmean(obs_c)
        else:
            obs_c, mod_c = obs, mod
            obsmean_kd = np.nanmean(obs_c, axis=axis, keepdims=True)

        num = np.nansum((obs_c - mod_c) ** 2, axis=axis)
        denom = np.nansum((np.abs(mod_c - obsmean_kd) + np.abs(obs_c - obsmean_kd)) ** 2, axis=axis)
        with np.errstate(divide="ignore", invalid="ignore"):
            result = 1.0 - (num / denom)
            if np.ndim(result) == 0:
                if num == 0 and denom == 0:
                    result = np.array(1.0)
                elif denom == 0:
                    result = np.array(-np.inf)
            else:
                result = np.where((num == 0) & (denom == 0), 1.0, result)
                result = np.where((num != 0) & (denom == 0), -np.inf, result)
        return result.item() if np.ndim(result) == 0 else result

KGE(obs, mod, axis=None)

Kling-Gupta Efficiency (KGE).

Typical Use Cases

  • Quantifying the overall agreement between model and observations, combining correlation, bias, and variability.
  • Used in hydrology, meteorology, and environmental model evaluation.

Typical Values and Range

  • Range: -∞ to 1
  • 1: Perfect agreement between model and observations
  • 0: Moderate skill
  • Negative values: Poor skill

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable of such, optional Axis along which to compute KGE.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Kling-Gupta efficiency (unitless, -∞ to 1).

Examples

import numpy as np from monet_stats.correlation_metrics import KGE obs = np.array([1, 2, 3]) mod = np.array([1.1, 1.9, 3.2]) KGE(obs, mod) 0.8988771192996924

Source code in src/monet_stats/correlation_metrics.py
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
def KGE(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Kling-Gupta Efficiency (KGE).

    Typical Use Cases
    -----------------
    - Quantifying the overall agreement between model and observations,
      combining correlation, bias, and variability.
    - Used in hydrology, meteorology, and environmental model evaluation.

    Typical Values and Range
    ------------------------
    - Range: -∞ to 1
    - 1: Perfect agreement between model and observations
    - 0: Moderate skill
    - Negative values: Poor skill

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable of such, optional
        Axis along which to compute KGE.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Kling-Gupta efficiency (unitless, -∞ to 1).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.correlation_metrics import KGE
    >>> obs = np.array([1, 2, 3])
    >>> mod = np.array([1.1, 1.9, 3.2])
    >>> KGE(obs, mod)
    0.8988771192996924
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis

        r = xr.corr(obs, mod, dim=dim)
        alpha = mod.std(dim=dim) / obs.std(dim=dim)
        beta = mod.mean(dim=dim) / obs.mean(dim=dim)
        result = 1.0 - ((r - 1.0) ** 2 + (alpha - 1.0) ** 2 + (beta - 1.0) ** 2) ** 0.5
        # Update history
        history = f"KGE computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        if axis is None:
            from scipy.stats import pearsonr

            obsc, modc = matchedcompressed(obs, mod)
            if len(obsc) < 2:
                r = 0.0
            else:
                r, _ = pearsonr(obsc, modc)
        else:
            # Manual vectorized correlation for numpy with axis
            obs_mean = np.nanmean(obs, axis=axis, keepdims=True)
            mod_mean = np.nanmean(mod, axis=axis, keepdims=True)
            obs_std = obs - obs_mean
            mod_std = mod - mod_mean
            num = np.nansum(obs_std * mod_std, axis=axis)
            den = np.sqrt(np.nansum(obs_std**2, axis=axis) * np.nansum(mod_std**2, axis=axis))
            with np.errstate(divide="ignore", invalid="ignore"):
                r = num / den
                r = np.where(np.isnan(r), 0.0, r)

        alpha = np.ma.std(mod, axis=axis) / np.ma.std(obs, axis=axis)
        beta = np.ma.mean(mod, axis=axis) / np.ma.mean(obs, axis=axis)
        result = 1.0 - ((r - 1.0) ** 2 + (alpha - 1.0) ** 2 + (beta - 1.0) ** 2) ** 0.5
        return result.item() if np.ndim(result) == 0 else result

R2(obs, mod, axis=None)

Coefficient of Determination (R^2, unitless).

Typical Use Cases

  • Quantifying how well model predictions explain the variance in observations.
  • Used in regression analysis, model skill assessment, and forecast verification.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute the statistic.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Coefficient of determination (R^2).

Examples

import numpy as np from monet_stats.correlation_metrics import R2 obs = np.array([1, 2, 3, 4]) mod = np.array([1.1, 1.9, 3.2, 3.8]) R2(obs, mod) 0.9846153846153847

Source code in src/monet_stats/correlation_metrics.py
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
def R2(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Coefficient of Determination (R^2, unitless).

    Typical Use Cases
    -----------------
    - Quantifying how well model predictions explain the variance in observations.
    - Used in regression analysis, model skill assessment, and forecast
      verification.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute the statistic.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Coefficient of determination (R^2).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.correlation_metrics import R2
    >>> obs = np.array([1, 2, 3, 4])
    >>> mod = np.array([1.1, 1.9, 3.2, 3.8])
    >>> R2(obs, mod)
    0.9846153846153847
    """
    from scipy.stats import pearsonr

    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        if axis is None:
            # Default to all dimensions if None
            dim = obs.dims
        elif isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis

        def _pearsonr2(a, b):
            if np.var(a) == 0 or np.var(b) == 0:
                return 0.0
            r_val, _ = pearsonr(a, b)
            if np.isnan(r_val):
                return 0.0
            return r_val**2

        result = xr.apply_ufunc(
            _pearsonr2,
            obs,
            mod,
            input_core_dims=[[dim] if isinstance(dim, str) else list(dim)] * 2,
            output_core_dims=[[]],
            vectorize=True,
            dask="parallelized",
            dask_gufunc_kwargs={"allow_rechunk": True},
            output_dtypes=[float],
        )
        # Update history
        history = f"R2 computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        if axis is None:
            obsc, modc = matchedcompressed(obs, mod)
            if np.var(obsc) == 0 or np.var(modc) == 0:
                return 0.0
            r_val, _ = pearsonr(obsc, modc)
            if np.isnan(r_val):
                return 0.0
            return r_val**2
        else:
            # Manual vectorized R2
            obs_mean = np.nanmean(obs, axis=axis, keepdims=True)
            mod_mean = np.nanmean(mod, axis=axis, keepdims=True)
            obs_std = obs - obs_mean
            mod_std = mod - mod_mean
            num = np.nansum(obs_std * mod_std, axis=axis)
            den = np.sqrt(np.nansum(obs_std**2, axis=axis) * np.nansum(mod_std**2, axis=axis))
            with np.errstate(divide="ignore", invalid="ignore"):
                r = num / den
                result = np.where(np.isnan(r), 0.0, r**2)
                return result.item() if np.ndim(result) == 0 else result

RMSE(obs, mod, axis=None)

Root Mean Square Error (RMSE, model unit).

Typical Use Cases

  • Quantifying the average magnitude of errors between model and observations.
  • Used in model evaluation, forecast verification, and regression analysis.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute the statistic.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Root mean square error value(s).

Examples

import numpy as np from monet_stats.correlation_metrics import RMSE obs = np.array([1, 2, 3, 4]) mod = np.array([2, 2, 2, 2]) RMSE(obs, mod) 1.118033988749895

Source code in src/monet_stats/correlation_metrics.py
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
def RMSE(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Root Mean Square Error (RMSE, model unit).

    Typical Use Cases
    -----------------
    - Quantifying the average magnitude of errors between model and observations.
    - Used in model evaluation, forecast verification, and regression analysis.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute the statistic.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Root mean square error value(s).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.correlation_metrics import RMSE
    >>> obs = np.array([1, 2, 3, 4])
    >>> mod = np.array([2, 2, 2, 2])
    >>> RMSE(obs, mod)
    1.118033988749895
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis

        result = ((mod - obs) ** 2).mean(dim=dim, keep_attrs=True) ** 0.5
        # Update history
        history = f"RMSE computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        return np.ma.sqrt(np.ma.mean((np.subtract(mod, obs)) ** 2, axis=axis))

RMSEs(obs, mod, axis=None)

Root Mean Squared Error between observations and regression fit.

(RMSEs, model unit)

Typical Use Cases

  • Quantifying the error between observations and a regression fit to the model predictions.
  • Used in model evaluation to assess how well a regression fit to the model matches the observations.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model predicted values. axis : int, str, or iterable of such, optional Axis along which to compute the statistic.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray, optional Root mean squared error value(s), or None if regression fails.

Examples

import numpy as np from monet_stats.correlation_metrics import RMSEs obs = np.array([1, 2, 3, 4]) mod = np.array([2, 2, 2, 2]) RMSEs(obs, mod) 0.7071067811865476

Source code in src/monet_stats/correlation_metrics.py
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
def RMSEs(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray, None]:
    """
    Root Mean Squared Error between observations and regression fit.

    (RMSEs, model unit)

    Typical Use Cases
    -----------------
    - Quantifying the error between observations and a regression fit to the
      model predictions.
    - Used in model evaluation to assess how well a regression fit to the model
      matches the observations.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model predicted values.
    axis : int, str, or iterable of such, optional
        Axis along which to compute the statistic.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray, optional
        Root mean squared error value(s), or None if regression fails.

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.correlation_metrics import RMSEs
    >>> obs = np.array([1, 2, 3, 4])
    >>> mod = np.array([2, 2, 2, 2])
    >>> RMSEs(obs, mod)
    0.7071067811865476
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        if axis is None:
            dim = obs.dims
        elif isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis

        def _rmses(a, b):
            from scipy.stats import linregress

            mask = ~np.isnan(a) & ~np.isnan(b)
            if not np.any(mask):
                return np.nan
            m, c, _, _, _ = linregress(a[mask], b[mask])
            mod_hat = c + m * a
            return np.sqrt(np.mean((mod_hat - a) ** 2))

        result = xr.apply_ufunc(
            _rmses,
            obs,
            mod,
            input_core_dims=[[dim] if isinstance(dim, str) else list(dim)] * 2,
            output_core_dims=[[]],
            vectorize=True,
            dask="parallelized",
            dask_gufunc_kwargs={"allow_rechunk": True},
            output_dtypes=[float],
        )
        # Update history
        history = f"RMSEs computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        if axis is None:
            try:
                from scipy.stats import linregress

                obsc, modc = matchedcompressed(obs, mod)
                m, b, _, _, _ = linregress(obsc, modc)
                mod_hat = b + m * obs
                return RMSE(obs, mod_hat, axis=axis)
            except (ValueError, ZeroDivisionError):
                return None
        else:
            # Manual vectorized regression for numpy with axis
            obs = np.asarray(obs)
            mod = np.asarray(mod)
            if axis < 0:
                axis = obs.ndim + axis

            obs_moved = np.moveaxis(obs, axis, -1)
            mod_moved = np.moveaxis(mod, axis, -1)
            other_shape = obs_moved.shape[:-1]
            obs_flat = obs_moved.reshape(-1, obs_moved.shape[-1])
            mod_flat = mod_moved.reshape(-1, mod_moved.shape[-1])

            results = []
            from scipy.stats import linregress

            for i in range(len(obs_flat)):
                mask = ~np.isnan(obs_flat[i]) & ~np.isnan(mod_flat[i])
                if np.sum(mask) < 2:
                    results.append(np.nan)
                else:
                    m, b, _, _, _ = linregress(obs_flat[i][mask], mod_flat[i][mask])
                    mod_hat = b + m * obs_flat[i]
                    results.append(np.sqrt(np.nanmean((mod_hat - obs_flat[i]) ** 2)))
            return np.array(results).reshape(other_shape)

RMSEu(obs, mod, axis=None)

Root Mean Squared Error between regression fit and model predictions.

(RMSEu, model unit)

Typical Use Cases

  • Quantifying the error between a linear regression fit to observations and the model predictions.
  • Used in model evaluation to assess how well a regression fit to obs matches the model output.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model predicted values. axis : int, str, or iterable of such, optional Axis along which to compute the statistic.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray, optional Root mean squared error value(s), or None if regression fails.

Examples

import numpy as np from monet_stats.correlation_metrics import RMSEu obs = np.array([1, 2, 3, 4]) mod = np.array([2, 2, 2, 2]) RMSEu(obs, mod) 0.7071067811865476

Source code in src/monet_stats/correlation_metrics.py
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
def RMSEu(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray, None]:
    """
    Root Mean Squared Error between regression fit and model predictions.

    (RMSEu, model unit)

    Typical Use Cases
    -----------------
    - Quantifying the error between a linear regression fit to observations and
      the model predictions.
    - Used in model evaluation to assess how well a regression fit to obs
      matches the model output.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model predicted values.
    axis : int, str, or iterable of such, optional
        Axis along which to compute the statistic.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray, optional
        Root mean squared error value(s), or None if regression fails.

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.correlation_metrics import RMSEu
    >>> obs = np.array([1, 2, 3, 4])
    >>> mod = np.array([2, 2, 2, 2])
    >>> RMSEu(obs, mod)
    0.7071067811865476
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        if axis is None:
            dim = obs.dims
        elif isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis

        def _rmseu(a, b):
            from scipy.stats import linregress

            mask = ~np.isnan(a) & ~np.isnan(b)
            if not np.any(mask):
                return np.nan
            m, c, _, _, _ = linregress(a[mask], b[mask])
            mod_hat = c + m * a
            return np.sqrt(np.mean((mod_hat - b) ** 2))

        result = xr.apply_ufunc(
            _rmseu,
            obs,
            mod,
            input_core_dims=[[dim] if isinstance(dim, str) else list(dim)] * 2,
            output_core_dims=[[]],
            vectorize=True,
            dask="parallelized",
            dask_gufunc_kwargs={"allow_rechunk": True},
            output_dtypes=[float],
        )
        # Update history
        history = f"RMSEu computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        if axis is None:
            try:
                from scipy.stats import linregress

                obsc, modc = matchedcompressed(obs, mod)
                m, b, _, _, _ = linregress(obsc, modc)
                mod_hat = b + m * obs
                return RMSE(mod_hat, mod, axis=axis)
            except (ValueError, ZeroDivisionError):
                return None
        else:
            obs = np.asarray(obs)
            mod = np.asarray(mod)
            if axis < 0:
                axis = obs.ndim + axis

            obs_moved = np.moveaxis(obs, axis, -1)
            mod_moved = np.moveaxis(mod, axis, -1)
            other_shape = obs_moved.shape[:-1]
            obs_flat = obs_moved.reshape(-1, obs_moved.shape[-1])
            mod_flat = mod_moved.reshape(-1, mod_moved.shape[-1])

            results = []
            from scipy.stats import linregress

            for i in range(len(obs_flat)):
                mask = ~np.isnan(obs_flat[i]) & ~np.isnan(mod_flat[i])
                if np.sum(mask) < 2:
                    results.append(np.nan)
                else:
                    m, b, _, _, _ = linregress(obs_flat[i][mask], mod_flat[i][mask])
                    mod_hat = b + m * obs_flat[i]
                    results.append(np.sqrt(np.nanmean((mod_hat - mod_flat[i]) ** 2)))
            return np.array(results).reshape(other_shape)

WDAC(obs, mod, axis=None)

Wind Direction Anomaly Correlation (WDAC).

Parameters

obs : numpy.ndarray or xarray.DataArray Observed wind direction values (degrees). mod : numpy.ndarray or xarray.DataArray Modeled wind direction values (degrees). axis : int, str, or iterable of such, optional Axis along which to compute the metric.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray WDAC value(s).

Examples

import numpy as np from monet_stats.correlation_metrics import WDAC obs = np.array([350, 10, 20]) mod = np.array([345, 15, 25]) WDAC(obs, mod) 0.9992386127814763

Source code in src/monet_stats/correlation_metrics.py
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
def WDAC(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Wind Direction Anomaly Correlation (WDAC).

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed wind direction values (degrees).
    mod : numpy.ndarray or xarray.DataArray
        Modeled wind direction values (degrees).
    axis : int, str, or iterable of such, optional
        Axis along which to compute the metric.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        WDAC value(s).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.correlation_metrics import WDAC
    >>> obs = np.array([350, 10, 20])
    >>> mod = np.array([345, 15, 25])
    >>> WDAC(obs, mod)
    0.9992386127814763
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis

        obs_rad = obs * np.pi / 180.0
        mod_rad = mod * np.pi / 180.0
        obs_anom = obs_rad - obs_rad.mean(dim=dim)
        mod_anom = mod_rad - mod_rad.mean(dim=dim)
        numerator = (np.sin(obs_anom) * np.sin(mod_anom)).sum(dim=dim)
        denominator = np.sqrt((np.sin(obs_anom) ** 2).sum(dim=dim) * (np.sin(mod_anom) ** 2).sum(dim=dim))
        result = numerator / denominator
        # Update history
        history = f"WDAC computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        obs_rad = np.deg2rad(obs)
        mod_rad = np.deg2rad(mod)
        if axis is not None:
            obs_bar_rad = np.ma.mean(obs_rad, axis=axis, keepdims=True)
            mod_bar_rad = np.ma.mean(mod_rad, axis=axis, keepdims=True)
        else:
            obs_bar_rad = np.ma.mean(obs_rad)
            mod_bar_rad = np.ma.mean(mod_rad)

        obs_anom = obs_rad - obs_bar_rad
        mod_anom = mod_rad - mod_bar_rad
        numerator = np.ma.sum(np.sin(obs_anom) * np.sin(mod_anom), axis=axis)
        denominator = np.ma.sqrt(
            np.ma.sum(np.sin(obs_anom) ** 2, axis=axis) * np.ma.sum(np.sin(mod_anom) ** 2, axis=axis)
        )
        return numerator / denominator

WDIOA(obs, mod, axis=None)

Wind Direction Index of Agreement (WDIOA).

Standard version.

Typical Use Cases

  • Quantifying the agreement between observed and modeled wind directions, accounting for circularity.
  • Used in wind energy, meteorology, and air quality studies to assess wind direction model performance.

Typical Values and Range

  • Range: 0 to 1
  • 1: Perfect agreement between observed and modeled wind directions
  • 0: No agreement (as bad as using the mean of observations)

Parameters

obs : numpy.ndarray or xarray.DataArray Observed wind direction values (degrees). mod : numpy.ndarray or xarray.DataArray Modeled wind direction values (degrees). axis : int, str, or iterable of such, optional Axis along which to compute the metric.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Wind direction index of agreement (unitless, 0-1).

Examples

import numpy as np from monet_stats.correlation_metrics import WDIOA obs = np.array([350, 10, 20]) mod = np.array([345, 15, 25]) WDIOA(obs, mod) 0.8

Source code in src/monet_stats/correlation_metrics.py
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
def WDIOA(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Wind Direction Index of Agreement (WDIOA).

    Standard version.

    Typical Use Cases
    -----------------
    - Quantifying the agreement between observed and modeled wind directions,
      accounting for circularity.
    - Used in wind energy, meteorology, and air quality studies to assess wind
      direction model performance.

    Typical Values and Range
    ------------------------
    - Range: 0 to 1
    - 1: Perfect agreement between observed and modeled wind directions
    - 0: No agreement (as bad as using the mean of observations)

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed wind direction values (degrees).
    mod : numpy.ndarray or xarray.DataArray
        Modeled wind direction values (degrees).
    axis : int, str, or iterable of such, optional
        Axis along which to compute the metric.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Wind direction index of agreement (unitless, 0-1).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.correlation_metrics import WDIOA
    >>> obs = np.array([350, 10, 20])
    >>> mod = np.array([345, 15, 25])
    >>> WDIOA(obs, mod)
    0.8
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis

        num = abs(circlebias(obs - mod)).sum(dim=dim)
        mean_obs = obs.mean(dim=dim)
        denom = (abs(circlebias(mod - mean_obs)) + abs(circlebias(obs - mean_obs))).sum(dim=dim)

        result = 1.0 - (num / denom)
        result = xr.where(denom == 0, 1.0, result)

        # Update history
        history = f"WDIOA computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        num = np.ma.sum(np.ma.abs(circlebias(np.subtract(obs, mod))), axis=axis)
        mean_obs = np.ma.mean(obs, axis=axis, keepdims=True)
        denom = np.ma.sum(
            np.ma.abs(circlebias(np.subtract(mod, mean_obs))) + np.ma.abs(circlebias(np.subtract(obs, mean_obs))),
            axis=axis,
        )
        result = np.where(denom == 0, 1.0, 1.0 - (num / denom))
        return result.item() if np.ndim(result) == 0 else result

WDIOA_m(obs, mod, axis=None)

Wind Direction Index of Agreement (WDIOA_m).

Robust to masked arrays.

Typical Use Cases

  • Quantifying the agreement between observed and modeled wind directions, accounting for circularity.
  • Used in wind energy, meteorology, and air quality studies to assess wind direction model performance.

Typical Values and Range

  • Range: 0 to 1
  • 1: Perfect agreement between observed and modeled wind directions
  • 0: No agreement (as bad as using the mean of observations)

Parameters

obs : numpy.ndarray or xarray.DataArray Observed wind direction values (degrees). mod : numpy.ndarray or xarray.DataArray Modeled wind direction values (degrees). axis : int, str, or iterable of such, optional Axis along which to compute the metric.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Wind direction index of agreement (unitless, 0-1).

Examples

import numpy as np from monet_stats.correlation_metrics import WDIOA_m obs = np.array([350, 10, 20]) mod = np.array([345, 15, 25]) WDIOA_m(obs, mod) 0.8

Source code in src/monet_stats/correlation_metrics.py
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
def WDIOA_m(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Wind Direction Index of Agreement (WDIOA_m).

    Robust to masked arrays.

    Typical Use Cases
    -----------------
    - Quantifying the agreement between observed and modeled wind directions,
      accounting for circularity.
    - Used in wind energy, meteorology, and air quality studies to assess wind
      direction model performance.

    Typical Values and Range
    ------------------------
    - Range: 0 to 1
    - 1: Perfect agreement between observed and modeled wind directions
    - 0: No agreement (as bad as using the mean of observations)

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed wind direction values (degrees).
    mod : numpy.ndarray or xarray.DataArray
        Modeled wind direction values (degrees).
    axis : int, str, or iterable of such, optional
        Axis along which to compute the metric.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Wind direction index of agreement (unitless, 0-1).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.correlation_metrics import WDIOA_m
    >>> obs = np.array([350, 10, 20])
    >>> mod = np.array([345, 15, 25])
    >>> WDIOA_m(obs, mod)
    0.8
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis

        obsmean = obs.mean(dim=dim)
        num = (abs(circlebias_m(obs - mod))).sum(dim=dim)
        denom = (abs(circlebias_m(mod - obsmean)) + abs(circlebias_m(obs - obsmean))).sum(dim=dim)

        result = 1.0 - (num / denom)
        result = xr.where(denom == 0, 1.0, result)

        # Update history
        history = f"WDIOA_m computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        obsmean = np.ma.mean(obs, axis=axis, keepdims=True)
        num = np.ma.sum(np.ma.abs(circlebias_m(np.subtract(obs, mod))), axis=axis)
        denom = np.ma.sum(
            np.ma.abs(circlebias_m(np.subtract(mod, obsmean))) + np.ma.abs(circlebias_m(np.subtract(obs, obsmean))),
            axis=axis,
        )
        result = np.where(denom == 0, 1.0, 1.0 - (num / denom))
        return result.item() if np.ndim(result) == 0 else result

WDRMSE(obs, mod, axis=None)

Wind Direction Root Mean Square Error (WDRMSE, model unit).

Standard version.

Typical Use Cases

  • Quantifying the average magnitude of wind direction errors, accounting for circularity.
  • Used in wind energy, meteorology, and air quality studies to assess wind direction model performance.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed wind direction values (degrees). mod : numpy.ndarray or xarray.DataArray Model predicted wind direction values (degrees). axis : int, str, or iterable of such, optional Axis along which to compute the statistic.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Wind direction root mean square error (degrees).

Examples

import numpy as np from monet_stats.correlation_metrics import WDRMSE obs = np.array([350, 10, 20]) mod = np.array([10, 20, 30]) WDRMSE(obs, mod) 20.0

Source code in src/monet_stats/correlation_metrics.py
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
def WDRMSE(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Wind Direction Root Mean Square Error (WDRMSE, model unit).

    Standard version.

    Typical Use Cases
    -----------------
    - Quantifying the average magnitude of wind direction errors, accounting for
      circularity.
    - Used in wind energy, meteorology, and air quality studies to assess wind
      direction model performance.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed wind direction values (degrees).
    mod : numpy.ndarray or xarray.DataArray
        Model predicted wind direction values (degrees).
    axis : int, str, or iterable of such, optional
        Axis along which to compute the statistic.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Wind direction root mean square error (degrees).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.correlation_metrics import WDRMSE
    >>> obs = np.array([350, 10, 20])
    >>> mod = np.array([10, 20, 30])
    >>> WDRMSE(obs, mod)
    20.0
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis

        result = (circlebias(mod - obs) ** 2).mean(dim=dim, keep_attrs=True) ** 0.5
        # Update history
        history = f"WDRMSE computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        return np.ma.sqrt(np.ma.mean((circlebias(np.subtract(mod, obs))) ** 2, axis=axis))

WDRMSE_m(obs, mod, axis=None)

Wind Direction Root Mean Square Error (WDRMSE, model unit).

Robust to masked arrays.

Typical Use Cases

  • Quantifying the average magnitude of wind direction errors, accounting for circularity, robust to masked arrays.
  • Used in wind energy, meteorology, and air quality studies to assess wind direction model performance.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed wind direction values (degrees). mod : numpy.ndarray or xarray.DataArray Model predicted wind direction values (degrees). axis : int, str, or iterable of such, optional Axis along which to compute the statistic.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Wind direction root mean square error (degrees).

Examples

import numpy as np from monet_stats.correlation_metrics import WDRMSE_m obs = np.array([350, 10, 20]) mod = np.array([10, 20, 30]) WDRMSE_m(obs, mod) 20.0

Source code in src/monet_stats/correlation_metrics.py
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
def WDRMSE_m(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Wind Direction Root Mean Square Error (WDRMSE, model unit).

    Robust to masked arrays.

    Typical Use Cases
    -----------------
    - Quantifying the average magnitude of wind direction errors, accounting for
      circularity, robust to masked arrays.
    - Used in wind energy, meteorology, and air quality studies to assess wind
      direction model performance.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed wind direction values (degrees).
    mod : numpy.ndarray or xarray.DataArray
        Model predicted wind direction values (degrees).
    axis : int, str, or iterable of such, optional
        Axis along which to compute the statistic.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Wind direction root mean square error (degrees).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.correlation_metrics import WDRMSE_m
    >>> obs = np.array([350, 10, 20])
    >>> mod = np.array([10, 20, 30])
    >>> WDRMSE_m(obs, mod)
    20.0
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis

        result = (circlebias_m(mod - obs) ** 2).mean(dim=dim, keep_attrs=True) ** 0.5
        # Update history
        history = f"WDRMSE_m computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        return np.ma.sqrt(np.ma.mean((circlebias_m(np.subtract(mod, obs))) ** 2, axis=axis))

d1(obs, mod, axis=None)

Modified Index of Agreement (d1).

Typical Use Cases

  • Quantifying the agreement between model and observations, less sensitive to outliers than IOA.
  • Used in model evaluation for robust skill assessment.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model predicted values. axis : int, str, or iterable of such, optional Axis along which to compute the statistic.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Modified index of agreement (unitless, 0-1).

Examples

import numpy as np from monet_stats.correlation_metrics import d1 obs = np.array([1, 2, 3]) mod = np.array([2, 2, 4]) d1(obs, mod) 0.5

Source code in src/monet_stats/correlation_metrics.py
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
def d1(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Modified Index of Agreement (d1).

    Typical Use Cases
    -----------------
    - Quantifying the agreement between model and observations, less sensitive
      to outliers than IOA.
    - Used in model evaluation for robust skill assessment.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model predicted values.
    axis : int, str, or iterable of such, optional
        Axis along which to compute the statistic.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Modified index of agreement (unitless, 0-1).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.correlation_metrics import d1
    >>> obs = np.array([1, 2, 3])
    >>> mod = np.array([2, 2, 4])
    >>> d1(obs, mod)
    0.5
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis

        num = abs(obs - mod).sum(dim=dim)
        mean_obs = obs.mean(dim=dim)
        denom = (abs(mod - mean_obs) + abs(obs - mean_obs)).sum(dim=dim)
        result = 1.0 - (num / denom)
        result = xr.where((num == 0) & (denom == 0), 1.0, result)
        result = xr.where((num != 0) & (denom == 0), -np.inf, result)

        # Update history
        history = f"d1 computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        num = np.ma.abs(np.subtract(obs, mod)).sum(axis=axis)
        mean_obs = np.ma.mean(obs, axis=axis, keepdims=True)
        denom = (np.ma.abs(np.subtract(mod, mean_obs)) + np.ma.abs(np.subtract(obs, mean_obs))).sum(axis=axis)
        with np.errstate(divide="ignore", invalid="ignore"):
            result = 1.0 - (num / denom)
            result = np.where((num == 0) & (denom == 0), 1.0, result)
            result = np.where((num != 0) & (denom == 0), -np.inf, result)
        return result.item() if np.ndim(result) == 0 else result

kendalltau(obs, mod, axis=None)

Kendall rank correlation coefficient.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable of such, optional Axis or dimension name along which to compute the coefficient.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Kendall rank correlation coefficient.

Examples

import numpy as np from monet_stats.correlation_metrics import kendalltau obs = np.array([1, 2, 3]) mod = np.array([2, 2, 4]) kendalltau(obs, mod) 1.0

Source code in src/monet_stats/correlation_metrics.py
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
def kendalltau(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Kendall rank correlation coefficient.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension name along which to compute the coefficient.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Kendall rank correlation coefficient.

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.correlation_metrics import kendalltau
    >>> obs = np.array([1, 2, 3])
    >>> mod = np.array([2, 2, 4])
    >>> kendalltau(obs, mod)
    1.0
    """
    from scipy.stats import kendalltau as _kendalltau

    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        if axis is None:
            dim = obs.dims
        elif isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis

        def _kendalltau_onlytau(a, b):
            mask = ~np.isnan(a) & ~np.isnan(b)
            if np.sum(mask) < 2:
                return np.nan
            return _kendalltau(a[mask], b[mask])[0]

        result = xr.apply_ufunc(
            _kendalltau_onlytau,
            obs,
            mod,
            input_core_dims=[[dim] if isinstance(dim, str) else list(dim)] * 2,
            output_core_dims=[[]],
            vectorize=True,
            dask="parallelized",
            dask_gufunc_kwargs={"allow_rechunk": True},
            output_dtypes=[float],
        )
        # Update history
        history = f"kendalltau computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        if axis is None:
            obsc, modc = matchedcompressed(obs, mod)
            if len(obsc) < 2:
                return np.nan
            return _kendalltau(obsc, modc)[0]
        else:
            # Fallback for numpy with axis: manual loop over other axes
            obs = np.asarray(obs)
            mod = np.asarray(mod)
            if axis < 0:
                axis = obs.ndim + axis

            obs_moved = np.moveaxis(obs, axis, -1)
            mod_moved = np.moveaxis(mod, axis, -1)

            other_shape = obs_moved.shape[:-1]
            obs_flat = obs_moved.reshape(-1, obs_moved.shape[-1])
            mod_flat = mod_moved.reshape(-1, mod_moved.shape[-1])

            results = []
            for i in range(len(obs_flat)):
                mask = ~np.isnan(obs_flat[i]) & ~np.isnan(mod_flat[i])
                if np.sum(mask) < 2:
                    results.append(np.nan)
                else:
                    results.append(_kendalltau(obs_flat[i][mask], mod_flat[i][mask])[0])

            return np.array(results).reshape(other_shape)

matchmasks(a1, a2)

Match and combine masks from two masked arrays.

Typical Use Cases

  • Ensuring that two arrays have the same mask for paired statistical calculations.
  • Used in metrics that require both arrays to have valid data at the same locations (e.g., correlation, regression).

Parameters

a1 : array-like or numpy.ma.MaskedArray First input array. a2 : array-like or numpy.ma.MaskedArray Second input array.

Returns

tuple of numpy.ma.MaskedArray Tuple of (a1_masked, a2_masked) with combined mask.

Examples

import numpy as np from monet.util import stats a1 = np.ma.array([1, 2, 3], mask=[0, 1, 0]) a2 = np.ma.array([4, 5, 6], mask=[0, 0, 1]) stats.matchmasks(a1, a2) (masked_array(data=[1, --, 3], mask=[False, True, False]), masked_array(data=[4, --, --], mask=[False, False, True]))

Source code in src/monet_stats/correlation_metrics.py
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
def matchmasks(a1: ArrayLike, a2: ArrayLike) -> Tuple[np.ma.MaskedArray, np.ma.MaskedArray]:
    """
    Match and combine masks from two masked arrays.

    Typical Use Cases
    -----------------
    - Ensuring that two arrays have the same mask for paired statistical calculations.
    - Used in metrics that require both arrays to have valid data at the same locations (e.g., correlation, regression).

    Parameters
    ----------
    a1 : array-like or numpy.ma.MaskedArray
        First input array.
    a2 : array-like or numpy.ma.MaskedArray
        Second input array.

    Returns
    -------
    tuple of numpy.ma.MaskedArray
        Tuple of (a1_masked, a2_masked) with combined mask.

    Examples
    --------
    >>> import numpy as np
    >>> from monet.util import stats
    >>> a1 = np.ma.array([1, 2, 3], mask=[0, 1, 0])
    >>> a2 = np.ma.array([4, 5, 6], mask=[0, 0, 1])
    >>> stats.matchmasks(a1, a2)
    (masked_array(data=[1, --, 3], mask=[False,  True, False]),
     masked_array(data=[4, --, --], mask=[False, False,  True]))
    """
    mask = np.ma.getmaskarray(a1) | np.ma.getmaskarray(a2)
    return np.ma.masked_where(mask, a1), np.ma.masked_where(mask, a2)

pearsonr(obs, mod, axis=None)

Pearson correlation coefficient.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable of such, optional Axis or dimension name along which to compute the coefficient.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Pearson correlation coefficient.

Examples

import numpy as np from monet_stats.correlation_metrics import pearsonr obs = np.array([1, 2, 3]) mod = np.array([2, 4, 6]) pearsonr(obs, mod) 1.0

Source code in src/monet_stats/correlation_metrics.py
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
def pearsonr(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Pearson correlation coefficient.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension name along which to compute the coefficient.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Pearson correlation coefficient.

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.correlation_metrics import pearsonr
    >>> obs = np.array([1, 2, 3])
    >>> mod = np.array([2, 4, 6])
    >>> pearsonr(obs, mod)
    1.0
    """
    from scipy.stats import pearsonr as _pearsonr

    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        if axis is None:
            dim = obs.dims
        elif isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis

        def _pearsonr_onlyr(a, b):
            mask = ~np.isnan(a) & ~np.isnan(b)
            if np.sum(mask) < 2 or np.var(a[mask]) == 0 or np.var(b[mask]) == 0:
                return np.nan
            return _pearsonr(a[mask], b[mask])[0]

        result = xr.apply_ufunc(
            _pearsonr_onlyr,
            obs,
            mod,
            input_core_dims=[[dim] if isinstance(dim, str) else list(dim)] * 2,
            output_core_dims=[[]],
            vectorize=True,
            dask="parallelized",
            dask_gufunc_kwargs={"allow_rechunk": True},
            output_dtypes=[float],
        )
        # Update history
        history = f"pearsonr computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        if axis is None:
            obsc, modc = matchedcompressed(obs, mod)
            if len(obsc) < 2 or np.var(obsc) == 0 or np.var(modc) == 0:
                return 0.0
            r_val, _ = _pearsonr(obsc, modc)
            return r_val if not np.isnan(r_val) else 0.0
        else:
            # For numpy with axis, use manual vectorized correlation
            obs_mean = np.nanmean(obs, axis=axis, keepdims=True)
            mod_mean = np.nanmean(mod, axis=axis, keepdims=True)
            obs_std = obs - obs_mean
            mod_std = mod - mod_mean
            num = np.nansum(obs_std * mod_std, axis=axis)
            den = np.sqrt(np.nansum(obs_std**2, axis=axis) * np.nansum(mod_std**2, axis=axis))
            with np.errstate(divide="ignore", invalid="ignore"):
                result = num / den
                return result.item() if np.ndim(result) == 0 else result

spearmanr(obs, mod, axis=None)

Spearman rank correlation coefficient.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable of such, optional Axis along which to compute the coefficient.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Spearman rank correlation coefficient.

Examples

import numpy as np from monet_stats.correlation_metrics import spearmanr obs = np.array([1, 2, 3]) mod = np.array([2, 2, 4]) spearmanr(obs, mod) 0.8660254037844387

Source code in src/monet_stats/correlation_metrics.py
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
def spearmanr(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Spearman rank correlation coefficient.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable of such, optional
        Axis along which to compute the coefficient.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Spearman rank correlation coefficient.

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.correlation_metrics import spearmanr
    >>> obs = np.array([1, 2, 3])
    >>> mod = np.array([2, 2, 4])
    >>> spearmanr(obs, mod)
    0.8660254037844387
    """
    from scipy.stats import spearmanr as _spearmanr

    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        if axis is None:
            dim = obs.dims
        elif isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis

        def _spearmanr_onlyrho(a, b):
            mask = ~np.isnan(a) & ~np.isnan(b)
            if np.sum(mask) < 2:
                return np.nan
            return _spearmanr(a[mask], b[mask])[0]

        result = xr.apply_ufunc(
            _spearmanr_onlyrho,
            obs,
            mod,
            input_core_dims=[[dim] if isinstance(dim, str) else list(dim)] * 2,
            output_core_dims=[[]],
            vectorize=True,
            dask="parallelized",
            dask_gufunc_kwargs={"allow_rechunk": True},
            output_dtypes=[float],
        )
        # Update history
        history = f"spearmanr computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        if axis is None:
            obsc, modc = matchedcompressed(obs, mod)
            if len(obsc) < 2:
                return np.nan
            return _spearmanr(obsc, modc)[0]
        else:
            # Fallback for numpy with axis: manual loop over other axes
            obs = np.asarray(obs)
            mod = np.asarray(mod)
            if axis < 0:
                axis = obs.ndim + axis

            # Move axis to last position
            obs_moved = np.moveaxis(obs, axis, -1)
            mod_moved = np.moveaxis(mod, axis, -1)

            # Reshape all other axes into one
            other_shape = obs_moved.shape[:-1]
            obs_flat = obs_moved.reshape(-1, obs_moved.shape[-1])
            mod_flat = mod_moved.reshape(-1, mod_moved.shape[-1])

            results = []
            for i in range(len(obs_flat)):
                mask = ~np.isnan(obs_flat[i]) & ~np.isnan(mod_flat[i])
                if np.sum(mask) < 2:
                    results.append(np.nan)
                else:
                    results.append(_spearmanr(obs_flat[i][mask], mod_flat[i][mask])[0])

            return np.array(results).reshape(other_shape)

taylor_skill(obs, mod, axis=None)

Taylor Skill Score (TSS).

Typical Use Cases

  • Summarizing model performance in a single skill score for use in Taylor diagrams.
  • Used in climate, weather, and environmental model evaluation.

Typical Values and Range

  • Range: 0 to 1
  • 1: Perfect agreement between model and observations
  • 0: No skill

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable of such, optional Axis along which to compute the skill score.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Taylor skill score (unitless, 0-1).

Examples

import numpy as np from monet_stats.correlation_metrics import taylor_skill obs = np.array([1, 2, 3]) mod = np.array([1.1, 1.9, 3.2]) taylor_skill(obs, mod) 0.9995574044955781

Source code in src/monet_stats/correlation_metrics.py
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
def taylor_skill(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Taylor Skill Score (TSS).

    Typical Use Cases
    -----------------
    - Summarizing model performance in a single skill score for use in Taylor
      diagrams.
    - Used in climate, weather, and environmental model evaluation.

    Typical Values and Range
    ------------------------
    - Range: 0 to 1
    - 1: Perfect agreement between model and observations
    - 0: No skill

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable of such, optional
        Axis along which to compute the skill score.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Taylor skill score (unitless, 0-1).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.correlation_metrics import taylor_skill
    >>> obs = np.array([1, 2, 3])
    >>> mod = np.array([1.1, 1.9, 3.2])
    >>> taylor_skill(obs, mod)
    0.9995574044955781
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis

        std_obs = obs.std(dim=dim)
        std_mod = mod.std(dim=dim)
        corr = xr.corr(obs, mod, dim=dim)

        # Calculate Taylor Skill Score using the common formula
        # S = 4 * (1 + R) / ( (sigma_p/sigma_o + sigma_o/sigma_p)^2 * (1 + R_max) )
        # Assuming R_max = 1.0
        norm_std = std_mod / std_obs
        result = (4.0 * (corr + 1.0)) / ((norm_std + 1.0 / norm_std) ** 2 * 2.0)
        # Update history
        history = f"taylor_skill computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        std_obs = np.ma.std(obs, axis=axis)
        std_mod = np.ma.std(mod, axis=axis)
        from scipy.stats import pearsonr

        if axis is None:
            if np.ma.is_masked(obs):
                corr = pearsonr(obs.compressed(), mod.compressed())[0]
            else:
                corr = pearsonr(obs, mod)[0]
        else:
            # Vectorized correlation over axis for numpy
            obs_mean = np.nanmean(obs, axis=axis, keepdims=True)
            mod_mean = np.nanmean(mod, axis=axis, keepdims=True)
            obs_anom = obs - obs_mean
            mod_anom = mod - mod_mean
            num_corr = np.nansum(obs_anom * mod_anom, axis=axis)
            den_corr = np.sqrt(np.nansum(obs_anom**2, axis=axis) * np.nansum(mod_anom**2, axis=axis))
            with np.errstate(divide="ignore", invalid="ignore"):
                corr = num_corr / den_corr

        norm_std = std_mod / std_obs
        with np.errstate(divide="ignore", invalid="ignore"):
            result = (4.0 * (corr + 1.0)) / ((norm_std + 1.0 / norm_std) ** 2 * 2.0)
            result = np.where(np.isnan(result) | np.isinf(result), 1.0, result)
        return result.item() if np.ndim(result) == 0 else result

Error Metrics

Error Metrics for Model Evaluation

COE(obs, mod, axis=None)

Center of Mass Error (COE).

The COE measures the displacement between the centroids (centers of mass) of two fields. For spatial data, this represents the shift in the center of a feature (e.g., a storm or a pollutant plume).

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values (typically 2D spatial field). mod : numpy.ndarray or xarray.DataArray Model or predicted values (typically 2D spatial field). axis : int, str, or iterable of such, optional Axis or dimension(s) over which to compute the centroid. If None, computes over all axes.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Center of mass error (Euclidean distance between centroids).

Examples

import numpy as np from monet_stats.error_metrics import COE obs = np.zeros((5, 5)) obs[2, 2] = 1.0 # Peak at center (2, 2) mod = np.zeros((5, 5)) mod[3, 3] = 1.0 # Peak shifted to (3, 3)

Displacement is sqrt(1^2 + 1^2) = sqrt(2) approx 1.414

np.allclose(COE(obs, mod), np.sqrt(2)) True

Source code in src/monet_stats/error_metrics.py
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
def COE(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Center of Mass Error (COE).

    The COE measures the displacement between the centroids (centers of mass)
    of two fields. For spatial data, this represents the shift in the center
    of a feature (e.g., a storm or a pollutant plume).

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values (typically 2D spatial field).
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values (typically 2D spatial field).
    axis : int, str, or iterable of such, optional
        Axis or dimension(s) over which to compute the centroid.
        If None, computes over all axes.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Center of mass error (Euclidean distance between centroids).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.error_metrics import COE
    >>> obs = np.zeros((5, 5))
    >>> obs[2, 2] = 1.0  # Peak at center (2, 2)
    >>> mod = np.zeros((5, 5))
    >>> mod[3, 3] = 1.0  # Peak shifted to (3, 3)
    >>> # Displacement is sqrt(1^2 + 1^2) = sqrt(2) approx 1.414
    >>> np.allclose(COE(obs, mod), np.sqrt(2))
    True
    """
    from .utils_stats import _update_history

    def _get_centroid(da: xr.DataArray, dims: Iterable[str]) -> List[xr.DataArray]:
        """Helper to calculate centroid of a DataArray."""
        total = da.sum(dim=dims)
        # Handle zero sum to avoid division by zero
        total_safe = xr.where(total == 0, 1e-10, total)
        coords_list = []
        for d in dims:
            # Check if coord exists and is numeric
            if d in da.coords and np.issubdtype(da.coords[d].dtype, np.number):
                coord = da.coords[d]
            else:
                # Fallback to dimension indices
                coord = xr.DataArray(np.arange(da.sizes[d]), dims=d, name=d)
            # Weighted mean of coordinate
            c = (da * coord).sum(dim=dims) / total_safe
            coords_list.append(c)
        return coords_list

    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        if axis is None:
            dims = list(obs.dims)
        elif isinstance(axis, (int, str)):
            dims = [obs.dims[axis] if isinstance(axis, int) else axis]
        else:
            dims = [obs.dims[d] if isinstance(d, int) else d for d in axis]

        c_obs = _get_centroid(obs, dims)
        c_mod = _get_centroid(mod, dims)

        # Euclidean distance
        dist_sq = sum((cm - co) ** 2 for cm, co in zip(c_mod, c_obs))
        result = dist_sq**0.5

        return _update_history(result, "Center of Mass Error (COE)")

    # Fallback to numpy
    obs_arr = np.asanyarray(obs)
    mod_arr = np.asanyarray(mod)

    if axis is None:
        axes = tuple(range(obs_arr.ndim))
    elif isinstance(axis, int):
        axes = (axis,)
    else:
        axes = tuple(axis)

    def _get_numpy_centroid(arr: np.ndarray, axes_tuple: Tuple[int, ...]) -> List[np.ndarray]:
        """Helper to calculate centroid of a NumPy array."""
        total = np.sum(arr, axis=axes_tuple)
        total_safe = np.where(total == 0, 1e-10, total)
        c_list = []
        for ax in axes_tuple:
            # Create coordinate array for this axis
            shape = [1] * arr.ndim
            shape[ax] = arr.shape[ax]
            coord = np.arange(arr.shape[ax]).reshape(shape)
            c = np.sum(arr * coord, axis=axes_tuple) / total_safe
            c_list.append(c)
        return c_list

    c_obs_np = _get_numpy_centroid(obs_arr, axes)
    c_mod_np = _get_numpy_centroid(mod_arr, axes)

    dist_sq_np = sum((cm - co) ** 2 for cm, co in zip(c_mod_np, c_obs_np))
    return dist_sq_np**0.5

CORR_INDEX(obs, mod, axis=None)

Correlation Index (CORR_INDEX).

Typical Use Cases

  • Measuring the linear relationship between observed and modeled values.
  • Used as a component in model evaluation.
  • Quantifies how well model captures observed patterns.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute correlation index.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Correlation index (unitless, -1 to 1).

Examples

import numpy as np from monet_stats.error_metrics import CORR_INDEX obs = np.array([1, 2, 3, 4]) mod = np.array([2, 4, 6, 8]) CORR_INDEX(obs, mod) 1.0

Source code in src/monet_stats/error_metrics.py
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
def CORR_INDEX(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Correlation Index (CORR_INDEX).

    Typical Use Cases
    -----------------
    - Measuring the linear relationship between observed and modeled values.
    - Used as a component in model evaluation.
    - Quantifies how well model captures observed patterns.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute correlation index.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Correlation index (unitless, -1 to 1).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.error_metrics import CORR_INDEX
    >>> obs = np.array([1, 2, 3, 4])
    >>> mod = np.array([2, 4, 6, 8])
    >>> CORR_INDEX(obs, mod)
    1.0
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        # Using xarray's built-in correlation function
        result = xr.corr(obs, mod, dim=dim)
        # Update history
        history = f"CORR_INDEX computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        # Fallback to numpy-compatible logic
        obs = np.asarray(obs)
        mod = np.asarray(mod)
        if axis is None:
            from scipy.stats import pearsonr

            return pearsonr(obs.flatten(), mod.flatten())[0]
        else:
            # Manual vectorized correlation over axis for robustness across scipy versions
            obs_mean = np.mean(obs, axis=axis, keepdims=True)
            mod_mean = np.mean(mod, axis=axis, keepdims=True)
            obs_std = obs - obs_mean
            mod_std = mod - mod_mean
            num = np.sum(obs_std * mod_std, axis=axis)
            den = np.sqrt(np.sum(obs_std**2, axis=axis) * np.sum(mod_std**2, axis=axis))
            return num / den

CRMSE(obs, mod, axis=None)

Centered Root Mean Square Error (CRMSE).

Typical Use Cases

  • Quantifying the error between anomalies (deviations from mean) of model and observations.
  • Used in Taylor diagrams, model evaluation, and forecast verification.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute CRMSE.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Centered root mean square error.

Examples

import numpy as np from monet_stats.error_metrics import CRMSE obs = np.array([1, 2, 3]) mod = np.array([2, 2, 4]) CRMSE(obs, mod) 0.4714045207910317

Source code in src/monet_stats/error_metrics.py
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
def CRMSE(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Centered Root Mean Square Error (CRMSE).

    Typical Use Cases
    -----------------
    - Quantifying the error between anomalies (deviations from mean) of model
      and observations.
    - Used in Taylor diagrams, model evaluation, and forecast verification.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute CRMSE.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Centered root mean square error.

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.error_metrics import CRMSE
    >>> obs = np.array([1, 2, 3])
    >>> mod = np.array([2, 2, 4])
    >>> CRMSE(obs, mod)
    0.4714045207910317
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        o_ = obs - obs.mean(dim=dim)
        m_ = mod - mod.mean(dim=dim)
        result = ((m_ - o_) ** 2).mean(dim=dim, keep_attrs=True) ** 0.5
        # Update history
        history = f"CRMSE computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        o_ = np.subtract(obs, np.mean(obs, axis=axis, keepdims=True))
        m_ = np.subtract(mod, np.mean(mod, axis=axis, keepdims=True))
        return (np.ma.abs(m_ - o_) ** 2).mean(axis=axis) ** 0.5

IOA(obs, mod, axis=None)

Index of Agreement (IOA).

Typical Use Cases

  • Quantifying the agreement between model and observations, normalized by total deviation.
  • Used in model evaluation for skill assessment.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute IOA.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Index of agreement (unitless, 0-1).

Examples

import numpy as np from monet_stats.error_metrics import IOA obs = np.array([1, 2, 3]) mod = np.array([2, 2, 4]) IOA(obs, mod) 0.8

Source code in src/monet_stats/error_metrics.py
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
def IOA(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Index of Agreement (IOA).

    Typical Use Cases
    -----------------
    - Quantifying the agreement between model and observations, normalized by
      total deviation.
    - Used in model evaluation for skill assessment.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute IOA.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Index of agreement (unitless, 0-1).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.error_metrics import IOA
    >>> obs = np.array([1, 2, 3])
    >>> mod = np.array([2, 2, 4])
    >>> IOA(obs, mod)
    0.8
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        obs_mean = obs.mean(dim=dim)
        num = ((obs - mod) ** 2).sum(dim=dim)
        denom = ((abs(mod - obs_mean) + abs(obs - obs_mean)) ** 2).sum(dim=dim)
        result = 1.0 - (num / denom)
        # Update history
        history = f"IOA computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        obs_mean = np.mean(obs, axis=axis, keepdims=True)
        num = np.sum((obs - mod) ** 2, axis=axis)
        denom = np.sum((np.abs(mod - obs_mean) + np.abs(obs - obs_mean)) ** 2, axis=axis)
        return 1.0 - (num / denom)

IOA_m(obs, mod, axis=None)

Index of Agreement (IOA) - robust to masked arrays.

Typical Use Cases

  • Quantifying the agreement between model and observations, normalized by total deviation, robust to missing data.
  • Used in model evaluation for skill assessment with incomplete datasets.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute IOA.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Index of agreement (unitless, 0-1).

Examples

import numpy as np from monet_stats.error_metrics import IOA_m obs = np.array([1, 2, 3]) mod = np.array([2, 2, 4]) IOA_m(obs, mod) 0.8

Source code in src/monet_stats/error_metrics.py
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
def IOA_m(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Index of Agreement (IOA) - robust to masked arrays.

    Typical Use Cases
    -----------------
    - Quantifying the agreement between model and observations, normalized by
      total deviation, robust to missing data.
    - Used in model evaluation for skill assessment with incomplete datasets.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute IOA.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Index of agreement (unitless, 0-1).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.error_metrics import IOA_m
    >>> obs = np.array([1, 2, 3])
    >>> mod = np.array([2, 2, 4])
    >>> IOA_m(obs, mod)
    0.8
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        # IOA implementation for xarray already handles NaNs
        return IOA(obs, mod, axis=axis)
    else:
        obs_mean = np.ma.mean(obs, axis=axis, keepdims=True)
        num = np.ma.sum((obs - mod) ** 2, axis=axis)
        denom = np.ma.sum((np.ma.abs(mod - obs_mean) + np.ma.abs(obs - obs_mean)) ** 2, axis=axis)
        return 1.0 - (num / denom)

LOG_ERROR(obs, mod, axis=None)

Logarithmic Error Metric.

Typical Use Cases

  • Quantifying errors for variables that span several orders of magnitude.
  • Used in atmospheric sciences for concentration data (e.g., pollutants).
  • Helpful when relative rather than absolute errors are important.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values (should be positive). mod : numpy.ndarray or xarray.DataArray Model or predicted values (should be positive). axis : int, str, or iterable of such, optional Axis or dimension along which to compute log error.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Logarithmic error metric.

Examples

import numpy as np from monet_stats.error_metrics import LOG_ERROR obs = np.array([1, 100]) mod = np.array([2, 200]) LOG_ERROR(obs, mod) 0.34657359027997264

Source code in src/monet_stats/error_metrics.py
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
def LOG_ERROR(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Logarithmic Error Metric.

    Typical Use Cases
    -----------------
    - Quantifying errors for variables that span several orders of magnitude.
    - Used in atmospheric sciences for concentration data (e.g., pollutants).
    - Helpful when relative rather than absolute errors are important.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values (should be positive).
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values (should be positive).
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute log error.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Logarithmic error metric.

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.error_metrics import LOG_ERROR
    >>> obs = np.array([1, 100])
    >>> mod = np.array([2, 200])
    >>> LOG_ERROR(obs, mod)
    0.34657359027997264
    """
    # Add small epsilon to avoid log(0) and handle negative values
    epsilon = 1e-10

    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        # Use abs to handle potential negative values, then add epsilon
        obs_safe = abs(obs) + epsilon
        mod_safe = abs(mod) + epsilon
        obs_log = np.log(obs_safe)
        mod_log = np.log(mod_safe)
        result = ((mod_log - obs_log) ** 2).mean(dim=dim, keep_attrs=True) ** 0.5
        # Update history
        history = f"LOG_ERROR computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        # Use abs to handle potential negative values, then add epsilon
        obs_safe = np.abs(obs) + epsilon
        mod_safe = np.abs(mod) + epsilon
        obs_log = np.log(obs_safe)
        mod_log = np.log(mod_safe)

        result = np.sqrt(np.mean((mod_log - obs_log) ** 2, axis=axis))
        # Return 0 for perfect agreement
        if np.array_equal(obs, mod):
            return 0.0
        return result

MAE(obs, mod, axis=None)

Mean Absolute Error (MAE).

Typical Use Cases

  • Quantifying the average magnitude of errors between model and observations, regardless of direction.
  • Used in model evaluation, forecast verification, and regression analysis.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute MAE.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Mean absolute error.

Examples

import numpy as np from monet_stats.error_metrics import MAE obs = np.array([1, 2, 3]) mod = np.array([2, 2, 4]) MAE(obs, mod) 0.6666666666666666

Source code in src/monet_stats/error_metrics.py
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
def MAE(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Mean Absolute Error (MAE).

    Typical Use Cases
    -----------------
    - Quantifying the average magnitude of errors between model and observations,
      regardless of direction.
    - Used in model evaluation, forecast verification, and regression analysis.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute MAE.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Mean absolute error.

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.error_metrics import MAE
    >>> obs = np.array([1, 2, 3])
    >>> mod = np.array([2, 2, 4])
    >>> MAE(obs, mod)
    0.6666666666666666
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        result = abs(mod - obs).mean(dim=dim, keep_attrs=True)
        # Update history
        history = f"MAE computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        return np.ma.abs(np.subtract(mod, obs)).mean(axis=axis)

MAE_m(obs, mod, axis=None)

Mean Absolute Error (MAE) - robust to masked arrays.

Typical Use Cases

  • Quantifying the average magnitude of errors between model and observations, regardless of direction, robust to missing data.
  • Used in model evaluation, forecast verification, and regression analysis with incomplete datasets.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute MAE.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Mean absolute error.

Examples

import numpy as np from monet_stats.error_metrics import MAE_m obs = np.array([1, 2, 3]) mod = np.array([2, 2, 4]) MAE_m(obs, mod) 0.6666666666666666

Source code in src/monet_stats/error_metrics.py
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
def MAE_m(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Mean Absolute Error (MAE) - robust to masked arrays.

    Typical Use Cases
    -----------------
    - Quantifying the average magnitude of errors between model and
      observations, regardless of direction, robust to missing data.
    - Used in model evaluation, forecast verification, and regression analysis
      with incomplete datasets.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute MAE.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Mean absolute error.

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.error_metrics import MAE_m
    >>> obs = np.array([1, 2, 3])
    >>> mod = np.array([2, 2, 4])
    >>> MAE_m(obs, mod)
    0.6666666666666666
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        # MAE implementation for xarray already handles NaNs
        return MAE(obs, mod, axis=axis)
    else:
        return np.ma.mean(np.ma.abs(np.subtract(mod, obs)), axis=axis)

MAE_norm(obs, mod, axis=None)

Normalized Mean Absolute Error (MAE_norm).

Normalizes MAE by the range of observations.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute normalized MAE.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Normalized mean absolute error (unitless).

Source code in src/monet_stats/error_metrics.py
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
def MAE_norm(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Normalized Mean Absolute Error (MAE_norm).

    Normalizes MAE by the range of observations.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute normalized MAE.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Normalized mean absolute error (unitless).
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        mae = abs(mod - obs).mean(dim=dim, keep_attrs=True)
        obs_min = obs.min(dim=dim)
        obs_max = obs.max(dim=dim)
        obs_range = obs_max - obs_min
        # Avoid division by zero
        result = xr.where(obs_range == 0, mae, mae / obs_range)
        # Update history
        history = f"MAE_norm computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        mae = np.mean(np.abs(np.subtract(mod, obs)), axis=axis)
        obs_min = np.min(obs, axis=axis)
        obs_max = np.max(obs, axis=axis)
        obs_range = obs_max - obs_min
        # Avoid division by zero
        result = np.where(obs_range == 0, mae, mae / obs_range)
        return result.item() if np.ndim(result) == 0 else result

MAPE(obs, mod, axis=None)

Mean Absolute Percentage Error (MAPE).

Typical Use Cases

  • Quantifying the average relative error between model and observations as a percentage.
  • Used in time series forecasting, regression, and model evaluation for percentage-based error assessment.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute MAPE.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Mean absolute percentage error (in percent).

Examples

import numpy as np from monet_stats.error_metrics import MAPE obs = np.array([1, 2, 3]) mod = np.array([2, 2, 4]) MAPE(obs, mod) 50.0

Source code in src/monet_stats/error_metrics.py
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
def MAPE(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Mean Absolute Percentage Error (MAPE).

    Typical Use Cases
    -----------------
    - Quantifying the average relative error between model and observations
      as a percentage.
    - Used in time series forecasting, regression, and model evaluation for
      percentage-based error assessment.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute MAPE.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Mean absolute percentage error (in percent).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.error_metrics import MAPE
    >>> obs = np.array([1, 2, 3])
    >>> mod = np.array([2, 2, 4])
    >>> MAPE(obs, mod)
    50.0
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        result = (100 * abs(mod - obs) / abs(obs)).mean(dim=dim, keep_attrs=True)
        # Update history
        history = f"MAPE computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        return (100 * np.ma.abs(np.subtract(mod, obs)) / np.ma.abs(obs)).mean(axis=axis)

MAPE_mod(obs, mod, axis=None)

Modified Mean Absolute Percentage Error (MAPE).

This version handles cases where observations might be zero or near zero by using a small epsilon to avoid division by zero.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute MAPE.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Mean absolute percentage error (in percent).

Source code in src/monet_stats/error_metrics.py
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
def MAPE_mod(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Modified Mean Absolute Percentage Error (MAPE).

    This version handles cases where observations might be zero or near zero
    by using a small epsilon to avoid division by zero.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute MAPE.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Mean absolute percentage error (in percent).
    """
    # Small epsilon to avoid division by zero
    epsilon = 1e-8

    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        # Add epsilon to avoid division by zero
        obs_safe = xr.where(abs(obs) < epsilon, epsilon, obs)
        result = (100 * abs(mod - obs) / abs(obs_safe)).mean(dim=dim, keep_attrs=True)
        # Update history
        history = f"MAPE_mod computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        # Add epsilon to avoid division by zero
        obs_safe = np.where(np.abs(obs) < epsilon, epsilon, obs)
        return (100 * np.abs(np.subtract(mod, obs)) / np.abs(obs_safe)).mean(axis=axis)

MAPEm(obs, mod, axis=None)

Mean Absolute Percentage Error (MAPE) - robust to masked arrays.

Typical Use Cases

  • Quantifying the average relative error between model and observations as a percentage, robust to missing data.
  • Used in time series forecasting, regression, and model evaluation for percentage-based error assessment.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute MAPE.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Mean absolute percentage error (in percent).

Examples

import numpy as np from monet_stats.error_metrics import MAPEm obs = np.array([1, 2, 3]) mod = np.array([2, 2, 4]) MAPEm(obs, mod) 50.0

Source code in src/monet_stats/error_metrics.py
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
def MAPEm(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Mean Absolute Percentage Error (MAPE) - robust to masked arrays.

    Typical Use Cases
    -----------------
    - Quantifying the average relative error between model and observations as
      a percentage, robust to missing data.
    - Used in time series forecasting, regression, and model evaluation for
      percentage-based error assessment.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute MAPE.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Mean absolute percentage error (in percent).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.error_metrics import MAPEm
    >>> obs = np.array([1, 2, 3])
    >>> mod = np.array([2, 2, 4])
    >>> MAPEm(obs, mod)
    50.0
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        # MAPE implementation for xarray already handles NaNs
        return MAPE(obs, mod, axis=axis)
    else:
        return 100 * np.ma.mean(np.ma.abs((mod - obs) / obs), axis=axis)

MASE(obs, mod, axis=None)

Mean Absolute Scaled Error (MASE).

Typical Use Cases

  • Quantifying model error relative to the error of a simple baseline model (e.g., naive forecast).
  • Used in time series forecasting and model evaluation.
  • Provides scale-independent comparison across different datasets.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute MASE.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Mean absolute scaled error (unitless).

Examples

import numpy as np from monet_stats.error_metrics import MASE obs = np.array([1, 2, 3, 4]) mod = np.array([1.1, 2.1, 3.1, 4.1]) MASE(obs, mod) 0.1

Source code in src/monet_stats/error_metrics.py
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
def MASE(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Mean Absolute Scaled Error (MASE).

    Typical Use Cases
    -----------------
    - Quantifying model error relative to the error of a simple baseline model
      (e.g., naive forecast).
    - Used in time series forecasting and model evaluation.
    - Provides scale-independent comparison across different datasets.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute MASE.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Mean absolute scaled error (unitless).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.error_metrics import MASE
    >>> obs = np.array([1, 2, 3, 4])
    >>> mod = np.array([1.1, 2.1, 3.1, 4.1])
    >>> MASE(obs, mod)
    0.1
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis

        # Calculate naive forecast error (using previous observation)
        # Assuming 'time' is a dimension for shift
        # If 'time' is not present, we use the provided dimension or axis
        if "time" in obs.dims:
            naive_error = abs(obs - obs.shift(time=1)).mean(dim=dim, skipna=True)
        else:
            # Fallback if time is not named 'time'
            naive_error = abs(obs - obs.shift({obs.dims[0]: 1})).mean(dim=dim, skipna=True)

        model_error = abs(mod - obs).mean(dim=dim, keep_attrs=True)
        result = model_error / naive_error
        # Update history
        history = f"MASE computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        # Calculate naive forecast error (using previous observation)
        if axis is not None:
            naive_diff = np.diff(obs, axis=axis)
            naive_error = np.mean(np.abs(naive_diff), axis=axis)
        else:
            naive_diff = np.diff(obs)
            naive_error = np.mean(np.abs(naive_diff))
        model_error = np.mean(np.abs(np.subtract(mod, obs)), axis=axis)
        return model_error / naive_error

MASE_mod(obs, mod, axis=None)

Modified Mean Absolute Scaled Error (MASE).

This version handles cases where the naive forecast error is zero by using a small epsilon to avoid division by zero.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute MASE.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Mean absolute scaled error (unitless).

Source code in src/monet_stats/error_metrics.py
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
def MASE_mod(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Modified Mean Absolute Scaled Error (MASE).

    This version handles cases where the naive forecast error is zero
    by using a small epsilon to avoid division by zero.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute MASE.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Mean absolute scaled error (unitless).
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        # Calculate naive forecast error (using previous observation)
        if "time" in obs.dims:
            naive_error = abs(obs - obs.shift(time=1)).mean(dim=dim, skipna=True)
        else:
            naive_error = abs(obs - obs.shift({obs.dims[0]: 1})).mean(dim=dim, skipna=True)

        model_error = abs(mod - obs).mean(dim=dim, keep_attrs=True)
        # Avoid division by zero
        result = xr.where(naive_error == 0, model_error, model_error / naive_error)
        # Update history
        history = f"MASE_mod computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        # Calculate naive forecast error (using previous observation)
        if axis is not None:
            naive_diff = np.diff(obs, axis=axis)
            naive_error = np.mean(np.abs(naive_diff), axis=axis)
        else:
            naive_diff = np.diff(obs)
            naive_error = np.mean(np.abs(naive_diff))
        model_error = np.mean(np.abs(np.subtract(mod, obs)), axis=axis)
        # Avoid division by zero
        result = np.where(naive_error == 0, model_error, model_error / naive_error)
        return result.item() if np.ndim(result) == 0 else result

MASEm(obs, mod, axis=None)

Mean Absolute Scaled Error (MASE) - robust to masked arrays.

Typical Use Cases

  • Quantifying model error relative to the error of a simple baseline model (e.g., naive forecast), robust to masked arrays.
  • Used in time series forecasting and model evaluation with missing data.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute MASE.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Mean absolute scaled error (unitless).

Examples

import numpy as np from monet_stats.error_metrics import MASEm obs = np.array([1, 2, 3, 4]) mod = np.array([1.1, 2.1, 3.1, 4.1]) MASEm(obs, mod) 0.1

Source code in src/monet_stats/error_metrics.py
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
def MASEm(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Mean Absolute Scaled Error (MASE) - robust to masked arrays.

    Typical Use Cases
    -----------------
    - Quantifying model error relative to the error of a simple baseline model
      (e.g., naive forecast), robust to masked arrays.
    - Used in time series forecasting and model evaluation with missing data.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute MASE.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Mean absolute scaled error (unitless).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.error_metrics import MASEm
    >>> obs = np.array([1, 2, 3, 4])
    >>> mod = np.array([1.1, 2.1, 3.1, 4.1])
    >>> MASEm(obs, mod)
    0.1
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        # MASE implementation for xarray already handles NaNs with skipna=True
        return MASE(obs, mod, axis=axis)
    else:
        # Calculate naive forecast error (using previous observation) with masked arrays
        if axis is not None:
            # Use numpy's gradient-like approach for masked arrays
            naive_diff = np.ma.diff(obs, axis=axis)
            naive_error = np.ma.mean(np.ma.abs(naive_diff), axis=axis)
        else:
            naive_diff = np.ma.diff(obs)
            naive_error = np.ma.mean(np.ma.abs(naive_diff))
        model_error = np.ma.mean(np.ma.abs(np.subtract(mod, obs)), axis=axis)
        return model_error / naive_error

MB(obs, mod, axis=None)

Mean Bias (MB).

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute the mean bias.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Mean bias value(s) = mean(model - observation). Positive values indicate model overestimation.

Source code in src/monet_stats/error_metrics.py
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
def MB(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Mean Bias (MB).

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute the mean bias.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Mean bias value(s) = mean(model - observation).
        Positive values indicate model overestimation.
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        result = (mod - obs).mean(dim=dim, keep_attrs=True)
        # Update history
        history = f"MB computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        return np.ma.mean(np.subtract(mod, obs), axis=axis)

MNB(obs, mod, axis=None)

Mean Normalized Bias (%).

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute the bias.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Mean normalized bias (percent).

Source code in src/monet_stats/error_metrics.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
def MNB(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Mean Normalized Bias (%).

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute the bias.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Mean normalized bias (percent).
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        result = ((mod - obs) / obs).mean(dim=dim, keep_attrs=True) * 100.0
        # Update history
        history = f"MNB computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        return np.ma.masked_invalid((mod - obs) / obs).mean(axis=axis) * 100.0

MNE(obs, mod, axis=None)

Mean Normalized Gross Error (%).

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute the error.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Mean normalized gross error (percent).

Source code in src/monet_stats/error_metrics.py
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
def MNE(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Mean Normalized Gross Error (%).

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute the error.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Mean normalized gross error (percent).
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        result = (abs(mod - obs) / obs).mean(dim=dim, keep_attrs=True) * 100.0
        # Update history
        history = f"MNE computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        return np.ma.masked_invalid(np.ma.abs(mod - obs) / obs).mean(axis=axis) * 100.0

MO(obs, mod, axis=None)

Mean Error (MO) - Mean of (model - observation).

Typical Use Cases

  • Quantifying the average bias between model predictions and observations.
  • Used in model evaluation to assess systematic errors.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute the mean error.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Mean error (model - observation) in observation units. Returns 0.0 for perfect agreement.

Examples

import numpy as np from monet_stats.error_metrics import MO obs = np.array([1, 2, 3, 4, 5]) mod = np.array([1.1, 2.1, 3.1, 4.1, 5.1]) MO(obs, mod) 0.1

Source code in src/monet_stats/error_metrics.py
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
def MO(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Mean Error (MO) - Mean of (model - observation).

    Typical Use Cases
    -----------------
    - Quantifying the average bias between model predictions and observations.
    - Used in model evaluation to assess systematic errors.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute the mean error.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Mean error (model - observation) in observation units.
        Returns 0.0 for perfect agreement.

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.error_metrics import MO
    >>> obs = np.array([1, 2, 3, 4, 5])
    >>> mod = np.array([1.1, 2.1, 3.1, 4.1, 5.1])
    >>> MO(obs, mod)
    0.1
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        result = (mod - obs).mean(dim=dim, keep_attrs=True)
        # Update history
        history = f"MO computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        return np.mean(np.subtract(mod, obs), axis=axis)

MP(obs=None, mod=None, axis=None)

Mean Predictions (model unit).

Typical Use Cases

  • Calculating the average value of model predictions for baseline or climatological reference.
  • Used in normalization, anomaly calculation, and summary statistics for model output.

Parameters

obs : numpy.ndarray or xarray.DataArray, optional Observed values (not used for MP but included for signature matching). mod : numpy.ndarray or xarray.DataArray Model predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute the mean.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Mean of predictions.

Source code in src/monet_stats/error_metrics.py
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
def MP(
    obs: Optional[Union[np.ndarray, xr.DataArray]] = None,
    mod: Union[np.ndarray, xr.DataArray] = None,
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Mean Predictions (model unit).

    Typical Use Cases
    -----------------
    - Calculating the average value of model predictions for baseline or
      climatological reference.
    - Used in normalization, anomaly calculation, and summary statistics for
      model output.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray, optional
        Observed values (not used for MP but included for signature matching).
    mod : numpy.ndarray or xarray.DataArray
        Model predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute the mean.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Mean of predictions.
    """
    if isinstance(mod, xr.DataArray):
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = mod.dims[axis]
        else:
            dim = axis
        result = mod.mean(dim=dim, keep_attrs=True)
        # Update history
        history = f"MP computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        return np.mean(mod, axis=axis)

MdnB(obs, mod, axis=None)

Median Bias (MdnB).

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute the median bias.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Median bias value(s) = median(model - observation). Positive values indicate model overestimation.

Source code in src/monet_stats/error_metrics.py
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
def MdnB(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Median Bias (MdnB).

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute the median bias.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Median bias value(s) = median(model - observation).
        Positive values indicate model overestimation.
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        result = (mod - obs).median(dim=dim, keep_attrs=True)
        # Update history
        history = f"MdnB computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        return np.ma.median(np.subtract(mod, obs), axis=axis)

MdnNB(obs, mod, axis=None)

Median Normalized Bias (%).

Typical Use Cases

  • Assessing the central tendency of model bias relative to observations, less sensitive to outliers than mean.
  • Useful for robust model evaluation in the presence of skewed or non-normal error distributions.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute the bias.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Median normalized bias (percent).

Source code in src/monet_stats/error_metrics.py
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
def MdnNB(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Median Normalized Bias (%).

    Typical Use Cases
    -----------------
    - Assessing the central tendency of model bias relative to observations,
      less sensitive to outliers than mean.
    - Useful for robust model evaluation in the presence of skewed or non-normal
      error distributions.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute the bias.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Median normalized bias (percent).
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        result = ((mod - obs) / obs).median(dim=dim, keep_attrs=True) * 100.0
        # Update history
        history = f"MdnNB computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        return np.ma.median(np.ma.masked_invalid((mod - obs) / obs), axis=axis) * 100.0

MdnNE(obs, mod, axis=None)

Median Normalized Gross Error (%).

Typical Use Cases

  • Evaluating the typical magnitude of model errors relative to observations, robust to outliers.
  • Useful for summarizing error magnitude in non-Gaussian or heavy-tailed error distributions.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute the error.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Median normalized gross error (percent).

Source code in src/monet_stats/error_metrics.py
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
def MdnNE(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Median Normalized Gross Error (%).

    Typical Use Cases
    -----------------
    - Evaluating the typical magnitude of model errors relative to observations,
      robust to outliers.
    - Useful for summarizing error magnitude in non-Gaussian or heavy-tailed
      error distributions.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute the error.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Median normalized gross error (percent).
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        result = (abs(mod - obs) / obs).median(dim=dim, keep_attrs=True) * 100.0
        # Update history
        history = f"MdnNE computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        return np.ma.median(np.ma.masked_invalid(np.ma.abs(mod - obs) / obs), axis=axis) * 100.0

MdnO(obs, mod, axis=None)

Median Error (MdnO) - Median of (model - observation).

Typical Use Cases

  • Quantifying the typical bias between model predictions and observations, robust to outliers.
  • Used in robust model evaluation for non-parametric error assessment.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute the median error.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Median error (model - observation) in observation units. Returns 0.0 for perfect agreement.

Examples

import numpy as np from monet_stats.error_metrics import MdnO obs = np.array([1, 2, 3, 4, 5]) mod = np.array([1.1, 2.1, 3.1, 4.1, 5.1]) MdnO(obs, mod) 0.1

Source code in src/monet_stats/error_metrics.py
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
def MdnO(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Median Error (MdnO) - Median of (model - observation).

    Typical Use Cases
    -----------------
    - Quantifying the typical bias between model predictions and observations,
      robust to outliers.
    - Used in robust model evaluation for non-parametric error assessment.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute the median error.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Median error (model - observation) in observation units.
        Returns 0.0 for perfect agreement.

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.error_metrics import MdnO
    >>> obs = np.array([1, 2, 3, 4, 5])
    >>> mod = np.array([1.1, 2.1, 3.1, 4.1, 5.1])
    >>> MdnO(obs, mod)
    0.1
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        result = (mod - obs).median(dim=dim, keep_attrs=True)
        # Update history
        history = f"MdnO computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        return np.median(np.subtract(mod, obs), axis=axis)

MdnP(obs, mod, axis=None)

Median Error (MdnP) - Median of (model - observation).

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute the median error.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Median error (model - observation) in model units. Returns 0.0 for perfect agreement.

Source code in src/monet_stats/error_metrics.py
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
def MdnP(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Median Error (MdnP) - Median of (model - observation).

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute the median error.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Median error (model - observation) in model units.
        Returns 0.0 for perfect agreement.
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        result = (mod - obs).median(dim=dim, keep_attrs=True)
        # Update history
        history = f"MdnP computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        return np.median(np.subtract(mod, obs), axis=axis)

MedAE(obs, mod, axis=None)

Median Absolute Error (MedAE).

Typical Use Cases

  • Evaluating the typical magnitude of errors, robust to outliers and non-normal error distributions.
  • Used in robust regression, model evaluation, and forecast verification.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute MedAE.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Median absolute error.

Examples

import numpy as np from monet_stats.error_metrics import MedAE obs = np.array([1, 2, 3]) mod = np.array([2, 2, 4]) MedAE(obs, mod) 1.0

Source code in src/monet_stats/error_metrics.py
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
def MedAE(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Median Absolute Error (MedAE).

    Typical Use Cases
    -----------------
    - Evaluating the typical magnitude of errors, robust to outliers and
      non-normal error distributions.
    - Used in robust regression, model evaluation, and forecast verification.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute MedAE.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Median absolute error.

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.error_metrics import MedAE
    >>> obs = np.array([1, 2, 3])
    >>> mod = np.array([2, 2, 4])
    >>> MedAE(obs, mod)
    1.0
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        result = abs(mod - obs).median(dim=dim, keep_attrs=True)
        # Update history
        history = f"MedAE computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        return np.ma.median(np.ma.abs(np.subtract(mod, obs)), axis=axis)

MedAE_m(obs, mod, axis=None)

Median Absolute Error (MedAE) - robust to masked arrays and outliers.

Typical Use Cases

  • Evaluating the typical magnitude of errors, robust to outliers and non-normal error distributions with missing data.
  • Used in robust regression, model evaluation, and forecast verification with incomplete datasets.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute MedAE.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Median absolute error.

Examples

import numpy as np from monet_stats.error_metrics import MedAE_m obs = np.array([1, 2, 3]) mod = np.array([2, 2, 4]) MedAE_m(obs, mod) 1.0

Source code in src/monet_stats/error_metrics.py
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
def MedAE_m(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Median Absolute Error (MedAE) - robust to masked arrays and outliers.

    Typical Use Cases
    -----------------
    - Evaluating the typical magnitude of errors, robust to outliers and
      non-normal error distributions with missing data.
    - Used in robust regression, model evaluation, and forecast verification
      with incomplete datasets.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute MedAE.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Median absolute error.

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.error_metrics import MedAE_m
    >>> obs = np.array([1, 2, 3])
    >>> mod = np.array([2, 2, 4])
    >>> MedAE_m(obs, mod)
    1.0
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        # MedAE implementation for xarray already handles NaNs
        return MedAE(obs, mod, axis=axis)
    else:
        return np.ma.median(np.ma.abs(np.subtract(mod, obs)), axis=axis)

NMSE(obs, mod, axis=None)

Normalized Mean Square Error (NMSE).

Typical Use Cases

  • Quantifying the normalized squared error between model and observations.
  • Used in model evaluation to compare performance across different variables or sites with different scales.
  • Provides dimensionless error metric for cross-comparison.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute NMSE.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Normalized mean square error (unitless).

Examples

import numpy as np from monet_stats.error_metrics import NMSE obs = np.array([1, 2, 3, 4]) mod = np.array([2, 2, 2, 2]) NMSE(obs, mod) 0.25

Source code in src/monet_stats/error_metrics.py
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
def NMSE(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Normalized Mean Square Error (NMSE).

    Typical Use Cases
    -----------------
    - Quantifying the normalized squared error between model and observations.
    - Used in model evaluation to compare performance across different variables
      or sites with different scales.
    - Provides dimensionless error metric for cross-comparison.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute NMSE.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Normalized mean square error (unitless).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.error_metrics import NMSE
    >>> obs = np.array([1, 2, 3, 4])
    >>> mod = np.array([2, 2, 2, 2])
    >>> NMSE(obs, mod)
    0.25
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        mse = ((mod - obs) ** 2).mean(dim=dim, keep_attrs=True)
        obs_var = obs.var(dim=dim)
        # Handle case where variance is 0 (perfect agreement)
        result = xr.where(obs_var == 0, 0, mse / obs_var)
        # Update history
        history = f"NMSE computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        mse = np.mean((np.subtract(mod, obs)) ** 2, axis=axis)
        obs_var = np.var(obs, axis=axis)
        # Handle case where variance is 0 (perfect agreement)
        result = np.where(obs_var == 0, 0, mse / obs_var)
        return result.item() if np.ndim(result) == 0 else result

NMdnGE(obs, mod, axis=None)

Normalized Median Gross Error (%).

Typical Use Cases

  • Comparing the typical (median) error magnitude, normalized by the mean observation, for robust model evaluation.
  • Useful for inter-comparison of model performance across sites or variables with different scales.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute the error.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Normalized median gross error (percent).

Examples

import numpy as np from monet_stats.error_metrics import NMdnGE obs = np.array([1, 2, 3, 4, 100]) mod = np.array([1.1, 2.1, 3.1, 4.1, 105]) NMdnGE(obs, mod) 0.45454545454545453

Source code in src/monet_stats/error_metrics.py
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
def NMdnGE(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Normalized Median Gross Error (%).

    Typical Use Cases
    -----------------
    - Comparing the typical (median) error magnitude, normalized by the mean
      observation, for robust model evaluation.
    - Useful for inter-comparison of model performance across sites or variables
      with different scales.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute the error.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Normalized median gross error (percent).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.error_metrics import NMdnGE
    >>> obs = np.array([1, 2, 3, 4, 100])
    >>> mod = np.array([1.1, 2.1, 3.1, 4.1, 105])
    >>> NMdnGE(obs, mod)
    0.45454545454545453
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        result = (abs(mod - obs).median(dim=dim) / obs.mean(dim=dim)) * 100.0
        # Update history
        history = f"NMdnGE computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        return np.ma.masked_invalid(np.ma.median(np.ma.abs(mod - obs), axis=axis) / np.ma.mean(obs, axis=axis)) * 100.0

NO(obs, mod=None, axis=None)

N Observations (#).

Typical Use Cases

  • Counting the number of valid (non-masked) observations in a dataset.
  • Used to report sample size for statistical summaries and model evaluation.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray, optional Model predicted values (not used for NO but included for signature matching). axis : int, str, or iterable of such, optional Axis or dimension along which to count.

Returns

int, numpy.ndarray, or xarray.DataArray Number of valid observations.

Source code in src/monet_stats/error_metrics.py
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
def NO(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Optional[Union[np.ndarray, xr.DataArray]] = None,
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[int, np.ndarray, xr.DataArray]:
    """
    N Observations (#).

    Typical Use Cases
    -----------------
    - Counting the number of valid (non-masked) observations in a dataset.
    - Used to report sample size for statistical summaries and model evaluation.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray, optional
        Model predicted values (not used for NO but included for signature matching).
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to count.

    Returns
    -------
    int, numpy.ndarray, or xarray.DataArray
        Number of valid observations.
    """
    if isinstance(obs, xr.DataArray):
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        return obs.count(dim=dim)
    else:
        return (~np.ma.getmaskarray(obs)).sum(axis=axis)

NOP(obs, mod, axis=None)

N Observations/Prediction Pairs (#).

Typical Use Cases

  • Counting the number of valid observation-prediction pairs for paired statistical analysis.
  • Used to ensure sample size consistency in paired model evaluation metrics.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to count.

Returns

int, numpy.ndarray, or xarray.DataArray Number of valid pairs.

Source code in src/monet_stats/error_metrics.py
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
def NOP(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[int, np.ndarray, xr.DataArray]:
    """
    N Observations/Prediction Pairs (#).

    Typical Use Cases
    -----------------
    - Counting the number of valid observation-prediction pairs for paired
      statistical analysis.
    - Used to ensure sample size consistency in paired model evaluation metrics.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to count.

    Returns
    -------
    int, numpy.ndarray, or xarray.DataArray
        Number of valid pairs.
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        # count() on aligned xarray handles NaNs in both by alignment if NaNs are coords,
        # but if NaNs are in data, we need to mask.
        # However, count() counts non-NaN values.
        # To get pairs where BOTH are not NaN:
        mask = obs.notnull() & mod.notnull()
        return mask.sum(dim=dim)
    else:
        obsc, modc = matchmasks(obs, mod)
        return (~np.ma.getmaskarray(obsc)).sum(axis=axis)

NP(obs=None, mod=None, axis=None)

N Predictions (#).

Typical Use Cases

  • Counting the number of valid (non-masked) model predictions in a dataset.
  • Used to report sample size for model output and for filtering invalid predictions.

Parameters

obs : numpy.ndarray or xarray.DataArray, optional Observed values (not used for NP but included for signature matching). mod : numpy.ndarray or xarray.DataArray Model predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to count.

Returns

int, numpy.ndarray, or xarray.DataArray Number of valid predictions.

Source code in src/monet_stats/error_metrics.py
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
def NP(
    obs: Optional[Union[np.ndarray, xr.DataArray]] = None,
    mod: Union[np.ndarray, xr.DataArray] = None,
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[int, np.ndarray, xr.DataArray]:
    """
    N Predictions (#).

    Typical Use Cases
    -----------------
    - Counting the number of valid (non-masked) model predictions in a dataset.
    - Used to report sample size for model output and for filtering invalid
      predictions.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray, optional
        Observed values (not used for NP but included for signature matching).
    mod : numpy.ndarray or xarray.DataArray
        Model predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to count.

    Returns
    -------
    int, numpy.ndarray, or xarray.DataArray
        Number of valid predictions.
    """
    if isinstance(mod, xr.DataArray):
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = mod.dims[axis]
        else:
            dim = axis
        return mod.count(dim=dim)
    else:
        return (~np.ma.getmaskarray(mod)).sum(axis=axis)

NRMSE(obs, mod, axis=None)

Normalized Root Mean Square Error (NRMSE).

Typical Use Cases

  • Quantifying the relative error between model and observations, normalized by the range of observations.
  • Used in model evaluation to compare performance across different variables or sites with different scales.
  • Provides dimensionless error metric for cross-comparison.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute NRMSE.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Normalized root mean square error (unitless).

Examples

import numpy as np from monet_stats.error_metrics import NRMSE obs = np.array([1, 2, 3, 4]) mod = np.array([2, 2, 2, 2]) NRMSE(obs, mod) 0.4714045207910317

Source code in src/monet_stats/error_metrics.py
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
def NRMSE(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Normalized Root Mean Square Error (NRMSE).

    Typical Use Cases
    -----------------
    - Quantifying the relative error between model and observations, normalized
      by the range of observations.
    - Used in model evaluation to compare performance across different variables
      or sites with different scales.
    - Provides dimensionless error metric for cross-comparison.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute NRMSE.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Normalized root mean square error (unitless).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.error_metrics import NRMSE
    >>> obs = np.array([1, 2, 3, 4])
    >>> mod = np.array([2, 2, 2, 2])
    >>> NRMSE(obs, mod)
    0.4714045207910317
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        rmse = ((mod - obs) ** 2).mean(dim=dim, keep_attrs=True) ** 0.5
        obs_range = obs.max(dim=dim) - obs.min(dim=dim)
        result = xr.where(obs_range == 0, 0, rmse / obs_range)
        # Update history
        history = f"NRMSE computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        rmse = np.ma.sqrt(np.ma.mean((np.subtract(mod, obs)) ** 2, axis=axis))
        obs_range = np.ma.max(obs, axis=axis) - np.ma.min(obs, axis=axis)
        with np.errstate(divide="ignore", invalid="ignore"):
            result = np.where(obs_range == 0, 0, rmse / obs_range)
            return result.item() if np.ndim(result) == 0 else result

NSC(obs, mod, axis=None)

Nash-Sutcliffe Coefficient (NSC) - Alternative to NSE.

Typical Use Cases

  • Quantifying the predictive power of hydrological models relative to the mean of observations.
  • Used in hydrology, meteorology, and environmental model evaluation.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute NSC.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Nash-Sutcliffe coefficient (unitless).

Examples

import numpy as np from monet_stats.error_metrics import NSC obs = np.array([1, 2, 3, 4]) mod = np.array([2, 2, 2, 2]) NSC(obs, mod) -0.33333333333333326

Source code in src/monet_stats/error_metrics.py
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
def NSC(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Nash-Sutcliffe Coefficient (NSC) - Alternative to NSE.

    Typical Use Cases
    -----------------
    - Quantifying the predictive power of hydrological models relative to
      the mean of observations.
    - Used in hydrology, meteorology, and environmental model evaluation.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute NSC.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Nash-Sutcliffe coefficient (unitless).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.error_metrics import NSC
    >>> obs = np.array([1, 2, 3, 4])
    >>> mod = np.array([2, 2, 2, 2])
    >>> NSC(obs, mod)
    -0.33333333333333326
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        obs_mean = obs.mean(dim=dim)
        numerator = ((obs - mod) ** 2).sum(dim=dim)
        denominator = ((obs - obs_mean) ** 2).sum(dim=dim)
        result = 1.0 - (numerator / denominator)
        # Update history
        history = f"NSC computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        obs_mean = np.mean(obs, axis=axis, keepdims=True)
        numerator = np.sum((obs - mod) ** 2, axis=axis)
        denominator = np.sum((obs - obs_mean) ** 2, axis=axis)
        return 1.0 - (numerator / denominator)

NSE_alpha(obs, mod, axis=None)

NSE Alpha - Decomposed NSE component measuring ratio of standard deviations.

Typical Use Cases

  • Quantifying the model's ability to capture the variability of observations.
  • Used in model evaluation to assess how well model represents observed variability.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute NSE_alpha.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray NSE alpha component (unitless).

Examples

import numpy as np from monet_stats.error_metrics import NSE_alpha obs = np.array([1, 2, 3, 4]) mod = np.array([2, 2, 2, 2]) NSE_alpha(obs, mod) 0.0

Source code in src/monet_stats/error_metrics.py
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
def NSE_alpha(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    NSE Alpha - Decomposed NSE component measuring ratio of standard deviations.

    Typical Use Cases
    -----------------
    - Quantifying the model's ability to capture the variability of observations.
    - Used in model evaluation to assess how well model represents observed
      variability.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute NSE_alpha.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        NSE alpha component (unitless).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.error_metrics import NSE_alpha
    >>> obs = np.array([1, 2, 3, 4])
    >>> mod = np.array([2, 2, 2, 2])
    >>> NSE_alpha(obs, mod)
    0.0
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        result = mod.std(dim=dim) / obs.std(dim=dim)
        # Update history
        history = f"NSE_alpha computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        return np.std(mod, axis=axis) / np.std(obs, axis=axis)

NSE_beta(obs, mod, axis=None)

NSE Beta - Decomposed NSE component measuring bias.

Typical Use Cases

  • Quantifying the systematic bias between model and observations.
  • Used in model evaluation to assess mean differences between model and observations.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute NSE_beta.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray NSE beta component (unitless).

Examples

import numpy as np from monet_stats.error_metrics import NSE_beta obs = np.array([1, 2, 3, 4]) mod = np.array([2, 2, 2, 2]) NSE_beta(obs, mod) 0.5

Source code in src/monet_stats/error_metrics.py
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
def NSE_beta(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    NSE Beta - Decomposed NSE component measuring bias.

    Typical Use Cases
    -----------------
    - Quantifying the systematic bias between model and observations.
    - Used in model evaluation to assess mean differences between model and
      observations.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute NSE_beta.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        NSE beta component (unitless).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.error_metrics import NSE_beta
    >>> obs = np.array([1, 2, 3, 4])
    >>> mod = np.array([2, 2, 2, 2])
    >>> NSE_beta(obs, mod)
    0.5
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        result = mod.mean(dim=dim) / obs.mean(dim=dim)
        # Update history
        history = f"NSE_beta computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        return np.mean(mod, axis=axis) / np.mean(obs, axis=axis)

RM(obs, mod, axis=None)

Root Mean Error (RM) - Root of mean squared error.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute the error.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Root of mean squared error (observation units). Returns 0.0 for perfect agreement.

Source code in src/monet_stats/error_metrics.py
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
def RM(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Root Mean Error (RM) - Root of mean squared error.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute the error.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Root of mean squared error (observation units).
        Returns 0.0 for perfect agreement.
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        result = np.sqrt(((obs - mod) ** 2).mean(dim=dim, keep_attrs=True))
        # Update history
        history = f"RM computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        return np.sqrt(np.mean((np.subtract(obs, mod)) ** 2, axis=axis))

RMSE(obs, mod, axis=None)

Root Mean Square Error (RMSE).

Typical Use Cases

  • Quantifying the average magnitude of errors between model and observations, accounting for large errors more heavily than MAE.
  • Used in model evaluation, forecast verification, and regression analysis.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute RMSE.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Root mean square error.

Examples

import numpy as np from monet_stats.error_metrics import RMSE obs = np.array([1, 2, 3]) mod = np.array([2, 2, 4]) RMSE(obs, mod) 0.816496580927726

Source code in src/monet_stats/error_metrics.py
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
def RMSE(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Root Mean Square Error (RMSE).

    Typical Use Cases
    -----------------
    - Quantifying the average magnitude of errors between model and observations,
      accounting for large errors more heavily than MAE.
    - Used in model evaluation, forecast verification, and regression analysis.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute RMSE.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Root mean square error.

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.error_metrics import RMSE
    >>> obs = np.array([1, 2, 3])
    >>> mod = np.array([2, 2, 4])
    >>> RMSE(obs, mod)
    0.816496580927726
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        result = ((mod - obs) ** 2).mean(dim=dim, keep_attrs=True) ** 0.5
        # Update history
        history = f"RMSE computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        return np.sqrt(np.mean((np.subtract(mod, obs)) ** 2, axis=axis))

RMSE_m(obs, mod, axis=None)

Root Mean Square Error (RMSE) - robust to masked arrays.

Typical Use Cases

  • Quantifying the average magnitude of errors between model and observations, accounting for large errors more heavily than MAE, robust to missing data.
  • Used in model evaluation, forecast verification, and regression analysis with incomplete datasets.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute RMSE.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Root mean square error.

Examples

import numpy as np from monet_stats.error_metrics import RMSE_m obs = np.array([1, 2, 3]) mod = np.array([2, 2, 4]) RMSE_m(obs, mod) 0.816496580927726

Source code in src/monet_stats/error_metrics.py
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
def RMSE_m(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Root Mean Square Error (RMSE) - robust to masked arrays.

    Typical Use Cases
    -----------------
    - Quantifying the average magnitude of errors between model and
      observations, accounting for large errors more heavily than MAE,
      robust to missing data.
    - Used in model evaluation, forecast verification, and regression analysis
      with incomplete datasets.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute RMSE.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Root mean square error.

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.error_metrics import RMSE_m
    >>> obs = np.array([1, 2, 3])
    >>> mod = np.array([2, 2, 4])
    >>> RMSE_m(obs, mod)
    0.816496580927726
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        # RMSE implementation for xarray already handles NaNs
        return RMSE(obs, mod, axis=axis)
    else:
        return np.ma.sqrt(np.ma.mean((np.subtract(mod, obs)) ** 2, axis=axis))

RMSE_norm(obs, mod, axis=None)

Normalized Root Mean Square Error (RMSE_norm).

Normalizes RMSE by the range of observations.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute normalized RMSE.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Normalized root mean square error (unitless).

Source code in src/monet_stats/error_metrics.py
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
def RMSE_norm(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Normalized Root Mean Square Error (RMSE_norm).

    Normalizes RMSE by the range of observations.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute normalized RMSE.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Normalized root mean square error (unitless).
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        rmse = ((mod - obs) ** 2).mean(dim=dim, keep_attrs=True) ** 0.5
        obs_min = obs.min(dim=dim)
        obs_max = obs.max(dim=dim)
        obs_range = obs_max - obs_min
        # Avoid division by zero
        result = xr.where(obs_range == 0, rmse, rmse / obs_range)
        # Update history
        history = f"RMSE_norm computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        rmse = np.sqrt(np.mean((np.subtract(mod, obs)) ** 2, axis=axis))
        obs_min = np.min(obs, axis=axis)
        obs_max = np.max(obs, axis=axis)
        obs_range = obs_max - obs_min
        # Avoid division by zero
        result = np.where(obs_range == 0, rmse, rmse / obs_range)
        return result.item() if np.ndim(result) == 0 else result

RMSPE(obs, mod, axis=None)

Root Mean Square Percentage Error (RMSPE).

Typical Use Cases

  • Quantifying the average relative error between model and observations as a percentage, emphasizing larger errors.
  • Used in time series forecasting, regression, and model evaluation for percentage-based error assessment.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute RMSPE.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Root mean square percentage error (in percent).

Examples

import numpy as np from monet_stats.error_metrics import RMSPE obs = np.array([1, 2, 3]) mod = np.array([2, 2, 4]) RMSPE(obs, mod) 50.0

Source code in src/monet_stats/error_metrics.py
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
def RMSPE(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Root Mean Square Percentage Error (RMSPE).

    Typical Use Cases
    -----------------
    - Quantifying the average relative error between model and observations as
      a percentage, emphasizing larger errors.
    - Used in time series forecasting, regression, and model evaluation for
      percentage-based error assessment.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute RMSPE.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Root mean square percentage error (in percent).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.error_metrics import RMSPE
    >>> obs = np.array([1, 2, 3])
    >>> mod = np.array([2, 2, 4])
    >>> RMSPE(obs, mod)
    50.0
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        result = (100 * ((mod - obs) / obs) ** 2).mean(dim=dim, keep_attrs=True) ** 0.5
        # Update history
        history = f"RMSPE computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        return 100 * np.ma.sqrt(np.ma.mean(((mod - obs) / obs) ** 2, axis=axis))

RMdn(obs, mod, axis=None)

Root Median Error (RMdn) - Root of median squared error.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute the error.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Root of median squared error (observation units). Returns 0.0 for perfect agreement.

Source code in src/monet_stats/error_metrics.py
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
def RMdn(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Root Median Error (RMdn) - Root of median squared error.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute the error.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Root of median squared error (observation units).
        Returns 0.0 for perfect agreement.
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        result = np.sqrt(((obs - mod) ** 2).median(dim=dim, keep_attrs=True))
        # Update history
        history = f"RMdn computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        squared_errors = (np.subtract(obs, mod)) ** 2
        return np.sqrt(np.median(squared_errors, axis=axis))

STDO(obs, mod, axis=None)

Standard deviation of Observation Errors (obs - mod).

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute the standard deviation. If None, computes over all axes.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Standard deviation of (observation - model) errors. Returns 0.0 for perfect agreement.

Examples

import numpy as np from monet_stats.error_metrics import STDO obs = np.array([1.0, 2.0, 3.0]) mod = np.array([1.1, 1.9, 3.2]) STDO(obs, mod) 0.1247219128924647

Source code in src/monet_stats/error_metrics.py
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
def STDO(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Standard deviation of Observation Errors (obs - mod).

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute the standard deviation.
        If None, computes over all axes.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Standard deviation of (observation - model) errors.
        Returns 0.0 for perfect agreement.

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.error_metrics import STDO
    >>> obs = np.array([1.0, 2.0, 3.0])
    >>> mod = np.array([1.1, 1.9, 3.2])
    >>> STDO(obs, mod)
    0.1247219128924647
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        errors = obs - mod
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        result = errors.std(dim=dim, keep_attrs=True)
        # Update history
        history = f"STDO computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result

    # Fallback to numpy-compatible logic
    errors = np.subtract(obs, mod)
    return np.std(errors, axis=axis)

STDP(obs, mod, axis=None)

Standard deviation of Prediction Errors (mod - obs).

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute the standard deviation. If None, computes over all axes.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Standard deviation of (model - observation) errors. Returns 0.0 for perfect agreement.

Examples

import numpy as np from monet_stats.error_metrics import STDP obs = np.array([1.0, 2.0, 3.0]) mod = np.array([1.1, 1.9, 3.2]) STDP(obs, mod) 0.1247219128924647

Source code in src/monet_stats/error_metrics.py
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
def STDP(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Standard deviation of Prediction Errors (mod - obs).

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute the standard deviation.
        If None, computes over all axes.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Standard deviation of (model - observation) errors.
        Returns 0.0 for perfect agreement.

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.error_metrics import STDP
    >>> obs = np.array([1.0, 2.0, 3.0])
    >>> mod = np.array([1.1, 1.9, 3.2])
    >>> STDP(obs, mod)
    0.1247219128924647
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        errors = mod - obs
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        result = errors.std(dim=dim, keep_attrs=True)
        # Update history
        history = f"STDP computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result

    # Fallback to numpy-compatible logic
    errors = np.subtract(mod, obs)
    return np.std(errors, axis=axis)

VOLUMETRIC_ERROR(obs, mod, axis=None)

Volumetric Error Metric.

Typical Use Cases

  • Quantifying the volume difference between observed and modeled features.
  • Used in hydrology for flood extent verification.
  • Applied in meteorology for precipitation volume verification.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute volumetric error.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Volumetric error metric.

Examples

import numpy as np from monet_stats.error_metrics import VOLUMETRIC_ERROR obs = np.array([1, 2, 3]) mod = np.array([2, 2, 4]) VOLUMETRIC_ERROR(obs, mod) 0.2

Source code in src/monet_stats/error_metrics.py
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
def VOLUMETRIC_ERROR(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Volumetric Error Metric.

    Typical Use Cases
    -----------------
    - Quantifying the volume difference between observed and modeled features.
    - Used in hydrology for flood extent verification.
    - Applied in meteorology for precipitation volume verification.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute volumetric error.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Volumetric error metric.

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.error_metrics import VOLUMETRIC_ERROR
    >>> obs = np.array([1, 2, 3])
    >>> mod = np.array([2, 2, 4])
    >>> VOLUMETRIC_ERROR(obs, mod)
    0.2
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        obs_sum = obs.sum(dim=dim)
        mod_sum = mod.sum(dim=dim)
        result = abs(mod_sum - obs_sum) / abs(obs_sum)
        # Update history
        history = f"VOLUMETRIC_ERROR computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        obs_sum = np.sum(obs, axis=axis)
        mod_sum = np.sum(mod, axis=axis)
        return np.abs(mod_sum - obs_sum) / np.abs(obs_sum)

WDMB(obs, mod, axis=None)

Wind Direction Mean Bias (WDMB, standard version).

This version uses circlebias, which is not robust to masked arrays. Use this if your data are dense and do not contain missing values.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed wind direction values (degrees). mod : numpy.ndarray or xarray.DataArray Model predicted wind direction values (degrees). axis : int, str, or iterable of such, optional Axis or dimension along which to compute the mean bias.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Mean wind direction bias (degrees).

Source code in src/monet_stats/error_metrics.py
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
def WDMB(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Wind Direction Mean Bias (WDMB, standard version).

    This version uses circlebias, which is not robust to masked arrays.
    Use this if your data are dense and do not contain missing values.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed wind direction values (degrees).
    mod : numpy.ndarray or xarray.DataArray
        Model predicted wind direction values (degrees).
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute the mean bias.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Mean wind direction bias (degrees).
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        result = circlebias(mod - obs).mean(dim=dim, keep_attrs=True)
        # Update history
        history = f"WDMB computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        return np.ma.mean(circlebias(np.subtract(mod, obs)), axis=axis)

WDMB_m(obs, mod, axis=None)

Wind Direction Mean Bias (WDMB, robust version for masked arrays).

This version uses circlebias_m, which is robust to masked arrays and missing data. Use this if your data may contain NaNs or masked values.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed wind direction values (degrees). mod : numpy.ndarray or xarray.DataArray Model predicted wind direction values (degrees). axis : int, str, or iterable of such, optional Axis or dimension along which to compute the mean bias.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Mean wind direction bias (degrees).

Source code in src/monet_stats/error_metrics.py
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
def WDMB_m(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Wind Direction Mean Bias (WDMB, robust version for masked arrays).

    This version uses circlebias_m, which is robust to masked arrays and
    missing data. Use this if your data may contain NaNs or masked values.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed wind direction values (degrees).
    mod : numpy.ndarray or xarray.DataArray
        Model predicted wind direction values (degrees).
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute the mean bias.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Mean wind direction bias (degrees).
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        result = circlebias_m(mod - obs).mean(dim=dim, keep_attrs=True)
        # Update history
        history = f"WDMB_m computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        return np.ma.mean(circlebias_m(np.subtract(mod, obs)), axis=axis)

WDMdnB(obs, mod, axis=None)

Wind Direction Median Bias (WDMdnB).

Parameters

obs : numpy.ndarray or xarray.DataArray Observed wind direction values (degrees). mod : numpy.ndarray or xarray.DataArray Model predicted wind direction values (degrees). axis : int, str, or iterable of such, optional Axis or dimension along which to compute the median bias.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Median wind direction bias (degrees).

Source code in src/monet_stats/error_metrics.py
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
def WDMdnB(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Wind Direction Median Bias (WDMdnB).

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed wind direction values (degrees).
    mod : numpy.ndarray or xarray.DataArray
        Model predicted wind direction values (degrees).
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute the median bias.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Median wind direction bias (degrees).
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        result = circlebias(mod - obs).median(dim=dim, keep_attrs=True)
        # Update history
        history = f"WDMdnB computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        return np.ma.median(circlebias(np.subtract(mod, obs)), axis=axis)

bias_fraction(obs, mod, axis=None)

Bias Fraction (BF).

Quantifies the fraction of total error that is due to systematic bias.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute bias fraction.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Bias fraction (unitless, 0-1).

Source code in src/monet_stats/error_metrics.py
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
def bias_fraction(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Bias Fraction (BF).

    Quantifies the fraction of total error that is due to systematic bias.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute bias fraction.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Bias fraction (unitless, 0-1).
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        bias = (mod - obs).mean(dim=dim)
        total_error = np.sqrt(((mod - obs) ** 2).mean(dim=dim, keep_attrs=True))
        # Avoid division by zero
        result = xr.where(total_error == 0, 0, (bias**2) / (total_error**2))
        # Update history
        history = f"bias_fraction computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        bias = np.mean(np.subtract(mod, obs), axis=axis)
        total_error = np.sqrt(np.mean((np.subtract(mod, obs)) ** 2, axis=axis))
        # Avoid division by zero
        result = np.where(total_error == 0, 0, (bias**2) / (total_error**2))
        return result.item() if np.ndim(result) == 0 else result

sMAPE(obs, mod, axis=None)

Symmetric Mean Absolute Percentage Error (sMAPE).

Typical Use Cases

  • Quantifying the average relative error between model and observations, normalized by their mean.
  • Used in time series forecasting, regression, and model evaluation for percentage-based error assessment.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute sMAPE.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Symmetric mean absolute percentage error (in percent).

Examples

import numpy as np from monet_stats.error_metrics import sMAPE obs = np.array([1, 2, 3]) mod = np.array([2, 2, 4]) sMAPE(obs, mod) 28.57142857142857

Source code in src/monet_stats/error_metrics.py
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
def sMAPE(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Symmetric Mean Absolute Percentage Error (sMAPE).

    Typical Use Cases
    -----------------
    - Quantifying the average relative error between model and observations,
      normalized by their mean.
    - Used in time series forecasting, regression, and model evaluation for
      percentage-based error assessment.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute sMAPE.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Symmetric mean absolute percentage error (in percent).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.error_metrics import sMAPE
    >>> obs = np.array([1, 2, 3])
    >>> mod = np.array([2, 2, 4])
    >>> sMAPE(obs, mod)
    28.57142857142857
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis
        result = (200 * abs(mod - obs) / (abs(mod) + abs(obs))).mean(dim=dim, keep_attrs=True)
        # Update history
        history = f"sMAPE computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        return (200 * np.ma.abs(np.subtract(mod, obs)) / (np.ma.abs(mod) + np.ma.abs(obs))).mean(axis=axis)

sMAPEm(obs, mod, axis=None)

Symmetric Mean Absolute Percentage Error (sMAPE) - robust to masked arrays.

Typical Use Cases

  • Quantifying the average relative error between model and observations, normalized by their mean, robust to missing data.
  • Used in time series forecasting, regression, and model evaluation for percentage-based error assessment.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute sMAPE.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Symmetric mean absolute percentage error (in percent).

Examples

import numpy as np from monet_stats.error_metrics import sMAPEm obs = np.array([1, 2, 3]) mod = np.array([2, 2, 4]) sMAPEm(obs, mod) 28.57142857142857

Source code in src/monet_stats/error_metrics.py
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
def sMAPEm(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Symmetric Mean Absolute Percentage Error (sMAPE) - robust to masked arrays.

    Typical Use Cases
    -----------------
    - Quantifying the average relative error between model and observations,
      normalized by their mean, robust to missing data.
    - Used in time series forecasting, regression, and model evaluation for
      percentage-based error assessment.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute sMAPE.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Symmetric mean absolute percentage error (in percent).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.error_metrics import sMAPEm
    >>> obs = np.array([1, 2, 3])
    >>> mod = np.array([2, 2, 4])
    >>> sMAPEm(obs, mod)
    28.57142857142857
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        # sMAPE implementation for xarray already handles NaNs
        return sMAPE(obs, mod, axis=axis)
    else:
        return 200 * np.ma.mean(np.ma.abs(mod - obs) / (np.ma.abs(mod) + np.ma.abs(obs)), axis=axis)

Efficiency Metrics

Efficiency Metrics for Model Evaluation

MSE(obs, mod, axis=None)

Mean Squared Error (MSE).

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute the error.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Mean squared error.

Examples

import numpy as np from monet_stats.efficiency_metrics import MSE obs = np.array([1, 2, 3]) mod = np.array([2, 2, 4]) MSE(obs, mod) 0.6666666666666666

Source code in src/monet_stats/efficiency_metrics.py
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
def MSE(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Mean Squared Error (MSE).

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute the error.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Mean squared error.

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.efficiency_metrics import MSE
    >>> obs = np.array([1, 2, 3])
    >>> mod = np.array([2, 2, 4])
    >>> MSE(obs, mod)
    0.6666666666666666
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis

        result = ((mod - obs) ** 2).mean(dim=dim, keep_attrs=True)

        # Update history
        history = f"MSE computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        return np.nanmean((mod - obs) ** 2, axis=axis)

NSE(obs, mod, axis=None)

Nash-Sutcliffe Efficiency (NSE).

Typical Use Cases

  • Quantifying the predictive power of hydrological models relative to the mean of observations.
  • Used in hydrology, meteorology, and environmental model evaluation.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute the statistic.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Nash-Sutcliffe efficiency (unitless).

Examples

import numpy as np from monet_stats.efficiency_metrics import NSE obs = np.array([1, 2, 3, 4]) mod = np.array([1.1, 2.1, 2.9, 4.1]) NSE(obs, mod) 0.98

Source code in src/monet_stats/efficiency_metrics.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
def NSE(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Nash-Sutcliffe Efficiency (NSE).

    Typical Use Cases
    -----------------
    - Quantifying the predictive power of hydrological models relative to the
      mean of observations.
    - Used in hydrology, meteorology, and environmental model evaluation.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute the statistic.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Nash-Sutcliffe efficiency (unitless).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.efficiency_metrics import NSE
    >>> obs = np.array([1, 2, 3, 4])
    >>> mod = np.array([1.1, 2.1, 2.9, 4.1])
    >>> NSE(obs, mod)
    0.98
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis

        obs_mean = obs.mean(dim=dim)
        numerator = ((obs - mod) ** 2).sum(dim=dim)
        denominator = ((obs - obs_mean) ** 2).sum(dim=dim)

        # Handle division by zero
        result = 1.0 - (numerator / denominator)
        result = xr.where((numerator == 0) & (denominator == 0), 1.0, result)
        result = xr.where((numerator != 0) & (denominator == 0), -np.inf, result)

        # Update history
        history = f"NSE computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        obs_mean = np.nanmean(obs, axis=axis, keepdims=True)
        numerator = np.nansum((obs - mod) ** 2, axis=axis)
        denominator = np.nansum((obs - obs_mean) ** 2, axis=axis)

        with np.errstate(divide="ignore", invalid="ignore"):
            result = 1.0 - (numerator / denominator)
            result = np.where((numerator == 0) & (denominator == 0), 1.0, result)
            result = np.where((numerator != 0) & (denominator == 0), -np.inf, result)
        return result.item() if np.ndim(result) == 0 else result

NSElog(obs, mod, axis=None)

Log Nash-Sutcliffe Efficiency (NSElog).

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values (positive values only). mod : numpy.ndarray or xarray.DataArray Model predicted values (positive values only). axis : int, str, or iterable of such, optional Axis or dimension along which to compute the statistic.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Log Nash-Sutcliffe efficiency (unitless).

Examples

import numpy as np from monet_stats.efficiency_metrics import NSElog obs = np.array([1, 10, 100]) mod = np.array([1.1, 9.0, 110]) NSElog(obs, mod) 0.988

Source code in src/monet_stats/efficiency_metrics.py
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
def NSElog(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Log Nash-Sutcliffe Efficiency (NSElog).

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values (positive values only).
    mod : numpy.ndarray or xarray.DataArray
        Model predicted values (positive values only).
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute the statistic.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Log Nash-Sutcliffe efficiency (unitless).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.efficiency_metrics import NSElog
    >>> obs = np.array([1, 10, 100])
    >>> mod = np.array([1.1, 9.0, 110])
    >>> NSElog(obs, mod)
    0.988
    """
    epsilon = 1e-6
    obs_log = np.log(obs + epsilon)
    mod_log = np.log(mod + epsilon)
    return NSE(obs_log, mod_log, axis=axis)

NSEm(obs, mod, axis=None)

Nash-Sutcliffe Efficiency (NSE) - robust to masked arrays.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute the statistic.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Nash-Sutcliffe efficiency (unitless).

Examples

import numpy as np from monet_stats.efficiency_metrics import NSEm obs = np.array([1, 2, np.nan, 4]) mod = np.array([1.1, 2.1, 3.0, 4.1]) NSEm(obs, mod) 0.985

Source code in src/monet_stats/efficiency_metrics.py
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
def NSEm(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Nash-Sutcliffe Efficiency (NSE) - robust to masked arrays.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute the statistic.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Nash-Sutcliffe efficiency (unitless).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.efficiency_metrics import NSEm
    >>> obs = np.array([1, 2, np.nan, 4])
    >>> mod = np.array([1.1, 2.1, 3.0, 4.1])
    >>> NSEm(obs, mod)
    0.985
    """
    # Standard NSE implementation already handles NaNs if using nan-aware functions
    return NSE(obs, mod, axis=axis)

PC(obs, mod, axis=None, tolerance=0.1)

Percent of Correct (PC).

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute the statistic. tolerance : float, optional Fraction of observed value used as tolerance (default 0.1).

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Percent of correct predictions (0-100%).

Examples

import numpy as np from monet_stats.efficiency_metrics import PC obs = np.array([1, 2, 3, 4]) mod = np.array([1.05, 2.5, 2.95, 4.05]) PC(obs, mod) 75.0

Source code in src/monet_stats/efficiency_metrics.py
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
def PC(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
    tolerance: float = 0.1,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Percent of Correct (PC).

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute the statistic.
    tolerance : float, optional
        Fraction of observed value used as tolerance (default 0.1).

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Percent of correct predictions (0-100%).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.efficiency_metrics import PC
    >>> obs = np.array([1, 2, 3, 4])
    >>> mod = np.array([1.05, 2.5, 2.95, 4.05])
    >>> PC(obs, mod)
    75.0
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis

        tol = tolerance * np.abs(obs)
        correct = np.abs(obs - mod) <= tol
        result = (correct.sum(dim=dim) / correct.count(dim=dim)) * 100.0

        # Update history
        history = f"PC computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        tol = tolerance * np.abs(obs)
        correct = np.abs(obs - mod) <= tol
        total = np.sum(~np.isnan(correct), axis=axis)
        correct_sum = np.nansum(correct, axis=axis)
        return (correct_sum / total) * 100.0

mNSE(obs, mod, axis=None)

Modified Nash-Sutcliffe Efficiency (mNSE).

Uses absolute differences instead of squared differences.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute the statistic.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Modified Nash-Sutcliffe efficiency (unitless).

Examples

import numpy as np from monet_stats.efficiency_metrics import mNSE obs = np.array([1, 2, 3, 4]) mod = np.array([1.1, 2.1, 2.9, 4.1]) mNSE(obs, mod) 0.92

Source code in src/monet_stats/efficiency_metrics.py
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
def mNSE(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Modified Nash-Sutcliffe Efficiency (mNSE).

    Uses absolute differences instead of squared differences.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute the statistic.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Modified Nash-Sutcliffe efficiency (unitless).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.efficiency_metrics import mNSE
    >>> obs = np.array([1, 2, 3, 4])
    >>> mod = np.array([1.1, 2.1, 2.9, 4.1])
    >>> mNSE(obs, mod)
    0.92
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis

        obs_mean = obs.mean(dim=dim)
        numerator = np.abs(obs - mod).sum(dim=dim)
        denominator = np.abs(obs - obs_mean).sum(dim=dim)

        result = 1.0 - (numerator / denominator)
        result = xr.where((numerator == 0) & (denominator == 0), 1.0, result)
        result = xr.where((numerator != 0) & (denominator == 0), -np.inf, result)

        # Update history
        history = f"mNSE computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        obs_mean = np.nanmean(obs, axis=axis, keepdims=True)
        numerator = np.nansum(np.abs(obs - mod), axis=axis)
        denominator = np.nansum(np.abs(obs - obs_mean), axis=axis)

        with np.errstate(divide="ignore", invalid="ignore"):
            result = 1.0 - (numerator / denominator)
            result = np.where((numerator == 0) & (denominator == 0), 1.0, result)
            result = np.where((numerator != 0) & (denominator == 0), -np.inf, result)
        return result.item() if np.ndim(result) == 0 else result

rNSE(obs, mod, axis=None)

Relative Nash-Sutcliffe Efficiency (rNSE).

Normalizes errors by the range of observed values.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model predicted values. axis : int, str, or iterable of such, optional Axis or dimension along which to compute the statistic.

Returns

numpy.number, numpy.ndarray, or xarray.DataArray Relative Nash-Sutcliffe efficiency (unitless).

Examples

import numpy as np from monet_stats.efficiency_metrics import rNSE obs = np.array([1, 2, 3, 4]) mod = np.array([1.1, 2.1, 2.9, 4.1]) rNSE(obs, mod) 0.992

Source code in src/monet_stats/efficiency_metrics.py
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
def rNSE(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Relative Nash-Sutcliffe Efficiency (rNSE).

    Normalizes errors by the range of observed values.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model predicted values.
    axis : int, str, or iterable of such, optional
        Axis or dimension along which to compute the statistic.

    Returns
    -------
    numpy.number, numpy.ndarray, or xarray.DataArray
        Relative Nash-Sutcliffe efficiency (unitless).

    Examples
    --------
    >>> import numpy as np
    >>> from monet_stats.efficiency_metrics import rNSE
    >>> obs = np.array([1, 2, 3, 4])
    >>> mod = np.array([1.1, 2.1, 2.9, 4.1])
    >>> rNSE(obs, mod)
    0.992
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Handle axis vs dim
        if axis is not None and isinstance(axis, int):
            dim = obs.dims[axis]
        else:
            dim = axis

        obs_mean = obs.mean(dim=dim)
        obs_range = obs.max(dim=dim) - obs.min(dim=dim)
        # Avoid division by zero in normalization
        obs_range_safe = xr.where(obs_range == 0, 1.0, obs_range)

        numerator = (((obs - mod) / obs_range_safe) ** 2).sum(dim=dim)
        denominator = (((obs - obs_mean) / obs_range_safe) ** 2).sum(dim=dim)

        result = 1.0 - (numerator / denominator)
        result = xr.where((numerator == 0) & (denominator == 0), 1.0, result)
        result = xr.where((numerator != 0) & (denominator == 0), -np.inf, result)

        # Update history
        history = f"rNSE computed at {pd.Timestamp.now().isoformat()}"
        result.attrs["history"] = f"{result.attrs.get('history', '')}\n{history}".strip()
        return result
    else:
        obs_mean = np.nanmean(obs, axis=axis, keepdims=True)
        obs_range = np.nanmax(obs, axis=axis, keepdims=True) - np.nanmin(obs, axis=axis, keepdims=True)
        obs_range_safe = np.where(obs_range == 0, 1.0, obs_range)

        with np.errstate(divide="ignore", invalid="ignore"):
            numerator = np.nansum(((obs - mod) / obs_range_safe) ** 2, axis=axis)
            denominator = np.nansum(((obs - obs_mean) / obs_range_safe) ** 2, axis=axis)
            result = 1.0 - (numerator / denominator)
            result = np.where((numerator == 0) & (denominator == 0), 1.0, result)
            result = np.where((numerator != 0) & (denominator == 0), -np.inf, result)
        return result.item() if np.ndim(result) == 0 else result

Relative Metrics

Relative/Percentage Metrics for Model Evaluation (Aero Protocol Compliant)

FB(obs, mod, axis=None)

Fractional Bias (%)

Typical Use Cases

  • Quantifying the average bias as a fraction of the sum of model and observed values.
  • Used in air quality and meteorological model evaluation for normalized bias assessment.

Parameters

obs : xarray.DataArray or numpy.ndarray Observed values. mod : xarray.DataArray or numpy.ndarray Model predicted values. axis : int or str or None, optional Axis or dimension along which to compute the statistic.

Returns

xarray.DataArray or numpy.ndarray or float Fractional bias (percent).

Source code in src/monet_stats/relative_metrics.py
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
def FB(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Fractional Bias (%)

    Typical Use Cases
    -----------------
    - Quantifying the average bias as a fraction of the sum of model and observed values.
    - Used in air quality and meteorological model evaluation for normalized bias assessment.

    Parameters
    ----------
    obs : xarray.DataArray or numpy.ndarray
        Observed values.
    mod : xarray.DataArray or numpy.ndarray
        Model predicted values.
    axis : int or str or None, optional
        Axis or dimension along which to compute the statistic.

    Returns
    -------
    xarray.DataArray or numpy.ndarray or float
        Fractional bias (percent).

    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        dim = axis
        if isinstance(axis, int):
            dim = obs.dims[axis]
        res = (((mod - obs) / (mod + obs)).mean(dim=dim) * 2.0) * 100.0
        return _update_history(res, "Fractional Bias (FB)")
    else:
        obs_arr = np.asanyarray(obs)
        mod_arr = np.asanyarray(mod)
        return (np.ma.masked_invalid((mod_arr - obs_arr) / (mod_arr + obs_arr)).mean(axis=axis) * 2.0) * 100.0

FE(obs, mod, axis=None)

Fractional Error (%)

Typical Use Cases

  • Quantifying the average magnitude of model errors as a fraction of the sum of model and observed values.
  • Used in air quality and meteorological model evaluation for normalized error assessment.

Parameters

obs : xarray.DataArray or numpy.ndarray Observed values. mod : xarray.DataArray or numpy.ndarray Model predicted values. axis : int or str or None, optional Axis or dimension along which to compute the statistic.

Returns

xarray.DataArray or numpy.ndarray or float Fractional error (percent).

Source code in src/monet_stats/relative_metrics.py
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
def FE(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Fractional Error (%)

    Typical Use Cases
    -----------------
    - Quantifying the average magnitude of model errors as a fraction of the sum of model and observed values.
    - Used in air quality and meteorological model evaluation for normalized error assessment.

    Parameters
    ----------
    obs : xarray.DataArray or numpy.ndarray
        Observed values.
    mod : xarray.DataArray or numpy.ndarray
        Model predicted values.
    axis : int or str or None, optional
        Axis or dimension along which to compute the statistic.

    Returns
    -------
    xarray.DataArray or numpy.ndarray or float
        Fractional error (percent).

    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        dim = axis
        if isinstance(axis, int):
            dim = obs.dims[axis]
        res = (abs(mod - obs) / (mod + obs)).mean(dim=dim) * 2.0 * 100.0
        return _update_history(res, "Fractional Error (FE)")
    else:
        obs_arr = np.ma.asanyarray(obs)
        mod_arr = np.ma.asanyarray(mod)
        return (np.ma.mean(np.ma.abs(mod_arr - obs_arr) / (mod_arr + obs_arr), axis=axis)) * 2.0 * 100.0

ME(obs, mod, axis=None)

Mean Gross Error (model and obs unit)

Typical Use Cases

  • Quantifying the average magnitude of model errors, regardless of direction.
  • Used in model evaluation to summarize overall error size.

Parameters

obs : xarray.DataArray or numpy.ndarray Observed values. mod : xarray.DataArray or numpy.ndarray Model predicted values. axis : int or str or None, optional Axis or dimension along which to compute the statistic.

Returns

xarray.DataArray or numpy.ndarray or float Mean gross error value(s).

Examples

import numpy as np obs = np.array([1, 2, 3, 4]) mod = np.array([2, 2, 2, 2]) ME(obs, mod) 1.0

Source code in src/monet_stats/relative_metrics.py
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
def ME(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Mean Gross Error (model and obs unit)

    Typical Use Cases
    -----------------
    - Quantifying the average magnitude of model errors, regardless of direction.
    - Used in model evaluation to summarize overall error size.

    Parameters
    ----------
    obs : xarray.DataArray or numpy.ndarray
        Observed values.
    mod : xarray.DataArray or numpy.ndarray
        Model predicted values.
    axis : int or str or None, optional
        Axis or dimension along which to compute the statistic.

    Returns
    -------
    xarray.DataArray or numpy.ndarray or float
        Mean gross error value(s).

    Examples
    --------
    >>> import numpy as np
    >>> obs = np.array([1, 2, 3, 4])
    >>> mod = np.array([2, 2, 2, 2])
    >>> ME(obs, mod)
    1.0
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        dim = axis
        if isinstance(axis, int):
            dim = obs.dims[axis]
        res = abs(mod - obs).mean(dim=dim)
        return _update_history(res, "Mean Gross Error (ME)")
    else:
        obs_arr = np.asanyarray(obs)
        mod_arr = np.asanyarray(mod)
        return np.mean(np.abs(mod_arr - obs_arr), axis=axis)

MNPB(obs, mod, paxis, axis=None)

Mean Normalized Peak Bias (%)

Parameters

obs : xarray.DataArray or numpy.ndarray Observed values. mod : xarray.DataArray or numpy.ndarray Model predicted values. paxis : int or str Axis or dimension along which to compute the peak (e.g., time or space). axis : int or str or None, optional Axis or dimension along which to compute the mean of normalized peak bias.

Returns

xarray.DataArray or numpy.ndarray or float Mean normalized peak bias (percent).

Source code in src/monet_stats/relative_metrics.py
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
def MNPB(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    paxis: Union[int, str],
    axis: Optional[Union[int, str]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Mean Normalized Peak Bias (%)

    Parameters
    ----------
    obs : xarray.DataArray or numpy.ndarray
        Observed values.
    mod : xarray.DataArray or numpy.ndarray
        Model predicted values.
    paxis : int or str
        Axis or dimension along which to compute the peak (e.g., time or space).
    axis : int or str or None, optional
        Axis or dimension along which to compute the mean of normalized peak bias.

    Returns
    -------
    xarray.DataArray or numpy.ndarray or float
        Mean normalized peak bias (percent).
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        pdim = paxis
        if isinstance(paxis, int):
            pdim = obs.dims[paxis]
        mdim = axis
        if isinstance(axis, int):
            mdim = obs.dims[axis]
        res = (((mod.max(dim=pdim) - obs.max(dim=pdim)) / obs.max(dim=pdim)).mean(dim=mdim)) * 100.0
        return _update_history(res, "Mean Normalized Peak Bias (MNPB)")
    else:
        obs_arr = np.ma.asanyarray(obs)
        mod_arr = np.ma.asanyarray(mod)
        return (
            (np.ma.max(mod_arr, axis=paxis) - np.ma.max(obs_arr, axis=paxis)) / np.ma.max(obs_arr, axis=paxis)
        ).mean(axis=axis) * 100.0

MNPE(obs, mod, paxis, axis=None)

Mean Normalized Peak Error (MNPE, %)

Typical Use Cases

  • Quantifying the average error in peak values between model and observations, normalized by observed peaks.
  • Used in model evaluation for extreme events, such as air quality exceedances or meteorological extremes.

Parameters

obs : xarray.DataArray or numpy.ndarray Observed values. mod : xarray.DataArray or numpy.ndarray Model predicted values. paxis : int or str Axis or dimension along which to compute the peak (e.g., time or space). axis : int or str or None, optional Axis or dimension along which to compute the mean of normalized peak error.

Returns

xarray.DataArray or numpy.ndarray or float Mean normalized peak error (percent).

Examples

import numpy as np obs = np.array([[1, 2, 3], [2, 3, 4]]) mod = np.array([[2, 2, 2], [2, 2, 5]]) MNPE(obs, mod, paxis=1) 33.33333333333333

Source code in src/monet_stats/relative_metrics.py
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
def MNPE(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    paxis: Union[int, str],
    axis: Optional[Union[int, str]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Mean Normalized Peak Error (MNPE, %)

    Typical Use Cases
    -----------------
    - Quantifying the average error in peak values between model and observations, normalized by observed peaks.
    - Used in model evaluation for extreme events, such as air quality exceedances or meteorological extremes.

    Parameters
    ----------
    obs : xarray.DataArray or numpy.ndarray
        Observed values.
    mod : xarray.DataArray or numpy.ndarray
        Model predicted values.
    paxis : int or str
        Axis or dimension along which to compute the peak (e.g., time or space).
    axis : int or str or None, optional
        Axis or dimension along which to compute the mean of normalized peak error.

    Returns
    -------
    xarray.DataArray or numpy.ndarray or float
        Mean normalized peak error (percent).

    Examples
    --------
    >>> import numpy as np
    >>> obs = np.array([[1, 2, 3], [2, 3, 4]])
    >>> mod = np.array([[2, 2, 2], [2, 2, 5]])
    >>> MNPE(obs, mod, paxis=1)
    33.33333333333333
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        pdim = paxis
        if isinstance(paxis, int):
            pdim = obs.dims[paxis]
        mdim = axis
        if isinstance(axis, int):
            mdim = obs.dims[axis]
        res = (abs(mod.max(dim=pdim) - obs.max(dim=pdim)) / obs.max(dim=pdim)).mean(dim=mdim) * 100.0
        return _update_history(res, "Mean Normalized Peak Error (MNPE)")
    else:
        obs_arr = np.ma.asanyarray(obs)
        mod_arr = np.ma.asanyarray(mod)
        return (
            np.ma.abs(np.ma.max(mod_arr, axis=paxis) - np.ma.max(obs_arr, axis=paxis)) / np.ma.max(obs_arr, axis=paxis)
        ).mean(axis=axis) * 100.0

MPE(obs, mod, axis=None)

Mean Peak Error (%)

Typical Use Cases

  • Quantifying the average error in peak values between model and observations.
  • Used in model evaluation for extreme events, such as air quality exceedances or meteorological extremes.

Parameters

obs : xarray.DataArray or numpy.ndarray Observed values. mod : xarray.DataArray or numpy.ndarray Model predicted values. axis : int or str or None, optional Axis or dimension along which to compute the mean of peak error.

Returns

xarray.DataArray or numpy.ndarray or float Mean peak error (percent).

Examples

import numpy as np obs = np.array([[1, 2, 3], [2, 3, 4]]) mod = np.array([[2, 2, 2], [2, 2, 5]]) MPE(obs, mod) 33.33333333

Source code in src/monet_stats/relative_metrics.py
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
def MPE(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Mean Peak Error (%)

    Typical Use Cases
    -----------------
    - Quantifying the average error in peak values between model and observations.
    - Used in model evaluation for extreme events, such as air quality exceedances
      or meteorological extremes.

    Parameters
    ----------
    obs : xarray.DataArray or numpy.ndarray
        Observed values.
    mod : xarray.DataArray or numpy.ndarray
        Model predicted values.
    axis : int or str or None, optional
        Axis or dimension along which to compute the mean of peak error.

    Returns
    -------
    xarray.DataArray or numpy.ndarray or float
        Mean peak error (percent).

    Examples
    --------
    >>> import numpy as np
    >>> obs = np.array([[1, 2, 3], [2, 3, 4]])
    >>> mod = np.array([[2, 2, 2], [2, 2, 5]])
    >>> MPE(obs, mod)
    33.33333333
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        dim = axis
        if isinstance(axis, int):
            dim = obs.dims[axis]
        res = (abs(mod.max(dim=dim) - obs.max(dim=dim)) / obs.max(dim=dim)).mean() * 100.0
        return _update_history(res, "Mean Peak Error (MPE)")
    else:
        obs_arr = np.ma.asanyarray(obs)
        mod_arr = np.ma.asanyarray(mod)
        return (
            np.ma.abs(np.ma.max(mod_arr, axis=axis) - np.ma.max(obs_arr, axis=axis)) / np.ma.max(obs_arr, axis=axis)
        ).mean() * 100.0

MdnE(obs, mod, axis=None)

Median Gross Error (model and obs unit)

Typical Use Cases

  • Evaluating the typical magnitude of model errors, robust to outliers.
  • Used in model evaluation when error distributions are skewed or non-normal.

Parameters

obs : xarray.DataArray or numpy.ndarray Observed values. mod : xarray.DataArray or numpy.ndarray Model predicted values. axis : int or str or None, optional Axis or dimension along which to compute the statistic.

Returns

xarray.DataArray or numpy.ndarray or float Median gross error value(s).

Examples

import numpy as np obs = np.array([1, 2, 3, 4]) mod = np.array([2, 2, 2, 2]) MdnE(obs, mod) 1.0

Source code in src/monet_stats/relative_metrics.py
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
def MdnE(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Median Gross Error (model and obs unit)

    Typical Use Cases
    -----------------
    - Evaluating the typical magnitude of model errors, robust to outliers.
    - Used in model evaluation when error distributions are skewed or non-normal.

    Parameters
    ----------
    obs : xarray.DataArray or numpy.ndarray
        Observed values.
    mod : xarray.DataArray or numpy.ndarray
        Model predicted values.
    axis : int or str or None, optional
        Axis or dimension along which to compute the statistic.

    Returns
    -------
    xarray.DataArray or numpy.ndarray or float
        Median gross error value(s).

    Examples
    --------
    >>> import numpy as np
    >>> obs = np.array([1, 2, 3, 4])
    >>> mod = np.array([2, 2, 2, 2])
    >>> MdnE(obs, mod)
    1.0
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        dim = axis
        if isinstance(axis, int):
            dim = obs.dims[axis]
        res = abs(mod - obs).median(dim=dim)
        return _update_history(res, "Median Gross Error (MdnE)")
    else:
        obs_arr = np.ma.asanyarray(obs)
        mod_arr = np.ma.asanyarray(mod)
        return np.ma.median(np.ma.abs(mod_arr - obs_arr), axis=axis)

MdnNPB(obs, mod, paxis, axis=None)

Median Normalized Peak Bias (%)

Parameters

obs : xarray.DataArray or numpy.ndarray Observed values. mod : xarray.DataArray or numpy.ndarray Model predicted values. paxis : int or str Axis or dimension along which to compute the peak (e.g., time or space). axis : int or str or None, optional Axis or dimension along which to compute the median of normalized peak bias.

Returns

xarray.DataArray or numpy.ndarray or float Median normalized peak bias (percent).

Source code in src/monet_stats/relative_metrics.py
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
def MdnNPB(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    paxis: Union[int, str],
    axis: Optional[Union[int, str]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Median Normalized Peak Bias (%)

    Parameters
    ----------
    obs : xarray.DataArray or numpy.ndarray
        Observed values.
    mod : xarray.DataArray or numpy.ndarray
        Model predicted values.
    paxis : int or str
        Axis or dimension along which to compute the peak (e.g., time or space).
    axis : int or str or None, optional
        Axis or dimension along which to compute the median of normalized peak bias.

    Returns
    -------
    xarray.DataArray or numpy.ndarray or float
        Median normalized peak bias (percent).
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        pdim = paxis
        if isinstance(paxis, int):
            pdim = obs.dims[paxis]
        mdim = axis
        if isinstance(axis, int):
            mdim = obs.dims[axis]
        res = ((mod.max(dim=pdim) - obs.max(dim=pdim)) / obs.max(dim=pdim)).median(dim=mdim) * 100.0
        return _update_history(res, "Median Normalized Peak Bias (MdnNPB)")
    else:
        obs_arr = np.ma.asanyarray(obs)
        mod_arr = np.ma.asanyarray(mod)
        return (
            np.ma.median(
                ((np.ma.max(mod_arr, axis=paxis) - np.ma.max(obs_arr, axis=paxis)) / np.ma.max(obs_arr, axis=paxis)),
                axis=axis,
            )
            * 100.0
        )

MdnNPE(obs, mod, paxis, axis=None)

Median Normalized Peak Error (MdnNPE, %)

Typical Use Cases

  • Evaluating the typical error in peak values between model and observations, normalized by observed peaks, robust to outliers.
  • Used in robust model evaluation for extreme events, such as air quality exceedances or meteorological extremes.

Parameters

obs : xarray.DataArray or numpy.ndarray Observed values. mod : xarray.DataArray or numpy.ndarray Model predicted values. paxis : int or str Axis or dimension along which to compute the peak (e.g., time or space). axis : int or str or None, optional Axis or dimension along which to compute the median of normalized peak error.

Returns

xarray.DataArray or numpy.ndarray or float Median normalized peak error (percent).

Examples

import numpy as np obs = np.array([[1, 2, 3], [2, 3, 4]]) mod = np.array([[2, 2, 2], [2, 2, 5]]) MdnNPE(obs, mod, paxis=1) 33.33333333333333

Source code in src/monet_stats/relative_metrics.py
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
def MdnNPE(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    paxis: Union[int, str],
    axis: Optional[Union[int, str]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Median Normalized Peak Error (MdnNPE, %)

    Typical Use Cases
    -----------------
    - Evaluating the typical error in peak values between model and observations,
      normalized by observed peaks, robust to outliers.
    - Used in robust model evaluation for extreme events, such as air quality exceedances
      or meteorological extremes.

    Parameters
    ----------
    obs : xarray.DataArray or numpy.ndarray
        Observed values.
    mod : xarray.DataArray or numpy.ndarray
        Model predicted values.
    paxis : int or str
        Axis or dimension along which to compute the peak (e.g., time or space).
    axis : int or str or None, optional
        Axis or dimension along which to compute the median of normalized peak error.

    Returns
    -------
    xarray.DataArray or numpy.ndarray or float
        Median normalized peak error (percent).

    Examples
    --------
    >>> import numpy as np
    >>> obs = np.array([[1, 2, 3], [2, 3, 4]])
    >>> mod = np.array([[2, 2, 2], [2, 2, 5]])
    >>> MdnNPE(obs, mod, paxis=1)
    33.33333333333333
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        pdim = paxis
        if isinstance(paxis, int):
            pdim = obs.dims[paxis]
        mdim = axis
        if isinstance(axis, int):
            mdim = obs.dims[axis]
        res = (abs(mod.max(dim=pdim) - obs.max(dim=pdim)) / obs.max(dim=pdim)).median(dim=mdim) * 100.0
        return _update_history(res, "Median Normalized Peak Error (MdnNPE)")
    else:
        obs_arr = np.ma.asanyarray(obs)
        mod_arr = np.ma.asanyarray(mod)
        return (
            np.ma.median(
                (
                    np.ma.abs(np.ma.max(mod_arr, axis=paxis) - np.ma.max(obs_arr, axis=paxis))
                    / np.ma.max(obs_arr, axis=paxis)
                ),
                axis=axis,
            )
            * 100.0
        )

MdnPE(obs, mod, axis=None)

Median Peak Error (%)

Typical Use Cases

  • Evaluating the typical error in peak values between model and observations, robust to outliers.
  • Used in robust model evaluation for extreme events, such as air quality exceedances or meteorological extremes.

Parameters

obs : xarray.DataArray or numpy.ndarray Observed values. mod : xarray.DataArray or numpy.ndarray Model predicted values. axis : int or str or None, optional Axis or dimension along which to compute the median of peak error.

Returns

xarray.DataArray or numpy.ndarray or float Median peak error (percent).

Examples

import numpy as np obs = np.array([[1, 2, 3], [2, 3, 4]]) mod = np.array([[2, 2, 2], [2, 2, 5]]) MdnPE(obs, mod) 33.333333333

Source code in src/monet_stats/relative_metrics.py
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
def MdnPE(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Median Peak Error (%)

    Typical Use Cases
    -----------------
    - Evaluating the typical error in peak values between model and observations,
      robust to outliers.
    - Used in robust model evaluation for extreme events, such as air quality
      exceedances or meteorological extremes.

    Parameters
    ----------
    obs : xarray.DataArray or numpy.ndarray
        Observed values.
    mod : xarray.DataArray or numpy.ndarray
        Model predicted values.
    axis : int or str or None, optional
        Axis or dimension along which to compute the median of peak error.

    Returns
    -------
    xarray.DataArray or numpy.ndarray or float
        Median peak error (percent).

    Examples
    --------
    >>> import numpy as np
    >>> obs = np.array([[1, 2, 3], [2, 3, 4]])
    >>> mod = np.array([[2, 2, 2], [2, 2, 5]])
    >>> MdnPE(obs, mod)
    33.333333333
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        dim = axis
        if isinstance(axis, int):
            dim = obs.dims[axis]
        res = (abs(mod.max(dim=dim) - obs.max(dim=dim)) / obs.max(dim=dim)).median() * 100.0
        return _update_history(res, "Median Peak Error (MdnPE)")
    else:
        obs_arr = np.ma.asanyarray(obs)
        mod_arr = np.ma.asanyarray(mod)
        return (
            np.ma.median(
                (
                    np.ma.abs(np.ma.max(mod_arr, axis=axis) - np.ma.max(obs_arr, axis=axis))
                    / np.ma.max(obs_arr, axis=axis)
                ),
                axis=axis,
            )
            * 100.0
        )

NMB(obs, mod, axis=None)

Normalized Mean Bias (%)

Typical Use Cases

  • Comparing model bias across variables or datasets with different units or scales.
  • Common in regulatory and operational air quality model performance reports.

Parameters

obs : xarray.DataArray or numpy.ndarray Observed values. mod : xarray.DataArray or numpy.ndarray Model predicted values. axis : int or str or None, optional Axis or dimension along which to compute the statistic.

Returns

xarray.DataArray or numpy.ndarray or float Normalized mean bias (percent).

Examples

import numpy as np obs = np.array([1, 2, 3]) mod = np.array([1.1, 2.2, 3.3]) NMB(obs, mod) 10.0

Source code in src/monet_stats/relative_metrics.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def NMB(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Normalized Mean Bias (%)

    Typical Use Cases
    -----------------
    - Comparing model bias across variables or datasets with different units or scales.
    - Common in regulatory and operational air quality model performance reports.

    Parameters
    ----------
    obs : xarray.DataArray or numpy.ndarray
        Observed values.
    mod : xarray.DataArray or numpy.ndarray
        Model predicted values.
    axis : int or str or None, optional
        Axis or dimension along which to compute the statistic.

    Returns
    -------
    xarray.DataArray or numpy.ndarray or float
        Normalized mean bias (percent).

    Examples
    --------
    >>> import numpy as np
    >>> obs = np.array([1, 2, 3])
    >>> mod = np.array([1.1, 2.2, 3.3])
    >>> NMB(obs, mod)
    10.0
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Ensure we use dimension name if axis is int
        dim = axis
        if isinstance(axis, int):
            dim = obs.dims[axis]
        res = (mod - obs).sum(dim=dim) / obs.sum(dim=dim) * 100.0
        return _update_history(res, "Normalized Mean Bias (NMB)")
    else:
        obs_arr = np.asanyarray(obs)
        mod_arr = np.asanyarray(mod)
        return (mod_arr - obs_arr).sum(axis=axis) / obs_arr.sum(axis=axis) * 100.0

NMB_ABS(obs, mod, axis=None)

Normalized Mean Bias - Absolute of the denominator (%)

Typical Use Cases

  • Quantifying normalized mean bias when the denominator (sum of observations) may be negative or zero.
  • Used for robust model evaluation in cases with possible sign changes in the observed data sum.

Parameters

obs : xarray.DataArray or numpy.ndarray Observed values. mod : xarray.DataArray or numpy.ndarray Model predicted values. axis : int or str or None, optional Axis or dimension along which to compute the statistic.

Returns

xarray.DataArray or numpy.ndarray or float Normalized mean bias with absolute denominator (percent).

Source code in src/monet_stats/relative_metrics.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
def NMB_ABS(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Normalized Mean Bias - Absolute of the denominator (%)

    Typical Use Cases
    -----------------
    - Quantifying normalized mean bias when the denominator (sum of observations) may be negative or zero.
    - Used for robust model evaluation in cases with possible sign changes in the observed data sum.

    Parameters
    ----------
    obs : xarray.DataArray or numpy.ndarray
        Observed values.
    mod : xarray.DataArray or numpy.ndarray
        Model predicted values.
    axis : int or str or None, optional
        Axis or dimension along which to compute the statistic.

    Returns
    -------
    xarray.DataArray or numpy.ndarray or float
        Normalized mean bias with absolute denominator (percent).
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        dim = axis
        if isinstance(axis, int):
            dim = obs.dims[axis]
        res = (mod - obs).sum(dim=dim) / abs(obs.sum(dim=dim)) * 100.0
        return _update_history(res, "Normalized Mean Bias Absolute (NMB_ABS)")
    else:
        obs_arr = np.asanyarray(obs)
        mod_arr = np.asanyarray(mod)
        return (mod_arr - obs_arr).sum(axis=axis) / np.abs(obs_arr.sum(axis=axis)) * 100.0

NME(obs, mod, axis=None)

Normalized Mean Error (%)

Typical Use Cases

  • Quantifying the average magnitude of model errors relative to observations.
  • Used for model evaluation and comparison across variables or datasets with different scales.

Parameters

obs : xarray.DataArray or numpy.ndarray Observed values. mod : xarray.DataArray or numpy.ndarray Model predicted values. axis : int or str or None, optional Axis or dimension along which to compute the statistic.

Returns

xarray.DataArray or numpy.ndarray or float Normalized mean error (percent).

Examples

import numpy as np obs = np.array([1, 2, 3, 4]) mod = np.array([2, 2, 2, 2]) NME(obs, mod) 37.5

Source code in src/monet_stats/relative_metrics.py
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
def NME(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Normalized Mean Error (%)

    Typical Use Cases
    -----------------
    - Quantifying the average magnitude of model errors relative to observations.
    - Used for model evaluation and comparison across variables or datasets with different scales.

    Parameters
    ----------
    obs : xarray.DataArray or numpy.ndarray
        Observed values.
    mod : xarray.DataArray or numpy.ndarray
        Model predicted values.
    axis : int or str or None, optional
        Axis or dimension along which to compute the statistic.

    Returns
    -------
    xarray.DataArray or numpy.ndarray or float
        Normalized mean error (percent).

    Examples
    --------
    >>> import numpy as np
    >>> obs = np.array([1, 2, 3, 4])
    >>> mod = np.array([2, 2, 2, 2])
    >>> NME(obs, mod)
    37.5
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        dim = axis
        if isinstance(axis, int):
            dim = obs.dims[axis]
        res = (abs(mod - obs).sum(dim=dim) / obs.sum(dim=dim)) * 100
        return _update_history(res, "Normalized Mean Error (NME)")
    else:
        obs_arr = np.ma.asanyarray(obs)
        mod_arr = np.ma.asanyarray(mod)
        return (np.ma.abs(mod_arr - obs_arr).sum(axis=axis) / obs_arr.sum(axis=axis)) * 100

NME_m(obs, mod, axis=None)

Normalized Mean Error (%) (avoid single block error in np.ma)

Typical Use Cases

  • Quantifying the average magnitude of model errors relative to observations, robust to masked arrays.
  • Used for model evaluation when data may contain masked or missing values.

Parameters

obs : xarray.DataArray or numpy.ndarray Observed values. mod : xarray.DataArray or numpy.ndarray Model predicted values. axis : int or str or None, optional Axis or dimension along which to compute the statistic.

Returns

xarray.DataArray or numpy.ndarray or float Normalized mean error (percent).

Examples

import numpy as np obs = np.array([1, 2, 3, 4]) mod = np.array([2, 2, 2, 2]) NME_m(obs, mod) 37.5

Source code in src/monet_stats/relative_metrics.py
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
def NME_m(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Normalized Mean Error (%) (avoid single block error in np.ma)

    Typical Use Cases
    -----------------
    - Quantifying the average magnitude of model errors relative to observations, robust to masked arrays.
    - Used for model evaluation when data may contain masked or missing values.

    Parameters
    ----------
    obs : xarray.DataArray or numpy.ndarray
        Observed values.
    mod : xarray.DataArray or numpy.ndarray
        Model predicted values.
    axis : int or str or None, optional
        Axis or dimension along which to compute the statistic.

    Returns
    -------
    xarray.DataArray or numpy.ndarray or float
        Normalized mean error (percent).

    Examples
    --------
    >>> import numpy as np
    >>> obs = np.array([1, 2, 3, 4])
    >>> mod = np.array([2, 2, 2, 2])
    >>> NME_m(obs, mod)
    37.5
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        dim = axis
        if isinstance(axis, int):
            dim = obs.dims[axis]
        res = (abs(mod - obs).sum(dim=dim) / obs.sum(dim=dim)) * 100
        return _update_history(res, "Normalized Mean Error (NME_m)")
    else:
        obs_arr = np.asanyarray(obs)
        mod_arr = np.asanyarray(mod)
        return (np.abs(mod_arr - obs_arr).sum(axis=axis) / obs_arr.sum(axis=axis)) * 100

NME_m_ABS(obs, mod, axis=None)

Normalized Mean Error (%) - Absolute of the denominator (avoid single block error in np.ma)

Typical Use Cases

  • Quantifying normalized mean error when the denominator (sum of observations) may be negative or zero, robust to masked arrays.
  • Used for model evaluation with possible sign changes or missing values in observed data.

Parameters

obs : xarray.DataArray or numpy.ndarray Observed values. mod : xarray.DataArray or numpy.ndarray Model predicted values. axis : int or str or None, optional Axis or dimension along which to compute the statistic.

Returns

xarray.DataArray or numpy.ndarray or float Normalized mean error with absolute denominator (percent).

Examples

import numpy as np obs = np.array([1, 2, 3, 4]) mod = np.array([2, 2, 2, 2]) NME_m_ABS(obs, mod) 37.5

Source code in src/monet_stats/relative_metrics.py
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
def NME_m_ABS(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Normalized Mean Error (%) - Absolute of the denominator
    (avoid single block error in np.ma)

    Typical Use Cases
    -----------------
    - Quantifying normalized mean error when the denominator (sum of observations)
      may be negative or zero, robust to masked arrays.
    - Used for model evaluation with possible sign changes or missing values in observed data.

    Parameters
    ----------
    obs : xarray.DataArray or numpy.ndarray
        Observed values.
    mod : xarray.DataArray or numpy.ndarray
        Model predicted values.
    axis : int or str or None, optional
        Axis or dimension along which to compute the statistic.

    Returns
    -------
    xarray.DataArray or numpy.ndarray or float
        Normalized mean error with absolute denominator (percent).

    Examples
    --------
    >>> import numpy as np
    >>> obs = np.array([1, 2, 3, 4])
    >>> mod = np.array([2, 2, 2, 2])
    >>> NME_m_ABS(obs, mod)
    37.5
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        dim = axis
        if isinstance(axis, int):
            dim = obs.dims[axis]
        res = (abs(mod - obs).sum(dim=dim) / abs(obs.sum(dim=dim))) * 100
        return _update_history(res, "Normalized Mean Error Absolute (NME_m_ABS)")
    else:
        obs_arr = np.asanyarray(obs)
        mod_arr = np.asanyarray(mod)
        return (np.abs(mod_arr - obs_arr).sum(axis=axis) / np.abs(obs_arr.sum(axis=axis))) * 100

NMPB(obs, mod, paxis, axis=None)

Normalized Mean Peak Bias (NMPB, %)

Typical Use Cases

  • Quantifying the average bias in peak values, normalized by the mean of observed peaks.
  • Used in model evaluation for extreme events, especially when comparing across sites or time periods.

Parameters

obs : xarray.DataArray or numpy.ndarray Observed values. mod : xarray.DataArray or numpy.ndarray Model predicted values. paxis : int or str Axis or dimension along which to compute the peak (e.g., time or space). axis : int or str or None, optional Axis or dimension along which to compute the mean of normalized peak bias.

Returns

xarray.DataArray or numpy.ndarray or float Normalized mean peak bias (percent).

Examples

import numpy as np obs = np.array([[1, 2, 3], [2, 3, 4]]) mod = np.array([[2, 2, 2], [2, 2, 5]]) NMPB(obs, mod, paxis=1) 33.33333333333333

Source code in src/monet_stats/relative_metrics.py
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
def NMPB(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    paxis: Union[int, str],
    axis: Optional[Union[int, str]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Normalized Mean Peak Bias (NMPB, %)

    Typical Use Cases
    -----------------
    - Quantifying the average bias in peak values, normalized by the mean of observed peaks.
    - Used in model evaluation for extreme events, especially when comparing across sites or time periods.

    Parameters
    ----------
    obs : xarray.DataArray or numpy.ndarray
        Observed values.
    mod : xarray.DataArray or numpy.ndarray
        Model predicted values.
    paxis : int or str
        Axis or dimension along which to compute the peak (e.g., time or space).
    axis : int or str or None, optional
        Axis or dimension along which to compute the mean of normalized peak bias.

    Returns
    -------
    xarray.DataArray or numpy.ndarray or float
        Normalized mean peak bias (percent).

    Examples
    --------
    >>> import numpy as np
    >>> obs = np.array([[1, 2, 3], [2, 3, 4]])
    >>> mod = np.array([[2, 2, 2], [2, 2, 5]])
    >>> NMPB(obs, mod, paxis=1)
    33.33333333333333
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        pdim = paxis
        if isinstance(paxis, int):
            pdim = obs.dims[paxis]
        mdim = axis
        if isinstance(axis, int):
            mdim = obs.dims[axis]
        res = ((mod.max(dim=pdim) - obs.max(dim=pdim)).mean(dim=mdim) / obs.max(dim=pdim).mean(dim=mdim)) * 100.0
        return _update_history(res, "Normalized Mean Peak Bias (NMPB)")
    else:
        obs_arr = np.ma.asanyarray(obs)
        mod_arr = np.ma.asanyarray(mod)
        return (
            (np.ma.max(mod_arr, axis=paxis) - np.ma.max(obs_arr, axis=paxis)).mean(axis=axis)
            / np.ma.max(obs_arr, axis=paxis).mean(axis=axis)
        ) * 100.0

NMPE(obs, mod, paxis, axis=None)

Normalized Mean Peak Error (NMPE, %)

Typical Use Cases

  • Quantifying the average error in peak values, normalized by the mean of observed peaks.
  • Used in model evaluation for extreme events, especially when comparing across sites or time periods.

Parameters

obs : xarray.DataArray or numpy.ndarray Observed values. mod : xarray.DataArray or numpy.ndarray Model predicted values. paxis : int or str Axis or dimension along which to compute the peak (e.g., time or space). axis : int or str or None, optional Axis or dimension along which to compute the mean of normalized peak error.

Returns

xarray.DataArray or numpy.ndarray or float Normalized mean peak error (percent).

Examples

import numpy as np obs = np.array([[1, 2, 3], [2, 3, 4]]) mod = np.array([[2, 2, 2], [2, 2, 5]]) NMPE(obs, mod, paxis=1) 33.33333333333333

Source code in src/monet_stats/relative_metrics.py
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
def NMPE(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    paxis: Union[int, str],
    axis: Optional[Union[int, str]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Normalized Mean Peak Error (NMPE, %)

    Typical Use Cases
    -----------------
    - Quantifying the average error in peak values, normalized by the mean of observed peaks.
    - Used in model evaluation for extreme events, especially when comparing across sites or time periods.

    Parameters
    ----------
    obs : xarray.DataArray or numpy.ndarray
        Observed values.
    mod : xarray.DataArray or numpy.ndarray
        Model predicted values.
    paxis : int or str
        Axis or dimension along which to compute the peak (e.g., time or space).
    axis : int or str or None, optional
        Axis or dimension along which to compute the mean of normalized peak error.

    Returns
    -------
    xarray.DataArray or numpy.ndarray or float
        Normalized mean peak error (percent).

    Examples
    --------
    >>> import numpy as np
    >>> obs = np.array([[1, 2, 3], [2, 3, 4]])
    >>> mod = np.array([[2, 2, 2], [2, 2, 5]])
    >>> NMPE(obs, mod, paxis=1)
    33.33333333333333
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        pdim = paxis
        if isinstance(paxis, int):
            pdim = obs.dims[paxis]
        mdim = axis
        if isinstance(axis, int):
            mdim = obs.dims[axis]
        res = (abs(mod.max(dim=pdim) - obs.max(dim=pdim)).mean(dim=mdim) / obs.max(dim=pdim).mean(dim=mdim)) * 100.0
        return _update_history(res, "Normalized Mean Peak Error (NMPE)")
    else:
        obs_arr = np.ma.asanyarray(obs)
        mod_arr = np.ma.asanyarray(mod)
        return (
            np.ma.abs(np.ma.max(mod_arr, axis=paxis) - np.ma.max(obs_arr, axis=paxis)).mean(axis=axis)
            / np.ma.max(obs_arr, axis=paxis).mean(axis=axis)
        ) * 100.0

NMdnB(obs, mod, axis=None)

Normalized Median Bias (%)

Typical Use Cases

  • Assessing the central tendency of normalized bias, robust to outliers and non-normal distributions.
  • Used for robust model evaluation across variables or sites with different scales.

Parameters

obs : xarray.DataArray or numpy.ndarray Observed values. mod : xarray.DataArray or numpy.ndarray Model predicted values. axis : int or str or None, optional Axis or dimension along which to compute the statistic.

Returns

xarray.DataArray or numpy.ndarray or float Normalized median bias (percent).

Examples

import numpy as np obs = np.array([1, 2, 3, 4, 100]) # 100 is an outlier mod = np.array([1.1, 2.2, 3.3, 4.4, 105]) NMdnB(obs, mod) 10.0

Source code in src/monet_stats/relative_metrics.py
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
def NMdnB(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Normalized Median Bias (%)

    Typical Use Cases
    -----------------
    - Assessing the central tendency of normalized bias, robust to outliers and non-normal distributions.
    - Used for robust model evaluation across variables or sites with different scales.

    Parameters
    ----------
    obs : xarray.DataArray or numpy.ndarray
        Observed values.
    mod : xarray.DataArray or numpy.ndarray
        Model predicted values.
    axis : int or str or None, optional
        Axis or dimension along which to compute the statistic.

    Returns
    -------
    xarray.DataArray or numpy.ndarray or float
        Normalized median bias (percent).

    Examples
    --------
    >>> import numpy as np
    >>> obs = np.array([1, 2, 3, 4, 100])  # 100 is an outlier
    >>> mod = np.array([1.1, 2.2, 3.3, 4.4, 105])
    >>> NMdnB(obs, mod)
    10.0
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        dim = axis
        if isinstance(axis, int):
            dim = obs.dims[axis]
        res = (mod - obs).median(dim=dim) / obs.median(dim=dim) * 100.0
        return _update_history(res, "Normalized Median Bias (NMdnB)")
    else:
        obs_arr = np.ma.asanyarray(obs)
        mod_arr = np.ma.asanyarray(mod)
        return np.ma.median(mod_arr - obs_arr, axis=axis) / np.ma.median(obs_arr, axis=axis) * 100.0

NMdnE(obs, mod, axis=None)

Normalized Median Error (%)

Typical Use Cases

  • Evaluating the typical magnitude of model errors relative to observations, robust to outliers.
  • Used for robust model evaluation and comparison across variables or datasets with different scales.

Parameters

obs : xarray.DataArray or numpy.ndarray Observed values. mod : xarray.DataArray or numpy.ndarray Model predicted values. axis : int or str or None, optional Axis or dimension along which to compute the statistic.

Returns

xarray.DataArray or numpy.ndarray or float Normalized median error (percent).

Examples

import numpy as np obs = np.array([1, 2, 3, 4]) mod = np.array([2, 2, 2, 2]) NMdnE(obs, mod) 33.33333333333333

Source code in src/monet_stats/relative_metrics.py
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
def NMdnE(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Normalized Median Error (%)

    Typical Use Cases
    -----------------
    - Evaluating the typical magnitude of model errors relative to observations, robust to outliers.
    - Used for robust model evaluation and comparison across variables or datasets with different scales.

    Parameters
    ----------
    obs : xarray.DataArray or numpy.ndarray
        Observed values.
    mod : xarray.DataArray or numpy.ndarray
        Model predicted values.
    axis : int or str or None, optional
        Axis or dimension along which to compute the statistic.

    Returns
    -------
    xarray.DataArray or numpy.ndarray or float
        Normalized median error (percent).

    Examples
    --------
    >>> import numpy as np
    >>> obs = np.array([1, 2, 3, 4])
    >>> mod = np.array([2, 2, 2, 2])
    >>> NMdnE(obs, mod)
    33.33333333333333
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        dim = axis
        if isinstance(axis, int):
            dim = obs.dims[axis]
        res = abs(mod - obs).median(dim=dim) / obs.median(dim=dim) * 100
        return _update_history(res, "Normalized Median Error (NMdnE)")
    else:
        obs_arr = np.ma.asanyarray(obs)
        mod_arr = np.ma.asanyarray(mod)
        return np.ma.median(np.ma.abs(mod_arr - obs_arr), axis=axis) / np.ma.median(obs_arr, axis=axis) * 100

NMdnPB(obs, mod, paxis, axis=None)

Normalized Median Peak Bias (NMdnPB, %)

Typical Use Cases

  • Evaluating the typical bias in peak values, normalized by the median of observed peaks, robust to outliers.
  • Used in robust model evaluation for extreme events, especially when comparing across sites or time periods.

Parameters

obs : xarray.DataArray or numpy.ndarray Observed values. mod : xarray.DataArray or numpy.ndarray Model predicted values. paxis : int or str Axis or dimension along which to compute the peak (e.g., time or space). axis : int or str or None, optional Axis or dimension along which to compute the median of normalized peak bias.

Returns

xarray.DataArray or numpy.ndarray or float Normalized median peak bias (percent).

Examples

import numpy as np obs = np.array([[1, 2, 3], [2, 3, 4]]) mod = np.array([[2, 2, 2], [2, 2, 5]]) NMdnPB(obs, mod, paxis=1) 33.33333333333333

Source code in src/monet_stats/relative_metrics.py
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
def NMdnPB(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    paxis: Union[int, str],
    axis: Optional[Union[int, str]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Normalized Median Peak Bias (NMdnPB, %)

    Typical Use Cases
    -----------------
    - Evaluating the typical bias in peak values, normalized by the median of observed peaks, robust to outliers.
    - Used in robust model evaluation for extreme events, especially when comparing across sites or time periods.

    Parameters
    ----------
    obs : xarray.DataArray or numpy.ndarray
        Observed values.
    mod : xarray.DataArray or numpy.ndarray
        Model predicted values.
    paxis : int or str
        Axis or dimension along which to compute the peak (e.g., time or space).
    axis : int or str or None, optional
        Axis or dimension along which to compute the median of normalized peak bias.

    Returns
    -------
    xarray.DataArray or numpy.ndarray or float
        Normalized median peak bias (percent).

    Examples
    --------
    >>> import numpy as np
    >>> obs = np.array([[1, 2, 3], [2, 3, 4]])
    >>> mod = np.array([[2, 2, 2], [2, 2, 5]])
    >>> NMdnPB(obs, mod, paxis=1)
    33.33333333333333
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        pdim = paxis
        if isinstance(paxis, int):
            pdim = obs.dims[paxis]
        mdim = axis
        if isinstance(axis, int):
            mdim = obs.dims[axis]
        res = (mod.max(dim=pdim) - obs.max(dim=pdim)).median(dim=mdim) / obs.max(dim=pdim).median(dim=mdim) * 100.0
        return _update_history(res, "Normalized Median Peak Bias (NMdnPB)")
    else:
        obs_arr = np.ma.asanyarray(obs)
        mod_arr = np.ma.asanyarray(mod)
        return (
            np.ma.median(np.ma.max(mod_arr, axis=paxis) - np.ma.max(obs_arr, axis=paxis), axis=axis)
            / np.ma.median(np.ma.max(obs_arr, axis=paxis), axis=axis)
        ) * 100.0

NMdnPE(obs, mod, paxis, axis=None)

Normalized Median Peak Error (NMdnPE, %)

Typical Use Cases

  • Evaluating the typical error in peak values, normalized by the median of observed peaks, robust to outliers.
  • Used in robust model evaluation for extreme events, especially when comparing across sites or time periods.

Parameters

obs : xarray.DataArray or numpy.ndarray Observed values. mod : xarray.DataArray or numpy.ndarray Model predicted values. paxis : int or str Axis or dimension along which to compute the peak (e.g., time or space). axis : int or str or None, optional Axis or dimension along which to compute the median of normalized peak error.

Returns

xarray.DataArray or numpy.ndarray or float Normalized median peak error (percent).

Examples

import numpy as np obs = np.array([[1, 2, 3], [2, 3, 4]]) mod = np.array([[2, 2, 2], [2, 2, 5]]) NMdnPE(obs, mod, paxis=1) 33.33333333333333

Source code in src/monet_stats/relative_metrics.py
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
def NMdnPE(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    paxis: Union[int, str],
    axis: Optional[Union[int, str]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Normalized Median Peak Error (NMdnPE, %)

    Typical Use Cases
    -----------------
    - Evaluating the typical error in peak values, normalized by the median of observed peaks, robust to outliers.
    - Used in robust model evaluation for extreme events, especially when comparing across sites or time periods.

    Parameters
    ----------
    obs : xarray.DataArray or numpy.ndarray
        Observed values.
    mod : xarray.DataArray or numpy.ndarray
        Model predicted values.
    paxis : int or str
        Axis or dimension along which to compute the peak (e.g., time or space).
    axis : int or str or None, optional
        Axis or dimension along which to compute the median of normalized peak error.

    Returns
    -------
    xarray.DataArray or numpy.ndarray or float
        Normalized median peak error (percent).

    Examples
    --------
    >>> import numpy as np
    >>> obs = np.array([[1, 2, 3], [2, 3, 4]])
    >>> mod = np.array([[2, 2, 2], [2, 2, 5]])
    >>> NMdnPE(obs, mod, paxis=1)
    33.33333333333333
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        pdim = paxis
        if isinstance(paxis, int):
            pdim = obs.dims[paxis]
        mdim = axis
        if isinstance(axis, int):
            mdim = obs.dims[axis]
        res = (abs(mod.max(dim=pdim) - obs.max(dim=pdim))).median(dim=mdim) / obs.max(dim=pdim).median(dim=mdim) * 100.0
        return _update_history(res, "Normalized Median Peak Error (NMdnPE)")
    else:
        obs_arr = np.ma.asanyarray(obs)
        mod_arr = np.ma.asanyarray(mod)
        return (
            np.ma.median(
                np.ma.abs(np.ma.max(mod_arr, axis=paxis) - np.ma.max(obs_arr, axis=paxis)),
                axis=axis,
            )
            / np.ma.median(np.ma.max(obs_arr, axis=paxis), axis=axis)
        ) * 100.0

PSUTMNPB(obs, mod, axis=None)

Paired Space/Unpaired Time Mean Normalized Peak Bias (PSUTMNPB, %)

Wrapper for MNPB with paxis=0, axis=None.

Source code in src/monet_stats/relative_metrics.py
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
def PSUTMNPB(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Paired Space/Unpaired Time Mean Normalized Peak Bias (PSUTMNPB, %)

    Wrapper for MNPB with paxis=0, axis=None.
    """
    return MNPB(obs, mod, paxis=0, axis=None)

PSUTMNPE(obs, mod, axis=None)

Paired Space/Unpaired Time Mean Normalized Peak Error (PSUTMNPE, %)

Wrapper for MNPE with paxis=0, axis=None.

Source code in src/monet_stats/relative_metrics.py
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
def PSUTMNPE(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Paired Space/Unpaired Time Mean Normalized Peak Error (PSUTMNPE, %)

    Wrapper for MNPE with paxis=0, axis=None.
    """
    return MNPE(obs, mod, paxis=0, axis=None)

PSUTMdnNPB(obs, mod, axis=None)

Paired Space/Unpaired Time Median Normalized Peak Bias (PSUTMdnNPB, %)

Wrapper for MdnNPB with paxis=0, axis=None.

Source code in src/monet_stats/relative_metrics.py
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
def PSUTMdnNPB(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Paired Space/Unpaired Time Median Normalized Peak Bias (PSUTMdnNPB, %)

    Wrapper for MdnNPB with paxis=0, axis=None.
    """
    return MdnNPB(obs, mod, paxis=0, axis=None)

PSUTMdnNPE(obs, mod, axis=None)

Paired Space/Unpaired Time Median Normalized Peak Error (PSUTMdnNPE, %)

Wrapper for MdnNPE with paxis=0, axis=None.

Source code in src/monet_stats/relative_metrics.py
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
def PSUTMdnNPE(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Paired Space/Unpaired Time Median Normalized Peak Error (PSUTMdnNPE, %)

    Wrapper for MdnNPE with paxis=0, axis=None.
    """
    return MdnNPE(obs, mod, paxis=0, axis=None)

PSUTNMPB(obs, mod, axis=None)

Paired Space/Unpaired Time Normalized Mean Peak Bias (PSUTNMPB, %)

Wrapper for NMPB with paxis=0, axis=None.

Source code in src/monet_stats/relative_metrics.py
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
def PSUTNMPB(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Paired Space/Unpaired Time Normalized Mean Peak Bias (PSUTNMPB, %)

    Wrapper for NMPB with paxis=0, axis=None.
    """
    return NMPB(obs, mod, paxis=0, axis=None)

PSUTNMPE(obs, mod, axis=None)

Paired Space/Unpaired Time Normalized Mean Peak Error (PSUTNMPE, %)

Wrapper for NMPE with paxis=0, axis=None.

Source code in src/monet_stats/relative_metrics.py
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
def PSUTNMPE(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Paired Space/Unpaired Time Normalized Mean Peak Error (PSUTNMPE, %)

    Wrapper for NMPE with paxis=0, axis=None.
    """
    return NMPE(obs, mod, paxis=0, axis=None)

PSUTNMdnPB(obs, mod, axis=None)

Paired Space/Unpaired Time Normalized Median Peak Bias (PSUTNMdnPB, %)

Typical Use Cases

  • Evaluating the normalized median peak bias for spatially paired, temporally unpaired datasets, robust to outliers.
  • Used in robust model evaluation for spatial ensemble or multi-time analysis.

Parameters

obs : xarray.DataArray or numpy.ndarray Observed values. mod : xarray.DataArray or numpy.ndarray Model predicted values. axis : int or str or None, optional Axis or dimension along which to compute the median of normalized peak bias.

Returns

xarray.DataArray or numpy.ndarray or float Normalized median peak bias (percent).

Examples

import numpy as np obs = np.array([[1, 2, 3], [2, 3, 4]]) mod = np.array([[2, 2, 2], [2, 2, 5]]) PSUTNMdnPB(obs, mod) 33.33333333333333

Source code in src/monet_stats/relative_metrics.py
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
def PSUTNMdnPB(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Paired Space/Unpaired Time Normalized Median Peak Bias (PSUTNMdnPB, %)

    Typical Use Cases
    -----------------
    - Evaluating the normalized median peak bias for spatially paired, temporally unpaired datasets, robust to outliers.
    - Used in robust model evaluation for spatial ensemble or multi-time analysis.

    Parameters
    ----------
    obs : xarray.DataArray or numpy.ndarray
        Observed values.
    mod : xarray.DataArray or numpy.ndarray
        Model predicted values.
    axis : int or str or None, optional
        Axis or dimension along which to compute the median of normalized peak bias.

    Returns
    -------
    xarray.DataArray or numpy.ndarray or float
        Normalized median peak bias (percent).

    Examples
    --------
    >>> import numpy as np
    >>> obs = np.array([[1, 2, 3], [2, 3, 4]])
    >>> mod = np.array([[2, 2, 2], [2, 2, 5]])
    >>> PSUTNMdnPB(obs, mod)
    33.33333333333333
    """
    return NMdnPB(obs, mod, paxis=0, axis=None)

PSUTNMdnPE(obs, mod, axis=None)

Paired Space/Unpaired Time Normalized Median Peak Error (PSUTNMdnPE, %)

Typical Use Cases

  • Evaluating the normalized median peak error for spatially paired, temporally unpaired datasets, robust to outliers.
  • Used in robust model evaluation for spatial ensemble or multi-time analysis.

Parameters

obs : xarray.DataArray or numpy.ndarray Observed values. mod : xarray.DataArray or numpy.ndarray Model predicted values. axis : int or str or None, optional Axis or dimension along which to compute the median of normalized peak error.

Returns

xarray.DataArray or numpy.ndarray or float Normalized median peak error (percent).

Examples

import numpy as np obs = np.array([[1, 2, 3], [2, 3, 4]]) mod = np.array([[2, 2, 2], [2, 2, 5]]) PSUTNMdnPE(obs, mod) 33.33333333333333

Source code in src/monet_stats/relative_metrics.py
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
def PSUTNMdnPE(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Paired Space/Unpaired Time Normalized Median Peak Error (PSUTNMdnPE, %)

    Typical Use Cases
    -----------------
    - Evaluating the normalized median peak error for spatially paired, temporally unpaired
      datasets, robust to outliers.
    - Used in robust model evaluation for spatial ensemble or multi-time analysis.

    Parameters
    ----------
    obs : xarray.DataArray or numpy.ndarray
        Observed values.
    mod : xarray.DataArray or numpy.ndarray
        Model predicted values.
    axis : int or str or None, optional
        Axis or dimension along which to compute the median of normalized peak error.

    Returns
    -------
    xarray.DataArray or numpy.ndarray or float
        Normalized median peak error (percent).

    Examples
    --------
    >>> import numpy as np
    >>> obs = np.array([[1, 2, 3], [2, 3, 4]])
    >>> mod = np.array([[2, 2, 2], [2, 2, 5]])
    >>> PSUTNMdnPE(obs, mod)
    33.33333333333333
    """
    return NMdnPE(obs, mod, paxis=0, axis=None)

USUTPB(obs, mod, axis=None)

Unpaired Space/Unpaired Time Peak Bias (%)

Typical Use Cases

  • Assessing the bias in peak values between model and observations, regardless of spatial or temporal pairing.
  • Used in event-based or extreme value model evaluation, especially for air quality and meteorological extremes.

Parameters

obs : xarray.DataArray or numpy.ndarray Observed values. mod : xarray.DataArray or numpy.ndarray Model predicted values. axis : int or str or None, optional Axis or dimension along which to compute the statistic.

Returns

xarray.DataArray or numpy.ndarray or float Peak bias (percent).

Examples

import numpy as np obs = np.array([1, 2, 3, 4]) mod = np.array([2, 2, 2, 5]) USUTPB(obs, mod) 25.0

Source code in src/monet_stats/relative_metrics.py
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
def USUTPB(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Unpaired Space/Unpaired Time Peak Bias (%)

    Typical Use Cases
    -----------------
    - Assessing the bias in peak values between model and observations, regardless of spatial or temporal pairing.
    - Used in event-based or extreme value model evaluation, especially for air quality and meteorological extremes.

    Parameters
    ----------
    obs : xarray.DataArray or numpy.ndarray
        Observed values.
    mod : xarray.DataArray or numpy.ndarray
        Model predicted values.
    axis : int or str or None, optional
        Axis or dimension along which to compute the statistic.

    Returns
    -------
    xarray.DataArray or numpy.ndarray or float
        Peak bias (percent).

    Examples
    --------
    >>> import numpy as np
    >>> obs = np.array([1, 2, 3, 4])
    >>> mod = np.array([2, 2, 2, 5])
    >>> USUTPB(obs, mod)
    25.0
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        dim = axis
        if isinstance(axis, int):
            dim = obs.dims[axis]
        res = ((mod.max(dim=dim) - obs.max(dim=dim)) / obs.max(dim=dim)) * 100.0
        return _update_history(res, "Unpaired Space/Unpaired Time Peak Bias (USUTPB)")
    else:
        obs_arr = np.ma.asanyarray(obs)
        mod_arr = np.ma.asanyarray(mod)
        return ((np.ma.max(mod_arr, axis=axis) - np.ma.max(obs_arr, axis=axis)) / np.ma.max(obs_arr, axis=axis)) * 100.0

USUTPE(obs, mod, axis=None)

Unpaired Space/Unpaired Time Peak Error (%)

Typical Use Cases

  • Quantifying the error in peak values between model and observations, regardless of spatial or temporal pairing.
  • Used in event-based or extreme value model evaluation, especially for air quality and meteorological extremes.

Parameters

obs : xarray.DataArray or numpy.ndarray Observed values. mod : xarray.DataArray or numpy.ndarray Model predicted values. axis : int or str or None, optional Axis or dimension along which to compute the statistic.

Returns

xarray.DataArray or numpy.ndarray or float Peak error (percent).

Examples

import numpy as np obs = np.array([1, 2, 3, 4]) mod = np.array([2, 2, 2, 5]) USUTPE(obs, mod) 25.0

Source code in src/monet_stats/relative_metrics.py
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
def USUTPE(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Unpaired Space/Unpaired Time Peak Error (%)

    Typical Use Cases
    -----------------
    - Quantifying the error in peak values between model and observations, regardless of spatial or temporal pairing.
    - Used in event-based or extreme value model evaluation, especially for air quality and meteorological extremes.

    Parameters
    ----------
    obs : xarray.DataArray or numpy.ndarray
        Observed values.
    mod : xarray.DataArray or numpy.ndarray
        Model predicted values.
    axis : int or str or None, optional
        Axis or dimension along which to compute the statistic.

    Returns
    -------
    xarray.DataArray or numpy.ndarray or float
        Peak error (percent).

    Examples
    --------
    >>> import numpy as np
    >>> obs = np.array([1, 2, 3, 4])
    >>> mod = np.array([2, 2, 2, 5])
    >>> USUTPE(obs, mod)
    25.0
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        dim = axis
        if isinstance(axis, int):
            dim = obs.dims[axis]
        res = (abs(mod.max(dim=dim) - obs.max(dim=dim)) / obs.max(dim=dim)) * 100.0
        return _update_history(res, "Unpaired Space/Unpaired Time Peak Error (USUTPE)")
    else:
        obs_arr = np.ma.asanyarray(obs)
        mod_arr = np.ma.asanyarray(mod)
        return (
            np.ma.abs(np.ma.max(mod_arr, axis=axis) - np.ma.max(obs_arr, axis=axis)) / np.ma.max(obs_arr, axis=axis)
        ) * 100.0

WDME(obs, mod, axis=None)

Wind Direction Mean Gross Error (model and obs unit)

Typical Use Cases

  • Quantifying the average magnitude of wind direction errors, regardless of direction.
  • Used in wind energy, meteorology, and air quality studies to assess wind direction model performance.

Parameters

obs : xarray.DataArray or numpy.ndarray Observed wind direction values (degrees). mod : xarray.DataArray or numpy.ndarray Model predicted wind direction values (degrees). axis : int or str or None, optional Axis or dimension along which to compute the statistic.

Returns

xarray.DataArray or numpy.ndarray or float Mean gross error in wind direction (degrees).

Examples

import numpy as np obs = np.array([350, 10, 20]) mod = np.array([10, 20, 30]) WDME(obs, mod) 20.0

Source code in src/monet_stats/relative_metrics.py
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
def WDME(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Wind Direction Mean Gross Error (model and obs unit)

    Typical Use Cases
    -----------------
    - Quantifying the average magnitude of wind direction errors, regardless of direction.
    - Used in wind energy, meteorology, and air quality studies to assess wind direction model performance.

    Parameters
    ----------
    obs : xarray.DataArray or numpy.ndarray
        Observed wind direction values (degrees).
    mod : xarray.DataArray or numpy.ndarray
        Model predicted wind direction values (degrees).
    axis : int or str or None, optional
        Axis or dimension along which to compute the statistic.

    Returns
    -------
    xarray.DataArray or numpy.ndarray or float
        Mean gross error in wind direction (degrees).

    Examples
    --------
    >>> import numpy as np
    >>> obs = np.array([350, 10, 20])
    >>> mod = np.array([10, 20, 30])
    >>> WDME(obs, mod)
    20.0
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        dim = axis
        if isinstance(axis, int):
            dim = obs.dims[axis]
        res = abs(circlebias(mod - obs)).mean(dim=dim)
        return _update_history(res, "Wind Direction Mean Gross Error (WDME)")
    else:
        obs_arr = np.ma.asanyarray(obs)
        mod_arr = np.ma.asanyarray(mod)
        return np.ma.mean(np.ma.abs(circlebias(mod_arr - obs_arr)), axis=axis)

WDME_m(obs, mod, axis=None)

Wind Direction Mean Gross Error (model and obs unit) (avoid single block error in np.ma)

Typical Use Cases

  • Quantifying the average magnitude of wind direction errors, regardless of direction.
  • Used in wind energy, meteorology, and air quality studies to assess wind direction model performance.

Parameters

obs : xarray.DataArray or numpy.ndarray Observed wind direction values (degrees). mod : xarray.DataArray or numpy.ndarray Model predicted wind direction values (degrees). axis : int or str or None, optional Axis or dimension along which to compute the statistic.

Returns

xarray.DataArray or numpy.ndarray or float Mean gross error in wind direction (degrees).

Examples

import numpy as np obs = np.array([350, 10, 20]) mod = np.array([10, 20, 30]) WDME_m(obs, mod) 20.0

Source code in src/monet_stats/relative_metrics.py
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
def WDME_m(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Wind Direction Mean Gross Error (model and obs unit)
    (avoid single block error in np.ma)

    Typical Use Cases
    -----------------
    - Quantifying the average magnitude of wind direction errors, regardless of direction.
    - Used in wind energy, meteorology, and air quality studies to assess wind direction model performance.

    Parameters
    ----------
    obs : xarray.DataArray or numpy.ndarray
        Observed wind direction values (degrees).
    mod : xarray.DataArray or numpy.ndarray
        Model predicted wind direction values (degrees).
    axis : int or str or None, optional
        Axis or dimension along which to compute the statistic.

    Returns
    -------
    xarray.DataArray or numpy.ndarray or float
        Mean gross error in wind direction (degrees).

    Examples
    --------
    >>> import numpy as np
    >>> obs = np.array([350, 10, 20])
    >>> mod = np.array([10, 20, 30])
    >>> WDME_m(obs, mod)
    20.0
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        dim = axis
        if isinstance(axis, int):
            dim = obs.dims[axis]
        res = abs(circlebias_m(mod - obs)).mean(dim=dim)
        return _update_history(res, "Wind Direction Mean Gross Error (WDME_m)")
    else:
        obs_arr = np.asanyarray(obs)
        mod_arr = np.asanyarray(mod)
        return np.abs(circlebias_m(mod_arr - obs_arr)).mean(axis=axis)

WDMdnE(obs, mod, axis=None)

Wind Direction Median Gross Error (model and obs unit)

Typical Use Cases

  • Evaluating the typical magnitude of wind direction errors, robust to outliers.
  • Used in wind energy and meteorological applications for robust wind direction model evaluation.

Parameters

obs : xarray.DataArray or numpy.ndarray Observed wind direction values (degrees). mod : xarray.DataArray or numpy.ndarray Model predicted wind direction values (degrees). axis : int or str or None, optional Axis or dimension along which to compute the statistic.

Returns

xarray.DataArray or numpy.ndarray or float Median gross error in wind direction (degrees).

Examples

import numpy as np obs = np.array([350, 10, 20]) mod = np.array([10, 20, 30]) WDMdnE(obs, mod) 10.0

Source code in src/monet_stats/relative_metrics.py
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
def WDMdnE(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Wind Direction Median Gross Error (model and obs unit)

    Typical Use Cases
    -----------------
    - Evaluating the typical magnitude of wind direction errors, robust to outliers.
    - Used in wind energy and meteorological applications for robust wind direction model evaluation.

    Parameters
    ----------
    obs : xarray.DataArray or numpy.ndarray
        Observed wind direction values (degrees).
    mod : xarray.DataArray or numpy.ndarray
        Model predicted wind direction values (degrees).
    axis : int or str or None, optional
        Axis or dimension along which to compute the statistic.

    Returns
    -------
    xarray.DataArray or numpy.ndarray or float
        Median gross error in wind direction (degrees).

    Examples
    --------
    >>> import numpy as np
    >>> obs = np.array([350, 10, 20])
    >>> mod = np.array([10, 20, 30])
    >>> WDMdnE(obs, mod)
    10.0
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        dim = axis
        if isinstance(axis, int):
            dim = obs.dims[axis]
        cb = circlebias(mod - obs)
        res = abs(cb).median(dim=dim)
        return _update_history(res, "Wind Direction Median Gross Error (WDMdnE)")
    else:
        obs_arr = np.ma.asanyarray(obs)
        mod_arr = np.ma.asanyarray(mod)
        cb = circlebias(mod_arr - obs_arr)
        return np.ma.median(np.ma.abs(cb), axis=axis)

WDNMB_m(obs, mod, axis=None)

Wind Direction Normalized Mean Bias (%) (avoid single block error in np.ma)

Typical Use Cases

  • Comparing the average wind direction bias, normalized by observed wind direction, across sites or time periods.
  • Used in wind energy and meteorological model evaluation for directionally normalized performance.

Parameters

obs : xarray.DataArray or numpy.ndarray Observed wind direction values (degrees). mod : xarray.DataArray or numpy.ndarray Model predicted wind direction values (degrees). axis : int or str or None, optional Axis or dimension along which to compute the statistic.

Returns

xarray.DataArray or numpy.ndarray or float Wind direction normalized mean bias (percent).

Examples

import numpy as np obs = np.array([350, 10, 20]) mod = np.array([345, 15, 25]) WDNMB_m(obs, mod) -5.0

Source code in src/monet_stats/relative_metrics.py
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
def WDNMB_m(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Wind Direction Normalized Mean Bias (%) (avoid single block error in np.ma)

    Typical Use Cases
    -----------------
    - Comparing the average wind direction bias, normalized by observed wind direction, across sites or time periods.
    - Used in wind energy and meteorological model evaluation for directionally normalized performance.

    Parameters
    ----------
    obs : xarray.DataArray or numpy.ndarray
        Observed wind direction values (degrees).
    mod : xarray.DataArray or numpy.ndarray
        Model predicted wind direction values (degrees).
    axis : int or str or None, optional
        Axis or dimension along which to compute the statistic.

    Returns
    -------
    xarray.DataArray or numpy.ndarray or float
        Wind direction normalized mean bias (percent).

    Examples
    --------
    >>> import numpy as np
    >>> obs = np.array([350, 10, 20])
    >>> mod = np.array([345, 15, 25])
    >>> WDNMB_m(obs, mod)
    -5.0
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        dim = axis
        if isinstance(axis, int):
            dim = obs.dims[axis]
        diff = mod - obs
        cb = circlebias_m(diff)
        res = cb.sum(dim=dim) / obs.sum(dim=dim) * 100.0
        return _update_history(res, "Wind Direction Normalized Mean Bias (WDNMB_m)")
    else:
        obs_arr = np.asanyarray(obs)
        mod_arr = np.asanyarray(mod)
        diff = mod_arr - obs_arr
        return circlebias_m(diff).sum(axis=axis) / obs_arr.sum(axis=axis) * 100.0

Spatial & Ensemble Metrics

Spatial and Ensemble Metrics for Atmospheric Sciences (Aero Protocol Compliant)

BSS(obs, mod, threshold)

Brier Skill Score (BSS) for probabilistic forecasts.

Typical Use Cases

  • Evaluating the accuracy of probabilistic binary forecasts relative to climatology.
  • Common in meteorological verification for event occurrence.

Parameters

obs : xarray.DataArray or numpy.ndarray Observed binary outcomes (0 or 1) or continuous values (will be binarized). mod : xarray.DataArray or numpy.ndarray Forecast probabilities (0 to 1) or continuous values (will be binarized). threshold : float Threshold for converting values to binary events.

Returns

xarray.DataArray or numpy.ndarray or float Brier Skill Score.

Source code in src/monet_stats/spatial_ensemble_metrics.py
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
def BSS(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    threshold: float,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Brier Skill Score (BSS) for probabilistic forecasts.

    Typical Use Cases
    -----------------
    - Evaluating the accuracy of probabilistic binary forecasts relative to climatology.
    - Common in meteorological verification for event occurrence.

    Parameters
    ----------
    obs : xarray.DataArray or numpy.ndarray
        Observed binary outcomes (0 or 1) or continuous values (will be binarized).
    mod : xarray.DataArray or numpy.ndarray
        Forecast probabilities (0 to 1) or continuous values (will be binarized).
    threshold : float
        Threshold for converting values to binary events.

    Returns
    -------
    xarray.DataArray or numpy.ndarray or float
        Brier Skill Score.
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        # Binarize if not already
        o_bin = (obs >= threshold).astype(float)
        m_prob = (mod >= threshold).astype(float)

        bs = ((m_prob - o_bin) ** 2).mean()
        obs_clim = o_bin.mean()
        bs_ref = ((obs_clim - o_bin) ** 2).mean()

        res = xr.where(bs_ref != 0, 1 - (bs / bs_ref), 0.0)
        return _update_history(res, "Brier Skill Score (BSS)")

    o = np.asarray(obs)
    m = np.asarray(mod)
    o_bin = (o >= threshold).astype(float)
    m_prob = (m >= threshold).astype(float)

    bs = np.mean((m_prob - o_bin) ** 2)
    obs_clim = np.mean(o_bin)
    bs_ref = np.mean((obs_clim - o_bin) ** 2)

    if bs_ref == 0:
        return 0.0
    return 1 - (bs / bs_ref)

CRPS(ensemble, obs, axis=0)

Continuous Ranked Probability Score (CRPS) for ensemble forecasts.

Supports lazy evaluation via Xarray/Dask.

Parameters

ensemble : xarray.DataArray or numpy.ndarray Ensemble forecasts. If DataArray, should have an ensemble dimension. obs : xarray.DataArray or numpy.ndarray Observed values. axis : int or str, optional Axis or dimension corresponding to ensemble members. Default is 0.

Returns

xarray.DataArray or numpy.ndarray CRPS values.

Examples

import numpy as np ens = np.array([[1, 2], [2, 3], [3, 4]]) obs = np.array([2, 3]) CRPS(ens, obs, axis=0) array([0.22222222, 0.22222222])

Source code in src/monet_stats/spatial_ensemble_metrics.py
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
def CRPS(
    ensemble: Union[xr.DataArray, np.ndarray],
    obs: Union[xr.DataArray, np.ndarray],
    axis: Union[int, str] = 0,
) -> Union[xr.DataArray, np.ndarray]:
    """
    Continuous Ranked Probability Score (CRPS) for ensemble forecasts.

    Supports lazy evaluation via Xarray/Dask.

    Parameters
    ----------
    ensemble : xarray.DataArray or numpy.ndarray
        Ensemble forecasts. If DataArray, should have an ensemble dimension.
    obs : xarray.DataArray or numpy.ndarray
        Observed values.
    axis : int or str, optional
        Axis or dimension corresponding to ensemble members. Default is 0.

    Returns
    -------
    xarray.DataArray or numpy.ndarray
        CRPS values.

    Examples
    --------
    >>> import numpy as np
    >>> ens = np.array([[1, 2], [2, 3], [3, 4]])
    >>> obs = np.array([2, 3])
    >>> CRPS(ens, obs, axis=0)
    array([0.22222222, 0.22222222])
    """

    def _crps_numpy(ens, observation, ens_axis=0):
        ens_sorted = np.sort(ens, axis=ens_axis)
        n = ens.shape[ens_axis]
        # Compute empirical CDFs
        cdf_ens = np.arange(1, n + 1) / n
        shape = [1] * ens.ndim
        shape[ens_axis] = n
        cdf_ens = np.reshape(cdf_ens, shape)
        # Broadcast obs for comparison
        obs_broadcast = np.expand_dims(observation, ens_axis)
        cdf_obs = (ens_sorted >= obs_broadcast).astype(float)
        return np.sum((cdf_ens - cdf_obs) ** 2, axis=ens_axis)

    if isinstance(ensemble, xr.DataArray) and isinstance(obs, xr.DataArray):
        # Determine core dimension
        if isinstance(axis, int):
            ens_dim = ensemble.dims[axis]
        else:
            ens_dim = axis

        res = xr.apply_ufunc(
            _crps_numpy,
            ensemble,
            obs,
            input_core_dims=[[ens_dim], []],
            output_core_dims=[[]],
            kwargs={"ens_axis": -1},
            dask="parallelized",
            output_dtypes=[float],
            dask_gufunc_kwargs={"allow_rechunk": True},
        )
        return _update_history(res, "Continuous Ranked Probability Score (CRPS)")

    return _crps_numpy(np.asarray(ensemble), np.asarray(obs), ens_axis=axis)

EDS(obs, mod, threshold)

Extreme Dependency Score (EDS) for rare event detection.

Typical Use Cases

  • Assessing model performance for rare extreme events (e.g., heavy precipitation).
  • Used when traditional scores like CSI or ETS go to zero as the event becomes rarer.

Parameters

obs : xarray.DataArray or numpy.ndarray Observed field. mod : xarray.DataArray or numpy.ndarray Model field. threshold : float Event threshold to define the extreme event.

Returns

xarray.DataArray or numpy.ndarray or float Extreme Dependency Score.

Examples

import numpy as np obs = np.zeros((10, 10)); obs[5, 5] = 1 mod = np.zeros((10, 10)); mod[5, 5] = 1 EDS(obs, mod, threshold=0.5) 1.0

Source code in src/monet_stats/spatial_ensemble_metrics.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
def EDS(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    threshold: float,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Extreme Dependency Score (EDS) for rare event detection.

    Typical Use Cases
    -----------------
    - Assessing model performance for rare extreme events (e.g., heavy precipitation).
    - Used when traditional scores like CSI or ETS go to zero as the event becomes rarer.

    Parameters
    ----------
    obs : xarray.DataArray or numpy.ndarray
        Observed field.
    mod : xarray.DataArray or numpy.ndarray
        Model field.
    threshold : float
        Event threshold to define the extreme event.

    Returns
    -------
    xarray.DataArray or numpy.ndarray or float
        Extreme Dependency Score.

    Examples
    --------
    >>> import numpy as np
    >>> obs = np.zeros((10, 10)); obs[5, 5] = 1
    >>> mod = np.zeros((10, 10)); mod[5, 5] = 1
    >>> EDS(obs, mod, threshold=0.5)
    1.0
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        obs_bin = obs >= threshold
        mod_bin = mod >= threshold
        hits = (obs_bin & mod_bin).sum()
        n_obs = obs_bin.sum()
        n_mod = mod_bin.sum()
        n = obs.size

        # Use xr.where for lazy evaluation
        p = n_obs / n
        q = n_mod / n

        # We need to handle the log carefully for dask
        eds = np.log(hits / n) / np.log(p * q)
        # Handle cases where hits=0 or n_obs/n_mod=0 which would result in inf/nan
        # EDS is undefined if p=0 or q=0 or hits=0
        res = xr.where((hits > 0) & (p > 0) & (q > 0), eds, np.nan)
        return _update_history(res, "Extreme Dependency Score (EDS)")

    obs_bin = np.asarray(obs) >= threshold
    mod_bin = np.asarray(mod) >= threshold
    hits = np.logical_and(obs_bin, mod_bin).sum()
    n_obs = obs_bin.sum()
    n_mod = mod_bin.sum()
    n = np.size(obs)
    if hits == 0 or n_obs == 0 or n_mod == 0:
        return np.nan
    p = n_obs / n
    q = n_mod / n
    return np.log(hits / n) / np.log(p * q)

SAL(obs, mod, threshold=None)

Structure-Amplitude-Location (SAL) score for spatial verification.

Note: This metric currently triggers computation for Xarray/Dask inputs as it relies on scipy.ndimage for object identification.

Parameters

obs : xarray.DataArray or numpy.ndarray Observed 2D field. mod : xarray.DataArray or numpy.ndarray Model 2D field. threshold : float, optional Threshold for object identification. If None, uses mean of obs.

Returns

S : float Structure component (-2 to 2, 0 is best). A : float Amplitude component (-2 to 2, 0 is best). L : float Location component (0 to 2, 0 is best).

Source code in src/monet_stats/spatial_ensemble_metrics.py
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
def SAL(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    threshold: Optional[float] = None,
) -> Tuple[float, float, float]:
    """
    Structure-Amplitude-Location (SAL) score for spatial verification.

    Note: This metric currently triggers computation for Xarray/Dask inputs
    as it relies on scipy.ndimage for object identification.

    Parameters
    ----------
    obs : xarray.DataArray or numpy.ndarray
        Observed 2D field.
    mod : xarray.DataArray or numpy.ndarray
        Model 2D field.
    threshold : float, optional
        Threshold for object identification. If None, uses mean of obs.

    Returns
    -------
    S : float
        Structure component (-2 to 2, 0 is best).
    A : float
        Amplitude component (-2 to 2, 0 is best).
    L : float
        Location component (0 to 2, 0 is best).
    """
    import scipy.ndimage as ndi

    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        # We explicitly compute for now because SAL is inherently non-local
        # and hard to dask-ify without complex overlapping.
        obs_np = obs.values
        mod_np = mod.values
    else:
        obs_np = np.asarray(obs)
        mod_np = np.asarray(mod)

    if threshold is None:
        threshold = np.nanmean(obs_np)

    # Amplitude
    denom_a = np.nanmean(mod_np) + np.nanmean(obs_np)
    A = 2 * (np.nanmean(mod_np) - np.nanmean(obs_np)) / denom_a if denom_a != 0 else 0.0

    # Structure
    def structure(X):
        labeled, n = ndi.label(threshold <= X)
        if n == 0:
            return 0.0, 0.0
        masses = ndi.sum(X, labeled, index=np.arange(1, n + 1))
        max_mass = np.max(masses)
        total_mass = np.sum(masses)
        return max_mass, total_mass

    max_mod, sum_mod = structure(mod_np)
    max_obs, sum_obs = structure(obs_np)
    denom_s = (max_mod / sum_mod + max_obs / sum_obs) if sum_mod > 0 and sum_obs > 0 else 0
    S = 2 * (max_mod / sum_mod - max_obs / sum_obs) / denom_s if denom_s != 0 else 0.0

    # Location
    def centroid(X):
        labeled, n = ndi.label(threshold <= X)
        if n == 0:
            return np.array([np.nan, np.nan])
        centers = np.array(ndi.center_of_mass(X, labeled, index=np.arange(1, n + 1)))
        masses = ndi.sum(X, labeled, index=np.arange(1, n + 1))
        weighted = np.average(centers, axis=0, weights=masses)
        return weighted

    c_mod = centroid(mod_np)
    c_obs = centroid(obs_np)
    dist = np.linalg.norm(c_mod - c_obs)
    max_dist = np.sqrt(obs_np.shape[0] ** 2 + obs_np.shape[1] ** 2)
    L1 = dist / max_dist if max_dist != 0 else 0.0

    # Spread of objects
    def spread(X):
        labeled, n = ndi.label(threshold <= X)
        if n == 0:
            return 0.0
        centers = np.array(ndi.center_of_mass(X, labeled, index=np.arange(1, n + 1)))
        masses = ndi.sum(X, labeled, index=np.arange(1, n + 1))
        c = np.average(centers, axis=0, weights=masses)
        return np.average(np.linalg.norm(centers - c, axis=1), weights=masses)

    r_mod = spread(mod_np)
    r_obs = spread(obs_np)
    L2 = abs(r_mod - r_obs) / max_dist if max_dist != 0 else 0.0
    L = L1 + L2
    return S, A, L

ensemble_mean(ensemble, axis=0)

Calculate the ensemble mean.

Parameters

ensemble : xarray.DataArray or numpy.ndarray Ensemble forecasts. axis : int or str, optional Axis or dimension corresponding to ensemble members. Default is 0.

Returns

xarray.DataArray or numpy.ndarray Ensemble mean.

Source code in src/monet_stats/spatial_ensemble_metrics.py
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
def ensemble_mean(
    ensemble: Union[xr.DataArray, np.ndarray],
    axis: Union[int, str] = 0,
) -> Union[xr.DataArray, np.ndarray]:
    """
    Calculate the ensemble mean.

    Parameters
    ----------
    ensemble : xarray.DataArray or numpy.ndarray
        Ensemble forecasts.
    axis : int or str, optional
        Axis or dimension corresponding to ensemble members. Default is 0.

    Returns
    -------
    xarray.DataArray or numpy.ndarray
        Ensemble mean.
    """
    if isinstance(ensemble, xr.DataArray):
        dim = axis
        if isinstance(axis, int):
            dim = ensemble.dims[axis]
        res = ensemble.mean(dim=dim)
        return _update_history(res, "Ensemble Mean")
    return np.mean(ensemble, axis=axis)

ensemble_std(ensemble, axis=0)

Calculate the ensemble standard deviation.

Parameters

ensemble : xarray.DataArray or numpy.ndarray Ensemble forecasts. axis : int or str, optional Axis or dimension corresponding to ensemble members. Default is 0.

Returns

xarray.DataArray or numpy.ndarray Ensemble standard deviation.

Source code in src/monet_stats/spatial_ensemble_metrics.py
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
def ensemble_std(
    ensemble: Union[xr.DataArray, np.ndarray],
    axis: Union[int, str] = 0,
) -> Union[xr.DataArray, np.ndarray]:
    """
    Calculate the ensemble standard deviation.

    Parameters
    ----------
    ensemble : xarray.DataArray or numpy.ndarray
        Ensemble forecasts.
    axis : int or str, optional
        Axis or dimension corresponding to ensemble members. Default is 0.

    Returns
    -------
    xarray.DataArray or numpy.ndarray
        Ensemble standard deviation.
    """
    if isinstance(ensemble, xr.DataArray):
        dim = axis
        if isinstance(axis, int):
            dim = ensemble.dims[axis]
        res = ensemble.std(dim=dim)
        return _update_history(res, "Ensemble Standard Deviation")
    return np.std(ensemble, axis=axis)

rank_histogram(ensemble, obs, axis=0)

Calculate the rank histogram counts.

Parameters

ensemble : xarray.DataArray or numpy.ndarray Ensemble forecasts. obs : xarray.DataArray or numpy.ndarray Observed values. axis : int or str, optional Axis or dimension corresponding to ensemble members. Default is 0.

Returns

xarray.DataArray or numpy.ndarray Rank histogram counts.

Examples

import numpy as np ens = np.array([[1, 2], [2, 3], [3, 4]]) obs = np.array([2, 3]) rank_histogram(ens, obs, axis=0) array([0., 0., 2., 0.])

Source code in src/monet_stats/spatial_ensemble_metrics.py
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
def rank_histogram(
    ensemble: Union[xr.DataArray, np.ndarray],
    obs: Union[xr.DataArray, np.ndarray],
    axis: Union[int, str] = 0,
) -> Union[xr.DataArray, np.ndarray]:
    """
    Calculate the rank histogram counts.

    Parameters
    ----------
    ensemble : xarray.DataArray or numpy.ndarray
        Ensemble forecasts.
    obs : xarray.DataArray or numpy.ndarray
        Observed values.
    axis : int or str, optional
        Axis or dimension corresponding to ensemble members. Default is 0.

    Returns
    -------
    xarray.DataArray or numpy.ndarray
        Rank histogram counts.

    Examples
    --------
    >>> import numpy as np
    >>> ens = np.array([[1, 2], [2, 3], [3, 4]])
    >>> obs = np.array([2, 3])
    >>> rank_histogram(ens, obs, axis=0)
    array([0., 0., 2., 0.])
    """

    def _rank_numpy(ens, observation, ens_axis=0):
        o_exp = np.expand_dims(observation, ens_axis)
        full_ensemble = np.concatenate([ens, o_exp], axis=ens_axis)
        ranks = np.argsort(full_ensemble, axis=ens_axis)
        obs_rank = np.argmax(ranks == ens.shape[ens_axis], axis=ens_axis)
        n_ens = ens.shape[ens_axis]
        hist, _ = np.histogram(obs_rank, bins=np.arange(n_ens + 2))
        return hist.astype(float)

    if isinstance(ensemble, xr.DataArray) and isinstance(obs, xr.DataArray):
        if isinstance(axis, int):
            ens_dim = ensemble.dims[axis]
        else:
            ens_dim = axis

        def _rank_ufunc(ens, observation):
            o_exp = np.expand_dims(observation, -1)
            full_ensemble = np.concatenate([ens, o_exp], axis=-1)
            ranks = np.argsort(full_ensemble, axis=-1)
            return np.argmax(ranks == ens.shape[-1], axis=-1)

        obs_rank = xr.apply_ufunc(
            _rank_ufunc,
            ensemble,
            obs,
            input_core_dims=[[ens_dim], []],
            output_core_dims=[[]],
            dask="parallelized",
            output_dtypes=[int],
        )

        n_ens = ensemble.sizes[ens_dim]
        bins = np.arange(n_ens + 2)
        if hasattr(obs_rank.data, "dask"):
            import dask.array as da

            hist, _ = da.histogram(obs_rank.data, bins=bins)
            res = xr.DataArray(hist, dims="rank", coords={"rank": np.arange(n_ens + 1)})
        else:
            hist, _ = np.histogram(obs_rank.values, bins=bins)
            res = xr.DataArray(hist, dims="rank", coords={"rank": np.arange(n_ens + 1)})
        return _update_history(res, "Rank Histogram")

    return _rank_numpy(np.asarray(ensemble), np.asarray(obs), ens_axis=axis)

spread_error(ensemble, obs, axis=0)

Spread-Error Relationship for ensemble forecasts.

Typical Use Cases

  • Assessing if the ensemble spread is a good proxy for the forecast error.
  • Ideally, mean spread should equal RMSE of the ensemble mean.

Parameters

ensemble : xarray.DataArray or numpy.ndarray Ensemble forecasts. obs : xarray.DataArray or numpy.ndarray Observed values. axis : int or str, optional Axis or dimension corresponding to ensemble members. Default is 0.

Returns

mean_spread : float or xarray.DataArray Mean ensemble spread. mean_error : float or xarray.DataArray Mean absolute error of ensemble mean vs. obs.

Source code in src/monet_stats/spatial_ensemble_metrics.py
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
def spread_error(
    ensemble: Union[xr.DataArray, np.ndarray],
    obs: Union[xr.DataArray, np.ndarray],
    axis: Union[int, str] = 0,
) -> Tuple[Any, Any]:
    """
    Spread-Error Relationship for ensemble forecasts.

    Typical Use Cases
    -----------------
    - Assessing if the ensemble spread is a good proxy for the forecast error.
    - Ideally, mean spread should equal RMSE of the ensemble mean.

    Parameters
    ----------
    ensemble : xarray.DataArray or numpy.ndarray
        Ensemble forecasts.
    obs : xarray.DataArray or numpy.ndarray
        Observed values.
    axis : int or str, optional
        Axis or dimension corresponding to ensemble members. Default is 0.

    Returns
    -------
    mean_spread : float or xarray.DataArray
        Mean ensemble spread.
    mean_error : float or xarray.DataArray
        Mean absolute error of ensemble mean vs. obs.
    """
    if isinstance(ensemble, xr.DataArray) and isinstance(obs, xr.DataArray):
        if isinstance(axis, int):
            dim = ensemble.dims[axis]
        else:
            dim = axis

        spread = ensemble.std(dim=dim)
        ens_mean = ensemble.mean(dim=dim)
        error = abs(ens_mean - obs)

        # We return means over all remaining dimensions as well?
        # The original implementation returned np.mean(spread), np.mean(error)
        # which are scalars.
        m_spread = spread.mean()
        m_error = error.mean()

        return _update_history(m_spread, "Mean Ensemble Spread"), _update_history(m_error, "Mean Ensemble Error")

    ens = np.asarray(ensemble)
    observation = np.asarray(obs)
    spread = np.std(ens, axis=axis)
    ens_mean = np.mean(ens, axis=axis)
    error = np.abs(ens_mean - observation)
    return np.mean(spread), np.mean(error)

Utility Functions

Utility Functions for Statistics

angular_difference(angle1, angle2, units='degrees')

Calculate the smallest angular difference between two angles.

Backend-agnostic (supports NumPy and Xarray/Dask).

Parameters

angle1 : array-like First angle(s). angle2 : array-like Second angle(s). units : str, optional Units of angles ('degrees' or 'radians'). Default is 'degrees'.

Returns

array-like Smallest angular difference between the two angles.

Source code in src/monet_stats/utils_stats.py
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
def angular_difference(angle1: ArrayLike, angle2: ArrayLike, units: str = "degrees") -> Any:
    """
    Calculate the smallest angular difference between two angles.

    Backend-agnostic (supports NumPy and Xarray/Dask).

    Parameters
    ----------
    angle1 : array-like
        First angle(s).
    angle2 : array-like
        Second angle(s).
    units : str, optional
        Units of angles ('degrees' or 'radians'). Default is 'degrees'.

    Returns
    -------
    array-like
        Smallest angular difference between the two angles.
    """
    if units == "degrees":
        max_val = 360.0
    elif units == "radians":
        max_val = 2 * np.pi
    else:
        raise ValueError("units must be 'degrees' or 'radians'")

    if (hasattr(angle1, "attrs") and hasattr(angle1, "coords")) or (
        hasattr(angle2, "attrs") and hasattr(angle2, "coords")
    ):
        if (hasattr(angle1, "attrs") and hasattr(angle1, "coords")) and (
            hasattr(angle2, "attrs") and hasattr(angle2, "coords")
        ):
            angle1, angle2 = xr.align(angle1, angle2, join="inner")
        diff = abs(angle1 - angle2)
        result = xr.where(diff > max_val / 2, max_val - diff, diff)
        return _update_history(result, "angular_difference")

    angle1_arr = np.asarray(angle1)
    angle2_arr = np.asarray(angle2)
    diff = np.abs(angle1_arr - angle2_arr)
    return np.minimum(diff, max_val - diff)

circlebias(b)

Circular bias (wind direction difference, wrapped to [-180, 180] degrees).

Typical Use Cases

  • Calculating the signed difference between two wind directions, accounting for circularity.
  • Used in wind direction bias and error metrics to avoid artificial large errors across 0/360 boundaries.

Parameters

b : array-like Difference between two wind directions (degrees).

Returns

array-like Circularly wrapped difference (degrees).

Source code in src/monet_stats/utils_stats.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
def circlebias(b: ArrayLike) -> Any:
    """
    Circular bias (wind direction difference, wrapped to [-180, 180] degrees).

    Typical Use Cases
    -----------------
    - Calculating the signed difference between two wind directions, accounting
      for circularity.
    - Used in wind direction bias and error metrics to avoid artificial large
      errors across 0/360 boundaries.

    Parameters
    ----------
    b : array-like
        Difference between two wind directions (degrees).

    Returns
    -------
    array-like
        Circularly wrapped difference (degrees).
    """
    if hasattr(b, "attrs") and hasattr(b, "coords"):
        res = (b + 180) % 360 - 180
        return _update_history(res, "circlebias")

    return (np.asarray(b) + 180) % 360 - 180

circlebias_m(b)

Circular bias for wind direction (robust to masked arrays).

Typical Use Cases

  • Calculating the signed difference between two wind directions, accounting for circularity, robust to masked arrays.
  • Used in wind direction bias and error metrics for masked or missing data.

Parameters

b : array-like Difference between two wind directions (degrees).

Returns

array-like Circularly wrapped difference (degrees).

Source code in src/monet_stats/utils_stats.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
def circlebias_m(b: ArrayLike) -> Any:
    """
    Circular bias for wind direction (robust to masked arrays).

    Typical Use Cases
    -----------------
    - Calculating the signed difference between two wind directions, accounting
      for circularity, robust to masked arrays.
    - Used in wind direction bias and error metrics for masked or missing data.

    Parameters
    ----------
    b : array-like
        Difference between two wind directions (degrees).

    Returns
    -------
    array-like
        Circularly wrapped difference (degrees).
    """
    if hasattr(b, "attrs") and hasattr(b, "coords"):
        res = (b + 180) % 360 - 180
        return _update_history(res, "circlebias_m")

    b_masked = np.ma.masked_invalid(b)
    return (b_masked + 180) % 360 - 180

correlation(x, y, axis=None)

Calculate Pearson correlation coefficient between x and y.

Parameters

x : numpy.ndarray or xarray.DataArray First variable. y : numpy.ndarray or xarray.DataArray Second variable. axis : int, str, or iterable, optional Axis along which to compute correlation.

Returns

Union[np.number, np.ndarray, xr.DataArray] Pearson correlation coefficient.

Raises

ValueError If input arrays are empty.

Source code in src/monet_stats/utils_stats.py
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
def correlation(
    x: Union[np.ndarray, xr.DataArray],
    y: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Calculate Pearson correlation coefficient between x and y.

    Parameters
    ----------
    x : numpy.ndarray or xarray.DataArray
        First variable.
    y : numpy.ndarray or xarray.DataArray
        Second variable.
    axis : int, str, or iterable, optional
        Axis along which to compute correlation.

    Returns
    -------
    Union[np.number, np.ndarray, xr.DataArray]
        Pearson correlation coefficient.

    Raises
    ------
    ValueError
        If input arrays are empty.
    """
    if hasattr(x, "size") and x.size == 0:
        raise ValueError("Input arrays cannot be empty")
    if hasattr(y, "size") and y.size == 0:
        raise ValueError("Input arrays cannot be empty")

    from .correlation_metrics import pearsonr

    res = pearsonr(x, y, axis=axis)
    if hasattr(res, "attrs") and hasattr(res, "coords"):
        return _update_history(res, "correlation")
    return res

mae(obs, mod, axis=None)

Calculate Mean Absolute Error between observations and model.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable, optional Axis along which to compute MAE.

Returns

Union[np.number, np.ndarray, xr.DataArray] Mean absolute error.

Source code in src/monet_stats/utils_stats.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
def mae(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Calculate Mean Absolute Error between observations and model.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable, optional
        Axis along which to compute MAE.

    Returns
    -------
    Union[np.number, np.ndarray, xr.DataArray]
        Mean absolute error.
    """
    from .error_metrics import MAE

    res = MAE(obs, mod, axis=axis)
    if hasattr(res, "attrs") and hasattr(res, "coords"):
        return _update_history(res, "mae")
    return res

matchedcompressed(a1, a2)

Return compressed (non-masked) values from two masked arrays with matched masks.

Note: For Xarray DataArrays, this function will trigger a computation if the data is Dask-backed, as it returns NumPy ndarrays. For lazy operations, prefer using Xarray-native methods with skipna=True.

Parameters

a1 : array-like First input array. a2 : array-like Second input array.

Returns

tuple of ndarray Tuple of (a1_compressed, a2_compressed), both 1D arrays of valid values.

Source code in src/monet_stats/utils_stats.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
def matchedcompressed(a1: ArrayLike, a2: ArrayLike) -> Tuple[np.ndarray, np.ndarray]:
    """
    Return compressed (non-masked) values from two masked arrays with matched masks.

    Note: For Xarray DataArrays, this function will trigger a computation if
    the data is Dask-backed, as it returns NumPy ndarrays. For lazy operations,
    prefer using Xarray-native methods with `skipna=True`.

    Parameters
    ----------
    a1 : array-like
        First input array.
    a2 : array-like
        Second input array.

    Returns
    -------
    tuple of ndarray
        Tuple of (a1_compressed, a2_compressed), both 1D arrays of valid values.
    """
    # Handle Xarray objects by extracting values (explicitly mentioned as computation-triggering)
    if hasattr(a1, "values") and hasattr(a1, "coords"):
        a1 = a1.values
    if hasattr(a2, "values") and hasattr(a2, "coords"):
        a2 = a2.values

    # Convert to masked arrays to handle existing masks and NaNs
    a1_m = np.ma.masked_invalid(a1)
    a2_m = np.ma.masked_invalid(a2)

    # Handle mismatched shapes for numpy arrays by truncating
    if a1_m.shape != a2_m.shape:
        min_size = min(a1_m.size, a2_m.size)
        a1_m = a1_m.flat[:min_size]
        a2_m = a2_m.flat[:min_size]

    mask = np.ma.getmaskarray(a1_m) | np.ma.getmaskarray(a2_m)
    a1_matched = np.ma.masked_where(mask, a1_m)
    a2_matched = np.ma.masked_where(mask, a2_m)
    return a1_matched.compressed(), a2_matched.compressed()

matchmasks(a1, a2)

Match and combine masks from two masked arrays or align Xarray objects.

Parameters

a1 : array-like First input array. a2 : array-like Second input array.

Returns

tuple Tuple of (a1_matched, a2_matched).

Source code in src/monet_stats/utils_stats.py
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def matchmasks(a1: ArrayLike, a2: ArrayLike) -> Tuple[Any, Any]:
    """
    Match and combine masks from two masked arrays or align Xarray objects.

    Parameters
    ----------
    a1 : array-like
        First input array.
    a2 : array-like
        Second input array.

    Returns
    -------
    tuple
        Tuple of (a1_matched, a2_matched).
    """
    if isinstance(a1, xr.DataArray) and isinstance(a2, xr.DataArray):
        # Align xarray objects (works for dask-backed as well)
        return xr.align(a1, a2, join="inner")
    else:
        a1_arr = np.asanyarray(a1)
        a2_arr = np.asanyarray(a2)
        mask = np.ma.getmaskarray(a1_arr) | np.ma.getmaskarray(a2_arr)
        return np.ma.masked_where(mask, a1_arr), np.ma.masked_where(mask, a2_arr)

rmse(obs, mod, axis=None)

Calculate Root Mean Square Error between observations and model.

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values. mod : numpy.ndarray or xarray.DataArray Model or predicted values. axis : int, str, or iterable, optional Axis or dimension along which to compute RMSE.

Returns

Union[np.number, np.ndarray, xr.DataArray] Root mean square error.

Source code in src/monet_stats/utils_stats.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
def rmse(
    obs: Union[np.ndarray, xr.DataArray],
    mod: Union[np.ndarray, xr.DataArray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[np.number, np.ndarray, xr.DataArray]:
    """
    Calculate Root Mean Square Error between observations and model.

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values.
    mod : numpy.ndarray or xarray.DataArray
        Model or predicted values.
    axis : int, str, or iterable, optional
        Axis or dimension along which to compute RMSE.

    Returns
    -------
    Union[np.number, np.ndarray, xr.DataArray]
        Root mean square error.
    """
    from .error_metrics import RMSE

    res = RMSE(obs, mod, axis=axis)
    if hasattr(res, "attrs") and hasattr(res, "coords"):
        return _update_history(res, "rmse")
    return res

Contributing to API Documentation

If you find issues with the API documentation or would like to suggest improvements:

  1. Check the GitHub Issues
  2. Submit new issues with clear descriptions
  3. Consider contributing improvements via pull requests

For development documentation, see the Contributing Guide.