Skip to content

validate_callable_signature

yohou.utils.weighting.validate_callable_signature(time_weight)

Validate that callable has valid signature for time weighting.

Checks that the callable accepts either 1 parameter (global weighting) or 2 parameters (panel-aware weighting). Raises ValueError for invalid signatures.

Parameters

Name Type Description Default
time_weight Callable

Callable to validate. Must have signature (time: pl.Series) -> pl.Series or (time: pl.Series, group_name: str) -> pl.Series.

required

Returns

Type Description
int

Number of parameters (1 or 2) for valid signatures.

Raises

Type Description
ValueError

If callable signature is invalid (not 1 or 2 parameters).

See Also

Examples

>>> def global_weight(time):
...     return time * 0 + 1
>>> validate_callable_signature(global_weight)
1
>>> def panel_weight(time, group_name):
...     return time * 0 + 1
>>> validate_callable_signature(panel_weight)
2

Source Code

Show/Hide source
def validate_callable_signature(
    time_weight: Callable,
) -> int:
    """Validate that callable has valid signature for time weighting.

    Checks that the callable accepts either 1 parameter (global weighting)
    or 2 parameters (panel-aware weighting). Raises ValueError for invalid
    signatures.

    Parameters
    ----------
    time_weight : Callable
        Callable to validate. Must have signature (time: pl.Series) -> pl.Series
        or (time: pl.Series, group_name: str) -> pl.Series.

    Returns
    -------
    int
        Number of parameters (1 or 2) for valid signatures.

    Raises
    ------
    ValueError
        If callable signature is invalid (not 1 or 2 parameters).

    See Also
    --------
    - [`exponential_decay_weight`][yohou.utils.weighting.exponential_decay_weight] : Exponential decay weights for recent times.
    - [`linear_decay_weight`][yohou.utils.weighting.linear_decay_weight] : Linear decay weights for recent times.
    - [`seasonal_emphasis_weight`][yohou.utils.weighting.seasonal_emphasis_weight] : Weights emphasizing seasonal positions.
    - [`compose_weights`][yohou.utils.weighting.compose_weights] : Compose multiple weight functions by multiplication.
    - [`BaseReductionForecaster`][yohou.base.reduction.BaseReductionForecaster] : Reduction forecaster supporting time_weight.

    Examples
    --------
    >>> def global_weight(time):
    ...     return time * 0 + 1
    >>> validate_callable_signature(global_weight)
    1

    >>> def panel_weight(time, group_name):
    ...     return time * 0 + 1
    >>> validate_callable_signature(panel_weight)
    2

    """
    sig = inspect.signature(time_weight)
    n_params = len(sig.parameters)

    if n_params not in (1, 2):
        raise ValueError(
            f"time_weight callable must accept either 1 parameter "
            f"(time: pl.Series) or 2 parameters (time: pl.Series, group_name: str), "
            f"but got {n_params} parameters"
        )

    return n_params