Source code for openstef_beam.metrics.metrics_helpers

# SPDX-FileCopyrightText: 2025 Contributors to the OpenSTEF project <openstef@lfenergy.org>
#
# SPDX-License-Identifier: MPL-2.0

"""Helper functions shared between probabilistic and deterministic metrics."""

from collections.abc import Sequence

import numpy as np
import numpy.typing as npt
from pydantic import Field

from openstef_core.base_model import BaseConfig
from openstef_core.types import Quantile


[docs] class SampleWeighter(BaseConfig): """Weights samples by their magnitude relative to a scale, clipped to ``[a_min, a_max]``.""" a_min: float = Field(default=0.1, description="Minimum sample weight.") a_max: float = Field(default=1.0, description="Maximum sample weight.") exponent: float = Field(default=1.0, description="Exponent for sample weight calculation.")
[docs] def calculate_weights( self, values: npt.NDArray[np.floating], scale: float | npt.NDArray[np.floating], ) -> npt.NDArray[np.floating]: """Calculate weights for ``values`` given a scalar or per-sample ``scale``.""" return np.clip(np.abs(values / scale) ** self.exponent, a_min=self.a_min, a_max=self.a_max)
[docs] def equals_zero(number: float) -> bool: """Check if a floating-point number is effectively zero, considering floating-point precision.""" return bool(np.isclose(number, 0.0, rtol=1e-09, atol=1e-09))
[docs] def skill_score(score: float, reference_score: float, *, as_percentage: bool = True) -> float: """Calculate the skill of a score relative to a reference score. A skill score expresses how much better a forecast is than a reference forecast. It is only meaningful for non-negative metrics where lower values are better, such as CRPS or MAE. Interpretation: - Equal to the reference: 0 - Perfect forecast (score of 0): 1 (or 100%) - Twice as accurate as the reference: 0.5 (or 50%) - Worse than the reference: negative Args: score: The score of the evaluated forecast. reference_score: The score of the reference forecast. as_percentage: Whether to express the result as a percentage instead of a fraction. Returns: The skill score. Returns NaN if either input is NaN or if the reference score is zero. Example: Compare a forecast against a reference forecast >>> skill_score(0.5, 1.0) 50.0 >>> skill_score(1.0, 1.0) 0.0 >>> skill_score(2.0, 1.0) -100.0 >>> skill_score(0.5, 1.0, as_percentage=False) 0.5 """ if np.isnan(score) or np.isnan(reference_score) or equals_zero(reference_score): return float("NaN") skill = 1.0 - score / reference_score return float(skill * 100.0) if as_percentage else float(skill)
[docs] def represented_interval_weights( quantiles: Sequence[Quantile], ) -> npt.NDArray[np.floating]: """Calculate the probability interval each quantile represents on [0, 1]. Interval boundaries are placed at the midpoints between consecutive quantiles, with the outer edges fixed at 0 and 1. Each quantile is weighted by the width of its interval. Args: quantiles: Quantile levels with shape (num_quantiles,). Must be sorted in ascending order and contain values in (0, 1). Returns: The interval weights with shape (num_quantiles,). Weights are non-negative and sum to 1. Example: Unevenly spaced quantiles get different weights >>> import numpy as np >>> quantiles = np.array([0.05, 0.1, 0.5, 0.9, 0.95]) >>> represented_interval_weights(quantiles) array([0.075, 0.225, 0.4 , 0.225, 0.075]) """ q = np.asarray(quantiles, dtype=float).reshape(-1) boundaries = np.empty(len(q) + 1, dtype=float) boundaries[0] = 0.0 boundaries[-1] = 1.0 boundaries[1:-1] = 0.5 * (q[:-1] + q[1:]) return np.diff(boundaries)
[docs] def weighted_mean_error( errors: npt.NDArray[np.floating], sample_weights: npt.NDArray[np.floating] | None = None, *, allow_nan: bool = False, ) -> float: """Calculate the weighted mean of per-sample errors. Args: errors: Per-sample errors with shape (num_samples,), e.g. absolute or squared errors. sample_weights: Optional weights for each sample with shape (num_samples,). If None, all samples are weighted equally. allow_nan: If True, NaN errors are dropped together with their weights. If False, any NaN error results in a NaN mean. Returns: The weighted mean as a float. Returns NaN if no samples remain. """ if allow_nan: mask = ~np.isnan(errors) errors = errors[mask] if sample_weights is not None: sample_weights = np.asarray(sample_weights)[mask] if errors.size == 0: return float("NaN") return float(np.average(errors, weights=sample_weights))
[docs] def normalize_by_range( error: float, y_true: npt.NDArray[np.floating], *, lower_quantile: Quantile, upper_quantile: Quantile, norm_value: float | None, allow_nan: bool, ) -> float: """Normalize an error by the range of the true values or by a given norm value. Args: error: The error to normalize, e.g. a MAE or RMSE value. y_true: Ground truth values with shape (num_samples,). lower_quantile: Lower quantile of ``y_true`` for the range. Must be in [0, 1]. upper_quantile: Upper quantile of ``y_true`` for the range. Must be in [0, 1] and greater than lower_quantile. norm_value: Optional pre-calculated normalization value. If provided, it is used directly instead of the quantile range. allow_nan: If True, NaN values in ``y_true`` are ignored when computing the range. Returns: The normalized error as a float. Returns NaN if the error is NaN or the range is zero. """ if np.isnan(error): return float("NaN") if norm_value is not None: y_range = norm_value else: quantile = np.nanquantile if allow_nan else np.quantile y_range = quantile(y_true, q=upper_quantile) - quantile(y_true, q=lower_quantile) # Avoid division by zero if range is zero if y_range == 0: return float("NaN") return float(error / y_range)