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

Xarray Accessor (Pangeo Style)

The most recommended way to use Monet Stats with Xarray is via the .monet_stats accessor, which is automatically registered when you import monet_stats.

import monet_stats
import xarray as xr

# Load data
da = xr.open_dataarray("data.nc")

# Use accessor for analysis
climo = da.monet_stats.climatology(freq="month")
mda8 = da.monet_stats.mda8()
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()
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
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
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
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")
        dim = _resolve_axis_to_dim(obs, axis)

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

        bs = ((mod_binary - obs_binary) ** 2).mean(dim=dim)
        # bs_ref is p_bar * (1 - p_bar) where p_bar is the event frequency
        p_bar = obs_binary.mean(dim=dim)
        bs_ref = p_bar * (1.0 - p_bar)

        result = xr.where(bs_ref > 0, 1.0 - (bs / bs_ref), 0.0)
        result.attrs = obs.attrs.copy()
        return _update_history(result, "Binary Brier Skill Score (BSS_binary)")
    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)
        p_bar = np.nanmean(obs_binary, axis=axis)
        bs_ref = p_bar * (1.0 - p_bar)

        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
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
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
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)
        result.attrs = obs.attrs.copy()
        return _update_history(result, "Critical Success Index (CSI)")
    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

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

Find the threshold that maximizes the Critical Success Index (CSI) over a range.

Vectorized implementation (Aero Protocol).

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 CSI. max_csi : float Maximum CSI value achieved.

Source code in src/monet_stats/contingency_metrics.py
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
983
984
985
986
987
988
989
990
991
992
993
994
def CSI_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 Critical Success Index (CSI) over a range.

    Vectorized implementation (Aero Protocol).

    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 CSI.
    max_csi : float
        Maximum CSI value achieved.
    """
    thresholds = np.arange(minval_range, maxval_range, step_size)
    a, b, c, d = _contingency_table(obs, mod, minval=thresholds)

    denom = a + b + c
    with np.errstate(divide="ignore", invalid="ignore"):
        csi_values = np.where(denom > 0, a / denom, np.nan)

    if isinstance(csi_values, xr.DataArray):
        max_idx = csi_values.argmax(dim="threshold").values.item()
        max_val = csi_values.isel(threshold=max_idx).values.item()
    else:
        max_idx = np.nanargmax(csi_values)
        max_val = csi_values[max_idx]

    return float(thresholds[max_idx]), float(max_val)

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
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)
        result.attrs = obs.attrs.copy()
        return _update_history(result, "Equitable Threat Score (ETS)")
    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.

Vectorized implementation (Aero Protocol).

Typical Use Cases

  • Automated tuning of model thresholds to achieve the best possible predictive skill for rare events.

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.

Source code in src/monet_stats/contingency_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
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
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.

    Vectorized implementation (Aero Protocol).

    Typical Use Cases
    -----------------
    - Automated tuning of model thresholds to achieve the best possible
      predictive skill for rare events.

    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.
    """
    thresholds = np.arange(minval_range, maxval_range, step_size)
    a, b, c, d = _contingency_table(obs, mod, minval=thresholds)

    total = a + b + c + d
    random_hits = ((a + b) * (a + c)) / total
    denom = a + b + c - random_hits
    with np.errstate(divide="ignore", invalid="ignore"):
        ets_values = np.where(denom > 0, (a - random_hits) / denom, np.nan)

    if isinstance(ets_values, xr.DataArray):
        max_idx = ets_values.argmax(dim="threshold").values.item()
        max_ets = ets_values.isel(threshold=max_idx).values.item()
    else:
        max_idx = np.nanargmax(ets_values)
        max_ets = ets_values[max_idx]

    return float(thresholds[max_idx]), 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
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
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)
        result.attrs = obs.attrs.copy()
        return _update_history(result, "False Alarm Rate (FAR)")
    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.

Vectorized implementation (Aero Protocol).

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) (1.5, 0.0)

Source code in src/monet_stats/contingency_metrics.py
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
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.

    Vectorized implementation (Aero Protocol).

    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)
    (1.5, 0.0)
    """
    thresholds = np.arange(minval_range, maxval_range, step_size)
    a, b, c, d = _contingency_table(obs, mod, minval=thresholds)

    denom = a + c
    with np.errstate(divide="ignore", invalid="ignore"):
        far_values = np.where(denom > 0, c / denom, np.nan)

    if isinstance(far_values, xr.DataArray):
        min_idx = far_values.argmin(dim="threshold").values.item()
        min_val = far_values.isel(threshold=min_idx).values.item()
    else:
        min_idx = np.nanargmin(far_values)
        min_val = far_values[min_idx]

    return float(thresholds[min_idx]), float(min_val)

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

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

Typical Use Cases

  • Evaluating whether the model over- or under-predicts the frequency of events.
  • Used in air quality and weather forecasting to assess systematic bias in categorical predictions.

Typical Values and Range

  • Range: 0 to ∞
  • 1: Perfect (events occur with same frequency in model and observations)
  • 1: Over-prediction (model predicts events more often than observed)

  • < 1: Under-prediction (model predicts events less often than observed)

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
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
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.

    Typical Use Cases
    -----------------
    - Evaluating whether the model over- or under-predicts the frequency of events.
    - Used in air quality and weather forecasting to assess systematic bias in
      categorical predictions.

    Typical Values and Range
    ------------------------
    - Range: 0 to ∞
    - 1: Perfect (events occur with same frequency in model and observations)
    - > 1: Over-prediction (model predicts events more often than observed)
    - < 1: Under-prediction (model predicts events less often than observed)

    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)
        result.attrs = obs.attrs.copy()
        return _update_history(result, "Frequency Bias Index (FBI)")
    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
 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)
        result.attrs = obs.attrs.copy()
        return _update_history(result, "Heidke Skill Score (HSS)")
    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.

Vectorized implementation (Aero Protocol).

Typical Use Cases

  • Automated tuning of model thresholds to achieve the best possible overall categorical predictive skill.

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
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
769
770
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.

    Vectorized implementation (Aero Protocol).

    Typical Use Cases
    -----------------
    - Automated tuning of model thresholds to achieve the best possible
      overall categorical predictive skill.

    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)
    a, b, c, d = _contingency_table(obs, mod, minval=thresholds)

    denom = (a + c) * (c + d) + (a + b) * (b + d)
    with np.errstate(divide="ignore", invalid="ignore"):
        hss_values = np.where(denom > 0, 2 * (a * d - b * c) / denom, np.nan)

    if isinstance(hss_values, xr.DataArray):
        max_idx = hss_values.argmax(dim="threshold").values.item()
        max_hss = hss_values.isel(threshold=max_idx).values.item()
    else:
        max_idx = np.nanargmax(hss_values)
        max_hss = hss_values[max_idx]

    return float(thresholds[max_idx]), 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
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
298
299
300
301
302
303
304
305
306
307
308
309
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)
        result.attrs = obs.attrs.copy()
        return _update_history(result, "Probability of Detection (POD)")
    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.

Vectorized implementation (Aero Protocol).

Typical Use Cases

  • Determining the most sensitive threshold for event detection, prioritizing hits over all other categories.

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) (1.0, 1.0)

Source code in src/monet_stats/contingency_metrics.py
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
876
877
878
879
880
881
882
883
884
885
886
887
888
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.

    Vectorized implementation (Aero Protocol).

    Typical Use Cases
    -----------------
    - Determining the most sensitive threshold for event detection,
      prioritizing hits over all other categories.

    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)
    (1.0, 1.0)
    """
    thresholds = np.arange(minval_range, maxval_range, step_size)
    a, b, c, d = _contingency_table(obs, mod, minval=thresholds)

    denom = a + b
    with np.errstate(divide="ignore", invalid="ignore"):
        pod_values = np.where(denom > 0, a / denom, np.nan)

    if isinstance(pod_values, xr.DataArray):
        max_idx = pod_values.argmax(dim="threshold").values.item()
        max_val = pod_values.isel(threshold=max_idx).values.item()
    else:
        max_idx = np.nanargmax(pod_values)
        max_val = pod_values[max_idx]

    return float(thresholds[max_idx]), float(max_val)

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

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

Typical Use Cases

  • Assessing the ability of the model to distinguish between event and non-event occurrences.
  • Preferred over other scores for its independence from event frequency (prevalence).

Typical Values and Range

  • Range: -1 to 1
  • 1: Perfect forecast
  • 0: No skill
  • -1: Perfect mis-forecast (always wrong)

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
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
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).

    Typical Use Cases
    -----------------
    - Assessing the ability of the model to distinguish between event and non-event
      occurrences.
    - Preferred over other scores for its independence from event frequency
      (prevalence).

    Typical Values and Range
    ------------------------
    - Range: -1 to 1
    - 1: Perfect forecast
    - 0: No skill
    - -1: Perfect mis-forecast (always wrong)

    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
        result.attrs = obs.attrs.copy()
        return _update_history(result, "True Skill Statistic (TSS)")
    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

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

Find the threshold that maximizes the True Skill Statistic (TSS) over a range.

Vectorized implementation (Aero Protocol).

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 TSS. max_tss : float Maximum TSS value achieved.

Source code in src/monet_stats/contingency_metrics.py
 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
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
def TSS_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 True Skill Statistic (TSS) over a range.

    Vectorized implementation (Aero Protocol).

    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 TSS.
    max_tss : float
        Maximum TSS value achieved.
    """
    thresholds = np.arange(minval_range, maxval_range, step_size)
    a, b, c, d = _contingency_table(obs, mod, minval=thresholds)

    pod_denom = a + b
    pofd_denom = c + d

    if isinstance(a, xr.DataArray):
        pod = xr.where(pod_denom > 0, a / pod_denom, np.nan)
        pofd = xr.where(pofd_denom > 0, c / pofd_denom, np.nan)
        tss_values = pod - pofd
    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)
            tss_values = pod - pofd

    if isinstance(tss_values, xr.DataArray):
        max_idx = tss_values.argmax(dim="threshold").values.item()
        max_val = tss_values.isel(threshold=max_idx).values.item()
    else:
        max_idx = np.nanargmax(tss_values)
        max_val = tss_values[max_idx]

    return float(thresholds[max_idx]), float(max_val)

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

Calculate the 2x2 contingency table (Aero Protocol).

Typical Use Cases

  • Obtaining the raw counts of hits, misses, false alarms, and correct negatives to compute custom categorical scores.

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 detection. maxval : float, optional Maximum threshold for event detection. axis : int, str, or iterable of such, optional Axis along which to compute the scores.

Returns

Tuple[Union[np.number, np.ndarray, xr.DataArray], ...] A tuple of (hits, misses, false alarms, 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) print(f"Hits: {a}") Hits: 2

Source code in src/monet_stats/contingency_metrics.py
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
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 the 2x2 contingency table (Aero Protocol).

    Typical Use Cases
    -----------------
    - Obtaining the raw counts of hits, misses, false alarms, and correct negatives
      to compute custom categorical scores.

    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 detection.
    maxval : float, optional
        Maximum threshold for event detection.
    axis : int, str, or iterable of such, optional
        Axis along which to compute the scores.

    Returns
    -------
    Tuple[Union[np.number, np.ndarray, xr.DataArray], ...]
        A tuple of (hits, misses, false alarms, 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)
    >>> print(f"Hits: {a}")
    Hits: 2
    """
    res = _contingency_table(obs, mod, minval, maxval, axis=axis)
    if isinstance(res[0], xr.DataArray):
        return (
            _update_history(res[0], "Hits (a)"),
            _update_history(res[1], "Misses (b)"),
            _update_history(res[2], "False Alarms (c)"),
            _update_history(res[3], "Correct Negatives (d)"),
        )
    return res

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
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
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
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:
            if isinstance(axis, int):
                dim = obs.dims[axis]
            elif isinstance(axis, (list, tuple)):
                dim = [obs.dims[d] if isinstance(d, int) else d for d in axis]
            else:
                dim = axis
        else:
            dim = obs.dims

        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
        return _update_history(result, "AC")
    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)))
        result = p1 / p2
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
1335
1336
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
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:
            if isinstance(axis, int):
                dim = obs.dims[axis]
            elif isinstance(axis, (list, tuple)):
                dim = [obs.dims[d] if isinstance(d, int) else d for d in axis]
            else:
                dim = axis
        else:
            dim = obs.dims

        # 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
        return _update_history(result, "CCC")
    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
        result = numerator / denominator
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
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:
            if isinstance(axis, int):
                dim = obs.dims[axis]
            elif isinstance(axis, (list, tuple)):
                dim = [obs.dims[d] if isinstance(d, int) else d for d in axis]
            else:
                dim = axis
        else:
            dim = obs.dims

        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)

        return _update_history(result, "E1")
    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
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 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:
            if isinstance(axis, int):
                dim = obs.dims[axis]
            elif isinstance(axis, (list, tuple)):
                dim = [obs.dims[d] if isinstance(d, int) else d for d in axis]
            else:
                dim = axis
        else:
            dim = obs.dims

        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)

        return _update_history(result, "E1_prime")
    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 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
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
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")
        dim = _resolve_axis_to_dim(obs, 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)
        return _update_history(result, "IOA")
    else:
        obs_m = np.ma.masked_invalid(obs)
        mod_m = np.ma.masked_invalid(mod)
        obs_mean = np.ma.mean(obs_m, axis=axis, keepdims=True)
        num = np.ma.sum((obs_m - mod_m) ** 2, axis=axis)
        denom = np.ma.sum((np.ma.abs(mod_m - obs_mean) + np.ma.abs(obs_m - obs_mean)) ** 2, axis=axis)
        with np.errstate(divide="ignore", invalid="ignore"):
            result = 1.0 - (num / denom)
        return result.item() if hasattr(result, "item") and 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
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
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:
            if isinstance(axis, int):
                dim = obs.dims[axis]
            elif isinstance(axis, (list, tuple)):
                dim = [obs.dims[d] if isinstance(d, int) else d for d in axis]
            else:
                dim = axis
        else:
            dim = obs.dims

        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)

        return _update_history(result, "IOA_prime")
    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
 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
 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
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:
            if isinstance(axis, int):
                dim = obs.dims[axis]
            elif isinstance(axis, (list, tuple)):
                dim = [obs.dims[d] if isinstance(d, int) else d for d in axis]
            else:
                dim = axis
        else:
            dim = obs.dims

        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
        return _update_history(result, "KGE")
    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
 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
108
109
110
111
112
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
    """
    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

        # Use native xarray correlation for speed and laziness (Aero Protocol)
        r = xr.corr(obs, mod, dim=dim)
        result = r**2
        return _update_history(result, "R2")
    else:
        from scipy.stats import pearsonr

        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)
            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).

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
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
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
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")
        dim = _resolve_axis_to_dim(obs, axis)
        result = ((mod - obs) ** 2).mean(dim=dim, keep_attrs=True) ** 0.5
        return _update_history(result, "RMSE")
    else:
        result = np.ma.sqrt(np.ma.mean((np.subtract(mod, obs)) ** 2, axis=axis))
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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).

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
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
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).

    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
    """
    res = _vectorized_regression_stats(obs, mod, axis=axis, mode="RMSEs")
    return _update_history(res, "RMSEs")

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).

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
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
387
388
389
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).

    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
    """
    res = _vectorized_regression_stats(obs, mod, axis=axis, mode="RMSEu")
    return _update_history(res, "RMSEu")

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
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
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
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:
            if isinstance(axis, int):
                dim = obs.dims[axis]
            elif isinstance(axis, (list, tuple)):
                dim = [obs.dims[d] if isinstance(d, int) else d for d in axis]
            else:
                dim = axis
        else:
            dim = obs.dims

        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
        return _update_history(result, "WDAC")
    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)
        )
        result = numerator / denominator
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
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:
            if isinstance(axis, int):
                dim = obs.dims[axis]
            elif isinstance(axis, (list, tuple)):
                dim = [obs.dims[d] if isinstance(d, int) else d for d in axis]
            else:
                dim = axis
        else:
            dim = obs.dims

        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)

        return _update_history(result, "WDIOA")
    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
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
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
600
601
602
603
604
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:
            if isinstance(axis, int):
                dim = obs.dims[axis]
            elif isinstance(axis, (list, tuple)):
                dim = [obs.dims[d] if isinstance(d, int) else d for d in axis]
            else:
                dim = axis
        else:
            dim = obs.dims

        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)

        return _update_history(result, "WDIOA_m")
    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
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
225
226
227
228
229
230
231
232
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:
            if isinstance(axis, int):
                dim = obs.dims[axis]
            elif isinstance(axis, (list, tuple)):
                dim = [obs.dims[d] if isinstance(d, int) else d for d in axis]
            else:
                dim = axis
        else:
            dim = obs.dims

        result = (circlebias(mod - obs) ** 2).mean(dim=dim, keep_attrs=True) ** 0.5
        return _update_history(result, "WDRMSE")
    else:
        result = np.ma.sqrt(np.ma.mean((circlebias(np.subtract(mod, obs))) ** 2, axis=axis))
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
161
162
163
164
165
166
167
168
169
170
171
172
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:
            if isinstance(axis, int):
                dim = obs.dims[axis]
            elif isinstance(axis, (list, tuple)):
                dim = [obs.dims[d] if isinstance(d, int) else d for d in axis]
            else:
                dim = axis
        else:
            dim = obs.dims

        result = (circlebias_m(mod - obs) ** 2).mean(dim=dim, keep_attrs=True) ** 0.5
        return _update_history(result, "WDRMSE_m")
    else:
        result = np.ma.sqrt(np.ma.mean((circlebias_m(np.subtract(mod, obs))) ** 2, axis=axis))
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
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
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:
            if isinstance(axis, int):
                dim = obs.dims[axis]
            elif isinstance(axis, (list, tuple)):
                dim = [obs.dims[d] if isinstance(d, int) else d for d in axis]
            else:
                dim = axis
        else:
            dim = obs.dims

        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)

        return _update_history(result, "d1")
    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 tau correlation coefficient (Aero Protocol: Standardized).

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
1178
1179
1180
1181
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
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 tau correlation coefficient (Aero Protocol: Standardized).

    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

    # Standardize to DataArray to leverage Xarray's apply_ufunc vectorization
    is_numpy = not isinstance(obs, xr.DataArray)
    if is_numpy:
        obs = xr.DataArray(obs)
        mod = xr.DataArray(mod)
        if axis is not None:
            if isinstance(axis, int):
                dim = obs.dims[axis]
            elif isinstance(axis, Iterable) and not isinstance(axis, str):
                dim = [obs.dims[i] for i in axis]
            else:
                dim = axis
        else:
            dim = obs.dims
    else:
        if 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

    if axis is None:
        obsc, modc = matchedcompressed(obs, mod)
        if len(obsc) < 2:
            return np.nan
        return _kendalltau(obsc, modc)[0]

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

    # Use apply_ufunc to eliminate manual loops and support Dask
    icd = [dim] if isinstance(dim, (str, int)) else list(dim)
    result = xr.apply_ufunc(
        _kendalltau_onlytau,
        obs,
        mod,
        input_core_dims=[icd] * 2,
        output_core_dims=[[]],
        vectorize=True,
        dask="parallelized",
        dask_gufunc_kwargs={"allow_rechunk": True},
        output_dtypes=[float],
    )

    if is_numpy:
        return result.values
    return _update_history(result, "kendalltau")

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
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
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
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
    """
    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

        # Use native xarray correlation for speed and laziness (Aero Protocol)
        result = xr.corr(obs, mod, dim=dim)
        return _update_history(result, "pearsonr")
    else:
        from scipy.stats import pearsonr as _pearsonr

        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 with pairwise deletion
            obs = np.asanyarray(obs)
            mod = np.asanyarray(mod)
            mask = np.isnan(obs) | np.isnan(mod)
            obs = np.where(mask, np.nan, obs)
            mod = np.where(mask, np.nan, mod)

            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 (Aero Protocol: Vectorized).

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
1081
1082
1083
1084
1085
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
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
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 (Aero Protocol: Vectorized).

    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
    """
    # Handle Xarray/NumPy alignment and dimension resolution
    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
    else:
        dim = axis

    if axis is None:
        obsc, modc = matchedcompressed(obs, mod)
        if len(obsc) < 2:
            return np.nan
        from scipy.stats import spearmanr as _spearmanr

        return _spearmanr(obsc, modc)[0]

    # Spearman is Pearson on ranks. Use rankdata along the axis.
    from scipy.stats import rankdata

    # Apply pairwise masking to ensure ranks are computed on the same set of points
    mask = np.isnan(obs) | np.isnan(mod)
    obs = xr.where(mask, np.nan, obs) if isinstance(obs, xr.DataArray) else np.where(mask, np.nan, obs)
    mod = xr.where(mask, np.nan, mod) if isinstance(mod, xr.DataArray) else np.where(mask, np.nan, mod)

    def _rank_wrapper(data, axis):
        # Handle all-NaN slices to avoid Scipy warnings or errors
        if np.all(np.isnan(data)):
            return np.full(data.shape, np.nan)
        return rankdata(data, axis=axis, nan_policy="omit")

    # Use apply_ufunc for rankdata to support both NumPy and Xarray/Dask
    if isinstance(obs, xr.DataArray):
        icd = [dim] if isinstance(dim, (str, int)) else list(dim)
        obs_ranked = xr.apply_ufunc(
            _rank_wrapper,
            obs,
            input_core_dims=[icd],
            output_core_dims=[icd],
            kwargs={"axis": -1},
            dask="parallelized",
            dask_gufunc_kwargs={"allow_rechunk": True},
            output_dtypes=[float],
            keep_attrs=True,
        )
        mod_ranked = xr.apply_ufunc(
            _rank_wrapper,
            mod,
            input_core_dims=[icd],
            output_core_dims=[icd],
            kwargs={"axis": -1},
            dask="parallelized",
            dask_gufunc_kwargs={"allow_rechunk": True},
            output_dtypes=[float],
            keep_attrs=True,
        )
        return pearsonr(obs_ranked, mod_ranked, axis=dim)
    else:
        obs_ranked = _rank_wrapper(obs, axis=axis)
        mod_ranked = _rank_wrapper(mod, axis=axis)
        return pearsonr(obs_ranked, mod_ranked, axis=axis)

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
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
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
906
907
908
909
910
911
912
913
914
915
916
917
918
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:
            if isinstance(axis, int):
                dim = obs.dims[axis]
            elif isinstance(axis, (list, tuple)):
                dim = [obs.dims[d] if isinstance(d, int) else d for d in axis]
            else:
                dim = axis
        else:
            dim = obs.dims

        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)
        return _update_history(result, "taylor_skill")
    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
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
1992
1993
1994
1995
1996
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
2043
2044
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
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
    """

    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")
        dim = _resolve_axis_to_dim(obs, axis)
        if dim is None:
            dims = list(obs.dims)
        elif isinstance(dim, str):
            dims = [dim]
        else:
            dims = list(dim)

        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,)
    elif isinstance(axis, str):
        # Handle single string axis for consistency with xarray path
        axes = (obs_arr.ndim - 1,)  # Best guess for numpy if only string provided
    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))
    result = dist_sq_np**0.5
    return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
2153
2154
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
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")
        dim = _resolve_axis_to_dim(obs, axis)
        # Using xarray's built-in correlation function
        result = xr.corr(obs, mod, dim=dim)
        return _update_history(result, "CORR_INDEX")
    else:
        # Fallback to numpy-compatible logic
        obs = np.asarray(obs)
        mod = np.asarray(mod)
        if axis is None:
            from scipy.stats import pearsonr

            result = pearsonr(obs.flatten(), mod.flatten())[0]
            return result.item() if hasattr(result, "item") else float(result)
        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))
            result = num / den
            return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
 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
1027
1028
1029
1030
1031
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")
        dim = _resolve_axis_to_dim(obs, 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
        return _update_history(result, "CRMSE")
    else:
        o_ = np.subtract(obs, np.mean(obs, axis=axis, keepdims=True))
        m_ = np.subtract(mod, np.mean(mod, axis=axis, keepdims=True))
        result = (np.ma.abs(m_ - o_) ** 2).mean(axis=axis) ** 0.5
        return result.item() if hasattr(result, "item") and 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 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
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
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")
        dim = _resolve_axis_to_dim(obs, 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)
        return _update_history(result, "IOA")
    else:
        obs_m = np.ma.masked_invalid(obs)
        mod_m = np.ma.masked_invalid(mod)
        obs_mean = np.ma.mean(obs_m, axis=axis, keepdims=True)
        num = np.ma.sum((obs_m - mod_m) ** 2, axis=axis)
        denom = np.ma.sum((np.ma.abs(mod_m - obs_mean) + np.ma.abs(obs_m - obs_mean)) ** 2, axis=axis)
        with np.errstate(divide="ignore", invalid="ignore"):
            result = 1.0 - (num / denom)
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
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")
        dim = _resolve_axis_to_dim(obs, 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
        return _update_history(result, "LOG_ERROR")
    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.item() if hasattr(result, "item") and np.ndim(result) == 0 else 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
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
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")
        dim = _resolve_axis_to_dim(obs, axis)
        result = abs(mod - obs).mean(dim=dim, keep_attrs=True)
        return _update_history(result, "MAE")
    else:
        result = np.ma.abs(np.subtract(mod, obs)).mean(axis=axis)
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
1795
1796
1797
1798
1799
1800
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")
        dim = _resolve_axis_to_dim(obs, 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)
        return _update_history(result, "MAE_norm")
    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
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
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")
        dim = _resolve_axis_to_dim(obs, axis)
        result = (100 * abs(mod - obs) / abs(obs)).mean(dim=dim, keep_attrs=True)
        return _update_history(result, "MAPE")
    else:
        result = (100 * np.ma.abs(np.subtract(mod, obs)) / np.ma.abs(obs)).mean(axis=axis)
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
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
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")
        dim = _resolve_axis_to_dim(obs, 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)
        return _update_history(result, "MAPE_mod")
    else:
        # Add epsilon to avoid division by zero
        obs_safe = np.where(np.abs(obs) < epsilon, epsilon, obs)
        result = (100 * np.abs(np.subtract(mod, obs)) / np.abs(obs_safe)).mean(axis=axis)
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
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")
        dim = _resolve_axis_to_dim(obs, 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:
            # 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
        return _update_history(result, "MASE")
    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)
        result = model_error / naive_error
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
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")
        dim = _resolve_axis_to_dim(obs, 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)
        return _update_history(result, "MASE_mod")
    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
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
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
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)
        result = model_error / naive_error
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
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")
        dim = _resolve_axis_to_dim(obs, axis)
        result = (mod - obs).mean(dim=dim, keep_attrs=True)
        return _update_history(result, "MB")
    else:
        result = np.ma.mean(np.subtract(mod, obs), axis=axis)
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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).

Examples

import numpy as np obs = np.array([1, 2, 3]) mod = np.array([1.1, 2.2, 3.3]) MNB(obs, mod) 10.0

Source code in src/monet_stats/error_metrics.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
135
136
137
138
139
140
141
142
143
144
145
146
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).

    Examples
    --------
    >>> import numpy as np
    >>> obs = np.array([1, 2, 3])
    >>> mod = np.array([1.1, 2.2, 3.3])
    >>> MNB(obs, mod)
    10.0
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        dim = _resolve_axis_to_dim(obs, axis)
        result = ((mod - obs) / obs).mean(dim=dim, keep_attrs=True) * 100.0
        return _update_history(result, "MNB")
    else:
        result = np.ma.masked_invalid((mod - obs) / obs).mean(axis=axis) * 100.0
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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).

Examples

import numpy as np obs = np.array([1, 2, 3]) mod = np.array([1.1, 1.8, 3.3]) MNE(obs, mod) 10.0

Source code in src/monet_stats/error_metrics.py
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
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).

    Examples
    --------
    >>> import numpy as np
    >>> obs = np.array([1, 2, 3])
    >>> mod = np.array([1.1, 1.8, 3.3])
    >>> MNE(obs, mod)
    10.0
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        dim = _resolve_axis_to_dim(obs, axis)
        result = (abs(mod - obs) / obs).mean(dim=dim, keep_attrs=True) * 100.0
        return _update_history(result, "MNE")
    else:
        result = np.ma.masked_invalid(np.ma.abs(mod - obs) / obs).mean(axis=axis) * 100.0
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
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")
        dim = _resolve_axis_to_dim(obs, axis)
        result = (mod - obs).mean(dim=dim, keep_attrs=True)
        return _update_history(result, "MO")
    else:
        result = np.ma.mean(np.ma.masked_invalid(np.subtract(mod, obs)), axis=axis)
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
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):
        dim = _resolve_axis_to_dim(mod, axis)
        result = mod.mean(dim=dim, keep_attrs=True)
        return _update_history(result, "MP")
    else:
        result = np.ma.mean(np.ma.masked_invalid(mod), axis=axis)
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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.error_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/error_metrics.py
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
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.error_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")
        dim = _resolve_axis_to_dim(obs, axis)
        result = ((mod - obs) ** 2).mean(dim=dim, keep_attrs=True)
        return _update_history(result, "MSE")
    else:
        result = np.ma.mean((np.subtract(mod, obs)) ** 2, axis=axis)
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
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")
        dim = _resolve_axis_to_dim(obs, axis)
        if dim is None:
            dim = list(obs.dims)
        diff = mod - obs
        if hasattr(diff.data, "chunks"):
            dims_to_chunk = dim if isinstance(dim, (list, tuple)) else [dim]
            diff = diff.chunk({d: -1 for d in dims_to_chunk if d in diff.dims})
        result = diff.quantile(q=0.5, dim=dim, keep_attrs=True).drop_vars("quantile", errors="ignore")
        return _update_history(result, "MdnB")
    else:
        result = np.ma.median(np.subtract(mod, obs), axis=axis)
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
225
226
227
228
229
230
231
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")
        dim = _resolve_axis_to_dim(obs, axis)
        if dim is None:
            dim = list(obs.dims)
        diff = (mod - obs) / obs
        if hasattr(diff.data, "chunks"):
            dims_to_chunk = dim if isinstance(dim, (list, tuple)) else [dim]
            diff = diff.chunk({d: -1 for d in dims_to_chunk if d in diff.dims})
        result = diff.quantile(q=0.5, dim=dim, keep_attrs=True).drop_vars("quantile", errors="ignore") * 100.0
        return _update_history(result, "MdnNB")
    else:
        result = np.ma.median(np.ma.masked_invalid((mod - obs) / obs), axis=axis) * 100.0
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
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")
        dim = _resolve_axis_to_dim(obs, axis)
        if dim is None:
            dim = list(obs.dims)
        diff = abs(mod - obs) / obs
        if hasattr(diff.data, "chunks"):
            dims_to_chunk = dim if isinstance(dim, (list, tuple)) else [dim]
            diff = diff.chunk({d: -1 for d in dims_to_chunk if d in diff.dims})
        result = diff.quantile(q=0.5, dim=dim, keep_attrs=True).drop_vars("quantile", errors="ignore") * 100.0
        return _update_history(result, "MdnNE")
    else:
        result = np.ma.median(np.ma.masked_invalid(np.ma.abs(mod - obs) / obs), axis=axis) * 100.0
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
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")
        dim = _resolve_axis_to_dim(obs, axis)
        if dim is None:
            dim = list(obs.dims)
        diff = mod - obs
        if hasattr(diff.data, "chunks"):
            dims_to_chunk = dim if isinstance(dim, (list, tuple)) else [dim]
            diff = diff.chunk({d: -1 for d in dims_to_chunk if d in diff.dims})
        result = diff.quantile(q=0.5, dim=dim, keep_attrs=True).drop_vars("quantile", errors="ignore")
        return _update_history(result, "MdnO")
    else:
        result = np.median(np.subtract(mod, obs), axis=axis)
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
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")
        dim = _resolve_axis_to_dim(obs, axis)
        if dim is None:
            dim = list(obs.dims)
        diff = mod - obs
        if hasattr(diff.data, "chunks"):
            dims_to_chunk = dim if isinstance(dim, (list, tuple)) else [dim]
            diff = diff.chunk({d: -1 for d in dims_to_chunk if d in diff.dims})
        result = diff.quantile(q=0.5, dim=dim, keep_attrs=True).drop_vars("quantile", errors="ignore")
        return _update_history(result, "MdnP")
    else:
        result = np.median(np.subtract(mod, obs), axis=axis)
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
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")
        dim = _resolve_axis_to_dim(obs, axis)
        if dim is None:
            dim = list(obs.dims)
        diff_abs = abs(mod - obs)
        if hasattr(diff_abs.data, "chunks"):
            dims_to_chunk = dim if isinstance(dim, (list, tuple)) else [dim]
            diff_abs = diff_abs.chunk({d: -1 for d in dims_to_chunk if d in diff_abs.dims})
        result = diff_abs.quantile(q=0.5, dim=dim, keep_attrs=True).drop_vars("quantile", errors="ignore")
        return _update_history(result, "MedAE")
    else:
        result = np.ma.median(np.ma.abs(np.subtract(mod, obs)), axis=axis)
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
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")
        dim = _resolve_axis_to_dim(obs, 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)
        return _update_history(result, "NMSE")
    else:
        mse = np.ma.mean(np.ma.masked_invalid(np.subtract(mod, obs)) ** 2, axis=axis)
        obs_var = np.ma.var(np.ma.masked_invalid(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
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
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")
        dim = _resolve_axis_to_dim(obs, axis)
        if dim is None:
            dim = list(obs.dims)
        diff = abs(mod - obs)
        if hasattr(diff.data, "chunks"):
            dims_to_chunk = dim if isinstance(dim, (list, tuple)) else [dim]
            diff = diff.chunk({d: -1 for d in dims_to_chunk if d in diff.dims})
        result = (diff.quantile(q=0.5, dim=dim).drop_vars("quantile", errors="ignore") / obs.mean(dim=dim)) * 100.0
        return _update_history(result, "NMdnGE")
    else:
        result = (
            np.ma.masked_invalid(np.ma.median(np.ma.abs(mod - obs), axis=axis) / np.ma.mean(obs, axis=axis)) * 100.0
        )
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
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):
        dim = _resolve_axis_to_dim(obs, axis)
        return obs.count(dim=dim)
    else:
        result = (~np.ma.getmaskarray(obs)).sum(axis=axis)
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
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")
        dim = _resolve_axis_to_dim(obs, axis)
        # To get pairs where BOTH are not NaN:
        mask = obs.notnull() & mod.notnull()
        return mask.sum(dim=dim)
    else:
        obsc, modc = matchmasks(obs, mod)
        result = (~np.ma.getmaskarray(obsc)).sum(axis=axis)
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
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):
        dim = _resolve_axis_to_dim(mod, axis)
        return mod.count(dim=dim)
    else:
        result = (~np.ma.getmaskarray(mod)).sum(axis=axis)
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
1180
1181
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")
        dim = _resolve_axis_to_dim(obs, 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)
        return _update_history(result, "NRMSE")
    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
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
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")
        dim = _resolve_axis_to_dim(obs, 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)
        return _update_history(result, "NSC")
    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)
        result = 1.0 - (numerator / denominator)
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
1446
1447
1448
1449
1450
1451
1452
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")
        dim = _resolve_axis_to_dim(obs, axis)
        result = mod.std(dim=dim) / obs.std(dim=dim)
        return _update_history(result, "NSE_alpha")
    else:
        result = np.std(mod, axis=axis) / np.std(obs, axis=axis)
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
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")
        dim = _resolve_axis_to_dim(obs, axis)
        result = mod.mean(dim=dim) / obs.mean(dim=dim)
        return _update_history(result, "NSE_beta")
    else:
        result = np.mean(mod, axis=axis) / np.mean(obs, axis=axis)
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
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")
        dim = _resolve_axis_to_dim(obs, axis)
        result = np.sqrt(((obs - mod) ** 2).mean(dim=dim, keep_attrs=True))
        return _update_history(result, "RM")
    else:
        result = np.sqrt(np.mean((np.subtract(obs, mod)) ** 2, axis=axis))
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
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")
        dim = _resolve_axis_to_dim(obs, axis)
        result = ((mod - obs) ** 2).mean(dim=dim, keep_attrs=True) ** 0.5
        return _update_history(result, "RMSE")
    else:
        result = np.ma.sqrt(np.ma.mean((np.subtract(mod, obs)) ** 2, axis=axis))
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
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")
        dim = _resolve_axis_to_dim(obs, 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)
        return _update_history(result, "RMSE_norm")
    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
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
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")
        dim = _resolve_axis_to_dim(obs, axis)
        result = (100 * ((mod - obs) / obs) ** 2).mean(dim=dim, keep_attrs=True) ** 0.5
        return _update_history(result, "RMSPE")
    else:
        result = 100 * np.ma.sqrt(np.ma.mean(((mod - obs) / obs) ** 2, axis=axis))
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
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")
        dim = _resolve_axis_to_dim(obs, axis)
        if dim is None:
            dim = list(obs.dims)
        diff_sq = (obs - mod) ** 2
        if hasattr(diff_sq.data, "chunks"):
            dims_to_chunk = dim if isinstance(dim, (list, tuple)) else [dim]
            diff_sq = diff_sq.chunk({d: -1 for d in dims_to_chunk if d in diff_sq.dims})
        result = np.sqrt(diff_sq.quantile(q=0.5, dim=dim, keep_attrs=True).drop_vars("quantile", errors="ignore"))
        return _update_history(result, "RMdn")
    else:
        squared_errors = (np.subtract(obs, mod)) ** 2
        result = np.sqrt(np.median(squared_errors, axis=axis))
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
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
        dim = _resolve_axis_to_dim(obs, axis)
        result = errors.std(dim=dim, keep_attrs=True)
        return _update_history(result, "STDO")

    # Fallback to numpy-compatible logic
    errors = np.subtract(obs, mod)
    result = np.ma.std(np.ma.masked_invalid(errors), axis=axis)
    return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
 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
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
        dim = _resolve_axis_to_dim(obs, axis)
        result = errors.std(dim=dim, keep_attrs=True)
        return _update_history(result, "STDP")

    # Fallback to numpy-compatible logic
    errors = np.subtract(mod, obs)
    result = np.ma.std(np.ma.masked_invalid(errors), axis=axis)
    return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
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")
        dim = _resolve_axis_to_dim(obs, axis)
        obs_sum = obs.sum(dim=dim)
        mod_sum = mod.sum(dim=dim)
        result = abs(mod_sum - obs_sum) / abs(obs_sum)
        return _update_history(result, "VOLUMETRIC_ERROR")
    else:
        obs_sum = np.sum(obs, axis=axis)
        mod_sum = np.sum(mod, axis=axis)
        result = np.abs(mod_sum - obs_sum) / np.abs(obs_sum)
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

WDMB(obs, mod, axis=None)

Wind Direction Mean Bias (WDMB).

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
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
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).

    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")
        dim = _resolve_axis_to_dim(obs, axis)
        result = circlebias(mod - obs).mean(dim=dim, keep_attrs=True)
        return _update_history(result, "WDMB")
    else:
        result = np.ma.mean(circlebias(np.subtract(mod, obs)), axis=axis)
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
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")
        dim = _resolve_axis_to_dim(obs, axis)
        if dim is None:
            dim = list(obs.dims)
        diff = circlebias(mod - obs)
        if hasattr(diff.data, "chunks"):
            dims_to_chunk = dim if isinstance(dim, (list, tuple)) else [dim]
            diff = diff.chunk({d: -1 for d in dims_to_chunk if d in diff.dims})
        result = diff.quantile(q=0.5, dim=dim, keep_attrs=True).drop_vars("quantile", errors="ignore")
        return _update_history(result, "WDMdnB")
    else:
        result = np.ma.median(circlebias(np.subtract(mod, obs)), axis=axis)
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
1840
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")
        dim = _resolve_axis_to_dim(obs, 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))
        return _update_history(result, "bias_fraction")
    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
1082
1083
1084
1085
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
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")
        dim = _resolve_axis_to_dim(obs, axis)
        result = (200 * abs(mod - obs) / (abs(mod) + abs(obs))).mean(dim=dim, keep_attrs=True)
        return _update_history(result, "sMAPE")
    else:
        result = (200 * np.ma.abs(np.subtract(mod, obs)) / (np.ma.abs(mod) + np.ma.abs(obs))).mean(axis=axis)
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

Efficiency Metrics

Efficiency Metrics for Model Evaluation (Aero Protocol Compliant).

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
 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
 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
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:
            if isinstance(axis, int):
                dim = obs.dims[axis]
            elif isinstance(axis, (list, tuple)):
                dim = [obs.dims[d] if isinstance(d, int) else d for d in axis]
            else:
                dim = axis
        else:
            dim = obs.dims

        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
        return _update_history(result, "KGE")
    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

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
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
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")
        dim = _resolve_axis_to_dim(obs, axis)
        result = abs(mod - obs).mean(dim=dim, keep_attrs=True)
        return _update_history(result, "MAE")
    else:
        result = np.ma.abs(np.subtract(mod, obs)).mean(axis=axis)
        return result.item() if hasattr(result, "item") and 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
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
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")
        dim = _resolve_axis_to_dim(obs, axis)
        result = (100 * abs(mod - obs) / abs(obs)).mean(dim=dim, keep_attrs=True)
        return _update_history(result, "MAPE")
    else:
        result = (100 * np.ma.abs(np.subtract(mod, obs)) / np.ma.abs(obs)).mean(axis=axis)
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
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")
        dim = _resolve_axis_to_dim(obs, 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:
            # 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
        return _update_history(result, "MASE")
    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)
        result = model_error / naive_error
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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.error_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/error_metrics.py
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
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.error_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")
        dim = _resolve_axis_to_dim(obs, axis)
        result = ((mod - obs) ** 2).mean(dim=dim, keep_attrs=True)
        return _update_history(result, "MSE")
    else:
        result = np.ma.mean((np.subtract(mod, obs)) ** 2, axis=axis)
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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.992

Source code in src/monet_stats/efficiency_metrics.py
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
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.992
    """
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        dim = _resolve_axis_to_dim(obs, 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)

        return _update_history(result, "NSE")
    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).

Calculates NSE on logarithmic-transformed data to focus on lower values.

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
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
161
162
163
164
165
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).

    Calculates NSE on logarithmic-transformed data to focus on lower values.

    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
    # Avoid double history update by using .data or being careful
    # We apply log first, then call NSE. NSE will handle history if it's a DataArray.
    obs_log = np.log(obs + epsilon)
    mod_log = np.log(mod + epsilon)
    result = NSE(obs_log, mod_log, axis=axis)

    # If it's a DataArray, NSE already updated history to "NSE".
    # We might want to "fix" it to "NSElog".
    if isinstance(result, xr.DataArray):
        # Update history specifically for NSElog
        return _update_history(result, "NSElog")
    return result

NSEm(obs, mod, axis=None)

Nash-Sutcliffe Efficiency (NSE) - robust to masked arrays.

This function is a wrapper for NSE that explicitly handles masked data and NaNs.

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.995

Source code in src/monet_stats/efficiency_metrics.py
 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
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.

    This function is a wrapper for NSE that explicitly handles masked data and NaNs.

    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.995
    """
    # Standard NSE implementation already handles NaNs if using nan-aware functions
    res = NSE(obs, mod, axis=axis)
    if isinstance(res, xr.DataArray):
        return _update_history(res, "NSEm")
    return res

PC(obs, mod, axis=None, tolerance=0.1)

Percent of Correct (PC).

Calculates the percentage of model predictions that are within a specified tolerance of 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 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
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
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).

    Calculates the percentage of model predictions that are within a specified
    tolerance of 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 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")
        dim = _resolve_axis_to_dim(obs, axis)

        tol = tolerance * abs(obs)
        correct = abs(obs - mod) <= tol
        result = (correct.sum(dim=dim) / correct.count(dim=dim)) * 100.0

        return _update_history(result, "PC")
    else:
        obs = np.asanyarray(obs)
        mod = np.asanyarray(mod)
        mask = np.isnan(obs) | np.isnan(mod)

        tol = tolerance * np.abs(obs)
        correct = np.abs(obs - mod) <= tol

        total = np.sum(~mask, axis=axis)
        correct_sum = np.sum(correct & ~mask, axis=axis)

        with np.errstate(divide="ignore", invalid="ignore"):
            result = (correct_sum / total) * 100.0
            result = np.where(total == 0, np.nan, result)

        return result.item() if np.ndim(result) == 0 else result

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
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
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")
        dim = _resolve_axis_to_dim(obs, axis)

        obs_mean = obs.mean(dim=dim)
        numerator = abs(obs - mod).sum(dim=dim)
        denominator = 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)

        return _update_history(result, "mNSE")
    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 magnitude of observed values. Formula: 1 - [ sum( ((obs - mod)/obs)^2 ) / sum( ((obs - mean)/obs)^2 ) ]

Parameters

obs : numpy.ndarray or xarray.DataArray Observed values (should be non-zero for normalization). 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.994261721483555

Source code in src/monet_stats/efficiency_metrics.py
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
225
226
227
228
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 magnitude of observed values.
    Formula: 1 - [ sum( ((obs - mod)/obs)^2 ) / sum( ((obs - mean)/obs)^2 ) ]

    Parameters
    ----------
    obs : numpy.ndarray or xarray.DataArray
        Observed values (should be non-zero for normalization).
    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.994261721483555
    """
    epsilon = 1e-8
    if isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray):
        obs, mod = xr.align(obs, mod, join="inner")
        dim = _resolve_axis_to_dim(obs, axis)

        obs_mean = obs.mean(dim=dim)
        obs_safe = xr.where(abs(obs) < epsilon, epsilon, obs)

        numerator = (((obs - mod) / obs_safe) ** 2).sum(dim=dim)
        denominator = (((obs - obs_mean) / obs_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)

        return _update_history(result, "rNSE")
    else:
        obs_mean = np.nanmean(obs, axis=axis, keepdims=True)
        obs_safe = np.where(np.abs(obs) < epsilon, epsilon, obs)

        with np.errstate(divide="ignore", invalid="ignore"):
            numerator = np.nansum(((obs - mod) / obs_safe) ** 2, axis=axis)
            denominator = np.nansum(((obs - obs_mean) / obs_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
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
def FB(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str, Iterable[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 = _resolve_axis_to_dim(obs, 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)
        res = (np.ma.masked_invalid((mod_arr - obs_arr) / (mod_arr + obs_arr)).mean(axis=axis) * 2.0) * 100.0
        return res.item() if np.ndim(res) == 0 else res

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
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
def FE(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str, Iterable[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 = _resolve_axis_to_dim(obs, 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)
        res = (np.ma.mean(np.ma.abs(mod_arr - obs_arr) / (mod_arr + obs_arr), axis=axis)) * 2.0 * 100.0
        return res.item() if np.ndim(res) == 0 else res

ME(obs, mod, axis=None)

Mean Gross Error (model and obs unit). Alias for MAE.

Source code in src/monet_stats/relative_metrics.py
286
287
288
289
290
291
292
293
294
295
296
297
def ME(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Mean Gross Error (model and obs unit). Alias for MAE.
    """
    res = MAE(obs, mod, axis=axis)
    if isinstance(res, (xr.DataArray, xr.Dataset)):
        return _update_history(res, "Mean Gross Error (ME)")
    return res

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
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
830
831
832
833
834
835
836
837
838
def MNPB(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    paxis: Union[int, str, Iterable[Union[int, str]]],
    axis: Optional[Union[int, str, Iterable[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 = _resolve_axis_to_dim(obs, paxis)
        _intermediate = (mod.max(dim=pdim) - obs.max(dim=pdim)) / obs.max(dim=pdim)
        mdim = _resolve_axis_to_dim(_intermediate, axis)
        res = _intermediate.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)
        res = ((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
        return res.item() if np.ndim(res) == 0 else res

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
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
def MNPE(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    paxis: Union[int, str, Iterable[Union[int, str]]],
    axis: Optional[Union[int, str, Iterable[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 = _resolve_axis_to_dim(obs, paxis)
        _intermediate = abs(mod.max(dim=pdim) - obs.max(dim=pdim)) / obs.max(dim=pdim)
        mdim = _resolve_axis_to_dim(_intermediate, axis)
        res = _intermediate.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)
        res = (
            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
        return res.item() if np.ndim(res) == 0 else res

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
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
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
def MPE(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str, Iterable[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 = _resolve_axis_to_dim(obs, 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)
        res = (
            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
        return res.item() if np.ndim(res) == 0 else res

MdnE(obs, mod, axis=None)

Median Gross Error (model and obs unit). Alias for MedAE.

Source code in src/monet_stats/relative_metrics.py
300
301
302
303
304
305
306
307
308
309
310
311
def MdnE(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str, Iterable[Union[int, str]]]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Median Gross Error (model and obs unit). Alias for MedAE.
    """
    res = MedAE(obs, mod, axis=axis)
    if isinstance(res, (xr.DataArray, xr.Dataset)):
        return _update_history(res, "Median Gross Error (MdnE)")
    return res

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
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
def MdnNPB(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    paxis: Union[int, str, Iterable[Union[int, str]]],
    axis: Optional[Union[int, str, Iterable[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 = _resolve_axis_to_dim(obs, paxis)
        _intermediate = (mod.max(dim=pdim) - obs.max(dim=pdim)) / obs.max(dim=pdim)
        mdim = _resolve_axis_to_dim(_intermediate, axis)
        if mdim is None:
            mdim = list(_intermediate.dims)
        if hasattr(_intermediate.data, "chunks"):
            dims_to_chunk = [mdim] if isinstance(mdim, str) else list(mdim)
            _intermediate = _intermediate.chunk({d: -1 for d in dims_to_chunk})
        res = _intermediate.quantile(q=0.5, dim=mdim).drop_vars("quantile", errors="ignore") * 100.0
        return _update_history(res, "Median Normalized Peak Bias (MdnNPB)")
    else:
        obs_arr = np.ma.asanyarray(obs)
        mod_arr = np.ma.asanyarray(mod)
        result = (
            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
        )
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
 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
 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
def MdnNPE(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    paxis: Union[int, str, Iterable[Union[int, str]]],
    axis: Optional[Union[int, str, Iterable[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 = _resolve_axis_to_dim(obs, paxis)
        _intermediate = abs(mod.max(dim=pdim) - obs.max(dim=pdim)) / obs.max(dim=pdim)
        mdim = _resolve_axis_to_dim(_intermediate, axis)
        if mdim is None:
            mdim = list(_intermediate.dims)
        if hasattr(_intermediate.data, "chunks"):
            _intermediate = _intermediate.chunk({d: -1 for d in (mdim if isinstance(mdim, list) else [mdim])})
        res = _intermediate.quantile(q=0.5, dim=mdim).drop_vars("quantile", errors="ignore") * 100.0
        return _update_history(res, "Median Normalized Peak Error (MdnNPE)")
    else:
        obs_arr = np.ma.asanyarray(obs)
        mod_arr = np.ma.asanyarray(mod)
        result = (
            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
        )
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
def MdnPE(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str, Iterable[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 = _resolve_axis_to_dim(obs, axis)
        _intermediate = abs(mod.max(dim=dim) - obs.max(dim=dim)) / obs.max(dim=dim)
        mdim = list(_intermediate.dims)
        if hasattr(_intermediate.data, "chunks"):
            _intermediate = _intermediate.chunk({d: -1 for d in mdim})
        res = _intermediate.quantile(q=0.5, dim=mdim).drop_vars("quantile", errors="ignore") * 100.0
        return _update_history(res, "Median Peak Error (MdnPE)")
    else:
        obs_arr = np.ma.asanyarray(obs)
        mod_arr = np.ma.asanyarray(mod)
        result = (
            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
        )
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
def NMB(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str, Iterable[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")
        dim = _resolve_axis_to_dim(obs, 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)
        res = (mod_arr - obs_arr).sum(axis=axis) / obs_arr.sum(axis=axis) * 100.0
        return res.item() if np.ndim(res) == 0 else res

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
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
def NMB_ABS(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str, Iterable[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 = _resolve_axis_to_dim(obs, 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)
        res = (mod_arr - obs_arr).sum(axis=axis) / np.abs(obs_arr.sum(axis=axis)) * 100.0
        return res.item() if np.ndim(res) == 0 else res

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
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
600
601
602
603
def NME(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str, Iterable[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 = _resolve_axis_to_dim(obs, 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)
        res = (np.ma.abs(mod_arr - obs_arr).sum(axis=axis) / obs_arr.sum(axis=axis)) * 100
        return res.item() if np.ndim(res) == 0 else res

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
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
def NME_m(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str, Iterable[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 = _resolve_axis_to_dim(obs, 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)
        res = (np.abs(mod_arr - obs_arr).sum(axis=axis) / obs_arr.sum(axis=axis)) * 100
        return res.item() if np.ndim(res) == 0 else res

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
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
552
553
554
555
556
def NME_m_ABS(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str, Iterable[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 = _resolve_axis_to_dim(obs, 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)
        res = (np.abs(mod_arr - obs_arr).sum(axis=axis) / np.abs(obs_arr.sum(axis=axis))) * 100
        return res.item() if np.ndim(res) == 0 else res

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
1012
1013
1014
1015
1016
1017
1018
1019
1020
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
def NMPB(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    paxis: Union[int, str, Iterable[Union[int, str]]],
    axis: Optional[Union[int, str, Iterable[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 = _resolve_axis_to_dim(obs, paxis)
        _diff_mean = (mod.max(dim=pdim) - obs.max(dim=pdim)).mean(dim=_resolve_axis_to_dim(mod.max(dim=pdim), axis))
        _obs_mean = obs.max(dim=pdim).mean(dim=_resolve_axis_to_dim(obs.max(dim=pdim), axis))
        res = (_diff_mean / _obs_mean) * 100.0
        return _update_history(res, "Normalized Mean Peak Bias (NMPB)")
    else:
        obs_arr = np.ma.asanyarray(obs)
        mod_arr = np.ma.asanyarray(mod)
        res = (
            (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
        return res.item() if np.ndim(res) == 0 else res

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
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
1180
1181
1182
1183
1184
1185
1186
1187
def NMPE(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    paxis: Union[int, str, Iterable[Union[int, str]]],
    axis: Optional[Union[int, str, Iterable[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 = _resolve_axis_to_dim(obs, paxis)
        _diff_abs_mean = abs(mod.max(dim=pdim) - obs.max(dim=pdim)).mean(
            dim=_resolve_axis_to_dim(mod.max(dim=pdim), axis)
        )
        _obs_mean = obs.max(dim=pdim).mean(dim=_resolve_axis_to_dim(obs.max(dim=pdim), axis))
        res = (_diff_abs_mean / _obs_mean) * 100.0
        return _update_history(res, "Normalized Mean Peak Error (NMPE)")
    else:
        obs_arr = np.ma.asanyarray(obs)
        mod_arr = np.ma.asanyarray(mod)
        res = (
            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
        return res.item() if np.ndim(res) == 0 else res

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
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
def NMdnB(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str, Iterable[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 = _resolve_axis_to_dim(obs, axis)
        if dim is None:
            dim = list(obs.dims)
        diff = mod - obs
        if hasattr(diff.data, "chunks"):
            dims_to_chunk = [dim] if isinstance(dim, str) else list(dim)
            diff = diff.chunk({d: -1 for d in dims_to_chunk})
            obs = obs.chunk({d: -1 for d in dims_to_chunk})
        res = (
            diff.quantile(q=0.5, dim=dim).drop_vars("quantile", errors="ignore")
            / obs.quantile(q=0.5, dim=dim).drop_vars("quantile", errors="ignore")
            * 100.0
        )
        return _update_history(res, "Normalized Median Bias (NMdnB)")
    else:
        obs_arr = np.ma.asanyarray(obs)
        mod_arr = np.ma.asanyarray(mod)
        result = np.ma.median(mod_arr - obs_arr, axis=axis) / np.ma.median(obs_arr, axis=axis) * 100.0
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
def NMdnE(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str, Iterable[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 = _resolve_axis_to_dim(obs, axis)
        if dim is None:
            dim = list(obs.dims)
        diff_abs = abs(mod - obs)
        if hasattr(diff_abs.data, "chunks"):
            dims_to_chunk = [dim] if isinstance(dim, str) else list(dim)
            diff_abs = diff_abs.chunk({d: -1 for d in dims_to_chunk})
            obs = obs.chunk({d: -1 for d in dims_to_chunk})
        res = (
            diff_abs.quantile(q=0.5, dim=dim).drop_vars("quantile", errors="ignore")
            / obs.quantile(q=0.5, dim=dim).drop_vars("quantile", errors="ignore")
            * 100
        )
        return _update_history(res, "Normalized Median Error (NMdnE)")
    else:
        obs_arr = np.ma.asanyarray(obs)
        mod_arr = np.ma.asanyarray(mod)
        result = np.ma.median(np.ma.abs(mod_arr - obs_arr), axis=axis) / np.ma.median(obs_arr, axis=axis) * 100
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
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
def NMdnPB(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    paxis: Union[int, str, Iterable[Union[int, str]]],
    axis: Optional[Union[int, str, Iterable[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 = _resolve_axis_to_dim(obs, paxis)
        _diff = mod.max(dim=pdim) - obs.max(dim=pdim)
        _obs_max = obs.max(dim=pdim)
        mdim = _resolve_axis_to_dim(_diff, axis)
        if mdim is None:
            mdim = list(_diff.dims)
        if hasattr(_diff.data, "chunks"):
            dims_to_chunk = [mdim] if isinstance(mdim, str) else list(mdim)
            _diff = _diff.chunk({d: -1 for d in dims_to_chunk})
            _obs_max = _obs_max.chunk({d: -1 for d in dims_to_chunk})
        res = (
            _diff.quantile(q=0.5, dim=mdim).drop_vars("quantile", errors="ignore")
            / _obs_max.quantile(q=0.5, dim=mdim).drop_vars("quantile", errors="ignore")
            * 100.0
        )
        return _update_history(res, "Normalized Median Peak Bias (NMdnPB)")
    else:
        obs_arr = np.ma.asanyarray(obs)
        mod_arr = np.ma.asanyarray(mod)
        result = (
            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
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
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
def NMdnPE(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    paxis: Union[int, str, Iterable[Union[int, str]]],
    axis: Optional[Union[int, str, Iterable[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 = _resolve_axis_to_dim(obs, paxis)
        _diff_abs = abs(mod.max(dim=pdim) - obs.max(dim=pdim))
        _obs_max = obs.max(dim=pdim)
        mdim = _resolve_axis_to_dim(_diff_abs, axis)
        if mdim is None:
            mdim = list(_diff_abs.dims)
        if hasattr(_diff_abs.data, "chunks"):
            dims_to_chunk = [mdim] if isinstance(mdim, str) else list(mdim)
            _diff_abs = _diff_abs.chunk({d: -1 for d in dims_to_chunk})
            _obs_max = _obs_max.chunk({d: -1 for d in dims_to_chunk})
        res = (
            _diff_abs.quantile(q=0.5, dim=mdim).drop_vars("quantile", errors="ignore")
            / _obs_max.quantile(q=0.5, dim=mdim).drop_vars("quantile", errors="ignore")
            * 100.0
        )
        return _update_history(res, "Normalized Median Peak Error (NMdnPE)")
    else:
        obs_arr = np.ma.asanyarray(obs)
        mod_arr = np.ma.asanyarray(mod)
        result = (
            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
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
def PSUTMNPB(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str, Iterable[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
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
def PSUTMNPE(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str, Iterable[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
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
def PSUTMdnNPB(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str, Iterable[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
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
def PSUTMdnNPE(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str, Iterable[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
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
def PSUTNMPB(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str, Iterable[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
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
def PSUTNMPE(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str, Iterable[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
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
def PSUTNMdnPB(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str, Iterable[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
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
def PSUTNMdnPE(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str, Iterable[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
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
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
def USUTPB(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str, Iterable[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 = _resolve_axis_to_dim(obs, 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)
        res = ((np.ma.max(mod_arr, axis=axis) - np.ma.max(obs_arr, axis=axis)) / np.ma.max(obs_arr, axis=axis)) * 100.0
        return res.item() if np.ndim(res) == 0 else res

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
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
def USUTPE(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str, Iterable[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 = _resolve_axis_to_dim(obs, 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)
        res = (
            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
        return res.item() if np.ndim(res) == 0 else res

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
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
397
398
399
400
401
402
403
404
405
406
def WDME(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str, Iterable[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 = _resolve_axis_to_dim(obs, 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)
        res = np.ma.mean(np.ma.abs(circlebias(mod_arr - obs_arr)), axis=axis)
        return res.item() if np.ndim(res) == 0 else res

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
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
def WDME_m(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str, Iterable[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 = _resolve_axis_to_dim(obs, 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)
        res = np.abs(circlebias_m(mod_arr - obs_arr)).mean(axis=axis)
        return res.item() if np.ndim(res) == 0 else res

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
409
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
def WDMdnE(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str, Iterable[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 = _resolve_axis_to_dim(obs, axis)
        if dim is None:
            dim = list(obs.dims)
        cb = abs(circlebias(mod - obs))
        if hasattr(cb.data, "chunks"):
            dims_to_chunk = [dim] if isinstance(dim, str) else list(dim)
            cb = cb.chunk({d: -1 for d in dims_to_chunk})
        res = cb.quantile(q=0.5, dim=dim).drop_vars("quantile", errors="ignore")
        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)
        result = np.ma.median(np.ma.abs(cb), axis=axis)
        return result.item() if hasattr(result, "item") and np.ndim(result) == 0 else result

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
 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
def WDNMB_m(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    axis: Optional[Union[int, str, Iterable[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 = _resolve_axis_to_dim(obs, 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
        res = circlebias_m(diff).sum(axis=axis) / obs_arr.sum(axis=axis) * 100.0
        return res.item() if np.ndim(res) == 0 else res

Spatial & Ensemble Metrics

Spatial and Ensemble Metrics for Atmospheric Sciences (Aero Protocol Compliant)

BSS(obs, mod, threshold, dim=None, axis=None)

Brier Skill Score (BSS) for probabilistic forecasts (Aero Protocol).

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. dim : str or iterable of str, optional Dimension(s) along which to compute the score (xarray only). axis : int or iterable of int, optional Axis or axes along which to compute the score (numpy only).

Returns

xarray.DataArray, numpy.ndarray, or float Brier Skill Score.

Source code in src/monet_stats/spatial_ensemble_metrics.py
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
290
291
292
293
294
295
296
297
298
299
300
301
def BSS(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    threshold: float,
    dim: Optional[Union[str, Iterable[str]]] = None,
    axis: Optional[Union[int, Iterable[int]]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Brier Skill Score (BSS) for probabilistic forecasts (Aero Protocol).

    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.
    dim : str or iterable of str, optional
        Dimension(s) along which to compute the score (xarray only).
    axis : int or iterable of int, optional
        Axis or axes along which to compute the score (numpy only).

    Returns
    -------
    xarray.DataArray, 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(dim=dim)
        obs_clim = o_bin.mean(dim=dim)
        bs_ref = ((obs_clim - o_bin) ** 2).mean(dim=dim)

        res = xr.where(bs_ref != 0, 1.0 - (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.nanmean((m_prob - o_bin) ** 2, axis=axis)
    obs_clim = np.nanmean(o_bin, axis=axis)
    if axis is not None:
        # Keep dimensions for subtraction
        obs_clim_kd = np.nanmean(o_bin, axis=axis, keepdims=True)
    else:
        obs_clim_kd = obs_clim

    bs_ref = np.nanmean((obs_clim_kd - o_bin) ** 2, axis=axis)

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

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
 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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
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, dim=None, axis=None)

Extreme Dependency Score (EDS) for rare event detection (Aero Protocol).

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. dim : str or iterable of str, optional Dimension(s) along which to compute the score (xarray only). If None, reduces over all dimensions. axis : int or iterable of int, optional Axis or axes along which to compute the score (numpy only).

Returns

xarray.DataArray, 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
def EDS(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    threshold: float,
    dim: Optional[Union[str, Iterable[str]]] = None,
    axis: Optional[Union[int, Iterable[int]]] = None,
) -> Union[xr.DataArray, np.ndarray, float]:
    """
    Extreme Dependency Score (EDS) for rare event detection (Aero Protocol).

    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.
    dim : str or iterable of str, optional
        Dimension(s) along which to compute the score (xarray only).
        If None, reduces over all dimensions.
    axis : int or iterable of int, optional
        Axis or axes along which to compute the score (numpy only).

    Returns
    -------
    xarray.DataArray, 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

        mask = obs.notnull() & mod.notnull()
        obs_bin = obs_bin & mask
        mod_bin = mod_bin & mask

        hits = (obs_bin & mod_bin).sum(dim=dim)
        n_obs = obs_bin.sum(dim=dim)
        n_mod = mod_bin.sum(dim=dim)
        n = mask.sum(dim=dim)

        # EDS = log(hits/n) / log(n_obs*n_mod / n^2)
        # Avoid log(0) and division by zero
        # p = n_obs / n, q = n_mod / n
        with np.errstate(divide="ignore", invalid="ignore"):
            eds = xr.where(
                (hits > 0) & (n_obs > 0) & (n_mod > 0), np.log(hits / n) / np.log((n_obs / n) * (n_mod / n)), np.nan
            )

        return _update_history(eds, "Extreme Dependency Score (EDS)")

    # NumPy path
    obs_arr = np.asarray(obs)
    mod_arr = np.asarray(mod)
    mask = ~np.isnan(obs_arr) & ~np.isnan(mod_arr)

    obs_bin = (obs_arr >= threshold) & mask
    mod_bin = (mod_arr >= threshold) & mask

    hits = np.sum(obs_bin & mod_bin, axis=axis)
    n_obs = np.sum(obs_bin, axis=axis)
    n_mod = np.sum(mod_bin, axis=axis)
    n = np.sum(mask, axis=axis)

    with np.errstate(divide="ignore", invalid="ignore"):
        res = np.where(
            (hits > 0) & (n_obs > 0) & (n_mod > 0), np.log(hits / n) / np.log((n_obs / n) * (n_mod / n)), np.nan
        )
        return res.item() if np.ndim(res) == 0 else res

SAL(obs, mod, threshold=None, lat_dim='lat', lon_dim='lon')

Structure-Amplitude-Location (SAL) score for spatial verification (Aero Protocol).

This implementation is vectorized over non-spatial dimensions using xarray.apply_ufunc and supports lazy evaluation for dimensions other than the spatial ones.

Parameters

obs : xarray.DataArray or numpy.ndarray Observed field. Should be 2D (lat, lon) or multi-dimensional. mod : xarray.DataArray or numpy.ndarray Model field. threshold : float, optional Threshold for object identification. If None, uses mean of observations per slice (Lazy-friendly). lat_dim : str, optional Name of the latitude dimension. Default is 'lat'. lon_dim : str, optional Name of the longitude dimension. Default is 'lon'.

Returns

S, A, L : xarray.DataArray, numpy.ndarray, or float Structure, Amplitude, and Location components.

Examples

import xarray as xr import numpy as np obs = xr.DataArray(np.random.rand(10, 10, 10), dims=['time', 'lat', 'lon']) mod = xr.DataArray(np.random.rand(10, 10, 10), dims=['time', 'lat', 'lon']) S, A, L = SAL(obs, mod)

Source code in src/monet_stats/spatial_ensemble_metrics.py
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
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
def SAL(
    obs: Union[xr.DataArray, np.ndarray],
    mod: Union[xr.DataArray, np.ndarray],
    threshold: Optional[float] = None,
    lat_dim: str = "lat",
    lon_dim: str = "lon",
) -> Union[
    Tuple[xr.DataArray, xr.DataArray, xr.DataArray],
    Tuple[np.ndarray, np.ndarray, np.ndarray],
    Tuple[float, float, float],
]:
    """
    Structure-Amplitude-Location (SAL) score for spatial verification (Aero Protocol).

    This implementation is vectorized over non-spatial dimensions using `xarray.apply_ufunc`
    and supports lazy evaluation for dimensions other than the spatial ones.

    Parameters
    ----------
    obs : xarray.DataArray or numpy.ndarray
        Observed field. Should be 2D (lat, lon) or multi-dimensional.
    mod : xarray.DataArray or numpy.ndarray
        Model field.
    threshold : float, optional
        Threshold for object identification. If None, uses mean of observations
        per slice (Lazy-friendly).
    lat_dim : str, optional
        Name of the latitude dimension. Default is 'lat'.
    lon_dim : str, optional
        Name of the longitude dimension. Default is 'lon'.

    Returns
    -------
    S, A, L : xarray.DataArray, numpy.ndarray, or float
        Structure, Amplitude, and Location components.

    Examples
    --------
    >>> import xarray as xr
    >>> import numpy as np
    >>> obs = xr.DataArray(np.random.rand(10, 10, 10), dims=['time', 'lat', 'lon'])
    >>> mod = xr.DataArray(np.random.rand(10, 10, 10), dims=['time', 'lat', 'lon'])
    >>> S, A, L = SAL(obs, mod)
    """
    is_xr = isinstance(obs, xr.DataArray) and isinstance(mod, xr.DataArray)

    if is_xr:
        obs, mod = xr.align(obs, mod, join="inner")
        # Determine spatial dimensions
        if lat_dim not in obs.dims or lon_dim not in obs.dims:
            # Fallback to last two dimensions if lat/lon not found
            spatial_dims = [obs.dims[-2], obs.dims[-1]]
        else:
            spatial_dims = [lat_dim, lon_dim]
    else:
        # For numpy, assume last two dimensions are spatial
        spatial_dims = [-2, -1]

    def _sal_wrapper(o: np.ndarray, m: np.ndarray, t: Optional[float]) -> Tuple[float, float, float]:
        """
        Wrapper for _sal_numpy to be used with xarray.apply_ufunc.

        Parameters
        ----------
        o : numpy.ndarray
            Observed field slice.
        m : numpy.ndarray
            Model field slice.
        t : float, optional
            Threshold.

        Returns
        -------
        Tuple[float, float, float]
            S, A, L components.

        Examples
        --------
        >>> import numpy as np
        >>> o = np.random.rand(10, 10)
        >>> m = np.random.rand(10, 10)
        >>> _sal_wrapper(o, m, 0.5)
        """
        return _sal_numpy(o, m, t)

    res_s, res_a, res_l = xr.apply_ufunc(
        _sal_wrapper,
        obs,
        mod,
        threshold,
        input_core_dims=[spatial_dims, spatial_dims, []],
        output_core_dims=[[], [], []],
        vectorize=True,
        dask="parallelized",
        output_dtypes=[float, float, float],
    )

    if is_xr:
        res_s = _update_history(res_s, "SAL: Structure component")
        res_a = _update_history(res_a, "SAL: Amplitude component")
        res_l = _update_history(res_l, "SAL: Location component")

    return res_s, res_a, res_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
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 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
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
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
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
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
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, dim=None, reduce_axis=None)

Spread-Error Relationship for ensemble forecasts (Aero Protocol).

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. dim : str or iterable of str, optional Dimension(s) along which to compute the mean spread and error (xarray only). If None, reduces over all dimensions. reduce_axis : int or iterable of int, optional Axis or axes along which to compute the mean spread and error (numpy only).

Returns

mean_spread : float, numpy.ndarray, or xarray.DataArray Mean ensemble spread. mean_error : float, numpy.ndarray, or xarray.DataArray Mean absolute error of ensemble mean vs. obs.

Source code in src/monet_stats/spatial_ensemble_metrics.py
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
225
226
227
228
229
230
231
232
233
234
235
def spread_error(
    ensemble: Union[xr.DataArray, np.ndarray],
    obs: Union[xr.DataArray, np.ndarray],
    axis: Union[int, str] = 0,
    dim: Optional[Union[str, Iterable[str]]] = None,
    reduce_axis: Optional[Union[int, Iterable[int]]] = None,
) -> Tuple[Any, Any]:
    """
    Spread-Error Relationship for ensemble forecasts (Aero Protocol).

    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.
    dim : str or iterable of str, optional
        Dimension(s) along which to compute the mean spread and error (xarray only).
        If None, reduces over all dimensions.
    reduce_axis : int or iterable of int, optional
        Axis or axes along which to compute the mean spread and error (numpy only).

    Returns
    -------
    mean_spread : float, numpy.ndarray, or xarray.DataArray
        Mean ensemble spread.
    mean_error : float, numpy.ndarray, or xarray.DataArray
        Mean absolute error of ensemble mean vs. obs.
    """
    if isinstance(ensemble, xr.DataArray) and isinstance(obs, xr.DataArray):
        # Resolve ensemble dimension
        e_dim = axis
        if isinstance(axis, int):
            e_dim = ensemble.dims[axis]

        spread_field = ensemble.std(dim=e_dim)
        ens_mean_field = ensemble.mean(dim=e_dim)
        error_field = abs(ens_mean_field - obs)

        # Average over specified dimensions (or all remaining)
        m_spread = spread_field.mean(dim=dim)
        m_error = error_field.mean(dim=dim)

        return _update_history(m_spread, "Mean Ensemble Spread"), _update_history(m_error, "Mean Ensemble Error")

    # NumPy path
    ens = np.asarray(ensemble)
    observation = np.asarray(obs)

    # Calculate spread and ensemble mean
    spread_f = np.std(ens, axis=axis)
    ens_m_f = np.mean(ens, axis=axis)
    error_f = np.abs(ens_m_f - observation)

    # Average over specified axes
    m_spread = np.nanmean(spread_f, axis=reduce_axis)
    m_error = np.nanmean(error_f, axis=reduce_axis)

    if np.ndim(m_spread) == 0:
        return float(m_spread), float(m_error)
    return m_spread, m_error

Xarray Accessor

Xarray accessors for the MONET Stats package (Aero Protocol Compliant).

MonetDataArrayAccessor

Accessor for xarray.DataArray to provide MONET statistical methods.

Source code in src/monet_stats/accessor.py
 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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
@xr.register_dataarray_accessor("monet_stats")
class MonetDataArrayAccessor:
    """
    Accessor for xarray.DataArray to provide MONET statistical methods.
    """

    def __init__(self, xarray_obj: xr.DataArray) -> None:
        self._obj = xarray_obj

    def climatology(self, freq: str = "season", method: str = "mean", dim: str = "time") -> xr.DataArray:
        """
        Compute climatological statistics.

        Parameters
        ----------
        freq : str, optional
            Climatology frequency ('season', 'month', 'dayofyear', 'hour').
            Default is 'season'.
        method : str, optional
            Statistical method to apply ('mean', 'std', 'min', 'max', 'median').
            Default is 'mean'.
        dim : str, optional
            Dimension along which to compute climatology. Default is 'time'.

        Returns
        -------
        xarray.DataArray
            Climatological statistics.
        """
        return analysis.climatology(self._obj, freq=freq, method=method, dim=dim)

    def resample_data(self, freq: str = "MS", method: str = "mean", dim: str = "time", **kwargs: Any) -> xr.DataArray:
        """
        Resample data to a new temporal frequency.

        Parameters
        ----------
        freq : str, optional
            Resampling frequency (e.g., 'MS', 'W', 'D'). Default is 'MS'.
        method : str, optional
            Statistical method to apply ('mean', 'sum', 'min', 'max', 'std', 'median').
            Default is 'mean'.
        dim : str, optional
            Dimension along which to resample. Default is 'time'.
        **kwargs : Any
            Additional keyword arguments passed to the resample method.

        Returns
        -------
        xarray.DataArray
            Resampled data.
        """
        return analysis.resample_data(self._obj, freq=freq, method=method, dim=dim, **kwargs)

    def kz_filter(self, m: int, k: int, dim: str = "time") -> xr.DataArray:
        """
        Apply Kolmogorov-Zurbenko (KZ) filter.

        Parameters
        ----------
        m : int
            Window size for the moving average.
        k : int
            Number of iterations.
        dim : str, optional
            Dimension along which to apply the filter. Default is 'time'.

        Returns
        -------
        xarray.DataArray
            Filtered data.
        """
        return analysis.kz_filter(self._obj, m=m, k=k, dim=dim)

    def diurnal_cycle(self, method: str = "mean", dim: str = "time") -> xr.DataArray:
        """
        Compute the diurnal cycle (average hourly profile).

        Parameters
        ----------
        method : str, optional
            Statistical method to apply ('mean', 'median', 'std'). Default is 'mean'.
        dim : str, optional
            Dimension along which to compute the cycle. Default is 'time'.

        Returns
        -------
        xarray.DataArray
            Diurnal cycle.
        """
        return analysis.diurnal_cycle(self._obj, method=method, dim=dim)

    def rolling_mean_8h(self, dim: str = "time", min_periods: int = 6, center: bool = True) -> xr.DataArray:
        """
        Compute rolling 8-hour mean.

        Parameters
        ----------
        dim : str, optional
            Dimension along which to compute the mean. Default is 'time'.
        min_periods : int, optional
            Minimum number of observations in window. Default is 6.
        center : bool, optional
            If True, set the labels at the center of the window. Default is True.

        Returns
        -------
        xarray.DataArray
            Rolling 8-hour mean.
        """
        return analysis.rolling_mean_8h(self._obj, dim=dim, min_periods=min_periods, center=center)

    def rolling_mean_24h(self, dim: str = "time", min_periods: int = 18, center: bool = True) -> xr.DataArray:
        """
        Compute rolling 24-hour mean.

        Parameters
        ----------
        dim : str, optional
            Dimension along which to compute the mean. Default is 'time'.
        min_periods : int, optional
            Minimum number of observations in window. Default is 18.
        center : bool, optional
            If True, set the labels at the center of the window. Default is True.

        Returns
        -------
        xarray.DataArray
            Rolling 24-hour mean.
        """
        return analysis.rolling_mean_24h(self._obj, dim=dim, min_periods=min_periods, center=center)

    def mda1(self, dim: str = "time") -> xr.DataArray:
        """
        Compute Maximum Daily 1-hour Average (MDA1).

        Parameters
        ----------
        dim : str, optional
            Dimension along which to compute. Default is 'time'.

        Returns
        -------
        xarray.DataArray
            MDA1 values.
        """
        return analysis.mda1(self._obj, dim=dim)

    def mda8(self, dim: str = "time", min_periods: int = 6, center: bool = False) -> xr.DataArray:
        """
        Compute Maximum Daily 8-hour Average (MDA8).

        Parameters
        ----------
        dim : str, optional
            Dimension along which to compute. Default is 'time'.
        min_periods : int, optional
            Minimum number of observations for the 8-hour rolling mean. Default is 6.
        center : bool, optional
            Whether to center the 8-hour rolling window. Default is False.

        Returns
        -------
        xarray.DataArray
            MDA8 values.
        """
        return analysis.mda8(self._obj, dim=dim, min_periods=min_periods, center=center)

    def exceedance_count(self, threshold: float, dim: str = "time") -> xr.DataArray:
        """
        Count exceedances of a threshold.

        Parameters
        ----------
        threshold : float
            Value above which an exceedance is counted.
        dim : str, optional
            Dimension along which to count exceedances. Default is 'time'.

        Returns
        -------
        xarray.DataArray
            Number of exceedances.
        """
        return analysis.exceedance_count(self._obj, threshold=threshold, dim=dim)

    def percentile(self, q: Union[float, List[float], np.ndarray], dim: str = "time", **kwargs: Any) -> xr.DataArray:
        """
        Compute percentiles.

        Parameters
        ----------
        q : float or list of float
            Percentile(s) to compute (0-100).
        dim : str, optional
            Dimension over which to compute percentiles. Default is 'time'.
        **kwargs : Any
            Additional keyword arguments passed to xarray.quantile.

        Returns
        -------
        xarray.DataArray
            Computed percentiles.
        """
        return analysis.percentile(self._obj, q=q, dim=dim, **kwargs)

    def peak_timing(self, dim: str = "time") -> xr.DataArray:
        """
        Identify the coordinate value of the maximum.

        Parameters
        ----------
        dim : str, optional
            Dimension along which to find the peak. Default is 'time'.

        Returns
        -------
        xarray.DataArray
            Coordinate values where the maximum occurs.
        """
        return analysis.peak_timing(self._obj, dim=dim)

    def weighted_spatial_mean(
        self,
        lat_dim: str = "lat",
        lon_dim: str = "lon",
        weights: Optional[Union[xr.DataArray, np.ndarray]] = None,
    ) -> xr.DataArray:
        """
        Compute area-weighted spatial mean.

        Parameters
        ----------
        lat_dim : str, optional
            Name of the latitude dimension. Default is 'lat'.
        lon_dim : str, optional
            Name of the longitude dimension. Default is 'lon'.
        weights : xarray.DataArray or numpy.ndarray, optional
            Custom weights for the mean.

        Returns
        -------
        xarray.DataArray
            Area-weighted spatial mean.
        """
        return analysis.weighted_spatial_mean(self._obj, lat_dim=lat_dim, lon_dim=lon_dim, weights=weights)

    def fft_analysis(self, dim: str = "time", output: str = "psd") -> xr.DataArray:
        """
        Perform Fast Fourier Transform (FFT) analysis.

        Parameters
        ----------
        dim : str, optional
            Dimension along which to perform FFT. Default is 'time'.
        output : str, optional
            Type of output to return ('psd', 'magnitude', 'complex'). Default is 'psd'.

        Returns
        -------
        xarray.DataArray
            FFT results.
        """
        return analysis.fft_analysis(self._obj, dim=dim, output=output)

    def power_spectrum(
        self,
        dim: str = "time",
        fs: float = 1.0,
        window: str = "hann",
        nperseg: Optional[int] = None,
        **kwargs: Any,
    ) -> xr.DataArray:
        """
        Compute power spectrum using Welch's method.

        Parameters
        ----------
        dim : str, optional
            Dimension along which to compute the spectrum. Default is 'time'.
        fs : float, optional
            Sampling frequency. Default is 1.0.
        window : str, optional
            Desired window to use. Default is 'hann'.
        nperseg : int, optional
            Length of each segment.
        **kwargs : Any
            Additional keyword arguments passed to scipy.signal.welch.

        Returns
        -------
        xarray.DataArray
            Power spectral density.
        """
        return analysis.power_spectrum(self._obj, dim=dim, fs=fs, window=window, nperseg=nperseg, **kwargs)

    def seasonal_mean(self, dim: str = "time", weighted: bool = True) -> xr.DataArray:
        """
        Compute seasonal mean (DJF, MAM, JJA, SON).

        Parameters
        ----------
        dim : str, optional
            Dimension along which to compute the mean. Default is 'time'.
        weighted : bool, optional
            If True, weight by days in month. Default is True.

        Returns
        -------
        xarray.DataArray
            Seasonal means.
        """
        return analysis.seasonal_mean(self._obj, dim=dim, weighted=weighted)

    def monthly_climatology(self, dim: str = "time", method: str = "mean") -> xr.DataArray:
        """
        Compute monthly climatology.

        Parameters
        ----------
        dim : str, optional
            Dimension along which to compute the climatology. Default is 'time'.
        method : str, optional
            Statistical method to apply. Default is 'mean'.

        Returns
        -------
        xarray.DataArray
            Monthly climatology.
        """
        return analysis.monthly_climatology(self._obj, dim=dim, method=method)

    def anomalies(self, freq: str = "month", dim: str = "time") -> xr.DataArray:
        """
        Compute anomalies by subtracting the climatology.

        Parameters
        ----------
        freq : str, optional
            Climatology frequency ('season', 'month', 'dayofyear', 'hour').
            Default is 'month'.
        dim : str, optional
            Dimension along which to compute the anomalies. Default is 'time'.

        Returns
        -------
        xarray.DataArray
            Anomalies.
        """
        return analysis.anomalies(self._obj, freq=freq, dim=dim)

    def detrend(self, method: str = "linear", dim: str = "time") -> xr.DataArray:
        """
        Remove trend from data.

        Parameters
        ----------
        method : str, optional
            Detrending method ('linear', 'constant'). Default is 'linear'.
        dim : str, optional
            Dimension along which to detrend. Default is 'time'.

        Returns
        -------
        xarray.DataArray
            Detrended data.
        """
        return analysis.detrend(self._obj, method=method, dim=dim)

    def optimize(self, target_mb: float = 100.0) -> xr.DataArray:
        """
        Optimize performance by ensuring laziness and recommended chunks (Aero Protocol).

        Parameters
        ----------
        target_mb : float, optional
            Target size for each chunk in Megabytes. Default is 100.0.

        Returns
        -------
        xarray.DataArray
            Optimized DataArray.
        """
        from .utils_stats import _update_history

        if not performance._has_dask():
            return _update_history(self._obj, "Optimization skipped (Dask not installed)")

        # Ensure data is lazy
        res = performance.apply_lazy_threshold(self._obj, threshold_mb=0.1)
        # Always calculate and apply recommended chunks for the target size
        recommendation = performance.get_chunk_recommendation(res, target_mb=target_mb)
        res = res.chunk(recommendation)

        return _update_history(res, f"Optimized for performance (target={target_mb}MB)")

    def rechunk(self, chunks: Optional[dict] = None) -> xr.DataArray:
        """
        Apply new chunks to the DataArray (Aero Protocol provenance tracking).

        Parameters
        ----------
        chunks : dict, optional
            New chunk sizes. If None, uses optimal recommendations (~100MB).

        Returns
        -------
        xarray.DataArray
            Rechunked DataArray.
        """
        from .utils_stats import _update_history

        if not performance._has_dask():
            return _update_history(self._obj, "Rechunking skipped (Dask not installed)")

        if chunks is None:
            chunks = performance.get_chunk_recommendation(self._obj)

        res = self._obj.chunk(chunks)

        return _update_history(res, f"Rechunked with {chunks}")

    def taylor_statistics(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.Dataset:
        """
        Calculate components required for a Taylor diagram (Aero Protocol).

        Parameters
        ----------
        obs : xarray.DataArray
            Observed values (reference).
        dim : str or list of str, optional
            Dimension(s) along which to compute the statistics.

        Returns
        -------
        xarray.Dataset
            Dataset containing:
            - std_obs: Standard deviation of observations.
            - std_mod: Standard deviation of model predictions.
            - correlation: Pearson correlation coefficient.
        """
        obs, mod = xr.align(obs, self._obj, join="inner")
        from .utils_stats import _resolve_axis_to_dim, _update_history

        d = _resolve_axis_to_dim(obs, dim)

        res = xr.Dataset(
            {
                "std_obs": obs.std(dim=d),
                "std_mod": mod.std(dim=d),
                "correlation": correlation_metrics.pearsonr(obs, mod, axis=dim),
            }
        )
        return _update_history(res, "Taylor statistics components")

    def mae(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.DataArray:
        """
        Compute Mean Absolute Error (MAE).

        Parameters
        ----------
        obs : xarray.DataArray
            Observed values.
        dim : str or list of str, optional
            Dimension(s) along which to compute the metric.

        Returns
        -------
        xarray.DataArray
            Mean absolute error.
        """
        return error_metrics.MAE(obs, self._obj, axis=dim)

    def rmse(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.DataArray:
        """
        Compute Root Mean Square Error (RMSE).

        Parameters
        ----------
        obs : xarray.DataArray
            Observed values.
        dim : str or list of str, optional
            Dimension(s) along which to compute the metric.

        Returns
        -------
        xarray.DataArray
            Root mean square error.
        """
        return error_metrics.RMSE(obs, self._obj, axis=dim)

    def mb(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.DataArray:
        """
        Compute Mean Bias (MB).

        Parameters
        ----------
        obs : xarray.DataArray
            Observed values.
        dim : str or list of str, optional
            Dimension(s) along which to compute the metric.

        Returns
        -------
        xarray.DataArray
            Mean bias.
        """
        return error_metrics.MB(obs, self._obj, axis=dim)

    def ioa(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.DataArray:
        """
        Compute Index of Agreement (IOA).

        Parameters
        ----------
        obs : xarray.DataArray
            Observed values.
        dim : str or list of str, optional
            Dimension(s) along which to compute the metric.

        Returns
        -------
        xarray.DataArray
            Index of agreement.
        """
        return error_metrics.IOA(obs, self._obj, axis=dim)

    def crmse(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.DataArray:
        """
        Compute Centered Root Mean Square Error (CRMSE).

        Parameters
        ----------
        obs : xarray.DataArray
            Observed values.
        dim : str or list of str, optional
            Dimension(s) along which to compute the metric.

        Returns
        -------
        xarray.DataArray
            Centered root mean square error.
        """
        return error_metrics.CRMSE(obs, self._obj, axis=dim)

    def mdnb(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.DataArray:
        """
        Compute Median Bias (MdnB).

        Parameters
        ----------
        obs : xarray.DataArray
            Observed values.
        dim : str or list of str, optional
            Dimension(s) along which to compute the metric.

        Returns
        -------
        xarray.DataArray
            Median bias.
        """
        return error_metrics.MdnB(obs, self._obj, axis=dim)

    def nmse(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.DataArray:
        """
        Compute Normalized Mean Square Error (NMSE).

        Parameters
        ----------
        obs : xarray.DataArray
            Observed values.
        dim : str or list of str, optional
            Dimension(s) along which to compute the metric.

        Returns
        -------
        xarray.DataArray
            Normalized mean square error.
        """
        return error_metrics.NMSE(obs, self._obj, axis=dim)

    def pearsonr(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.DataArray:
        """
        Compute Pearson correlation coefficient.

        Parameters
        ----------
        obs : xarray.DataArray
            Observed values.
        dim : str or list of str, optional
            Dimension(s) along which to compute the metric.

        Returns
        -------
        xarray.DataArray
            Pearson correlation coefficient.
        """
        return correlation_metrics.pearsonr(obs, self._obj, axis=dim)

    def r2(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.DataArray:
        """
        Compute Coefficient of Determination (R^2).

        Parameters
        ----------
        obs : xarray.DataArray
            Observed values.
        dim : str or list of str, optional
            Dimension(s) along which to compute the metric.

        Returns
        -------
        xarray.DataArray
            Coefficient of determination.
        """
        return correlation_metrics.R2(obs, self._obj, axis=dim)

    def kge(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.DataArray:
        """
        Compute Kling-Gupta Efficiency (KGE).

        Parameters
        ----------
        obs : xarray.DataArray
            Observed values.
        dim : str or list of str, optional
            Dimension(s) along which to compute the metric.

        Returns
        -------
        xarray.DataArray
            Kling-Gupta efficiency.
        """
        return correlation_metrics.KGE(obs, self._obj, axis=dim)

    def ccc(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.DataArray:
        """
        Compute Concordance Correlation Coefficient (CCC).

        Parameters
        ----------
        obs : xarray.DataArray
            Observed values.
        dim : str or list of str, optional
            Dimension(s) along which to compute the metric.

        Returns
        -------
        xarray.DataArray
            Concordance correlation coefficient.
        """
        return correlation_metrics.CCC(obs, self._obj, axis=dim)

    def nmb(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.DataArray:
        """
        Compute Normalized Mean Bias (NMB).

        Parameters
        ----------
        obs : xarray.DataArray
            Observed values.
        dim : str or list of str, optional
            Dimension(s) along which to compute the metric.

        Returns
        -------
        xarray.DataArray
            Normalized mean bias.
        """
        return relative_metrics.NMB(obs, self._obj, axis=dim)

    def fb(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.DataArray:
        """
        Compute Fractional Bias (FB).

        Parameters
        ----------
        obs : xarray.DataArray
            Observed values.
        dim : str or list of str, optional
            Dimension(s) along which to compute the metric.

        Returns
        -------
        xarray.DataArray
            Fractional bias.
        """
        return relative_metrics.FB(obs, self._obj, axis=dim)

    def mnb(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.DataArray:
        """
        Compute Mean Normalized Bias (MNB).

        Parameters
        ----------
        obs : xarray.DataArray
            Observed values.
        dim : str or list of str, optional
            Dimension(s) along which to compute the metric.

        Returns
        -------
        xarray.DataArray
            Mean normalized bias.
        """
        return error_metrics.MNB(obs, self._obj, axis=dim)

    def mne(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.DataArray:
        """
        Compute Mean Normalized Gross Error (MNE).

        Parameters
        ----------
        obs : xarray.DataArray
            Observed values.
        dim : str or list of str, optional
            Dimension(s) along which to compute the metric.

        Returns
        -------
        xarray.DataArray
            Mean normalized gross error.
        """
        return error_metrics.MNE(obs, self._obj, axis=dim)

    def nse(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.DataArray:
        """
        Compute Nash-Sutcliffe Efficiency (NSE).

        Parameters
        ----------
        obs : xarray.DataArray
            Observed values.
        dim : str or list of str, optional
            Dimension(s) along which to compute the metric.

        Returns
        -------
        xarray.DataArray
            Nash-Sutcliffe efficiency.
        """
        return efficiency_metrics.NSE(obs, self._obj, axis=dim)

    def verify(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.Dataset:
        """
        Calculate a bundle of common evaluation metrics (Aero Protocol).

        Parameters
        ----------
        obs : xarray.DataArray
            Observed values.
        dim : str or list of str, optional
            Dimension(s) along which to compute the metrics.

        Returns
        -------
        xarray.Dataset
            Dataset containing: MAE, RMSE, MB, R, IOA, NMB, MNB, MNE, NSE, and R2.
        """
        metrics = {
            "MAE": error_metrics.MAE(obs, self._obj, axis=dim),
            "RMSE": error_metrics.RMSE(obs, self._obj, axis=dim),
            "MB": error_metrics.MB(obs, self._obj, axis=dim),
            "R": correlation_metrics.pearsonr(obs, self._obj, axis=dim),
            "IOA": error_metrics.IOA(obs, self._obj, axis=dim),
            "NMB": relative_metrics.NMB(obs, self._obj, axis=dim),
            "MNB": error_metrics.MNB(obs, self._obj, axis=dim),
            "MNE": error_metrics.MNE(obs, self._obj, axis=dim),
            "NSE": efficiency_metrics.NSE(obs, self._obj, axis=dim),
            "R2": correlation_metrics.R2(obs, self._obj, axis=dim),
        }
        res = xr.Dataset(metrics)
        from .utils_stats import _update_history

        return _update_history(res, "Verification metrics bundle (verify)")

    def plot_spatial(
        self,
        method: str = "matplotlib",
        lat_dim: str = "lat",
        lon_dim: str = "lon",
        title: Optional[str] = None,
        cmap: str = "viridis",
        **kwargs: Any,
    ) -> Any:
        """
        Plot spatial data following the Aero Protocol's Two-Track Rule.

        Parameters
        ----------
        method : str, optional
            Plotting track: 'matplotlib' (Track A) or 'hvplot' (Track B).
            Default is 'matplotlib'.
        lat_dim : str, optional
            Latitude dimension name. Default is 'lat'.
        lon_dim : str, optional
            Longitude dimension name. Default is 'lon'.
        title : str, optional
            Plot title.
        cmap : str, optional
            Colormap. Default is 'viridis'.
        **kwargs : Any
            Additional keyword arguments.

        Returns
        -------
        Any
            The plot object.
        """
        from .visualize import plot_spatial

        return plot_spatial(
            self._obj,
            method=method,
            lat_dim=lat_dim,
            lon_dim=lon_dim,
            title=title,
            cmap=cmap,
            **kwargs,
        )

anomalies(freq='month', dim='time')

Compute anomalies by subtracting the climatology.

Parameters

freq : str, optional Climatology frequency ('season', 'month', 'dayofyear', 'hour'). Default is 'month'. dim : str, optional Dimension along which to compute the anomalies. Default is 'time'.

Returns

xarray.DataArray Anomalies.

Source code in src/monet_stats/accessor.py
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
def anomalies(self, freq: str = "month", dim: str = "time") -> xr.DataArray:
    """
    Compute anomalies by subtracting the climatology.

    Parameters
    ----------
    freq : str, optional
        Climatology frequency ('season', 'month', 'dayofyear', 'hour').
        Default is 'month'.
    dim : str, optional
        Dimension along which to compute the anomalies. Default is 'time'.

    Returns
    -------
    xarray.DataArray
        Anomalies.
    """
    return analysis.anomalies(self._obj, freq=freq, dim=dim)

ccc(obs, dim=None)

Compute Concordance Correlation Coefficient (CCC).

Parameters

obs : xarray.DataArray Observed values. dim : str or list of str, optional Dimension(s) along which to compute the metric.

Returns

xarray.DataArray Concordance correlation coefficient.

Source code in src/monet_stats/accessor.py
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
def ccc(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.DataArray:
    """
    Compute Concordance Correlation Coefficient (CCC).

    Parameters
    ----------
    obs : xarray.DataArray
        Observed values.
    dim : str or list of str, optional
        Dimension(s) along which to compute the metric.

    Returns
    -------
    xarray.DataArray
        Concordance correlation coefficient.
    """
    return correlation_metrics.CCC(obs, self._obj, axis=dim)

climatology(freq='season', method='mean', dim='time')

Compute climatological statistics.

Parameters

freq : str, optional Climatology frequency ('season', 'month', 'dayofyear', 'hour'). Default is 'season'. method : str, optional Statistical method to apply ('mean', 'std', 'min', 'max', 'median'). Default is 'mean'. dim : str, optional Dimension along which to compute climatology. Default is 'time'.

Returns

xarray.DataArray Climatological statistics.

Source code in src/monet_stats/accessor.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
def climatology(self, freq: str = "season", method: str = "mean", dim: str = "time") -> xr.DataArray:
    """
    Compute climatological statistics.

    Parameters
    ----------
    freq : str, optional
        Climatology frequency ('season', 'month', 'dayofyear', 'hour').
        Default is 'season'.
    method : str, optional
        Statistical method to apply ('mean', 'std', 'min', 'max', 'median').
        Default is 'mean'.
    dim : str, optional
        Dimension along which to compute climatology. Default is 'time'.

    Returns
    -------
    xarray.DataArray
        Climatological statistics.
    """
    return analysis.climatology(self._obj, freq=freq, method=method, dim=dim)

crmse(obs, dim=None)

Compute Centered Root Mean Square Error (CRMSE).

Parameters

obs : xarray.DataArray Observed values. dim : str or list of str, optional Dimension(s) along which to compute the metric.

Returns

xarray.DataArray Centered root mean square error.

Source code in src/monet_stats/accessor.py
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
def crmse(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.DataArray:
    """
    Compute Centered Root Mean Square Error (CRMSE).

    Parameters
    ----------
    obs : xarray.DataArray
        Observed values.
    dim : str or list of str, optional
        Dimension(s) along which to compute the metric.

    Returns
    -------
    xarray.DataArray
        Centered root mean square error.
    """
    return error_metrics.CRMSE(obs, self._obj, axis=dim)

detrend(method='linear', dim='time')

Remove trend from data.

Parameters

method : str, optional Detrending method ('linear', 'constant'). Default is 'linear'. dim : str, optional Dimension along which to detrend. Default is 'time'.

Returns

xarray.DataArray Detrended data.

Source code in src/monet_stats/accessor.py
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
def detrend(self, method: str = "linear", dim: str = "time") -> xr.DataArray:
    """
    Remove trend from data.

    Parameters
    ----------
    method : str, optional
        Detrending method ('linear', 'constant'). Default is 'linear'.
    dim : str, optional
        Dimension along which to detrend. Default is 'time'.

    Returns
    -------
    xarray.DataArray
        Detrended data.
    """
    return analysis.detrend(self._obj, method=method, dim=dim)

diurnal_cycle(method='mean', dim='time')

Compute the diurnal cycle (average hourly profile).

Parameters

method : str, optional Statistical method to apply ('mean', 'median', 'std'). Default is 'mean'. dim : str, optional Dimension along which to compute the cycle. Default is 'time'.

Returns

xarray.DataArray Diurnal cycle.

Source code in src/monet_stats/accessor.py
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
def diurnal_cycle(self, method: str = "mean", dim: str = "time") -> xr.DataArray:
    """
    Compute the diurnal cycle (average hourly profile).

    Parameters
    ----------
    method : str, optional
        Statistical method to apply ('mean', 'median', 'std'). Default is 'mean'.
    dim : str, optional
        Dimension along which to compute the cycle. Default is 'time'.

    Returns
    -------
    xarray.DataArray
        Diurnal cycle.
    """
    return analysis.diurnal_cycle(self._obj, method=method, dim=dim)

exceedance_count(threshold, dim='time')

Count exceedances of a threshold.

Parameters

threshold : float Value above which an exceedance is counted. dim : str, optional Dimension along which to count exceedances. Default is 'time'.

Returns

xarray.DataArray Number of exceedances.

Source code in src/monet_stats/accessor.py
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
def exceedance_count(self, threshold: float, dim: str = "time") -> xr.DataArray:
    """
    Count exceedances of a threshold.

    Parameters
    ----------
    threshold : float
        Value above which an exceedance is counted.
    dim : str, optional
        Dimension along which to count exceedances. Default is 'time'.

    Returns
    -------
    xarray.DataArray
        Number of exceedances.
    """
    return analysis.exceedance_count(self._obj, threshold=threshold, dim=dim)

fb(obs, dim=None)

Compute Fractional Bias (FB).

Parameters

obs : xarray.DataArray Observed values. dim : str or list of str, optional Dimension(s) along which to compute the metric.

Returns

xarray.DataArray Fractional bias.

Source code in src/monet_stats/accessor.py
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
def fb(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.DataArray:
    """
    Compute Fractional Bias (FB).

    Parameters
    ----------
    obs : xarray.DataArray
        Observed values.
    dim : str or list of str, optional
        Dimension(s) along which to compute the metric.

    Returns
    -------
    xarray.DataArray
        Fractional bias.
    """
    return relative_metrics.FB(obs, self._obj, axis=dim)

fft_analysis(dim='time', output='psd')

Perform Fast Fourier Transform (FFT) analysis.

Parameters

dim : str, optional Dimension along which to perform FFT. Default is 'time'. output : str, optional Type of output to return ('psd', 'magnitude', 'complex'). Default is 'psd'.

Returns

xarray.DataArray FFT results.

Source code in src/monet_stats/accessor.py
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
def fft_analysis(self, dim: str = "time", output: str = "psd") -> xr.DataArray:
    """
    Perform Fast Fourier Transform (FFT) analysis.

    Parameters
    ----------
    dim : str, optional
        Dimension along which to perform FFT. Default is 'time'.
    output : str, optional
        Type of output to return ('psd', 'magnitude', 'complex'). Default is 'psd'.

    Returns
    -------
    xarray.DataArray
        FFT results.
    """
    return analysis.fft_analysis(self._obj, dim=dim, output=output)

ioa(obs, dim=None)

Compute Index of Agreement (IOA).

Parameters

obs : xarray.DataArray Observed values. dim : str or list of str, optional Dimension(s) along which to compute the metric.

Returns

xarray.DataArray Index of agreement.

Source code in src/monet_stats/accessor.py
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
def ioa(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.DataArray:
    """
    Compute Index of Agreement (IOA).

    Parameters
    ----------
    obs : xarray.DataArray
        Observed values.
    dim : str or list of str, optional
        Dimension(s) along which to compute the metric.

    Returns
    -------
    xarray.DataArray
        Index of agreement.
    """
    return error_metrics.IOA(obs, self._obj, axis=dim)

kge(obs, dim=None)

Compute Kling-Gupta Efficiency (KGE).

Parameters

obs : xarray.DataArray Observed values. dim : str or list of str, optional Dimension(s) along which to compute the metric.

Returns

xarray.DataArray Kling-Gupta efficiency.

Source code in src/monet_stats/accessor.py
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
def kge(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.DataArray:
    """
    Compute Kling-Gupta Efficiency (KGE).

    Parameters
    ----------
    obs : xarray.DataArray
        Observed values.
    dim : str or list of str, optional
        Dimension(s) along which to compute the metric.

    Returns
    -------
    xarray.DataArray
        Kling-Gupta efficiency.
    """
    return correlation_metrics.KGE(obs, self._obj, axis=dim)

kz_filter(m, k, dim='time')

Apply Kolmogorov-Zurbenko (KZ) filter.

Parameters

m : int Window size for the moving average. k : int Number of iterations. dim : str, optional Dimension along which to apply the filter. Default is 'time'.

Returns

xarray.DataArray Filtered data.

Source code in src/monet_stats/accessor.py
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
def kz_filter(self, m: int, k: int, dim: str = "time") -> xr.DataArray:
    """
    Apply Kolmogorov-Zurbenko (KZ) filter.

    Parameters
    ----------
    m : int
        Window size for the moving average.
    k : int
        Number of iterations.
    dim : str, optional
        Dimension along which to apply the filter. Default is 'time'.

    Returns
    -------
    xarray.DataArray
        Filtered data.
    """
    return analysis.kz_filter(self._obj, m=m, k=k, dim=dim)

mae(obs, dim=None)

Compute Mean Absolute Error (MAE).

Parameters

obs : xarray.DataArray Observed values. dim : str or list of str, optional Dimension(s) along which to compute the metric.

Returns

xarray.DataArray Mean absolute error.

Source code in src/monet_stats/accessor.py
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
def mae(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.DataArray:
    """
    Compute Mean Absolute Error (MAE).

    Parameters
    ----------
    obs : xarray.DataArray
        Observed values.
    dim : str or list of str, optional
        Dimension(s) along which to compute the metric.

    Returns
    -------
    xarray.DataArray
        Mean absolute error.
    """
    return error_metrics.MAE(obs, self._obj, axis=dim)

mb(obs, dim=None)

Compute Mean Bias (MB).

Parameters

obs : xarray.DataArray Observed values. dim : str or list of str, optional Dimension(s) along which to compute the metric.

Returns

xarray.DataArray Mean bias.

Source code in src/monet_stats/accessor.py
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
def mb(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.DataArray:
    """
    Compute Mean Bias (MB).

    Parameters
    ----------
    obs : xarray.DataArray
        Observed values.
    dim : str or list of str, optional
        Dimension(s) along which to compute the metric.

    Returns
    -------
    xarray.DataArray
        Mean bias.
    """
    return error_metrics.MB(obs, self._obj, axis=dim)

mda1(dim='time')

Compute Maximum Daily 1-hour Average (MDA1).

Parameters

dim : str, optional Dimension along which to compute. Default is 'time'.

Returns

xarray.DataArray MDA1 values.

Source code in src/monet_stats/accessor.py
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
def mda1(self, dim: str = "time") -> xr.DataArray:
    """
    Compute Maximum Daily 1-hour Average (MDA1).

    Parameters
    ----------
    dim : str, optional
        Dimension along which to compute. Default is 'time'.

    Returns
    -------
    xarray.DataArray
        MDA1 values.
    """
    return analysis.mda1(self._obj, dim=dim)

mda8(dim='time', min_periods=6, center=False)

Compute Maximum Daily 8-hour Average (MDA8).

Parameters

dim : str, optional Dimension along which to compute. Default is 'time'. min_periods : int, optional Minimum number of observations for the 8-hour rolling mean. Default is 6. center : bool, optional Whether to center the 8-hour rolling window. Default is False.

Returns

xarray.DataArray MDA8 values.

Source code in src/monet_stats/accessor.py
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
def mda8(self, dim: str = "time", min_periods: int = 6, center: bool = False) -> xr.DataArray:
    """
    Compute Maximum Daily 8-hour Average (MDA8).

    Parameters
    ----------
    dim : str, optional
        Dimension along which to compute. Default is 'time'.
    min_periods : int, optional
        Minimum number of observations for the 8-hour rolling mean. Default is 6.
    center : bool, optional
        Whether to center the 8-hour rolling window. Default is False.

    Returns
    -------
    xarray.DataArray
        MDA8 values.
    """
    return analysis.mda8(self._obj, dim=dim, min_periods=min_periods, center=center)

mdnb(obs, dim=None)

Compute Median Bias (MdnB).

Parameters

obs : xarray.DataArray Observed values. dim : str or list of str, optional Dimension(s) along which to compute the metric.

Returns

xarray.DataArray Median bias.

Source code in src/monet_stats/accessor.py
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
def mdnb(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.DataArray:
    """
    Compute Median Bias (MdnB).

    Parameters
    ----------
    obs : xarray.DataArray
        Observed values.
    dim : str or list of str, optional
        Dimension(s) along which to compute the metric.

    Returns
    -------
    xarray.DataArray
        Median bias.
    """
    return error_metrics.MdnB(obs, self._obj, axis=dim)

mnb(obs, dim=None)

Compute Mean Normalized Bias (MNB).

Parameters

obs : xarray.DataArray Observed values. dim : str or list of str, optional Dimension(s) along which to compute the metric.

Returns

xarray.DataArray Mean normalized bias.

Source code in src/monet_stats/accessor.py
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
def mnb(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.DataArray:
    """
    Compute Mean Normalized Bias (MNB).

    Parameters
    ----------
    obs : xarray.DataArray
        Observed values.
    dim : str or list of str, optional
        Dimension(s) along which to compute the metric.

    Returns
    -------
    xarray.DataArray
        Mean normalized bias.
    """
    return error_metrics.MNB(obs, self._obj, axis=dim)

mne(obs, dim=None)

Compute Mean Normalized Gross Error (MNE).

Parameters

obs : xarray.DataArray Observed values. dim : str or list of str, optional Dimension(s) along which to compute the metric.

Returns

xarray.DataArray Mean normalized gross error.

Source code in src/monet_stats/accessor.py
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
def mne(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.DataArray:
    """
    Compute Mean Normalized Gross Error (MNE).

    Parameters
    ----------
    obs : xarray.DataArray
        Observed values.
    dim : str or list of str, optional
        Dimension(s) along which to compute the metric.

    Returns
    -------
    xarray.DataArray
        Mean normalized gross error.
    """
    return error_metrics.MNE(obs, self._obj, axis=dim)

monthly_climatology(dim='time', method='mean')

Compute monthly climatology.

Parameters

dim : str, optional Dimension along which to compute the climatology. Default is 'time'. method : str, optional Statistical method to apply. Default is 'mean'.

Returns

xarray.DataArray Monthly climatology.

Source code in src/monet_stats/accessor.py
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
def monthly_climatology(self, dim: str = "time", method: str = "mean") -> xr.DataArray:
    """
    Compute monthly climatology.

    Parameters
    ----------
    dim : str, optional
        Dimension along which to compute the climatology. Default is 'time'.
    method : str, optional
        Statistical method to apply. Default is 'mean'.

    Returns
    -------
    xarray.DataArray
        Monthly climatology.
    """
    return analysis.monthly_climatology(self._obj, dim=dim, method=method)

nmb(obs, dim=None)

Compute Normalized Mean Bias (NMB).

Parameters

obs : xarray.DataArray Observed values. dim : str or list of str, optional Dimension(s) along which to compute the metric.

Returns

xarray.DataArray Normalized mean bias.

Source code in src/monet_stats/accessor.py
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
def nmb(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.DataArray:
    """
    Compute Normalized Mean Bias (NMB).

    Parameters
    ----------
    obs : xarray.DataArray
        Observed values.
    dim : str or list of str, optional
        Dimension(s) along which to compute the metric.

    Returns
    -------
    xarray.DataArray
        Normalized mean bias.
    """
    return relative_metrics.NMB(obs, self._obj, axis=dim)

nmse(obs, dim=None)

Compute Normalized Mean Square Error (NMSE).

Parameters

obs : xarray.DataArray Observed values. dim : str or list of str, optional Dimension(s) along which to compute the metric.

Returns

xarray.DataArray Normalized mean square error.

Source code in src/monet_stats/accessor.py
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
def nmse(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.DataArray:
    """
    Compute Normalized Mean Square Error (NMSE).

    Parameters
    ----------
    obs : xarray.DataArray
        Observed values.
    dim : str or list of str, optional
        Dimension(s) along which to compute the metric.

    Returns
    -------
    xarray.DataArray
        Normalized mean square error.
    """
    return error_metrics.NMSE(obs, self._obj, axis=dim)

nse(obs, dim=None)

Compute Nash-Sutcliffe Efficiency (NSE).

Parameters

obs : xarray.DataArray Observed values. dim : str or list of str, optional Dimension(s) along which to compute the metric.

Returns

xarray.DataArray Nash-Sutcliffe efficiency.

Source code in src/monet_stats/accessor.py
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
def nse(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.DataArray:
    """
    Compute Nash-Sutcliffe Efficiency (NSE).

    Parameters
    ----------
    obs : xarray.DataArray
        Observed values.
    dim : str or list of str, optional
        Dimension(s) along which to compute the metric.

    Returns
    -------
    xarray.DataArray
        Nash-Sutcliffe efficiency.
    """
    return efficiency_metrics.NSE(obs, self._obj, axis=dim)

optimize(target_mb=100.0)

Optimize performance by ensuring laziness and recommended chunks (Aero Protocol).

Parameters

target_mb : float, optional Target size for each chunk in Megabytes. Default is 100.0.

Returns

xarray.DataArray Optimized DataArray.

Source code in src/monet_stats/accessor.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
def optimize(self, target_mb: float = 100.0) -> xr.DataArray:
    """
    Optimize performance by ensuring laziness and recommended chunks (Aero Protocol).

    Parameters
    ----------
    target_mb : float, optional
        Target size for each chunk in Megabytes. Default is 100.0.

    Returns
    -------
    xarray.DataArray
        Optimized DataArray.
    """
    from .utils_stats import _update_history

    if not performance._has_dask():
        return _update_history(self._obj, "Optimization skipped (Dask not installed)")

    # Ensure data is lazy
    res = performance.apply_lazy_threshold(self._obj, threshold_mb=0.1)
    # Always calculate and apply recommended chunks for the target size
    recommendation = performance.get_chunk_recommendation(res, target_mb=target_mb)
    res = res.chunk(recommendation)

    return _update_history(res, f"Optimized for performance (target={target_mb}MB)")

peak_timing(dim='time')

Identify the coordinate value of the maximum.

Parameters

dim : str, optional Dimension along which to find the peak. Default is 'time'.

Returns

xarray.DataArray Coordinate values where the maximum occurs.

Source code in src/monet_stats/accessor.py
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
def peak_timing(self, dim: str = "time") -> xr.DataArray:
    """
    Identify the coordinate value of the maximum.

    Parameters
    ----------
    dim : str, optional
        Dimension along which to find the peak. Default is 'time'.

    Returns
    -------
    xarray.DataArray
        Coordinate values where the maximum occurs.
    """
    return analysis.peak_timing(self._obj, dim=dim)

pearsonr(obs, dim=None)

Compute Pearson correlation coefficient.

Parameters

obs : xarray.DataArray Observed values. dim : str or list of str, optional Dimension(s) along which to compute the metric.

Returns

xarray.DataArray Pearson correlation coefficient.

Source code in src/monet_stats/accessor.py
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
def pearsonr(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.DataArray:
    """
    Compute Pearson correlation coefficient.

    Parameters
    ----------
    obs : xarray.DataArray
        Observed values.
    dim : str or list of str, optional
        Dimension(s) along which to compute the metric.

    Returns
    -------
    xarray.DataArray
        Pearson correlation coefficient.
    """
    return correlation_metrics.pearsonr(obs, self._obj, axis=dim)

percentile(q, dim='time', **kwargs)

Compute percentiles.

Parameters

q : float or list of float Percentile(s) to compute (0-100). dim : str, optional Dimension over which to compute percentiles. Default is 'time'. **kwargs : Any Additional keyword arguments passed to xarray.quantile.

Returns

xarray.DataArray Computed percentiles.

Source code in src/monet_stats/accessor.py
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
def percentile(self, q: Union[float, List[float], np.ndarray], dim: str = "time", **kwargs: Any) -> xr.DataArray:
    """
    Compute percentiles.

    Parameters
    ----------
    q : float or list of float
        Percentile(s) to compute (0-100).
    dim : str, optional
        Dimension over which to compute percentiles. Default is 'time'.
    **kwargs : Any
        Additional keyword arguments passed to xarray.quantile.

    Returns
    -------
    xarray.DataArray
        Computed percentiles.
    """
    return analysis.percentile(self._obj, q=q, dim=dim, **kwargs)

plot_spatial(method='matplotlib', lat_dim='lat', lon_dim='lon', title=None, cmap='viridis', **kwargs)

Plot spatial data following the Aero Protocol's Two-Track Rule.

Parameters

method : str, optional Plotting track: 'matplotlib' (Track A) or 'hvplot' (Track B). Default is 'matplotlib'. lat_dim : str, optional Latitude dimension name. Default is 'lat'. lon_dim : str, optional Longitude dimension name. Default is 'lon'. title : str, optional Plot title. cmap : str, optional Colormap. Default is 'viridis'. **kwargs : Any Additional keyword arguments.

Returns

Any The plot object.

Source code in src/monet_stats/accessor.py
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
830
831
832
833
834
835
836
837
838
839
def plot_spatial(
    self,
    method: str = "matplotlib",
    lat_dim: str = "lat",
    lon_dim: str = "lon",
    title: Optional[str] = None,
    cmap: str = "viridis",
    **kwargs: Any,
) -> Any:
    """
    Plot spatial data following the Aero Protocol's Two-Track Rule.

    Parameters
    ----------
    method : str, optional
        Plotting track: 'matplotlib' (Track A) or 'hvplot' (Track B).
        Default is 'matplotlib'.
    lat_dim : str, optional
        Latitude dimension name. Default is 'lat'.
    lon_dim : str, optional
        Longitude dimension name. Default is 'lon'.
    title : str, optional
        Plot title.
    cmap : str, optional
        Colormap. Default is 'viridis'.
    **kwargs : Any
        Additional keyword arguments.

    Returns
    -------
    Any
        The plot object.
    """
    from .visualize import plot_spatial

    return plot_spatial(
        self._obj,
        method=method,
        lat_dim=lat_dim,
        lon_dim=lon_dim,
        title=title,
        cmap=cmap,
        **kwargs,
    )

power_spectrum(dim='time', fs=1.0, window='hann', nperseg=None, **kwargs)

Compute power spectrum using Welch's method.

Parameters

dim : str, optional Dimension along which to compute the spectrum. Default is 'time'. fs : float, optional Sampling frequency. Default is 1.0. window : str, optional Desired window to use. Default is 'hann'. nperseg : int, optional Length of each segment. **kwargs : Any Additional keyword arguments passed to scipy.signal.welch.

Returns

xarray.DataArray Power spectral density.

Source code in src/monet_stats/accessor.py
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
def power_spectrum(
    self,
    dim: str = "time",
    fs: float = 1.0,
    window: str = "hann",
    nperseg: Optional[int] = None,
    **kwargs: Any,
) -> xr.DataArray:
    """
    Compute power spectrum using Welch's method.

    Parameters
    ----------
    dim : str, optional
        Dimension along which to compute the spectrum. Default is 'time'.
    fs : float, optional
        Sampling frequency. Default is 1.0.
    window : str, optional
        Desired window to use. Default is 'hann'.
    nperseg : int, optional
        Length of each segment.
    **kwargs : Any
        Additional keyword arguments passed to scipy.signal.welch.

    Returns
    -------
    xarray.DataArray
        Power spectral density.
    """
    return analysis.power_spectrum(self._obj, dim=dim, fs=fs, window=window, nperseg=nperseg, **kwargs)

r2(obs, dim=None)

Compute Coefficient of Determination (R^2).

Parameters

obs : xarray.DataArray Observed values. dim : str or list of str, optional Dimension(s) along which to compute the metric.

Returns

xarray.DataArray Coefficient of determination.

Source code in src/monet_stats/accessor.py
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
def r2(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.DataArray:
    """
    Compute Coefficient of Determination (R^2).

    Parameters
    ----------
    obs : xarray.DataArray
        Observed values.
    dim : str or list of str, optional
        Dimension(s) along which to compute the metric.

    Returns
    -------
    xarray.DataArray
        Coefficient of determination.
    """
    return correlation_metrics.R2(obs, self._obj, axis=dim)

rechunk(chunks=None)

Apply new chunks to the DataArray (Aero Protocol provenance tracking).

Parameters

chunks : dict, optional New chunk sizes. If None, uses optimal recommendations (~100MB).

Returns

xarray.DataArray Rechunked DataArray.

Source code in src/monet_stats/accessor.py
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
def rechunk(self, chunks: Optional[dict] = None) -> xr.DataArray:
    """
    Apply new chunks to the DataArray (Aero Protocol provenance tracking).

    Parameters
    ----------
    chunks : dict, optional
        New chunk sizes. If None, uses optimal recommendations (~100MB).

    Returns
    -------
    xarray.DataArray
        Rechunked DataArray.
    """
    from .utils_stats import _update_history

    if not performance._has_dask():
        return _update_history(self._obj, "Rechunking skipped (Dask not installed)")

    if chunks is None:
        chunks = performance.get_chunk_recommendation(self._obj)

    res = self._obj.chunk(chunks)

    return _update_history(res, f"Rechunked with {chunks}")

resample_data(freq='MS', method='mean', dim='time', **kwargs)

Resample data to a new temporal frequency.

Parameters

freq : str, optional Resampling frequency (e.g., 'MS', 'W', 'D'). Default is 'MS'. method : str, optional Statistical method to apply ('mean', 'sum', 'min', 'max', 'std', 'median'). Default is 'mean'. dim : str, optional Dimension along which to resample. Default is 'time'. **kwargs : Any Additional keyword arguments passed to the resample method.

Returns

xarray.DataArray Resampled data.

Source code in src/monet_stats/accessor.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
def resample_data(self, freq: str = "MS", method: str = "mean", dim: str = "time", **kwargs: Any) -> xr.DataArray:
    """
    Resample data to a new temporal frequency.

    Parameters
    ----------
    freq : str, optional
        Resampling frequency (e.g., 'MS', 'W', 'D'). Default is 'MS'.
    method : str, optional
        Statistical method to apply ('mean', 'sum', 'min', 'max', 'std', 'median').
        Default is 'mean'.
    dim : str, optional
        Dimension along which to resample. Default is 'time'.
    **kwargs : Any
        Additional keyword arguments passed to the resample method.

    Returns
    -------
    xarray.DataArray
        Resampled data.
    """
    return analysis.resample_data(self._obj, freq=freq, method=method, dim=dim, **kwargs)

rmse(obs, dim=None)

Compute Root Mean Square Error (RMSE).

Parameters

obs : xarray.DataArray Observed values. dim : str or list of str, optional Dimension(s) along which to compute the metric.

Returns

xarray.DataArray Root mean square error.

Source code in src/monet_stats/accessor.py
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
def rmse(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.DataArray:
    """
    Compute Root Mean Square Error (RMSE).

    Parameters
    ----------
    obs : xarray.DataArray
        Observed values.
    dim : str or list of str, optional
        Dimension(s) along which to compute the metric.

    Returns
    -------
    xarray.DataArray
        Root mean square error.
    """
    return error_metrics.RMSE(obs, self._obj, axis=dim)

rolling_mean_24h(dim='time', min_periods=18, center=True)

Compute rolling 24-hour mean.

Parameters

dim : str, optional Dimension along which to compute the mean. Default is 'time'. min_periods : int, optional Minimum number of observations in window. Default is 18. center : bool, optional If True, set the labels at the center of the window. Default is True.

Returns

xarray.DataArray Rolling 24-hour mean.

Source code in src/monet_stats/accessor.py
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
def rolling_mean_24h(self, dim: str = "time", min_periods: int = 18, center: bool = True) -> xr.DataArray:
    """
    Compute rolling 24-hour mean.

    Parameters
    ----------
    dim : str, optional
        Dimension along which to compute the mean. Default is 'time'.
    min_periods : int, optional
        Minimum number of observations in window. Default is 18.
    center : bool, optional
        If True, set the labels at the center of the window. Default is True.

    Returns
    -------
    xarray.DataArray
        Rolling 24-hour mean.
    """
    return analysis.rolling_mean_24h(self._obj, dim=dim, min_periods=min_periods, center=center)

rolling_mean_8h(dim='time', min_periods=6, center=True)

Compute rolling 8-hour mean.

Parameters

dim : str, optional Dimension along which to compute the mean. Default is 'time'. min_periods : int, optional Minimum number of observations in window. Default is 6. center : bool, optional If True, set the labels at the center of the window. Default is True.

Returns

xarray.DataArray Rolling 8-hour mean.

Source code in src/monet_stats/accessor.py
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
def rolling_mean_8h(self, dim: str = "time", min_periods: int = 6, center: bool = True) -> xr.DataArray:
    """
    Compute rolling 8-hour mean.

    Parameters
    ----------
    dim : str, optional
        Dimension along which to compute the mean. Default is 'time'.
    min_periods : int, optional
        Minimum number of observations in window. Default is 6.
    center : bool, optional
        If True, set the labels at the center of the window. Default is True.

    Returns
    -------
    xarray.DataArray
        Rolling 8-hour mean.
    """
    return analysis.rolling_mean_8h(self._obj, dim=dim, min_periods=min_periods, center=center)

seasonal_mean(dim='time', weighted=True)

Compute seasonal mean (DJF, MAM, JJA, SON).

Parameters

dim : str, optional Dimension along which to compute the mean. Default is 'time'. weighted : bool, optional If True, weight by days in month. Default is True.

Returns

xarray.DataArray Seasonal means.

Source code in src/monet_stats/accessor.py
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
def seasonal_mean(self, dim: str = "time", weighted: bool = True) -> xr.DataArray:
    """
    Compute seasonal mean (DJF, MAM, JJA, SON).

    Parameters
    ----------
    dim : str, optional
        Dimension along which to compute the mean. Default is 'time'.
    weighted : bool, optional
        If True, weight by days in month. Default is True.

    Returns
    -------
    xarray.DataArray
        Seasonal means.
    """
    return analysis.seasonal_mean(self._obj, dim=dim, weighted=weighted)

taylor_statistics(obs, dim=None)

Calculate components required for a Taylor diagram (Aero Protocol).

Parameters

obs : xarray.DataArray Observed values (reference). dim : str or list of str, optional Dimension(s) along which to compute the statistics.

Returns

xarray.Dataset Dataset containing: - std_obs: Standard deviation of observations. - std_mod: Standard deviation of model predictions. - correlation: Pearson correlation coefficient.

Source code in src/monet_stats/accessor.py
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
def taylor_statistics(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.Dataset:
    """
    Calculate components required for a Taylor diagram (Aero Protocol).

    Parameters
    ----------
    obs : xarray.DataArray
        Observed values (reference).
    dim : str or list of str, optional
        Dimension(s) along which to compute the statistics.

    Returns
    -------
    xarray.Dataset
        Dataset containing:
        - std_obs: Standard deviation of observations.
        - std_mod: Standard deviation of model predictions.
        - correlation: Pearson correlation coefficient.
    """
    obs, mod = xr.align(obs, self._obj, join="inner")
    from .utils_stats import _resolve_axis_to_dim, _update_history

    d = _resolve_axis_to_dim(obs, dim)

    res = xr.Dataset(
        {
            "std_obs": obs.std(dim=d),
            "std_mod": mod.std(dim=d),
            "correlation": correlation_metrics.pearsonr(obs, mod, axis=dim),
        }
    )
    return _update_history(res, "Taylor statistics components")

verify(obs, dim=None)

Calculate a bundle of common evaluation metrics (Aero Protocol).

Parameters

obs : xarray.DataArray Observed values. dim : str or list of str, optional Dimension(s) along which to compute the metrics.

Returns

xarray.Dataset Dataset containing: MAE, RMSE, MB, R, IOA, NMB, MNB, MNE, NSE, and R2.

Source code in src/monet_stats/accessor.py
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
def verify(self, obs: xr.DataArray, dim: Optional[Union[str, List[str]]] = None) -> xr.Dataset:
    """
    Calculate a bundle of common evaluation metrics (Aero Protocol).

    Parameters
    ----------
    obs : xarray.DataArray
        Observed values.
    dim : str or list of str, optional
        Dimension(s) along which to compute the metrics.

    Returns
    -------
    xarray.Dataset
        Dataset containing: MAE, RMSE, MB, R, IOA, NMB, MNB, MNE, NSE, and R2.
    """
    metrics = {
        "MAE": error_metrics.MAE(obs, self._obj, axis=dim),
        "RMSE": error_metrics.RMSE(obs, self._obj, axis=dim),
        "MB": error_metrics.MB(obs, self._obj, axis=dim),
        "R": correlation_metrics.pearsonr(obs, self._obj, axis=dim),
        "IOA": error_metrics.IOA(obs, self._obj, axis=dim),
        "NMB": relative_metrics.NMB(obs, self._obj, axis=dim),
        "MNB": error_metrics.MNB(obs, self._obj, axis=dim),
        "MNE": error_metrics.MNE(obs, self._obj, axis=dim),
        "NSE": efficiency_metrics.NSE(obs, self._obj, axis=dim),
        "R2": correlation_metrics.R2(obs, self._obj, axis=dim),
    }
    res = xr.Dataset(metrics)
    from .utils_stats import _update_history

    return _update_history(res, "Verification metrics bundle (verify)")

weighted_spatial_mean(lat_dim='lat', lon_dim='lon', weights=None)

Compute area-weighted spatial mean.

Parameters

lat_dim : str, optional Name of the latitude dimension. Default is 'lat'. lon_dim : str, optional Name of the longitude dimension. Default is 'lon'. weights : xarray.DataArray or numpy.ndarray, optional Custom weights for the mean.

Returns

xarray.DataArray Area-weighted spatial mean.

Source code in src/monet_stats/accessor.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
def weighted_spatial_mean(
    self,
    lat_dim: str = "lat",
    lon_dim: str = "lon",
    weights: Optional[Union[xr.DataArray, np.ndarray]] = None,
) -> xr.DataArray:
    """
    Compute area-weighted spatial mean.

    Parameters
    ----------
    lat_dim : str, optional
        Name of the latitude dimension. Default is 'lat'.
    lon_dim : str, optional
        Name of the longitude dimension. Default is 'lon'.
    weights : xarray.DataArray or numpy.ndarray, optional
        Custom weights for the mean.

    Returns
    -------
    xarray.DataArray
        Area-weighted spatial mean.
    """
    return analysis.weighted_spatial_mean(self._obj, lat_dim=lat_dim, lon_dim=lon_dim, weights=weights)

MonetDatasetAccessor

Accessor for xarray.Dataset to provide MONET statistical methods.

Source code in src/monet_stats/accessor.py
 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
 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
 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
 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
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
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
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
1180
1181
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
@xr.register_dataset_accessor("monet_stats")
class MonetDatasetAccessor:
    """
    Accessor for xarray.Dataset to provide MONET statistical methods.
    """

    def __init__(self, xarray_obj: xr.Dataset) -> None:
        self._obj = xarray_obj

    def stats(
        self,
        obs_name: str = "Obs",
        mod_name: str = "Mod",
        threshold: float = 0.0,
        minval: Optional[float] = None,
        maxval: Optional[float] = None,
    ) -> dict:
        """
        Calculate summary statistics for observations and model results.

        Parameters
        ----------
        obs_name : str, optional
            Name of observation variable. Default is 'Obs'.
        mod_name : str, optional
            Name of model variable. Default is 'Mod'.
        threshold : float, optional
            Threshold for contingency scores. Default is 0.0.
        minval : float, optional
            Minimum value for filtering.
        maxval : float, optional
            Maximum value for filtering.

        Returns
        -------
        dict
            Dictionary of calculated statistics.
        """
        from . import stats

        return stats(
            self._obj,
            obs_name=obs_name,
            mod_name=mod_name,
            threshold=threshold,
            minval=minval,
            maxval=maxval,
        )

    def climatology(self, freq: str = "season", method: str = "mean", dim: str = "time") -> xr.Dataset:
        """
        Compute climatological statistics.

        Parameters
        ----------
        freq : str, optional
            Climatology frequency. Default is 'season'.
        method : str, optional
            Statistical method. Default is 'mean'.
        dim : str, optional
            Dimension along which to compute. Default is 'time'.

        Returns
        -------
        xarray.Dataset
            Climatological statistics.
        """
        return analysis.climatology(self._obj, freq=freq, method=method, dim=dim)

    def resample_data(self, freq: str = "MS", method: str = "mean", dim: str = "time", **kwargs: Any) -> xr.Dataset:
        """
        Resample data to a new temporal frequency.

        Parameters
        ----------
        freq : str, optional
            Resampling frequency. Default is 'MS'.
        method : str, optional
            Statistical method. Default is 'mean'.
        dim : str, optional
            Dimension along which to resample. Default is 'time'.
        **kwargs : Any
            Additional keyword arguments.

        Returns
        -------
        xarray.Dataset
            Resampled data.
        """
        return analysis.resample_data(self._obj, freq=freq, method=method, dim=dim, **kwargs)

    def kz_filter(self, m: int, k: int, dim: str = "time") -> xr.Dataset:
        """
        Apply Kolmogorov-Zurbenko (KZ) filter.

        Parameters
        ----------
        m : int
            Window size.
        k : int
            Number of iterations.
        dim : str, optional
            Dimension along which to apply. Default is 'time'.

        Returns
        -------
        xarray.Dataset
            Filtered data.
        """
        return analysis.kz_filter(self._obj, m=m, k=k, dim=dim)

    def diurnal_cycle(self, method: str = "mean", dim: str = "time") -> xr.Dataset:
        """
        Compute the diurnal cycle.

        Parameters
        ----------
        method : str, optional
            Statistical method. Default is 'mean'.
        dim : str, optional
            Dimension along which to compute. Default is 'time'.

        Returns
        -------
        xarray.Dataset
            Diurnal cycle.
        """
        return analysis.diurnal_cycle(self._obj, method=method, dim=dim)

    def rolling_mean_8h(self, dim: str = "time", min_periods: int = 6, center: bool = True) -> xr.Dataset:
        """
        Compute rolling 8-hour mean.

        Parameters
        ----------
        dim : str, optional
            Dimension along which to compute. Default is 'time'.
        min_periods : int, optional
            Minimum number of observations. Default is 6.
        center : bool, optional
            If True, center the labels. Default is True.

        Returns
        -------
        xarray.Dataset
            Rolling 8-hour mean.
        """
        return analysis.rolling_mean_8h(self._obj, dim=dim, min_periods=min_periods, center=center)

    def rolling_mean_24h(self, dim: str = "time", min_periods: int = 18, center: bool = True) -> xr.Dataset:
        """
        Compute rolling 24-hour mean.

        Parameters
        ----------
        dim : str, optional
            Dimension along which to compute. Default is 'time'.
        min_periods : int, optional
            Minimum number of observations. Default is 18.
        center : bool, optional
            If True, center the labels. Default is True.

        Returns
        -------
        xarray.Dataset
            Rolling 24-hour mean.
        """
        return analysis.rolling_mean_24h(self._obj, dim=dim, min_periods=min_periods, center=center)

    def mda1(self, dim: str = "time") -> xr.Dataset:
        """
        Compute Maximum Daily 1-hour Average (MDA1).

        Parameters
        ----------
        dim : str, optional
            Dimension along which to compute. Default is 'time'.

        Returns
        -------
        xarray.Dataset
            MDA1 values.
        """
        return analysis.mda1(self._obj, dim=dim)

    def mda8(self, dim: str = "time", min_periods: int = 6, center: bool = False) -> xr.Dataset:
        """
        Compute Maximum Daily 8-hour Average (MDA8).

        Parameters
        ----------
        dim : str, optional
            Dimension along which to compute. Default is 'time'.
        min_periods : int, optional
            Minimum number of observations. Default is 6.
        center : bool, optional
            Whether to center the window. Default is False.

        Returns
        -------
        xarray.Dataset
            MDA8 values.
        """
        return analysis.mda8(self._obj, dim=dim, min_periods=min_periods, center=center)

    def exceedance_count(self, threshold: float, dim: str = "time") -> xr.Dataset:
        """
        Count exceedances of a threshold.

        Parameters
        ----------
        threshold : float
            Threshold value.
        dim : str, optional
            Dimension along which to count. Default is 'time'.

        Returns
        -------
        xarray.Dataset
            Number of exceedances.
        """
        return analysis.exceedance_count(self._obj, threshold=threshold, dim=dim)

    def percentile(self, q: Union[float, List[float], np.ndarray], dim: str = "time", **kwargs: Any) -> xr.Dataset:
        """
        Compute percentiles.

        Parameters
        ----------
        q : float or list of float
            Percentile(s) (0-100).
        dim : str, optional
            Dimension over which to compute. Default is 'time'.
        **kwargs : Any
            Additional keyword arguments.

        Returns
        -------
        xarray.Dataset
            Computed percentiles.
        """
        return analysis.percentile(self._obj, q=q, dim=dim, **kwargs)

    def peak_timing(self, dim: str = "time") -> xr.Dataset:
        """
        Identify the coordinate value of the maximum.

        Parameters
        ----------
        dim : str, optional
            Dimension along which to find peak. Default is 'time'.

        Returns
        -------
        xarray.Dataset
            Coordinate values.
        """
        return analysis.peak_timing(self._obj, dim=dim)

    def weighted_spatial_mean(
        self,
        lat_dim: str = "lat",
        lon_dim: str = "lon",
        weights: Optional[Union[xr.DataArray, np.ndarray]] = None,
    ) -> xr.Dataset:
        """
        Compute area-weighted spatial mean.

        Parameters
        ----------
        lat_dim : str, optional
            Latitude dimension name. Default is 'lat'.
        lon_dim : str, optional
            Longitude dimension name. Default is 'lon'.
        weights : xarray.DataArray or numpy.ndarray, optional
            Custom weights.

        Returns
        -------
        xarray.Dataset
            Area-weighted spatial mean.
        """
        return analysis.weighted_spatial_mean(self._obj, lat_dim=lat_dim, lon_dim=lon_dim, weights=weights)

    def seasonal_mean(self, dim: str = "time", weighted: bool = True) -> xr.Dataset:
        """
        Compute seasonal mean (DJF, MAM, JJA, SON).

        Parameters
        ----------
        dim : str, optional
            Dimension along which to compute. Default is 'time'.
        weighted : bool, optional
            Weight by days in month. Default is True.

        Returns
        -------
        xarray.Dataset
            Seasonal means.
        """
        return analysis.seasonal_mean(self._obj, dim=dim, weighted=weighted)

    def monthly_climatology(self, dim: str = "time", method: str = "mean") -> xr.Dataset:
        """
        Compute monthly climatology.

        Parameters
        ----------
        dim : str, optional
            Dimension along which to compute. Default is 'time'.
        method : str, optional
            Statistical method. Default is 'mean'.

        Returns
        -------
        xarray.Dataset
            Monthly climatology.
        """
        return analysis.monthly_climatology(self._obj, dim=dim, method=method)

    def anomalies(self, freq: str = "month", dim: str = "time") -> xr.Dataset:
        """
        Compute anomalies by subtracting the climatology.

        Parameters
        ----------
        freq : str, optional
            Climatology frequency ('season', 'month', 'dayofyear', 'hour').
            Default is 'month'.
        dim : str, optional
            Dimension along which to compute the anomalies. Default is 'time'.

        Returns
        -------
        xarray.Dataset
            Anomalies.
        """
        return analysis.anomalies(self._obj, freq=freq, dim=dim)

    def detrend(self, method: str = "linear", dim: str = "time") -> xr.Dataset:
        """
        Remove trend from data.

        Parameters
        ----------
        method : str, optional
            Detrending method ('linear', 'constant'). Default is 'linear'.
        dim : str, optional
            Dimension along which to detrend. Default is 'time'.

        Returns
        -------
        xarray.Dataset
            Detrended data.
        """
        return analysis.detrend(self._obj, method=method, dim=dim)

    def optimize(self, target_mb: float = 100.0) -> xr.Dataset:
        """
        Optimize performance by ensuring laziness and recommended chunks (Aero Protocol).

        Parameters
        ----------
        target_mb : float, optional
            Target size for each chunk in Megabytes. Default is 100.0.

        Returns
        -------
        xarray.Dataset
            Optimized Dataset.
        """
        from .utils_stats import _update_history

        if not performance._has_dask():
            return _update_history(self._obj, "Optimization skipped (Dask not installed)")

        # Ensure data is lazy
        res = performance.apply_lazy_threshold(self._obj, threshold_mb=0.1)
        # Always calculate and apply recommended chunks for the target size
        recommendation = performance.get_chunk_recommendation(res, target_mb=target_mb)
        res = res.chunk(recommendation)

        return _update_history(res, f"Optimized for performance (target={target_mb}MB)")

    def rechunk(self, chunks: Optional[dict] = None) -> xr.Dataset:
        """
        Apply new chunks to the Dataset (Aero Protocol provenance tracking).

        Parameters
        ----------
        chunks : dict, optional
            New chunk sizes. If None, uses optimal recommendations (~100MB).

        Returns
        -------
        xarray.Dataset
            Rechunked Dataset.
        """
        from .utils_stats import _update_history

        if not performance._has_dask():
            return _update_history(self._obj, "Rechunking skipped (Dask not installed)")

        if chunks is None:
            chunks = performance.get_chunk_recommendation(self._obj)

        res = self._obj.chunk(chunks)

        return _update_history(res, f"Rechunked with {chunks}")

anomalies(freq='month', dim='time')

Compute anomalies by subtracting the climatology.

Parameters

freq : str, optional Climatology frequency ('season', 'month', 'dayofyear', 'hour'). Default is 'month'. dim : str, optional Dimension along which to compute the anomalies. Default is 'time'.

Returns

xarray.Dataset Anomalies.

Source code in src/monet_stats/accessor.py
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
def anomalies(self, freq: str = "month", dim: str = "time") -> xr.Dataset:
    """
    Compute anomalies by subtracting the climatology.

    Parameters
    ----------
    freq : str, optional
        Climatology frequency ('season', 'month', 'dayofyear', 'hour').
        Default is 'month'.
    dim : str, optional
        Dimension along which to compute the anomalies. Default is 'time'.

    Returns
    -------
    xarray.Dataset
        Anomalies.
    """
    return analysis.anomalies(self._obj, freq=freq, dim=dim)

climatology(freq='season', method='mean', dim='time')

Compute climatological statistics.

Parameters

freq : str, optional Climatology frequency. Default is 'season'. method : str, optional Statistical method. Default is 'mean'. dim : str, optional Dimension along which to compute. Default is 'time'.

Returns

xarray.Dataset Climatological statistics.

Source code in src/monet_stats/accessor.py
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
def climatology(self, freq: str = "season", method: str = "mean", dim: str = "time") -> xr.Dataset:
    """
    Compute climatological statistics.

    Parameters
    ----------
    freq : str, optional
        Climatology frequency. Default is 'season'.
    method : str, optional
        Statistical method. Default is 'mean'.
    dim : str, optional
        Dimension along which to compute. Default is 'time'.

    Returns
    -------
    xarray.Dataset
        Climatological statistics.
    """
    return analysis.climatology(self._obj, freq=freq, method=method, dim=dim)

detrend(method='linear', dim='time')

Remove trend from data.

Parameters

method : str, optional Detrending method ('linear', 'constant'). Default is 'linear'. dim : str, optional Dimension along which to detrend. Default is 'time'.

Returns

xarray.Dataset Detrended data.

Source code in src/monet_stats/accessor.py
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
def detrend(self, method: str = "linear", dim: str = "time") -> xr.Dataset:
    """
    Remove trend from data.

    Parameters
    ----------
    method : str, optional
        Detrending method ('linear', 'constant'). Default is 'linear'.
    dim : str, optional
        Dimension along which to detrend. Default is 'time'.

    Returns
    -------
    xarray.Dataset
        Detrended data.
    """
    return analysis.detrend(self._obj, method=method, dim=dim)

diurnal_cycle(method='mean', dim='time')

Compute the diurnal cycle.

Parameters

method : str, optional Statistical method. Default is 'mean'. dim : str, optional Dimension along which to compute. Default is 'time'.

Returns

xarray.Dataset Diurnal cycle.

Source code in src/monet_stats/accessor.py
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
def diurnal_cycle(self, method: str = "mean", dim: str = "time") -> xr.Dataset:
    """
    Compute the diurnal cycle.

    Parameters
    ----------
    method : str, optional
        Statistical method. Default is 'mean'.
    dim : str, optional
        Dimension along which to compute. Default is 'time'.

    Returns
    -------
    xarray.Dataset
        Diurnal cycle.
    """
    return analysis.diurnal_cycle(self._obj, method=method, dim=dim)

exceedance_count(threshold, dim='time')

Count exceedances of a threshold.

Parameters

threshold : float Threshold value. dim : str, optional Dimension along which to count. Default is 'time'.

Returns

xarray.Dataset Number of exceedances.

Source code in src/monet_stats/accessor.py
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
def exceedance_count(self, threshold: float, dim: str = "time") -> xr.Dataset:
    """
    Count exceedances of a threshold.

    Parameters
    ----------
    threshold : float
        Threshold value.
    dim : str, optional
        Dimension along which to count. Default is 'time'.

    Returns
    -------
    xarray.Dataset
        Number of exceedances.
    """
    return analysis.exceedance_count(self._obj, threshold=threshold, dim=dim)

kz_filter(m, k, dim='time')

Apply Kolmogorov-Zurbenko (KZ) filter.

Parameters

m : int Window size. k : int Number of iterations. dim : str, optional Dimension along which to apply. Default is 'time'.

Returns

xarray.Dataset Filtered data.

Source code in src/monet_stats/accessor.py
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
def kz_filter(self, m: int, k: int, dim: str = "time") -> xr.Dataset:
    """
    Apply Kolmogorov-Zurbenko (KZ) filter.

    Parameters
    ----------
    m : int
        Window size.
    k : int
        Number of iterations.
    dim : str, optional
        Dimension along which to apply. Default is 'time'.

    Returns
    -------
    xarray.Dataset
        Filtered data.
    """
    return analysis.kz_filter(self._obj, m=m, k=k, dim=dim)

mda1(dim='time')

Compute Maximum Daily 1-hour Average (MDA1).

Parameters

dim : str, optional Dimension along which to compute. Default is 'time'.

Returns

xarray.Dataset MDA1 values.

Source code in src/monet_stats/accessor.py
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
def mda1(self, dim: str = "time") -> xr.Dataset:
    """
    Compute Maximum Daily 1-hour Average (MDA1).

    Parameters
    ----------
    dim : str, optional
        Dimension along which to compute. Default is 'time'.

    Returns
    -------
    xarray.Dataset
        MDA1 values.
    """
    return analysis.mda1(self._obj, dim=dim)

mda8(dim='time', min_periods=6, center=False)

Compute Maximum Daily 8-hour Average (MDA8).

Parameters

dim : str, optional Dimension along which to compute. Default is 'time'. min_periods : int, optional Minimum number of observations. Default is 6. center : bool, optional Whether to center the window. Default is False.

Returns

xarray.Dataset MDA8 values.

Source code in src/monet_stats/accessor.py
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
def mda8(self, dim: str = "time", min_periods: int = 6, center: bool = False) -> xr.Dataset:
    """
    Compute Maximum Daily 8-hour Average (MDA8).

    Parameters
    ----------
    dim : str, optional
        Dimension along which to compute. Default is 'time'.
    min_periods : int, optional
        Minimum number of observations. Default is 6.
    center : bool, optional
        Whether to center the window. Default is False.

    Returns
    -------
    xarray.Dataset
        MDA8 values.
    """
    return analysis.mda8(self._obj, dim=dim, min_periods=min_periods, center=center)

monthly_climatology(dim='time', method='mean')

Compute monthly climatology.

Parameters

dim : str, optional Dimension along which to compute. Default is 'time'. method : str, optional Statistical method. Default is 'mean'.

Returns

xarray.Dataset Monthly climatology.

Source code in src/monet_stats/accessor.py
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
def monthly_climatology(self, dim: str = "time", method: str = "mean") -> xr.Dataset:
    """
    Compute monthly climatology.

    Parameters
    ----------
    dim : str, optional
        Dimension along which to compute. Default is 'time'.
    method : str, optional
        Statistical method. Default is 'mean'.

    Returns
    -------
    xarray.Dataset
        Monthly climatology.
    """
    return analysis.monthly_climatology(self._obj, dim=dim, method=method)

optimize(target_mb=100.0)

Optimize performance by ensuring laziness and recommended chunks (Aero Protocol).

Parameters

target_mb : float, optional Target size for each chunk in Megabytes. Default is 100.0.

Returns

xarray.Dataset Optimized Dataset.

Source code in src/monet_stats/accessor.py
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
def optimize(self, target_mb: float = 100.0) -> xr.Dataset:
    """
    Optimize performance by ensuring laziness and recommended chunks (Aero Protocol).

    Parameters
    ----------
    target_mb : float, optional
        Target size for each chunk in Megabytes. Default is 100.0.

    Returns
    -------
    xarray.Dataset
        Optimized Dataset.
    """
    from .utils_stats import _update_history

    if not performance._has_dask():
        return _update_history(self._obj, "Optimization skipped (Dask not installed)")

    # Ensure data is lazy
    res = performance.apply_lazy_threshold(self._obj, threshold_mb=0.1)
    # Always calculate and apply recommended chunks for the target size
    recommendation = performance.get_chunk_recommendation(res, target_mb=target_mb)
    res = res.chunk(recommendation)

    return _update_history(res, f"Optimized for performance (target={target_mb}MB)")

peak_timing(dim='time')

Identify the coordinate value of the maximum.

Parameters

dim : str, optional Dimension along which to find peak. Default is 'time'.

Returns

xarray.Dataset Coordinate values.

Source code in src/monet_stats/accessor.py
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
def peak_timing(self, dim: str = "time") -> xr.Dataset:
    """
    Identify the coordinate value of the maximum.

    Parameters
    ----------
    dim : str, optional
        Dimension along which to find peak. Default is 'time'.

    Returns
    -------
    xarray.Dataset
        Coordinate values.
    """
    return analysis.peak_timing(self._obj, dim=dim)

percentile(q, dim='time', **kwargs)

Compute percentiles.

Parameters

q : float or list of float Percentile(s) (0-100). dim : str, optional Dimension over which to compute. Default is 'time'. **kwargs : Any Additional keyword arguments.

Returns

xarray.Dataset Computed percentiles.

Source code in src/monet_stats/accessor.py
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
def percentile(self, q: Union[float, List[float], np.ndarray], dim: str = "time", **kwargs: Any) -> xr.Dataset:
    """
    Compute percentiles.

    Parameters
    ----------
    q : float or list of float
        Percentile(s) (0-100).
    dim : str, optional
        Dimension over which to compute. Default is 'time'.
    **kwargs : Any
        Additional keyword arguments.

    Returns
    -------
    xarray.Dataset
        Computed percentiles.
    """
    return analysis.percentile(self._obj, q=q, dim=dim, **kwargs)

rechunk(chunks=None)

Apply new chunks to the Dataset (Aero Protocol provenance tracking).

Parameters

chunks : dict, optional New chunk sizes. If None, uses optimal recommendations (~100MB).

Returns

xarray.Dataset Rechunked Dataset.

Source code in src/monet_stats/accessor.py
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
def rechunk(self, chunks: Optional[dict] = None) -> xr.Dataset:
    """
    Apply new chunks to the Dataset (Aero Protocol provenance tracking).

    Parameters
    ----------
    chunks : dict, optional
        New chunk sizes. If None, uses optimal recommendations (~100MB).

    Returns
    -------
    xarray.Dataset
        Rechunked Dataset.
    """
    from .utils_stats import _update_history

    if not performance._has_dask():
        return _update_history(self._obj, "Rechunking skipped (Dask not installed)")

    if chunks is None:
        chunks = performance.get_chunk_recommendation(self._obj)

    res = self._obj.chunk(chunks)

    return _update_history(res, f"Rechunked with {chunks}")

resample_data(freq='MS', method='mean', dim='time', **kwargs)

Resample data to a new temporal frequency.

Parameters

freq : str, optional Resampling frequency. Default is 'MS'. method : str, optional Statistical method. Default is 'mean'. dim : str, optional Dimension along which to resample. Default is 'time'. **kwargs : Any Additional keyword arguments.

Returns

xarray.Dataset Resampled data.

Source code in src/monet_stats/accessor.py
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
def resample_data(self, freq: str = "MS", method: str = "mean", dim: str = "time", **kwargs: Any) -> xr.Dataset:
    """
    Resample data to a new temporal frequency.

    Parameters
    ----------
    freq : str, optional
        Resampling frequency. Default is 'MS'.
    method : str, optional
        Statistical method. Default is 'mean'.
    dim : str, optional
        Dimension along which to resample. Default is 'time'.
    **kwargs : Any
        Additional keyword arguments.

    Returns
    -------
    xarray.Dataset
        Resampled data.
    """
    return analysis.resample_data(self._obj, freq=freq, method=method, dim=dim, **kwargs)

rolling_mean_24h(dim='time', min_periods=18, center=True)

Compute rolling 24-hour mean.

Parameters

dim : str, optional Dimension along which to compute. Default is 'time'. min_periods : int, optional Minimum number of observations. Default is 18. center : bool, optional If True, center the labels. Default is True.

Returns

xarray.Dataset Rolling 24-hour mean.

Source code in src/monet_stats/accessor.py
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
def rolling_mean_24h(self, dim: str = "time", min_periods: int = 18, center: bool = True) -> xr.Dataset:
    """
    Compute rolling 24-hour mean.

    Parameters
    ----------
    dim : str, optional
        Dimension along which to compute. Default is 'time'.
    min_periods : int, optional
        Minimum number of observations. Default is 18.
    center : bool, optional
        If True, center the labels. Default is True.

    Returns
    -------
    xarray.Dataset
        Rolling 24-hour mean.
    """
    return analysis.rolling_mean_24h(self._obj, dim=dim, min_periods=min_periods, center=center)

rolling_mean_8h(dim='time', min_periods=6, center=True)

Compute rolling 8-hour mean.

Parameters

dim : str, optional Dimension along which to compute. Default is 'time'. min_periods : int, optional Minimum number of observations. Default is 6. center : bool, optional If True, center the labels. Default is True.

Returns

xarray.Dataset Rolling 8-hour mean.

Source code in src/monet_stats/accessor.py
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
def rolling_mean_8h(self, dim: str = "time", min_periods: int = 6, center: bool = True) -> xr.Dataset:
    """
    Compute rolling 8-hour mean.

    Parameters
    ----------
    dim : str, optional
        Dimension along which to compute. Default is 'time'.
    min_periods : int, optional
        Minimum number of observations. Default is 6.
    center : bool, optional
        If True, center the labels. Default is True.

    Returns
    -------
    xarray.Dataset
        Rolling 8-hour mean.
    """
    return analysis.rolling_mean_8h(self._obj, dim=dim, min_periods=min_periods, center=center)

seasonal_mean(dim='time', weighted=True)

Compute seasonal mean (DJF, MAM, JJA, SON).

Parameters

dim : str, optional Dimension along which to compute. Default is 'time'. weighted : bool, optional Weight by days in month. Default is True.

Returns

xarray.Dataset Seasonal means.

Source code in src/monet_stats/accessor.py
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
def seasonal_mean(self, dim: str = "time", weighted: bool = True) -> xr.Dataset:
    """
    Compute seasonal mean (DJF, MAM, JJA, SON).

    Parameters
    ----------
    dim : str, optional
        Dimension along which to compute. Default is 'time'.
    weighted : bool, optional
        Weight by days in month. Default is True.

    Returns
    -------
    xarray.Dataset
        Seasonal means.
    """
    return analysis.seasonal_mean(self._obj, dim=dim, weighted=weighted)

stats(obs_name='Obs', mod_name='Mod', threshold=0.0, minval=None, maxval=None)

Calculate summary statistics for observations and model results.

Parameters

obs_name : str, optional Name of observation variable. Default is 'Obs'. mod_name : str, optional Name of model variable. Default is 'Mod'. threshold : float, optional Threshold for contingency scores. Default is 0.0. minval : float, optional Minimum value for filtering. maxval : float, optional Maximum value for filtering.

Returns

dict Dictionary of calculated statistics.

Source code in src/monet_stats/accessor.py
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
def stats(
    self,
    obs_name: str = "Obs",
    mod_name: str = "Mod",
    threshold: float = 0.0,
    minval: Optional[float] = None,
    maxval: Optional[float] = None,
) -> dict:
    """
    Calculate summary statistics for observations and model results.

    Parameters
    ----------
    obs_name : str, optional
        Name of observation variable. Default is 'Obs'.
    mod_name : str, optional
        Name of model variable. Default is 'Mod'.
    threshold : float, optional
        Threshold for contingency scores. Default is 0.0.
    minval : float, optional
        Minimum value for filtering.
    maxval : float, optional
        Maximum value for filtering.

    Returns
    -------
    dict
        Dictionary of calculated statistics.
    """
    from . import stats

    return stats(
        self._obj,
        obs_name=obs_name,
        mod_name=mod_name,
        threshold=threshold,
        minval=minval,
        maxval=maxval,
    )

weighted_spatial_mean(lat_dim='lat', lon_dim='lon', weights=None)

Compute area-weighted spatial mean.

Parameters

lat_dim : str, optional Latitude dimension name. Default is 'lat'. lon_dim : str, optional Longitude dimension name. Default is 'lon'. weights : xarray.DataArray or numpy.ndarray, optional Custom weights.

Returns

xarray.Dataset Area-weighted spatial mean.

Source code in src/monet_stats/accessor.py
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
def weighted_spatial_mean(
    self,
    lat_dim: str = "lat",
    lon_dim: str = "lon",
    weights: Optional[Union[xr.DataArray, np.ndarray]] = None,
) -> xr.Dataset:
    """
    Compute area-weighted spatial mean.

    Parameters
    ----------
    lat_dim : str, optional
        Latitude dimension name. Default is 'lat'.
    lon_dim : str, optional
        Longitude dimension name. Default is 'lon'.
    weights : xarray.DataArray or numpy.ndarray, optional
        Custom weights.

    Returns
    -------
    xarray.Dataset
        Area-weighted spatial mean.
    """
    return analysis.weighted_spatial_mean(self._obj, lat_dim=lat_dim, lon_dim=lon_dim, weights=weights)

Utility Functions

Utility Functions for Statistics (Aero Protocol Compliant).

angular_difference(angle1, angle2, units='degrees')

Calculate the smallest angular difference between two angles (Aero Protocol).

Backend-agnostic (supports NumPy and Xarray/Dask).

Parameters

angle1 : ArrayLike First angle(s). angle2 : ArrayLike Second angle(s). units : str, optional Units of angles ('degrees' or 'radians'). Default is 'degrees'.

Returns

Any Smallest angular difference between the two angles.

Source code in src/monet_stats/utils_stats.py
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
def angular_difference(angle1: ArrayLike, angle2: ArrayLike, units: str = "degrees") -> Any:
    """
    Calculate the smallest angular difference between two angles (Aero Protocol).

    Backend-agnostic (supports NumPy and Xarray/Dask).

    Parameters
    ----------
    angle1 : ArrayLike
        First angle(s).
    angle2 : ArrayLike
        Second angle(s).
    units : str, optional
        Units of angles ('degrees' or 'radians'). Default is 'degrees'.

    Returns
    -------
    Any
        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 isinstance(angle1, (xr.DataArray, xr.Dataset)) or isinstance(angle2, (xr.DataArray, xr.Dataset)):
        if isinstance(angle1, (xr.DataArray, xr.Dataset)) and isinstance(angle2, (xr.DataArray, xr.Dataset)):
            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.asanyarray(angle1)
    angle2_arr = np.asanyarray(angle2)
    diff = np.abs(angle1_arr - angle2_arr)
    return np.minimum(diff, max_val - diff)

circlebias(b)

Circular bias (wrapped to [-180, 180] degrees) (Aero Protocol).

Handles both dense and masked arrays, as well as Xarray/Dask objects.

Parameters

b : ArrayLike Difference between two wind directions (degrees).

Returns

Any Circularly wrapped difference (degrees).

Examples

circlebias(190) -170 circlebias(-190) 170

Source code in src/monet_stats/utils_stats.py
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
def circlebias(b: ArrayLike) -> Any:
    """
    Circular bias (wrapped to [-180, 180] degrees) (Aero Protocol).

    Handles both dense and masked arrays, as well as Xarray/Dask objects.

    Parameters
    ----------
    b : ArrayLike
        Difference between two wind directions (degrees).

    Returns
    -------
    Any
        Circularly wrapped difference (degrees).

    Examples
    --------
    >>> circlebias(190)
    -170
    >>> circlebias(-190)
    170
    """
    if isinstance(b, (xr.DataArray, xr.Dataset)):
        res = (b + 180) % 360 - 180
        return _update_history(res, "circlebias")

    # Handle both dense and masked numpy arrays
    b_arr = np.ma.masked_invalid(b)
    res_arr = (b_arr + 180) % 360 - 180

    if not np.ma.is_masked(res_arr) and not isinstance(b, np.ma.MaskedArray):
        if np.issubdtype(res_arr.dtype, np.floating):
            return res_arr.filled(np.nan)
        return np.ma.getdata(res_arr)

    return res_arr

circlebias_m(b)

Robust circular bias for wind direction (Alias for circlebias).

Parameters

b : ArrayLike Difference between two wind directions (degrees).

Returns

Any Circularly wrapped difference.

Source code in src/monet_stats/utils_stats.py
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
def circlebias_m(b: ArrayLike) -> Any:
    """
    Robust circular bias for wind direction (Alias for circlebias).

    Parameters
    ----------
    b : ArrayLike
        Difference between two wind directions (degrees).

    Returns
    -------
    Any
        Circularly wrapped difference.
    """
    return circlebias(b)

correlation(x, y, axis=None)

Calculate Pearson correlation coefficient (Alias for correlation_metrics.pearsonr).

Parameters

x : Union[np.ndarray, xr.DataArray] First variable. y : Union[np.ndarray, xr.DataArray] Second variable. axis : Union[int, str, 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
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
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 (Alias for correlation_metrics.pearsonr).

    Parameters
    ----------
    x : Union[np.ndarray, xr.DataArray]
        First variable.
    y : Union[np.ndarray, xr.DataArray]
        Second variable.
    axis : Union[int, str, 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 isinstance(res, (xr.DataArray, xr.Dataset)):
        return _update_history(res, "correlation")
    return res

mae(obs, mod, axis=None)

Calculate Mean Absolute Error (Alias for error_metrics.MAE).

Parameters

obs : Union[np.ndarray, xr.DataArray] Observed values. mod : Union[np.ndarray, xr.DataArray] Model or predicted values. axis : Union[int, str, 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
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
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 (Alias for error_metrics.MAE).

    Parameters
    ----------
    obs : Union[np.ndarray, xr.DataArray]
        Observed values.
    mod : Union[np.ndarray, xr.DataArray]
        Model or predicted values.
    axis : Union[int, str, 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 isinstance(res, (xr.DataArray, xr.Dataset)):
        return _update_history(res, "mae")
    return res

matchedcompressed(a1, a2)

Return compressed (non-masked) values from two matched arrays.

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 : ArrayLike First input array. a2 : ArrayLike Second input array.

Returns

Tuple[np.ndarray, np.ndarray] Tuple of (a1_compressed, a2_compressed), both 1D arrays of valid values.

Examples

import numpy as np a = np.array([1, np.nan, 3]) b = np.array([4, 5, 6]) matchedcompressed(a, b) (array([1., 3.]), array([4., 6.]))

Source code in src/monet_stats/utils_stats.py
 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
108
109
110
111
112
113
def matchedcompressed(a1: ArrayLike, a2: ArrayLike) -> Tuple[np.ndarray, np.ndarray]:
    """
    Return compressed (non-masked) values from two matched arrays.

    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 : ArrayLike
        First input array.
    a2 : ArrayLike
        Second input array.

    Returns
    -------
    Tuple[np.ndarray, np.ndarray]
        Tuple of (a1_compressed, a2_compressed), both 1D arrays of valid values.

    Examples
    --------
    >>> import numpy as np
    >>> a = np.array([1, np.nan, 3])
    >>> b = np.array([4, 5, 6])
    >>> matchedcompressed(a, b)
    (array([1., 3.]), array([4., 6.]))
    """
    # Handle Xarray objects by extracting values (triggers computation for Dask)
    if isinstance(a1, (xr.DataArray, xr.Dataset)):
        if hasattr(a1, "data") and hasattr(a1.data, "chunks"):
            warnings.warn(
                "matchedcompressed triggered computation on Dask-backed array. "
                "Consider using backend-agnostic xarray operations instead.",
                UserWarning,
                stacklevel=2,
            )
        a1 = a1.values
    if isinstance(a2, (xr.DataArray, xr.Dataset)):
        if hasattr(a2, "data") and hasattr(a2.data, "chunks"):
            warnings.warn(
                "matchedcompressed triggered computation on Dask-backed array. "
                "Consider using backend-agnostic xarray operations instead.",
                UserWarning,
                stacklevel=2,
            )
        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 by truncating both to the minimum size
    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 arrays or align Xarray objects (Aero Protocol).

Parameters

a1 : Any First input array or DataArray. a2 : Any Second input array or DataArray.

Returns

Tuple[Any, Any] Tuple of (a1_matched, a2_matched).

Source code in src/monet_stats/utils_stats.py
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
def matchmasks(a1: Any, a2: Any) -> Tuple[Any, Any]:
    """
    Match and combine masks from two arrays or align Xarray objects (Aero Protocol).

    Parameters
    ----------
    a1 : Any
        First input array or DataArray.
    a2 : Any
        Second input array or DataArray.

    Returns
    -------
    Tuple[Any, Any]
        Tuple of (a1_matched, a2_matched).
    """
    if isinstance(a1, (xr.DataArray, xr.Dataset)) and isinstance(a2, (xr.DataArray, xr.Dataset)):
        return xr.align(a1, a2, join="inner")

    a1_arr = np.asanyarray(a1)
    a2_arr = np.asanyarray(a2)

    # Unify mask handling for numpy
    a1_m = np.ma.masked_invalid(a1_arr)
    a2_m = np.ma.masked_invalid(a2_arr)

    common_mask = np.ma.getmaskarray(a1_m) | np.ma.getmaskarray(a2_m)
    return np.ma.masked_where(common_mask, a1_m), np.ma.masked_where(common_mask, a2_m)

rmse(obs, mod, axis=None)

Calculate Root Mean Square Error (Alias for error_metrics.RMSE).

Parameters

obs : Union[np.ndarray, xr.DataArray] Observed values. mod : Union[np.ndarray, xr.DataArray] Model or predicted values. axis : Union[int, str, Iterable], optional Axis 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
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
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 (Alias for error_metrics.RMSE).

    Parameters
    ----------
    obs : Union[np.ndarray, xr.DataArray]
        Observed values.
    mod : Union[np.ndarray, xr.DataArray]
        Model or predicted values.
    axis : Union[int, str, Iterable], optional
        Axis 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 isinstance(res, (xr.DataArray, xr.Dataset)):
        return _update_history(res, "rmse")
    return res

Visualization

Visualization utilities for the MONET Stats package (Aero Protocol Compliant).

This module implements the "Two-Track Rule" for scientific visualization: - Track A (Publication): Static quality using Matplotlib and Cartopy. - Track B (Exploration): Interactive exploration using HvPlot and GeoViews.

plot_spatial(da, method='matplotlib', lat_dim='lat', lon_dim='lon', title=None, cmap='viridis', **kwargs)

Plot spatial data following the Aero Protocol's Two-Track Rule.

Parameters

da : xarray.DataArray The spatial data to plot. Must have latitude and longitude coordinates. method : str, optional The plotting track to use: - 'matplotlib' (Track A): Static publication quality. - 'hvplot' (Track B): Interactive exploration. Default is 'matplotlib'. lat_dim : str, optional Name of the latitude dimension/coordinate. Default is 'lat'. lon_dim : str, optional Name of the longitude dimension/coordinate. Default is 'lon'. title : str, optional Title for the plot. cmap : str, optional Colormap to use. Default is 'viridis'. **kwargs : Any Additional keyword arguments passed to the underlying plotting function. For 'matplotlib', these are passed to da.plot(). For 'hvplot', these are passed to da.hvplot.quadmesh().

Returns

Any The plot object (matplotlib.axes.Axes or holoviews.element.Element).

Raises

ValueError If an unknown method is specified. ImportError If the required libraries for the chosen track are missing.

Examples

import xarray as xr import numpy as np da = xr.DataArray(np.random.rand(10, 10), ... coords={'lat': np.arange(10), 'lon': np.arange(10)}, ... dims=('lat', 'lon'))

Track A (Static)

ax = plot_spatial(da, method='matplotlib')

Track B (Interactive)

plot = plot_spatial(da, method='hvplot')

Source code in src/monet_stats/visualize.py
 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
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
def plot_spatial(
    da: xr.DataArray,
    method: str = "matplotlib",
    lat_dim: str = "lat",
    lon_dim: str = "lon",
    title: Optional[str] = None,
    cmap: str = "viridis",
    **kwargs: Any,
) -> Any:
    """
    Plot spatial data following the Aero Protocol's Two-Track Rule.

    Parameters
    ----------
    da : xarray.DataArray
        The spatial data to plot. Must have latitude and longitude coordinates.
    method : str, optional
        The plotting track to use:
        - 'matplotlib' (Track A): Static publication quality.
        - 'hvplot' (Track B): Interactive exploration.
        Default is 'matplotlib'.
    lat_dim : str, optional
        Name of the latitude dimension/coordinate. Default is 'lat'.
    lon_dim : str, optional
        Name of the longitude dimension/coordinate. Default is 'lon'.
    title : str, optional
        Title for the plot.
    cmap : str, optional
        Colormap to use. Default is 'viridis'.
    **kwargs : Any
        Additional keyword arguments passed to the underlying plotting function.
        For 'matplotlib', these are passed to `da.plot()`.
        For 'hvplot', these are passed to `da.hvplot.quadmesh()`.

    Returns
    -------
    Any
        The plot object (matplotlib.axes.Axes or holoviews.element.Element).

    Raises
    ------
    ValueError
        If an unknown method is specified.
    ImportError
        If the required libraries for the chosen track are missing.

    Examples
    --------
    >>> import xarray as xr
    >>> import numpy as np
    >>> da = xr.DataArray(np.random.rand(10, 10),
    ...                   coords={'lat': np.arange(10), 'lon': np.arange(10)},
    ...                   dims=('lat', 'lon'))
    >>> # Track A (Static)
    >>> ax = plot_spatial(da, method='matplotlib')
    >>> # Track B (Interactive)
    >>> plot = plot_spatial(da, method='hvplot')
    """
    if method == "matplotlib":
        try:
            import cartopy.crs as ccrs
            import matplotlib.pyplot as plt
        except ImportError:
            raise ImportError(
                "Track A (matplotlib) requires 'matplotlib' and 'cartopy'. "
                "Install them with 'pip install monet-stats[viz]'."
            )

        # Ensure projection is set in kwargs or defaults to PlateCarree
        projection = kwargs.pop("projection", ccrs.PlateCarree())
        transform = kwargs.pop("transform", ccrs.PlateCarree())

        if "ax" not in kwargs:
            fig = plt.figure(figsize=kwargs.pop("figsize", (10, 6)))
            ax = fig.add_subplot(1, 1, 1, projection=projection)
            kwargs["ax"] = ax
        else:
            ax = kwargs["ax"]

        plot = da.plot(transform=transform, cmap=cmap, **kwargs)

        if hasattr(ax, "coastlines"):
            ax.coastlines()
        if hasattr(ax, "gridlines"):
            ax.gridlines(draw_labels=True)

        if title:
            ax.set_title(title)

        _update_history(da, f"Plotted spatial data using Track A (matplotlib, projection={projection})")
        return ax

    elif method == "hvplot":
        try:
            import hvplot.xarray  # noqa: F401
        except ImportError:
            raise ImportError(
                "Track B (hvplot) requires 'hvplot' and 'geoviews'. Install them with 'pip install monet-stats[viz]'."
            )

        # Aero Protocol mandatory for large grids
        rasterize = kwargs.pop("rasterize", True)
        geo = kwargs.pop("geo", True)

        plot = da.hvplot.quadmesh(
            x=lon_dim,
            y=lat_dim,
            geo=geo,
            rasterize=rasterize,
            cmap=cmap,
            title=title,
            **kwargs,
        )

        _update_history(da, "Plotted spatial data using Track B (hvplot, rasterize=True)")
        return plot

    else:
        raise ValueError(f"Unknown plotting method: {method}. Must be 'matplotlib' or 'hvplot'.")

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.