Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 26 additions & 10 deletions src/scores/continuous/standard_impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,13 +282,13 @@ def mean_error(


def additive_bias(
fcst: XarrayLike,
obs: XarrayLike,
fcst: FlexibleArrayType,
obs: FlexibleArrayType,
*,
reduce_dims: Optional[FlexibleDimensionTypes] = None,
preserve_dims: Optional[FlexibleDimensionTypes] = None,
weights: Optional[XarrayLike] = None,
) -> XarrayLike:
weights: Optional[xr.DataArray] = None,
) -> FlexibleArrayType:
"""
Calculates the additive bias which is also sometimes called the mean error.

Expand Down Expand Up @@ -327,14 +327,30 @@ def additive_bias(
References:
- https://jwgfvr.github.io/forecastverification/index.html#meanerror

Notes:
- For xarray inputs, dimension reduction and optional weights are supported.
- For pandas/numpy inputs, reduction is not supported (result is the mean over all values)
and weights must be None.

"""
# Note - mean error call this function
reduce_dims = scores.utils.gather_dimensions(
fcst.dims, obs.dims, reduce_dims=reduce_dims, preserve_dims=preserve_dims
)
error = fcst - obs

score = aggregate(error, reduce_dims=reduce_dims, weights=weights)
fcst_is_xr = is_xarraylike(fcst)
obs_is_xr = is_xarraylike(obs)

if not (fcst_is_xr and obs_is_xr) and weights is not None:
raise ValueError("If `fcst` and `obs` are not xarray objects, `weights` must be None.")

if fcst_is_xr:
reduce_dims = scores.utils.gather_dimensions(
fcst.dims, obs.dims, reduce_dims=reduce_dims, preserve_dims=preserve_dims
)

error = fcst - obs # type: ignore

if is_xarraylike(error):
score = aggregate(error, reduce_dims=reduce_dims, weights=weights)
else:
score = error.mean()

return score

Expand Down
27 changes: 27 additions & 0 deletions src/scores/pandas/continuous.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,3 +110,30 @@ def mae(

"""
return __continuous.mae(fcst, obs, is_angular=is_angular)


def additive_bias(
fcst: PandasType,
obs: PandasType,
) -> PandasType:
"""Calculates the additive bias (mean error) from forecast and observed data.

A detailed explanation is on https://scores.readthedocs.io/en/stable/tutorials/Additive_and_multiplicative_bias.html

.. math ::
\\frac{1}{n} \\sum_{i=1}^n (\\text{forecast}_i - \\text{observed}_i)

Notes:
Dimensional reduction and weights are not supported for pandas and the user should
convert their data to xarray to use `reduce_dims`, `preserve_dims`, or `weights`.

Args:
fcst: Forecast or predicted variables in pandas.
obs: Observed variables in pandas.

Returns:
pandas.Series: An object containing a single floating point number representing
the additive bias for the supplied data. All dimensions will be reduced.

"""
return __continuous.additive_bias(fcst, obs) # type: ignore
9 changes: 9 additions & 0 deletions tests/continuous/test_standard.py
Original file line number Diff line number Diff line change
Expand Up @@ -811,6 +811,15 @@ def test_additive_bias(fcst, obs, reduce_dims, preserve_dims, weights, expected)
xr.testing.assert_equal(result, result2)


def test_additive_bias_raises_when_not_xarray_and_weights_given():
fcst = np.array([1, 2, 3])
obs = np.array([1, 2, 3])
weights = xr.DataArray([1, 2, 3])

with pytest.raises(ValueError):
scores.continuous.additive_bias(fcst=fcst, obs=obs, weights=weights)


def test_additive_bias_dask():
"""
Tests that continuous.additive_bias works with Dask
Expand Down
17 changes: 17 additions & 0 deletions tests/pandas/test_continuous.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
# pylint: disable=missing-function-docstring
# pylint: disable=line-too-long

import numbers

import numpy as np
import pandas as pd
import pytest
Expand Down Expand Up @@ -121,3 +123,18 @@ def test_mae_dataframe():
result = scores.continuous.mae(df["fcst"], df["obs"])
assert isinstance(result, float)
assert round(result, PRECISION) == expected


# Additive Bias (Mean Error)


def test_additive_bias_pandas_series():
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since you're expanding the input types for additive_bias you need to test for xarray inputs as well.

For 100% test coverage you'll need to check the exception is correctly raised.

Something like

 with pytest.raises(ValueError):
    scores.continuous.additive_bias(fcst=fcst, obs=obs, weights=xr.DataArray([1,2,3]))

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done the test

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@John-Sharples why do we need this in the pandas-specific API? Is the idea it's xarray plus pandas, or just pandas only?

Copy link
Contributor

@John-Sharples John-Sharples Feb 13, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My mistake, in putting it here it probably belongs in tests/continuous/test_standard.py

fcst = pd.Series([1, 3, 1, 3, 2, 2, 2, 1, 1, 2, 3])
obs = pd.Series([1, 1, 1, 2, 1, 2, 1, 1, 1, 3, 1])

expected = 0.5455

result = scores.continuous.additive_bias(fcst=fcst, obs=obs)

assert isinstance(result, numbers.Real)
assert round(float(result), PRECISION) == expected