From f8e257f210e64b6c16845d7adde3626a0509cc54 Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Thu, 26 Nov 2026 14:14:54 +0000 Subject: [PATCH 01/11] Depend on frequenz-core directly The SDK already imports frequenz.core, but only gets it through frequenz-channels, and it will now use frequenz.core.warnings too. The minimum version is the one frequenz-channels already requires, so the installed versions don't change. Signed-off-by: Leandro Lucarella --- pyproject.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/pyproject.toml b/pyproject.toml index 522e26b36..1740eb3c5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -33,6 +33,7 @@ dependencies = [ "frequenz-microgrid-component-graph >= 0.6.1, < 0.7", "frequenz-client-common >= 0.3.6, < 0.5.0", "frequenz-channels >= 1.13.0, < 3.0.0", + "frequenz-core >= 1.6.0, < 2", "frequenz-quantities[marshmallow] >= 1.0.0, < 2.0.0", "numpy >= 2.1.0, < 3", "typing_extensions >= 4.16.0, < 5", From 030a718736e21798e327af1881e2955a17edb1cc Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Thu, 26 Nov 2026 14:20:40 +0000 Subject: [PATCH 02/11] Add ResamplerConfig3, ResamplingContext and ResamplingFunction3 The resampler defaults (max_data_age_in_periods=3.0, closed and label on the right) are surprising outside control use cases: every value is the mean of the last three periods, and values are labelled with the end of their window, unlike reporting data and pandas. Changing the defaults of the existing classes would silently change the results of every user, so this adds a new configuration class with new defaults: each value is the mean of its own window, [start, end), labelled with the window start. ResamplerConfig3 doesn't inherit from ResamplerConfig. The old classes will be deprecated, and a subclass of a deprecated class warns when it is defined, so it would warn every time the SDK is imported. It always uses the wall clock timer, so it has no align_to, and only the resampling period can be passed by position, so fields can be added or reordered later without breaking anyone. Resampling functions for it receive a ResamplingContext instead of the configuration and the source properties. It holds both, plus the window being calculated, with helpers to find previous windows and the window of a sample. A function that only uses the newest window with data, for example, can't be written without knowing the window boundaries. New information can be added to the context later without changing the signature of resampling functions again. The new class also rejects a max_data_age_in_periods that is not finite, or too big for that many resampling periods to fit in a timedelta, which the old classes accepted and then failed while resampling. It also rejects resampling periods too small for the default timer configuration, which ResamplerConfig2 only found when the resampler created the timer. It checks them by creating that configuration, so the check always matches the timer. Its initial_buffer_len is called input_period_estimation_samples, as it is the number of samples to receive before estimating the input sampling period, and the buffer no longer starts with that length. The resampler doesn't accept the new class yet. Signed-off-by: Leandro Lucarella --- src/frequenz/sdk/timeseries/__init__.py | 6 + .../sdk/timeseries/_resampling/_config.py | 424 +++++++++++++++++- tests/timeseries/_resampling/test_config3.py | 251 +++++++++++ 3 files changed, 679 insertions(+), 2 deletions(-) create mode 100644 tests/timeseries/_resampling/test_config3.py diff --git a/src/frequenz/sdk/timeseries/__init__.py b/src/frequenz/sdk/timeseries/__init__.py index 288ea6b5a..0528e56df 100644 --- a/src/frequenz/sdk/timeseries/__init__.py +++ b/src/frequenz/sdk/timeseries/__init__.py @@ -47,8 +47,11 @@ DEFAULT_BUFFER_LEN_WARN, ResamplerConfig, ResamplerConfig2, + ResamplerConfig3, + ResamplingContext, ResamplingFunction, ResamplingFunction2, + ResamplingFunction3, WindowSide, ) from ._resampling._exceptions import ResamplingError, SourceStoppedError @@ -71,9 +74,12 @@ "ReceiverFetcher", "ResamplerConfig", "ResamplerConfig2", + "ResamplerConfig3", + "ResamplingContext", "ResamplingError", "ResamplingFunction", "ResamplingFunction2", + "ResamplingFunction3", "Sample", "Sample3Phase", "Sink", diff --git a/src/frequenz/sdk/timeseries/_resampling/_config.py b/src/frequenz/sdk/timeseries/_resampling/_config.py index 0b1cca300..f033fff53 100644 --- a/src/frequenz/sdk/timeseries/_resampling/_config.py +++ b/src/frequenz/sdk/timeseries/_resampling/_config.py @@ -8,12 +8,13 @@ import logging import statistics from collections.abc import Sequence -from dataclasses import dataclass, field +from dataclasses import KW_ONLY, dataclass, field from datetime import datetime, timedelta from enum import Enum -from typing import Protocol +from typing import Protocol, assert_never from frequenz.core.datetime import UNIX_EPOCH +from frequenz.core.typing import FloatInt from ._base_types import SourceProperties from ._wall_clock_timer import WallClockTimerConfig @@ -457,3 +458,422 @@ def __post_init__(self) -> None: f"tick_delay ({self.tick_delay}) should be smaller than " f"resampling_period ({self.resampling_period})" ) + + +@dataclass(frozen=True, kw_only=True) +class ResamplingContext: + """The information a resampling function gets besides the samples to resample. + + It has the resampling window being calculated, the configuration of the + resampler and the properties of the timeseries being resampled. + + All resampling windows are exactly one + [`resampling_period`][frequenz.sdk.timeseries.ResamplerConfig3.resampling_period] + long, so the boundaries of previous windows can be calculated from the current + one with [`window_bounds()`][frequenz.sdk.timeseries.ResamplingContext.window_bounds], + and [`window_offset()`][frequenz.sdk.timeseries.ResamplingContext.window_offset] + tells in which window a sample is. + + Example: + ```python + from collections.abc import Sequence + from datetime import datetime + + from frequenz.sdk.timeseries import ResamplingContext + + + def previous_window_size( + input_samples: Sequence[tuple[datetime, float]], + context: ResamplingContext, + /, + ) -> float: + return float( + sum(1 for t, _ in input_samples if context.window_offset(t) == -1) + ) + ``` + """ + + window_start: datetime + """The start of the resampling window being calculated. + + This is the start of the window, whatever + [`label`][frequenz.sdk.timeseries.ResamplerConfig3.label] is. + """ + + config: ResamplerConfig3 + """The configuration of the resampler.""" + + source_properties: SourceProperties + """The properties of the timeseries being resampled. + + They are the current properties of the timeseries, not a copy, so they keep + changing after the resampling function returns. They must not be modified. + """ + + @property + def window_end(self) -> datetime: + """The end of the resampling window being calculated.""" + return self.window_start + self.config.resampling_period + + def window_bounds(self, offset: int = 0) -> tuple[datetime, datetime]: + """Return the start and end of a window, relative to the current one. + + Which bound is included in the window depends on + [`closed`][frequenz.sdk.timeseries.ResamplerConfig3.closed]. + + Args: + offset: The position of the window relative to the current one: `0` + is the current window, `-1` the one before it, and so on. + + Returns: + The start and end of the window. + """ + start = self.window_start + self.config.resampling_period * offset + return start, start + self.config.resampling_period + + def window_offset(self, timestamp: datetime) -> int: + """Return the position of the window that contains a timestamp. + + A timestamp on the boundary between two windows belongs to the window on + its [`closed`][frequenz.sdk.timeseries.ResamplerConfig3.closed] side. + + Args: + timestamp: The timestamp to look for. + + Returns: + The position of the window relative to the current one: `0` is the + current window, `-1` the one before it, and so on. + """ + elapsed = timestamp - self.window_start + period = self.config.resampling_period + match self.config.closed: + case WindowSide.LEFT: + return elapsed // period + case WindowSide.RIGHT: + # This is ceil(elapsed / period) - 1 + return -(-elapsed // period) - 1 + case unexpected: + assert_never(unexpected) + + +class ResamplingFunction3(Protocol): + """A function that combines multiple samples into a new one. + + A resampling function produces a new sample based on a list of pre-existing + samples. It can do "upsampling" when the data rate of the `input_samples` + period is smaller than the `resampling_period`, or "downsampling" if it is + bigger. + + The function receives every sample that is not older than + [`max_data_age_in_periods`][frequenz.sdk.timeseries.ResamplerConfig3.max_data_age_in_periods], + so it can get samples from previous windows too, for example to extrapolate, + but never samples from future windows. + + Warning: Limitation + The resampler currently expects the samples of each timeseries to arrive + in timestamp order. Samples that arrive out of order can be wrongly left + out of or included in a window, and the function then receives them out + of order. See + [frequenz-sdk-python#47](https://github.com/frequenz-floss/frequenz-sdk-python/issues/47). + + Example: + ```python + from collections.abc import Sequence + from datetime import datetime, timedelta + + from frequenz.sdk.timeseries import ResamplerConfig3, ResamplingContext + + + def newest_value( + input_samples: Sequence[tuple[datetime, float]], + _context: ResamplingContext, + /, + ) -> float: + return input_samples[-1][1] + + + config = ResamplerConfig3( + timedelta(seconds=1), resampling_function=newest_value + ) + ``` + """ + + def __call__( + self, + input_samples: Sequence[tuple[datetime, float]], + context: ResamplingContext, + /, + ) -> FloatInt: + """Call the resampling function. + + Args: + input_samples: The samples to resample, as `(timestamp, value)` + tuples sorted by timestamp. It is never empty. + context: The resampling window being calculated, the configuration of + the resampler and the properties of the timeseries being resampled. + + Returns: + The value of the new sample. + """ + ... # pylint: disable=unnecessary-ellipsis + + +@dataclass(frozen=True) +class ResamplerConfig3: + """A resampler configuration. + + The resampler produces one value per resampling window, with all the samples + received for each timeseries that are not older than + [`max_data_age_in_periods`][frequenz.sdk.timeseries.ResamplerConfig3.max_data_age_in_periods]. + + With the default values, when downsampling, each resampled value is the mean of + the samples in its own window only. When upsampling, it can also include older + samples (see `max_data_age_in_periods`). Windows are closed on the left and + values are labelled with the start of their window, so with a 15-minute + resampling period, a value labelled 10:00 is the mean of the samples in + `[10:00, 10:15)`. This matches how reporting data and + [pandas](https://pandas.pydata.org/) label resampled data. + + The resampler always uses a + [`WallClockTimer`][frequenz.sdk.timeseries.WallClockTimer] to know when a + window ends. It can be configured with + [`timer_config`][frequenz.sdk.timeseries.ResamplerConfig3.timer_config]. + + Only `resampling_period` can be passed by position. + + Warning: Mixing window conventions + Timeseries resampled with different + [`label`][frequenz.sdk.timeseries.ResamplerConfig3.label] values are off by + one period, and with different + [`closed`][frequenz.sdk.timeseries.ResamplerConfig3.closed] values, samples + exactly on a window boundary go to different windows. When they are + combined, for example in a formula or when the output of a resampler is + resampled again, values from adjacent windows are silently paired. Use the + same values for all resamplers whose output is combined. + + When the output of a resampler is resampled again, both resamplers tick at + the same time, so the second one can process a window before the first one + sent its last value, whatever the window conventions are. + [`tick_delay`][frequenz.sdk.timeseries.ResamplerConfig3.tick_delay] can + reduce this. + + Warning: Limitation + The resampler currently expects the samples of each timeseries to arrive + in timestamp order. Samples that arrive out of order can be wrongly left + out of or included in a window. See + [frequenz-sdk-python#47](https://github.com/frequenz-floss/frequenz-sdk-python/issues/47). + """ + + resampling_period: timedelta + """The resampling period. + + This is the time it passes between resampled data should be calculated, and + the length of each resampling window. + + It must be a positive time span. Periods of a few microseconds also need a + `timer_config`, as the default one can't be created for them. + """ + + _: KW_ONLY + + max_data_age_in_periods: FloatInt = 1.0 + """The maximum age of the samples passed to the resampling function, in periods. + + Every sample that is not older than this is passed to the resampling function, + not only the samples in the current window. With the default resampling + function, a mean, a value bigger than 1.0 makes each resampled value an + average of several periods, which smooths and delays changes. + + The period is the `resampling_period` if we are downsampling (resampling + period bigger than the input period) or the *input sampling period* if we are + upsampling (input period bigger than the resampling period). So when + upsampling, even with 1.0 the resampling function can receive samples older + than the current window, and the default mean can include them. + + It must be at least 1.0, and small enough for that many resampling periods to + fit in a [`timedelta`][datetime.timedelta]. + + Example: + If `resampling_period` is 3 seconds, the input sampling period is + 1 and `max_data_age_in_periods` is 2, then data older than 3*2 + = 6 seconds will be discarded when creating a new sample and never + passed to the resampling function. + + If `resampling_period` is 3 seconds, the input sampling period is + 5 and `max_data_age_in_periods` is 2, then data older than 5*2 + = 10 seconds will be discarded when creating a new sample and never + passed to the resampling function. + """ + + resampling_function: ResamplingFunction3 = lambda samples, _: statistics.fmean( + s[1] for s in samples + ) + """The resampling function. + + This function is called with all the samples that are not older than + `max_data_age_in_periods`, and its result is sent as the resampled value. + + By default, it is the mean of all the samples it receives. + """ + + closed: WindowSide = WindowSide.LEFT + """Indicates which side of the resampling window is closed. + + If `WindowSide.LEFT` (default), the resampling window is closed on the left + side and open on the right, meaning it includes samples with timestamps + within the range `[start, end)`, where `start` and `end` are the boundaries of + the window. + + If `WindowSide.RIGHT`, the resampling window is closed on the right side and + open on the left, meaning it includes samples with timestamps within the + range `(start, end]`, where `start` and `end` are the boundaries of the + window. + """ + + label: WindowSide = WindowSide.LEFT + """Indicates the timestamp label of the resampled data. + + If `WindowSide.LEFT` (default), the timestamp of the resampled data + corresponds to the left boundary (start) of the resampling window. If + `WindowSide.RIGHT`, the timestamp corresponds to the right boundary (end) of + the resampling window. + + Resampled values are sent at the end of their window, or later with + `tick_delay`, so with `WindowSide.LEFT` the timestamp of a value is at least + one period older than the time it is sent. + """ + + input_period_estimation_samples: int = DEFAULT_BUFFER_LEN_INIT + """The number of samples to receive before estimating the input sampling period. + + The input sampling period is estimated once, at the first resampling after + receiving enough samples, and decides how old the relevant samples can be + when upsampling (see `max_data_age_in_periods`). Until it is known, samples + are not removed from the resampling buffer, except when it is full. + + The number of received samples must also be at least the number of seconds + in `max_data_age_in_periods` resampling periods. For example, with a + resampling period of 60 seconds and a `max_data_age_in_periods` of 3, the + input sampling period is estimated after receiving at least 180 samples (see + [frequenz-sdk-python#1497](https://github.com/frequenz-floss/frequenz-sdk-python/issues/1497)). + + It must be at least 1 and at most `max_buffer_len`. + """ + + warn_buffer_len: int = DEFAULT_BUFFER_LEN_WARN + """The number of samples above which a resampling buffer logs a warning. + + Old samples are removed from the buffer when resampling, so it only holds + the samples that are still relevant and the ones received since. If it + holds more samples than this value after removing old ones, a warning is + logged once, so buffers don't grow too big inadvertently. + + It must be at least 1 and at most `max_buffer_len`. + """ + + max_buffer_len: int = DEFAULT_BUFFER_LEN_MAX + """The maximum number of samples a resampling buffer can hold. + + When the buffer is full, the oldest sample is dropped when a new one is + added, even if it would be needed to resample. An error is logged once if + samples needed to resample may have been dropped. + + It must be bigger than `warn_buffer_len`. + """ + + timer_config: WallClockTimerConfig | None = None + """The custom configuration of the wall clock timer used to keep track of time. + + If not provided or `None`, a configuration will be created by passing the + [`resampling_period`][frequenz.sdk.timeseries.ResamplerConfig3.resampling_period] + to the [`from_interval()`][frequenz.sdk.timeseries.WallClockTimerConfig.from_interval] + method. + """ + + tick_delay: timedelta = timedelta(0) + """Delay before processing each resampling tick. + + This delays when resampling computation happens, while keeping the + resampling windows aligned to the original timer tick boundaries. This + delay is only a time-based buffer, not a strict synchronization mechanism. + + Warning: + This is an experimental option and may be changed or deprecated in + the future. + + Example: + This can be used in cascaded resampling setups to reduce timing races + where downstream windows are processed before upstream resampled values + are emitted. + + It must be non-negative and smaller than `resampling_period`. + """ + + def __post_init__(self) -> None: + """Check that config values are valid. + + Raises: + ValueError: If any value is out of range. + """ + if self.resampling_period <= timedelta(0): + raise ValueError( + f"resampling_period ({self.resampling_period}) must be positive" + ) + if self.timer_config is None: + # The resampler creates the default timer configuration like this. + try: + _ = WallClockTimerConfig.from_interval(self.resampling_period) + except ValueError as exc: + raise ValueError( + f"resampling_period ({self.resampling_period}) is too small for " + "the default timer configuration, pass a timer_config" + ) from exc + try: + # This also fails for values that are not finite. + _ = self.resampling_period * self.max_data_age_in_periods + except (OverflowError, ValueError) as exc: + raise ValueError( + f"max_data_age_in_periods ({self.max_data_age_in_periods}) must be a " + "finite number, small enough for that many resampling periods to " + "fit in a timedelta" + ) from exc + if self.max_data_age_in_periods < 1.0: + raise ValueError( + f"max_data_age_in_periods ({self.max_data_age_in_periods}) " + "must be at least 1.0" + ) + if self.warn_buffer_len < 1: + raise ValueError( + f"warn_buffer_len ({self.warn_buffer_len}) should be at least 1" + ) + if self.max_buffer_len <= self.warn_buffer_len: + raise ValueError( + f"max_buffer_len ({self.max_buffer_len}) should " + f"be bigger than warn_buffer_len ({self.warn_buffer_len})" + ) + if self.input_period_estimation_samples < 1: + raise ValueError( + "input_period_estimation_samples " + f"({self.input_period_estimation_samples}) should be at least 1" + ) + if self.input_period_estimation_samples > self.max_buffer_len: + raise ValueError( + "input_period_estimation_samples " + f"({self.input_period_estimation_samples}) is bigger than " + f"max_buffer_len ({self.max_buffer_len}), use a smaller " + "input_period_estimation_samples or a bigger max_buffer_len" + ) + if self.input_period_estimation_samples > self.warn_buffer_len: + _logger.warning( + "input_period_estimation_samples (%s) is bigger than " + "warn_buffer_len (%s)", + self.input_period_estimation_samples, + self.warn_buffer_len, + ) + if self.tick_delay < timedelta(0): + raise ValueError(f"tick_delay ({self.tick_delay}) should be non-negative") + if self.tick_delay >= self.resampling_period: + raise ValueError( + f"tick_delay ({self.tick_delay}) should be smaller than " + f"resampling_period ({self.resampling_period})" + ) diff --git a/tests/timeseries/_resampling/test_config3.py b/tests/timeseries/_resampling/test_config3.py new file mode 100644 index 000000000..2b81ee020 --- /dev/null +++ b/tests/timeseries/_resampling/test_config3.py @@ -0,0 +1,251 @@ +# License: MIT +# Copyright © 2026 Frequenz Energy-as-a-Service GmbH + +"""Tests for `ResamplerConfig3` and `ResamplingContext`.""" + +import dataclasses +import logging +import math +from datetime import datetime, timedelta, timezone + +import pytest + +from frequenz.sdk.timeseries import ( + DEFAULT_BUFFER_LEN_INIT, + DEFAULT_BUFFER_LEN_MAX, + DEFAULT_BUFFER_LEN_WARN, + ResamplerConfig3, + ResamplingContext, + SourceProperties, + WallClockTimerConfig, + WindowSide, +) + +_PERIOD = timedelta(seconds=10) +_START = datetime(2026, 1, 1, 12, 0, 0, tzinfo=timezone.utc) + + +def _context(config: ResamplerConfig3) -> ResamplingContext: + """Create a context for the window starting at `_START`.""" + return ResamplingContext( + window_start=_START, config=config, source_properties=SourceProperties() + ) + + +def test_defaults() -> None: + """Test the default values.""" + config = ResamplerConfig3(_PERIOD) + + assert config.resampling_period == _PERIOD + assert config.max_data_age_in_periods == 1.0 + assert config.closed == WindowSide.LEFT + assert config.label == WindowSide.LEFT + assert config.input_period_estimation_samples == DEFAULT_BUFFER_LEN_INIT + assert config.warn_buffer_len == DEFAULT_BUFFER_LEN_WARN + assert config.max_buffer_len == DEFAULT_BUFFER_LEN_MAX + assert config.timer_config is None + assert config.tick_delay == timedelta(0) + + +def test_default_resampling_function_is_mean() -> None: + """Test the default resampling function averages all samples it gets.""" + config = ResamplerConfig3(_PERIOD) + context = ResamplingContext( + window_start=_START, config=config, source_properties=SourceProperties() + ) + samples = [ + (_START - timedelta(seconds=5), 1.0), + (_START + timedelta(seconds=1), 2.0), + (_START + timedelta(seconds=2), 6.0), + ] + + assert config.resampling_function(samples, context) == 3.0 + + +def test_only_resampling_period_is_positional() -> None: + """Test only the resampling period can be passed by position.""" + with pytest.raises(TypeError): + ResamplerConfig3(_PERIOD, 3.0) # type: ignore[call-arg] + + +def test_all_fields() -> None: + """Test all fields can be set by keyword.""" + timer_config = WallClockTimerConfig.from_interval(_PERIOD) + config = ResamplerConfig3( + resampling_period=_PERIOD, + max_data_age_in_periods=3, + closed=WindowSide.RIGHT, + label=WindowSide.RIGHT, + input_period_estimation_samples=2, + warn_buffer_len=3, + max_buffer_len=4, + timer_config=timer_config, + tick_delay=timedelta(seconds=1), + ) + + assert config.max_data_age_in_periods == 3 + assert config.closed == WindowSide.RIGHT + assert config.label == WindowSide.RIGHT + assert config.input_period_estimation_samples == 2 + assert config.warn_buffer_len == 3 + assert config.max_buffer_len == 4 + assert config.timer_config is timer_config + assert config.tick_delay == timedelta(seconds=1) + + +@pytest.mark.parametrize( + "period", [timedelta(0), timedelta(seconds=-1)], ids=["zero", "negative"] +) +def test_resampling_period_must_be_positive(period: timedelta) -> None: + """Test a resampling period that is not positive is rejected.""" + with pytest.raises(ValueError, match=r"resampling_period .* must be positive"): + ResamplerConfig3(period) + + +@pytest.mark.parametrize("max_age", [0.0, 0.999]) +def test_max_data_age_must_be_at_least_one(max_age: float) -> None: + """Test maximum data ages smaller than 1.0 are rejected.""" + with pytest.raises(ValueError, match=r"must be at least 1\.0"): + ResamplerConfig3(_PERIOD, max_data_age_in_periods=max_age) + + +@pytest.mark.parametrize( + "max_age", [math.nan, math.inf, 1e20, 10**400], ids=["nan", "inf", "big", "huge"] +) +def test_max_data_age_must_fit_in_a_timedelta(max_age: float) -> None: + """Test maximum data ages that are not finite or too big are rejected.""" + with pytest.raises(ValueError, match=r"must be a finite number, small enough"): + ResamplerConfig3(_PERIOD, max_data_age_in_periods=max_age) + + +def test_tiny_resampling_period_needs_a_timer_config() -> None: + """Test periods too small for the default timer configuration are rejected.""" + period = timedelta(microseconds=1) + with pytest.raises(ValueError, match=r"too small for the default timer"): + ResamplerConfig3(period) + + config = ResamplerConfig3(period, timer_config=WallClockTimerConfig()) + assert config.resampling_period == period + + +@pytest.mark.parametrize( + "kwargs, message", + [ + ({"warn_buffer_len": 0}, r"warn_buffer_len \(0\) should be at least 1"), + ( + {"warn_buffer_len": 4, "max_buffer_len": 4}, + r"max_buffer_len \(4\) should be bigger than warn_buffer_len \(4\)", + ), + ( + {"input_period_estimation_samples": 0}, + r"input_period_estimation_samples \(0\) should be at least 1", + ), + ( + {"input_period_estimation_samples": DEFAULT_BUFFER_LEN_MAX + 1}, + r"input_period_estimation_samples .* is bigger than max_buffer_len", + ), + ({"tick_delay": timedelta(seconds=-1)}, r"should be non-negative"), + ({"tick_delay": _PERIOD}, r"should be smaller than resampling_period"), + ], +) +def test_invalid_values(kwargs: dict[str, object], message: str) -> None: + """Test invalid values are rejected.""" + with pytest.raises(ValueError, match=message): + ResamplerConfig3(_PERIOD, **kwargs) # type: ignore[arg-type] + + +def test_input_period_estimation_samples_bigger_than_warn_logs( + caplog: pytest.LogCaptureFixture, +) -> None: + """Test an initial buffer length bigger than the warning length logs a warning.""" + with caplog.at_level(logging.WARNING): + ResamplerConfig3( + _PERIOD, input_period_estimation_samples=DEFAULT_BUFFER_LEN_WARN + 1 + ) + + assert ( + "input_period_estimation_samples " + f"({DEFAULT_BUFFER_LEN_WARN + 1}) is bigger than " + f"warn_buffer_len ({DEFAULT_BUFFER_LEN_WARN})" + ) in caplog.messages + + +def test_context_is_frozen() -> None: + """Test the context can't be changed.""" + context = _context(ResamplerConfig3(_PERIOD)) + + with pytest.raises(dataclasses.FrozenInstanceError): + context.window_start = _START + _PERIOD # type: ignore[misc] + + +def test_context_window_end() -> None: + """Test the window end is one period after the window start.""" + context = _context(ResamplerConfig3(_PERIOD)) + + assert context.window_end == _START + _PERIOD + + +@pytest.mark.parametrize( + "offset, expected_start", + [ + (0, _START), + (-1, _START - _PERIOD), + (-3, _START - 3 * _PERIOD), + (1, _START + _PERIOD), + ], +) +def test_context_window_bounds(offset: int, expected_start: datetime) -> None: + """Test the bounds of windows relative to the current one.""" + context = _context(ResamplerConfig3(_PERIOD)) + + assert context.window_bounds(offset) == (expected_start, expected_start + _PERIOD) + + +def test_context_window_bounds_default_is_current() -> None: + """Test the default offset gives the current window.""" + context = _context(ResamplerConfig3(_PERIOD)) + + assert context.window_bounds() == (context.window_start, context.window_end) + + +_ONE_US = timedelta(microseconds=1) + + +@pytest.mark.parametrize( + "closed, timestamp, expected_offset", + [ + # Closed on the left: [start, end) + (WindowSide.LEFT, _START, 0), + (WindowSide.LEFT, _START + _ONE_US, 0), + (WindowSide.LEFT, _START + _PERIOD - _ONE_US, 0), + (WindowSide.LEFT, _START + _PERIOD, 1), + (WindowSide.LEFT, _START - _ONE_US, -1), + (WindowSide.LEFT, _START - _PERIOD, -1), + (WindowSide.LEFT, _START - _PERIOD - _ONE_US, -2), + (WindowSide.LEFT, _START - 5 * _PERIOD / 2, -3), + # Closed on the right: (start, end] + (WindowSide.RIGHT, _START, -1), + (WindowSide.RIGHT, _START + _ONE_US, 0), + (WindowSide.RIGHT, _START + _PERIOD, 0), + (WindowSide.RIGHT, _START + _PERIOD + _ONE_US, 1), + (WindowSide.RIGHT, _START - _ONE_US, -1), + (WindowSide.RIGHT, _START - _PERIOD, -2), + (WindowSide.RIGHT, _START - _PERIOD + _ONE_US, -1), + (WindowSide.RIGHT, _START - 5 * _PERIOD / 2, -3), + ], +) +def test_context_window_offset( + closed: WindowSide, timestamp: datetime, expected_offset: int +) -> None: + """Test finding the window of a timestamp, including on boundaries.""" + context = _context(ResamplerConfig3(_PERIOD, closed=closed)) + + offset = context.window_offset(timestamp) + + assert offset == expected_offset + start, end = context.window_bounds(offset) + match closed: + case WindowSide.LEFT: + assert start <= timestamp < end + case WindowSide.RIGHT: + assert start < timestamp <= end From 297411671737a6683dbfe02a7822ca5ad71cea1f Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Thu, 26 Nov 2026 14:24:20 +0000 Subject: [PATCH 03/11] Support ResamplerConfig3 in the resampler With a ResamplerConfig3 the resampler uses the wall clock timer, like with a ResamplerConfig2, and passes a ResamplingContext to the resampling function. ResamplerConfig2 is a subclass of ResamplerConfig, so the configuration is matched in that order. _calculate_window_end() now gets the narrowed ResamplerConfig, since the other configurations have no align_to. The parametrized resampler tests now run with all three classes. They use the old window conventions for ResamplerConfig3, and call its resampling function like the old classes do, so the same expectations hold. New tests cover the new defaults, the context and the default mean including older samples when upsampling. The docs now say the resampler expects samples in timestamp order, which it always did (#47). Signed-off-by: Leandro Lucarella --- .../sdk/timeseries/_resampling/_resampler.py | 108 ++++-- tests/timeseries/test_resampling.py | 322 +++++++++++++----- 2 files changed, 334 insertions(+), 96 deletions(-) diff --git a/src/frequenz/sdk/timeseries/_resampling/_resampler.py b/src/frequenz/sdk/timeseries/_resampling/_resampler.py index b21ad3a58..7494e1469 100644 --- a/src/frequenz/sdk/timeseries/_resampling/_resampler.py +++ b/src/frequenz/sdk/timeseries/_resampling/_resampler.py @@ -12,13 +12,20 @@ from typing import assert_never from frequenz.channels.timer import MonotonicTimer, TriggerAllMissed, _to_microseconds +from frequenz.core.typing import FloatInt from frequenz.quantities import Quantity from ..._internal._asyncio import cancel_and_await from .._base_types import Sample from ._base_types import Sink, Source, SourceProperties from ._buffer import _ResamplingBuffer -from ._config import ResamplerConfig, ResamplerConfig2, WindowSide +from ._config import ( + ResamplerConfig, + ResamplerConfig2, + ResamplerConfig3, + ResamplingContext, + WindowSide, +) from ._exceptions import ResamplingError, SourceStoppedError from ._wall_clock_timer import TickInfo, WallClockTimer @@ -38,14 +45,22 @@ class Resampler: samples coming to a resampled timeseries for a while, eventually the `Resampler` will produce `Sample`s with `None` as value, meaning there is no way to produce meaningful samples with the available data. + + Warning: Limitation + The resampler currently expects the samples of each timeseries to arrive + in timestamp order. Samples that arrive out of order can be wrongly left + out of or included in a window. See + [frequenz-sdk-python#47](https://github.com/frequenz-floss/frequenz-sdk-python/issues/47). """ - def __init__(self, config: ResamplerConfig) -> None: + def __init__( + self, config: ResamplerConfig3 | ResamplerConfig2 | ResamplerConfig + ) -> None: """Initialize an instance. Args: - config: The configuration for the resampler. If a `ResamplerConfig2` is - provided, the resampler will use a + config: The configuration for the resampler. If a `ResamplerConfig3` or + a `ResamplerConfig2` is provided, the resampler will use a [`WallClockTimer`][frequenz.sdk.timeseries.WallClockTimer] instead of a [`MonotonicTimer`][frequenz.channels.timer.MonotonicTimer]. """ @@ -58,11 +73,20 @@ def __init__(self, config: ResamplerConfig) -> None: self._timer: MonotonicTimer | WallClockTimer """The timer used to trigger the resampling windows.""" - if isinstance(config, ResamplerConfig2): - self._timer = WallClockTimer(config.resampling_period, config.timer_config) - return + # ResamplerConfig2 is a subclass of ResamplerConfig, so it has to be + # matched first. + match config: + case ResamplerConfig3() | ResamplerConfig2(): + self._timer = WallClockTimer( + config.resampling_period, config.timer_config + ) + return + case ResamplerConfig(): + pass + case unexpected: + assert_never(unexpected) - window_end, start_delay_time = self._calculate_window_end() + window_end, start_delay_time = self._calculate_window_end(config) self._window_end: datetime = window_end """The time in which the current window ends. @@ -87,7 +111,7 @@ def __init__(self, config: ResamplerConfig) -> None: ) # pylint: disable=protected-access @property - def config(self) -> ResamplerConfig: + def config(self) -> ResamplerConfig3 | ResamplerConfig2 | ResamplerConfig: """Get the resampler configuration. Returns: @@ -225,26 +249,31 @@ async def resample(self, *, one_shot: bool = False) -> None: if one_shot: break - def _calculate_window_end(self) -> tuple[datetime, timedelta]: + def _calculate_window_end( + self, config: ResamplerConfig + ) -> tuple[datetime, timedelta]: """Calculate the end of the current resampling window. The calculated resampling window end is a multiple of - `self._config.resampling_period` starting at `self._config.align_to`. + `config.resampling_period` starting at `config.align_to`. - if `self._config.align_to` is `None`, the current time is used. + if `config.align_to` is `None`, the current time is used. - If the current time is not aligned to `self._config.resampling_period`, then + If the current time is not aligned to `config.resampling_period`, then the end of the current resampling window will be more than one period away, to make sure to have some time to collect samples if the misalignment is too big. + Args: + config: The configuration for the resampler. + Returns: A tuple with the end of the current resampling window aligned to - `self._config.align_to` as the first item and the time we need to + `config.align_to` as the first item and the time we need to delay the timer start to make sure it is also aligned. """ now = datetime.now(timezone.utc) - period = self._config.resampling_period - align_to = self._config.align_to + period = config.resampling_period + align_to = config.align_to if align_to is None: return (now + period, timedelta(0)) @@ -278,7 +307,9 @@ class _ResamplingHelper: estimated, so samples are kept. """ - def __init__(self, name: str, config: ResamplerConfig) -> None: + def __init__( + self, name: str, config: ResamplerConfig3 | ResamplerConfig2 | ResamplerConfig + ) -> None: """Initialize an instance. Args: @@ -298,6 +329,15 @@ def __init__(self, name: str, config: ResamplerConfig) -> None: # as possible. self.add_sample: Callable[[tuple[datetime, float]], None] = self._buffer.add """Add a new sample to the buffer.""" + self._estimation_samples: int + """The number of samples to receive before estimating the input period.""" + match config: + case ResamplerConfig3(): + self._estimation_samples = config.input_period_estimation_samples + case ResamplerConfig(): + self._estimation_samples = config.initial_buffer_len + case unexpected: + assert_never(unexpected) @property def source_properties(self) -> SourceProperties: @@ -326,7 +366,7 @@ def _update_source_sample_period(self, now: datetime) -> bool: or props.sampling_start is None or props.received_samples < config.resampling_period.total_seconds() * config.max_data_age_in_periods - or props.received_samples < config.initial_buffer_len + or props.received_samples < self._estimation_samples # There might be a race between the first sample being received and # this function being called or now <= props.sampling_start @@ -386,7 +426,7 @@ def resample(self, timestamp: datetime) -> Sample[Quantity]: ) value = ( - conf.resampling_function(relevant_samples, conf, props) + self._call_resampling_function(relevant_samples, timestamp) if relevant_samples else None ) @@ -401,6 +441,36 @@ def resample(self, timestamp: datetime) -> Sample[Quantity]: return Sample(timestamp, None if value is None else Quantity(value)) + def _call_resampling_function( + self, + relevant_samples: list[tuple[datetime, float]], + timestamp: datetime, + ) -> FloatInt: + """Call the resampling function of the configuration. + + Args: + relevant_samples: The samples to pass to the resampling function. + timestamp: The end of the resampling window. + + Returns: + The value returned by the resampling function. + """ + conf = self._config + match conf: + case ResamplerConfig3(): + context = ResamplingContext( + window_start=timestamp - conf.resampling_period, + config=conf, + source_properties=self._source_properties, + ) + return conf.resampling_function(relevant_samples, context) + case ResamplerConfig(): + return conf.resampling_function( + relevant_samples, conf, self._source_properties + ) + case unexpected: + assert_never(unexpected) + class _StreamingHelper: """Resample data coming from a source, sending the results to a sink.""" diff --git a/tests/timeseries/test_resampling.py b/tests/timeseries/test_resampling.py index 133ac6c2c..5d3cbbd9a 100644 --- a/tests/timeseries/test_resampling.py +++ b/tests/timeseries/test_resampling.py @@ -5,7 +5,7 @@ import asyncio import logging -from collections.abc import AsyncIterator +from collections.abc import AsyncIterator, Sequence from datetime import datetime, timedelta, timezone from typing import Any, cast from unittest.mock import AsyncMock, MagicMock @@ -21,12 +21,16 @@ DEFAULT_BUFFER_LEN_WARN, ResamplerConfig, ResamplerConfig2, + ResamplerConfig3, + ResamplingContext, ResamplingFunction, + ResamplingFunction3, Sample, Sink, Source, SourceProperties, TickInfo, + WallClockTimer, WindowSide, ) from frequenz.sdk.timeseries._resampling._exceptions import ( @@ -42,6 +46,59 @@ # pylint: disable=too-many-arguments,disable=too-many-positional-arguments +_ConfigClass = type[ResamplerConfig] | type[ResamplerConfig3] +"""A resampler configuration class.""" + +_CONFIG_CLASSES = [ResamplerConfig, ResamplerConfig2, ResamplerConfig3] +"""All the resampler configuration classes, to parametrize tests.""" + + +def _make_config( + config_class: _ConfigClass, **kwargs: Any +) -> ResamplerConfig | ResamplerConfig3: + """Create a configuration for tests shared by all three classes. + + For `ResamplerConfig3`, default to right-closed, right-labelled windows and + adapt any custom resampling function from the old signature. The default + `max_data_age_in_periods` still depends on the configuration class. + """ + if config_class is ResamplerConfig3: + kwargs.setdefault("closed", WindowSide.RIGHT) + kwargs.setdefault("label", WindowSide.RIGHT) + if "initial_buffer_len" in kwargs: + kwargs["input_period_estimation_samples"] = kwargs.pop("initial_buffer_len") + if "resampling_function" in kwargs: + kwargs["resampling_function"] = _with_old_signature( + kwargs["resampling_function"] + ) + return config_class(**kwargs) + + +def _estimation_samples_name(config_class: _ConfigClass) -> str: + """Return the name of the setting called `initial_buffer_len` in the old classes.""" + if config_class is ResamplerConfig3: + return "input_period_estimation_samples" + return "initial_buffer_len" + + +def _with_old_signature(function: Any) -> ResamplingFunction3: + """Call a function with the arguments the old resampling functions receive. + + The old resampling functions receive the configuration and the source + properties as separate arguments, which `ResamplerConfig3` passes in a + `ResamplingContext`. This way the same expectations work for all classes. + """ + + def resampling_function( + input_samples: Sequence[tuple[datetime, float]], context: ResamplingContext, / + ) -> float: + return cast( + float, function(input_samples, context.config, context.source_properties) + ) + + return resampling_function + + @pytest.fixture(autouse=True) def event_loop_policy() -> async_solipsism.EventLoopPolicy: """Return an event loop policy that uses the async solipsism event loop.""" @@ -102,18 +159,19 @@ async def _assert_no_more_samples( @pytest.mark.parametrize("init_len", list(range(1, DEFAULT_BUFFER_LEN_WARN + 1, 16))) -@pytest.mark.parametrize("config_class", [ResamplerConfig, ResamplerConfig2]) +@pytest.mark.parametrize("config_class", _CONFIG_CLASSES) async def test_resampler_config_len_ok( init_len: int, - config_class: type[ResamplerConfig], + config_class: _ConfigClass, caplog: pytest.LogCaptureFixture, ) -> None: """Test checks on the resampling buffer.""" - config = config_class( + config = _make_config( + config_class, resampling_period=timedelta(seconds=1.0), initial_buffer_len=init_len, ) - assert config.initial_buffer_len == init_len + assert getattr(config, _estimation_samples_name(config_class)) == init_len # Ignore errors produced by wrongly finalized gRPC server in unrelated tests assert _filter_logs(caplog.record_tuples, logger_name="") == [] @@ -122,16 +180,18 @@ async def test_resampler_config_len_ok( "init_len", range(DEFAULT_BUFFER_LEN_WARN + 1, DEFAULT_BUFFER_LEN_MAX + 1, 64), ) -@pytest.mark.parametrize("config_class", [ResamplerConfig, ResamplerConfig2]) +@pytest.mark.parametrize("config_class", _CONFIG_CLASSES) async def test_resampler_config_len_warn( - init_len: int, config_class: type[ResamplerConfig], caplog: pytest.LogCaptureFixture + init_len: int, config_class: _ConfigClass, caplog: pytest.LogCaptureFixture ) -> None: """Test checks on the resampling buffer.""" - config = config_class( + config = _make_config( + config_class, resampling_period=timedelta(seconds=1.0), initial_buffer_len=init_len, ) - assert config.initial_buffer_len == init_len + name = _estimation_samples_name(config_class) + assert getattr(config, name) == init_len # Ignore errors produced by wrongly finalized gRPC server in unrelated tests assert _filter_logs( caplog.record_tuples, logger_name="frequenz.sdk.timeseries._resampling._config" @@ -139,7 +199,7 @@ async def test_resampler_config_len_warn( ( "frequenz.sdk.timeseries._resampling._config", logging.WARNING, - f"initial_buffer_len ({init_len}) is bigger than " + f"{name} ({init_len}) is bigger than " f"warn_buffer_len ({DEFAULT_BUFFER_LEN_WARN})", ) ] @@ -149,52 +209,56 @@ async def test_resampler_config_len_warn( "init_len", list(range(-2, 1)) + [DEFAULT_BUFFER_LEN_MAX + 1, DEFAULT_BUFFER_LEN_MAX + 2], ) -@pytest.mark.parametrize("config_class", [ResamplerConfig, ResamplerConfig2]) +@pytest.mark.parametrize("config_class", _CONFIG_CLASSES) async def test_resampler_config_len_error( - init_len: int, config_class: type[ResamplerConfig] + init_len: int, config_class: _ConfigClass ) -> None: """Test checks on the resampling buffer.""" with pytest.raises(ValueError): - _ = config_class( + _ = _make_config( + config_class, resampling_period=timedelta(seconds=1.0), initial_buffer_len=init_len, ) -@pytest.mark.parametrize("config_class", [ResamplerConfig, ResamplerConfig2]) +@pytest.mark.parametrize("config_class", _CONFIG_CLASSES) async def test_resampler_config_tick_delay_negative_error( - config_class: type[ResamplerConfig], + config_class: _ConfigClass, ) -> None: """Test that negative tick_delay values are rejected.""" with pytest.raises(ValueError, match="tick_delay"): - _ = config_class( + _ = _make_config( + config_class, resampling_period=timedelta(seconds=1.0), tick_delay=timedelta(milliseconds=-1), ) -@pytest.mark.parametrize("config_class", [ResamplerConfig, ResamplerConfig2]) +@pytest.mark.parametrize("config_class", _CONFIG_CLASSES) @pytest.mark.parametrize("tick_delay", [timedelta(seconds=1.0), timedelta(seconds=1.1)]) async def test_resampler_config_tick_delay_too_big_error( - config_class: type[ResamplerConfig], tick_delay: timedelta + config_class: _ConfigClass, tick_delay: timedelta ) -> None: """Test that tick_delay must be smaller than resampling_period.""" with pytest.raises(ValueError, match="smaller than resampling_period"): - _ = config_class( + _ = _make_config( + config_class, resampling_period=timedelta(seconds=1.0), tick_delay=tick_delay, ) -@pytest.mark.parametrize("config_class", [ResamplerConfig, ResamplerConfig2]) +@pytest.mark.parametrize("config_class", _CONFIG_CLASSES) async def test_helper_buffer_too_big( - config_class: type[ResamplerConfig], + config_class: _ConfigClass, fake_time: time_machine.Coordinates, caplog: pytest.LogCaptureFixture, ) -> None: """Test dropping relevant samples because the buffer is full is logged once.""" # The window has one more sample than the buffer can hold - config = config_class( + config = _make_config( + config_class, resampling_period=timedelta(seconds=DEFAULT_BUFFER_LEN_MAX + 2), max_data_age_in_periods=1, ) @@ -224,13 +288,14 @@ async def test_helper_buffer_too_big( assert len(helper._buffer) == DEFAULT_BUFFER_LEN_MAX -@pytest.mark.parametrize("config_class", [ResamplerConfig, ResamplerConfig2]) +@pytest.mark.parametrize("config_class", _CONFIG_CLASSES) async def test_helper_buffer_bigger_than_warn_len_is_logged_once( - config_class: type[ResamplerConfig], + config_class: _ConfigClass, caplog: pytest.LogCaptureFixture, ) -> None: """Test a buffer holding more than `warn_buffer_len` samples is logged once.""" - config = config_class( + config = _make_config( + config_class, resampling_period=timedelta(seconds=1), max_data_age_in_periods=1, closed=WindowSide.LEFT, @@ -255,16 +320,17 @@ async def test_helper_buffer_bigger_than_warn_len_is_logged_once( ] -@pytest.mark.parametrize("config_class", [ResamplerConfig, ResamplerConfig2]) +@pytest.mark.parametrize("config_class", _CONFIG_CLASSES) async def test_helper_keeps_window_samples_when_next_window_starts( - config_class: type[ResamplerConfig], + config_class: _ConfigClass, ) -> None: """Test a sample of the next window doesn't push out the window being resampled. The sample can arrive after the tick, but before the window of that tick is resampled, for example because of `tick_delay` or a late wakeup. """ - config = config_class( + config = _make_config( + config_class, resampling_period=timedelta(seconds=1), max_data_age_in_periods=1.0, closed=WindowSide.LEFT, @@ -293,16 +359,17 @@ def add_samples(first: int, last: int) -> None: assert helper.source_properties.dropped_samples == 0 -@pytest.mark.parametrize("config_class", [ResamplerConfig, ResamplerConfig2]) +@pytest.mark.parametrize("config_class", _CONFIG_CLASSES) async def test_helper_first_window_uses_all_its_samples( - config_class: type[ResamplerConfig], + config_class: _ConfigClass, ) -> None: """Test the first window uses all its samples, before the input period is known. Before the input period was estimated, the buffer kept only the newest `initial_buffer_len` samples, so the first window used only those. """ - config = config_class( + config = _make_config( + config_class, resampling_period=timedelta(seconds=60), max_data_age_in_periods=1.0, closed=WindowSide.LEFT, @@ -685,40 +752,37 @@ async def test_calculate_window_end_trivial_cases( ) -> None: """Test the calculation of the resampling window end for simple cases.""" resampling_period = timedelta(seconds=resampling_period_s) - resampler = Resampler( - ResamplerConfig( - resampling_period=resampling_period, - align_to=align_to, - ) + config = ResamplerConfig( + resampling_period=resampling_period, + align_to=align_to, ) + resampler = Resampler(config) fake_time.move_to(now) # pylint: disable-next=protected-access - assert resampler._calculate_window_end() == result + assert resampler._calculate_window_end(config) == result # Repeat the test with align_to=None, so the result should be align to now # instead - resampler_now = Resampler( - ResamplerConfig( - resampling_period=resampling_period, - align_to=now, - ) + config_now = ResamplerConfig( + resampling_period=resampling_period, + align_to=now, ) - resampler_none = Resampler( - ResamplerConfig( - resampling_period=resampling_period, - align_to=None, - ) + resampler_now = Resampler(config_now) + config_none = ResamplerConfig( + resampling_period=resampling_period, + align_to=None, ) + resampler_none = Resampler(config_none) fake_time.move_to(now) # pylint: disable=protected-access - none_result = resampler_none._calculate_window_end() - assert resampler_now._calculate_window_end() == none_result + none_result = resampler_none._calculate_window_end(config_none) + assert resampler_now._calculate_window_end(config_now) == none_result assert none_result[0] == now + resampling_period -@pytest.mark.parametrize("config_class", [ResamplerConfig, ResamplerConfig2]) +@pytest.mark.parametrize("config_class", _CONFIG_CLASSES) async def test_resampling_window_size_is_constant( - config_class: type[ResamplerConfig], + config_class: _ConfigClass, fake_time: time_machine.Coordinates, source_chan: Broadcast[Sample[Quantity]], ) -> None: @@ -731,7 +795,8 @@ async def test_resampling_window_size_is_constant( resampling_fun_mock = MagicMock( spec=ResamplingFunction, return_value=expected_resampled_value ) - config = config_class( + config = _make_config( + config_class, resampling_period=timedelta(seconds=resampling_period_s), max_data_age_in_periods=1.0, resampling_function=resampling_fun_mock, @@ -977,9 +1042,9 @@ async def test_timer_errors_are_logged( # pylint: disable=too-many-statements resampling_fun_mock.reset_mock() -@pytest.mark.parametrize("config_class", [ResamplerConfig, ResamplerConfig2]) +@pytest.mark.parametrize("config_class", _CONFIG_CLASSES) async def test_future_samples_not_included( - config_class: type[ResamplerConfig], + config_class: _ConfigClass, fake_time: time_machine.Coordinates, source_chan: Broadcast[Sample[Quantity]], ) -> None: @@ -992,7 +1057,8 @@ async def test_future_samples_not_included( resampling_fun_mock = MagicMock( spec=ResamplingFunction, return_value=expected_resampled_value ) - config = config_class( + config = _make_config( + config_class, resampling_period=timedelta(seconds=resampling_period_s), max_data_age_in_periods=2.0, resampling_function=resampling_fun_mock, @@ -1075,9 +1141,9 @@ async def test_future_samples_not_included( ) -@pytest.mark.parametrize("config_class", [ResamplerConfig, ResamplerConfig2]) +@pytest.mark.parametrize("config_class", _CONFIG_CLASSES) async def test_resampling_with_one_window( - config_class: type[ResamplerConfig], + config_class: _ConfigClass, fake_time: time_machine.Coordinates, source_chan: Broadcast[Sample[Quantity]], ) -> None: @@ -1090,7 +1156,8 @@ async def test_resampling_with_one_window( resampling_fun_mock = MagicMock( spec=ResamplingFunction, return_value=expected_resampled_value ) - config = config_class( + config = _make_config( + config_class, resampling_period=timedelta(seconds=resampling_period_s), max_data_age_in_periods=1.0, resampling_function=resampling_fun_mock, @@ -1204,9 +1271,9 @@ async def test_resampling_with_one_window( # Even when a lot could be refactored to use smaller functions, I'm allowing # too many statements because it makes following failures in tests more easy # when the code is very flat. -@pytest.mark.parametrize("config_class", [ResamplerConfig, ResamplerConfig2]) +@pytest.mark.parametrize("config_class", _CONFIG_CLASSES) async def test_resampling_with_one_and_a_half_windows( # pylint: disable=too-many-statements - config_class: type[ResamplerConfig], + config_class: _ConfigClass, fake_time: time_machine.Coordinates, source_chan: Broadcast[Sample[Quantity]], ) -> None: @@ -1219,7 +1286,8 @@ async def test_resampling_with_one_and_a_half_windows( # pylint: disable=too-ma resampling_fun_mock = MagicMock( spec=ResamplingFunction, return_value=expected_resampled_value ) - config = config_class( + config = _make_config( + config_class, resampling_period=timedelta(seconds=resampling_period_s), max_data_age_in_periods=1.5, resampling_function=resampling_fun_mock, @@ -1387,9 +1455,9 @@ async def test_resampling_with_one_and_a_half_windows( # pylint: disable=too-ma # Even when a lot could be refactored to use smaller functions, I'm allowing # too many statements because it makes following failures in tests more easy # when the code is very flat. -@pytest.mark.parametrize("config_class", [ResamplerConfig, ResamplerConfig2]) +@pytest.mark.parametrize("config_class", _CONFIG_CLASSES) async def test_resampling_with_two_windows( # pylint: disable=too-many-statements - config_class: type[ResamplerConfig], + config_class: _ConfigClass, fake_time: time_machine.Coordinates, source_chan: Broadcast[Sample[Quantity]], ) -> None: @@ -1402,7 +1470,8 @@ async def test_resampling_with_two_windows( # pylint: disable=too-many-statemen resampling_fun_mock = MagicMock( spec=ResamplingFunction, return_value=expected_resampled_value ) - config = config_class( + config = _make_config( + config_class, resampling_period=timedelta(seconds=resampling_period_s), max_data_age_in_periods=2.0, resampling_function=resampling_fun_mock, @@ -1571,9 +1640,9 @@ async def test_resampling_with_two_windows( # pylint: disable=too-many-statemen assert _get_buffered_samples(resampler, source_receiver) == 7 -@pytest.mark.parametrize("config_class", [ResamplerConfig, ResamplerConfig2]) +@pytest.mark.parametrize("config_class", _CONFIG_CLASSES) async def test_receiving_stopped_resampling_error( - config_class: type[ResamplerConfig], + config_class: _ConfigClass, fake_time: time_machine.Coordinates, source_chan: Broadcast[Sample[Quantity]], ) -> None: @@ -1586,7 +1655,8 @@ async def test_receiving_stopped_resampling_error( resampling_fun_mock = MagicMock( spec=ResamplingFunction, return_value=expected_resampled_value ) - config = config_class( + config = _make_config( + config_class, resampling_period=timedelta(seconds=resampling_period_s), max_data_age_in_periods=2.0, resampling_function=resampling_fun_mock, @@ -1637,9 +1707,9 @@ async def test_receiving_stopped_resampling_error( assert timeseries_error.source is source_receiver -@pytest.mark.parametrize("config_class", [ResamplerConfig, ResamplerConfig2]) +@pytest.mark.parametrize("config_class", _CONFIG_CLASSES) async def test_receiving_resampling_error( - config_class: type[ResamplerConfig], fake_time: time_machine.Coordinates + config_class: _ConfigClass, fake_time: time_machine.Coordinates ) -> None: """Test resampling stops if there is an unknown error.""" timestamp = datetime.now(timezone.utc) @@ -1651,7 +1721,8 @@ async def test_receiving_resampling_error( spec=ResamplingFunction, return_value=expected_resampled_value ) resampler = Resampler( - config_class( + _make_config( + config_class, resampling_period=timedelta(seconds=resampling_period_s), max_data_age_in_periods=2.0, resampling_function=resampling_fun_mock, @@ -1685,9 +1756,9 @@ async def make_fake_source() -> Source: assert isinstance(timeseries_error, TestException) -@pytest.mark.parametrize("config_class", [ResamplerConfig, ResamplerConfig2]) +@pytest.mark.parametrize("config_class", _CONFIG_CLASSES) async def test_timer_is_aligned( - config_class: type[ResamplerConfig], + config_class: _ConfigClass, fake_time: time_machine.Coordinates, source_chan: Broadcast[Sample[Quantity]], caplog: pytest.LogCaptureFixture, @@ -1699,14 +1770,15 @@ async def test_timer_is_aligned( # There is a small difference in behaviour between the (monotonic) Timer and the # WallClockTimer: the former will wait until it has at least one full period filled # with data, while the later fires at the next aligned period after it started. - is_wall_clock = issubclass(config_class, ResamplerConfig2) + is_wall_clock = config_class is not ResamplerConfig start_offset_s = 0 if is_wall_clock else resampling_period_s timestamp = datetime.now(timezone.utc) resampling_fun_mock = MagicMock( spec=ResamplingFunction, return_value=expected_resampled_value ) - config = config_class( + config = _make_config( + config_class, resampling_period=timedelta(seconds=resampling_period_s), max_data_age_in_periods=2.0, resampling_function=resampling_fun_mock, @@ -1836,9 +1908,9 @@ async def test_timer_is_aligned( resampling_fun_mock.reset_mock() -@pytest.mark.parametrize("config_class", [ResamplerConfig, ResamplerConfig2]) +@pytest.mark.parametrize("config_class", _CONFIG_CLASSES) async def test_resampling_all_zeros( - config_class: type[ResamplerConfig], + config_class: _ConfigClass, fake_time: time_machine.Coordinates, source_chan: Broadcast[Sample[Quantity]], ) -> None: @@ -1851,7 +1923,8 @@ async def test_resampling_all_zeros( resampling_fun_mock = MagicMock( spec=ResamplingFunction, return_value=expected_resampled_value ) - config = config_class( + config = _make_config( + config_class, resampling_period=timedelta(seconds=resampling_period_s), max_data_age_in_periods=1.0, resampling_function=resampling_fun_mock, @@ -2129,6 +2202,101 @@ async def test_resampler_label_option( ) +async def test_config3_uses_wall_clock_timer() -> None: + """Test the resampler uses a wall clock timer with a `ResamplerConfig3`.""" + resampler = Resampler(ResamplerConfig3(timedelta(seconds=1))) + + # pylint: disable-next=protected-access + assert isinstance(resampler._timer, WallClockTimer) + + +async def test_config3_defaults_resample_own_window_only( + fake_time: time_machine.Coordinates, + source_chan: Broadcast[Sample[Quantity]], +) -> None: + """Test the defaults average the samples of each window, labelled with its start.""" + timestamp = datetime.now(timezone.utc) + period = timedelta(seconds=2) + resampler = Resampler(ResamplerConfig3(period)) + source_sender = source_chan.new_sender() + sink_mock = AsyncMock(spec=Sink, return_value=True) + resampler.add_timeseries("test", source_chan.new_receiver(), sink_mock) + + # Window [0, 2): the sample at 2 is in the next window + await source_sender.send(Sample(timestamp, Quantity(5.0))) + await source_sender.send(Sample(timestamp + timedelta(seconds=1), Quantity(12.0))) + await source_sender.send(Sample(timestamp + period, Quantity(100.0))) + await _advance_time(fake_time, period.total_seconds()) + await resampler.resample(one_shot=True) + + sink_mock.assert_called_once_with(Sample(timestamp, Quantity(8.5))) + sink_mock.reset_mock() + + # Window [2, 4): the samples of the previous window are not included + await source_sender.send(Sample(timestamp + timedelta(seconds=3), Quantity(4.0))) + await _advance_time(fake_time, period.total_seconds()) + await resampler.resample(one_shot=True) + + sink_mock.assert_called_once_with(Sample(timestamp + period, Quantity(52.0))) + + +async def test_config3_default_mean_includes_older_samples_when_upsampling() -> None: + """Test the default mean can use samples older than the window when upsampling. + + When the input period is bigger than the resampling period, the maximum data + age is relative to the input period. + """ + start = datetime(2020, 1, 1, tzinfo=timezone.utc) + helper = _ResamplingHelper( + "test", + ResamplerConfig3(timedelta(seconds=1), input_period_estimation_samples=2), + ) + + helper.add_sample((start, 1.0)) + helper.add_sample((start + timedelta(seconds=3), 4.0)) + assert helper.resample(start + timedelta(seconds=4)).value == Quantity(4.0) + # The input period is estimated from 2 samples in 4 seconds + assert helper.source_properties.sampling_period == timedelta(seconds=2) + + # The window [4, 5) is empty, but the sample at 3 is not older than 2 seconds + assert helper.resample(start + timedelta(seconds=5)).value == Quantity(4.0) + + +async def test_config3_context( + fake_time: time_machine.Coordinates, +) -> None: + """Test each timeseries gets a context with the window and its own properties.""" + timestamp = datetime.now(timezone.utc) + period = timedelta(seconds=2) + resampling_fun_mock = MagicMock(spec=ResamplingFunction3, return_value=1.0) + config = ResamplerConfig3(period, resampling_function=resampling_fun_mock) + resampler = Resampler(config) + channels = [Broadcast[Sample[Quantity]](name=f"test-{i}") for i in range(2)] + receivers = [channel.new_receiver() for channel in channels] + for channel, receiver in zip(channels, receivers): + resampler.add_timeseries( + channel.name, receiver, AsyncMock(spec=Sink, return_value=True) + ) + await channel.new_sender().send(Sample(timestamp, Quantity(1.0))) + + await _advance_time(fake_time, period.total_seconds()) + await resampler.resample(one_shot=True) + + assert resampling_fun_mock.call_count == 2 + contexts = [call.args[1] for call in resampling_fun_mock.call_args_list] + assert contexts == [ + ResamplingContext( + window_start=timestamp, + config=config, + source_properties=resampler.get_source_properties(receiver), + ) + for receiver in receivers + ] + assert contexts[0].source_properties is not contexts[1].source_properties + for channel in channels: + await channel.aclose() + + def _get_buffered_samples(resampler: Resampler, source_receiver: Source) -> int: # pylint: disable-next=protected-access return len(resampler._resamplers[source_receiver]._helper._buffer) From 3ff70ea7e21e8475ad78f7bb9f4495916803e278 Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Fri, 27 Nov 2026 11:58:43 +0000 Subject: [PATCH 04/11] Don't fail resampling when the maximum data age goes back too far The resampler calculates the oldest relevant timestamp by subtracting max_data_age_in_periods periods from the end of the window. With a big enough maximum data age, the period times the age doesn't fit in a timedelta, or the result is before the oldest datetime, and every resampling raised OverflowError. The old configuration classes accept any maximum data age, so this can happen with them. ResamplerConfig3 rejects ages that don't fit in a timedelta with the resampling period, but the result can still be before the oldest datetime, and when upsampling, the age is relative to the input period, which can be longer. Now, when the oldest relevant timestamp can't be represented, all samples are relevant, which is what such a maximum data age means. Signed-off-by: Leandro Lucarella --- RELEASE_NOTES.md | 2 ++ .../sdk/timeseries/_resampling/_resampler.py | 9 ++++- tests/timeseries/test_resampling.py | 33 +++++++++++++++++++ 3 files changed, 43 insertions(+), 1 deletion(-) diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 3e439dddc..7a75629d5 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -27,3 +27,5 @@ - `max_buffer_len` logs an error, once per timeseries, when samples needed to resample may have been dropped because the buffer was full. - The resampler no longer logs a warning at every resampling while a timeseries has no relevant samples. It logs it once when the samples stop, and logs when they are back, with the number of windows without them. + +- The resampler no longer fails when `max_data_age_in_periods` is so big that the oldest relevant timestamp can't be represented. All samples are relevant then. diff --git a/src/frequenz/sdk/timeseries/_resampling/_resampler.py b/src/frequenz/sdk/timeseries/_resampling/_resampler.py index 7494e1469..0e1d8d355 100644 --- a/src/frequenz/sdk/timeseries/_resampling/_resampler.py +++ b/src/frequenz/sdk/timeseries/_resampling/_resampler.py @@ -413,7 +413,14 @@ def resample(self, timestamp: datetime) -> Sample[Quantity]: if props.sampling_period is not None else conf.resampling_period ) - minimum_relevant_timestamp = timestamp - period * conf.max_data_age_in_periods + try: + minimum_relevant_timestamp = ( + timestamp - period * conf.max_data_age_in_periods + ) + except OverflowError: + # The maximum data age goes back further than a datetime can, so all + # samples are relevant. + minimum_relevant_timestamp = datetime.min.replace(tzinfo=timezone.utc) # Samples older than the relevant ones won't be relevant for later windows # either, unless the input period is still unknown, as the look-back can diff --git a/tests/timeseries/test_resampling.py b/tests/timeseries/test_resampling.py index 5d3cbbd9a..af6fc59d2 100644 --- a/tests/timeseries/test_resampling.py +++ b/tests/timeseries/test_resampling.py @@ -359,6 +359,39 @@ def add_samples(first: int, last: int) -> None: assert helper.source_properties.dropped_samples == 0 +def _resample_with_max_age( + config_class: _ConfigClass, max_age: float +) -> Sample[Quantity]: + """Resample three samples, one per second, with the given maximum data age.""" + config = _make_config( + config_class, + resampling_period=timedelta(seconds=1), + max_data_age_in_periods=max_age, + ) + helper = _ResamplingHelper("test", config) + start = datetime(2020, 1, 1, tzinfo=timezone.utc) + for i in range(3): + helper.add_sample((start + timedelta(seconds=i), float(i))) + return helper.resample(start + timedelta(seconds=3)) + + +@pytest.mark.parametrize("config_class", _CONFIG_CLASSES) +async def test_helper_max_data_age_older_than_datetime( + config_class: _ConfigClass, +) -> None: + """Test a maximum data age that goes back before year 1 uses all samples.""" + assert _resample_with_max_age(config_class, 1e11).value == Quantity(1.0) + + +# ResamplerConfig3 rejects maximum data ages that don't fit in a timedelta +@pytest.mark.parametrize("config_class", _CONFIG_CLASSES[:2]) +async def test_helper_max_data_age_too_big_for_timedelta( + config_class: _ConfigClass, +) -> None: + """Test a maximum data age too big for a `timedelta` uses all samples.""" + assert _resample_with_max_age(config_class, 1e20).value == Quantity(1.0) + + @pytest.mark.parametrize("config_class", _CONFIG_CLASSES) async def test_helper_first_window_uses_all_its_samples( config_class: _ConfigClass, From 3cd6fb9cfd931b8b06ebe47c0fd8aeca14e23fca Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Thu, 26 Nov 2026 14:25:23 +0000 Subject: [PATCH 05/11] Accept ResamplerConfig3 wherever a resampler configuration is taken microgrid.initialize(), the data pipeline, the resampling actor and the MovingWindow now accept a ResamplerConfig3 too. They only use fields that all configurations have, or pass the configuration to the resampler. The configurations are listed in a union instead of a private alias, so the documentation doesn't show a private name, and removing the old classes later only needs a search. Signed-off-by: Leandro Lucarella --- src/frequenz/sdk/microgrid/__init__.py | 8 +++-- src/frequenz/sdk/microgrid/_data_pipeline.py | 10 ++++--- src/frequenz/sdk/microgrid/_resampling.py | 8 +++-- src/frequenz/sdk/timeseries/_moving_window.py | 6 ++-- tests/timeseries/test_moving_window.py | 29 +++++++++++++++---- 5 files changed, 46 insertions(+), 15 deletions(-) diff --git a/src/frequenz/sdk/microgrid/__init__.py b/src/frequenz/sdk/microgrid/__init__.py index 244212e29..0d255b715 100644 --- a/src/frequenz/sdk/microgrid/__init__.py +++ b/src/frequenz/sdk/microgrid/__init__.py @@ -389,7 +389,11 @@ from frequenz.microgrid_component_graph import ComponentGraphConfig, FormulaOverrides -from ..timeseries._resampling._config import ResamplerConfig +from ..timeseries._resampling._config import ( + ResamplerConfig, + ResamplerConfig2, + ResamplerConfig3, +) from . import _data_pipeline, connection_manager from ._data_pipeline import ( consumer, @@ -408,7 +412,7 @@ async def initialize( server_url: str, - resampler_config: ResamplerConfig, + resampler_config: ResamplerConfig3 | ResamplerConfig2 | ResamplerConfig, *, api_power_request_timeout: timedelta = timedelta(seconds=5.0), # pylint: disable-next: line-too-long diff --git a/src/frequenz/sdk/microgrid/_data_pipeline.py b/src/frequenz/sdk/microgrid/_data_pipeline.py index 9ba36e1f5..69814d493 100644 --- a/src/frequenz/sdk/microgrid/_data_pipeline.py +++ b/src/frequenz/sdk/microgrid/_data_pipeline.py @@ -28,7 +28,7 @@ from .._internal._channels import ChannelRegistry from ..actor._actor import Actor -from ..timeseries import ResamplerConfig +from ..timeseries import ResamplerConfig, ResamplerConfig2, ResamplerConfig3 from ..timeseries._voltage_streamer import VoltageStreamer from ._data_sourcing import ComponentMetricRequest, DataSourcingActor from ._power_managing._base_classes import DefaultPower, PowerManagerAlgorithm @@ -97,7 +97,7 @@ class _DataPipeline: # pylint: disable=too-many-instance-attributes def __init__( self, - resampler_config: ResamplerConfig, + resampler_config: ResamplerConfig3 | ResamplerConfig2 | ResamplerConfig, api_power_request_timeout: timedelta = timedelta(seconds=5.0), battery_power_manager_algorithm: PowerManagerAlgorithm = PowerManagerAlgorithm.SHIFTING_MATRYOSHKA, # noqa: E501 ) -> None: @@ -110,7 +110,9 @@ def __init__( battery_power_manager_algorithm: The power manager algorithm to use for batteries. """ - self._resampler_config: ResamplerConfig = resampler_config + self._resampler_config: ( + ResamplerConfig3 | ResamplerConfig2 | ResamplerConfig + ) = resampler_config self._channel_registry: ChannelRegistry = ChannelRegistry( name="Data Pipeline Registry" @@ -638,7 +640,7 @@ async def _stop(self) -> None: async def initialize( - resampler_config: ResamplerConfig, + resampler_config: ResamplerConfig3 | ResamplerConfig2 | ResamplerConfig, api_power_request_timeout: timedelta = timedelta(seconds=5.0), battery_power_manager_algorithm: PowerManagerAlgorithm = PowerManagerAlgorithm.SHIFTING_MATRYOSHKA, # noqa: E501 ) -> None: diff --git a/src/frequenz/sdk/microgrid/_resampling.py b/src/frequenz/sdk/microgrid/_resampling.py index 0d14cecc2..b1b791dda 100644 --- a/src/frequenz/sdk/microgrid/_resampling.py +++ b/src/frequenz/sdk/microgrid/_resampling.py @@ -14,7 +14,11 @@ from .._internal._channels import ChannelRegistry from ..actor._actor import Actor from ..timeseries import Sample -from ..timeseries._resampling._config import ResamplerConfig +from ..timeseries._resampling._config import ( + ResamplerConfig, + ResamplerConfig2, + ResamplerConfig3, +) from ..timeseries._resampling._exceptions import ResamplingError from ..timeseries._resampling._resampler import Resampler from ._data_sourcing import ComponentMetricRequest @@ -31,7 +35,7 @@ def __init__( # pylint: disable=too-many-arguments channel_registry: ChannelRegistry, data_sourcing_request_sender: Sender[ComponentMetricRequest], resampling_request_receiver: Receiver[ComponentMetricRequest], - config: ResamplerConfig, + config: ResamplerConfig3 | ResamplerConfig2 | ResamplerConfig, name: str | None = None, ) -> None: """Initialize an instance. diff --git a/src/frequenz/sdk/timeseries/_moving_window.py b/src/frequenz/sdk/timeseries/_moving_window.py index ddd3789a1..1c9175c68 100644 --- a/src/frequenz/sdk/timeseries/_moving_window.py +++ b/src/frequenz/sdk/timeseries/_moving_window.py @@ -18,7 +18,7 @@ from ..actor._background_service import BackgroundService from ._base_types import Sample -from ._resampling._config import ResamplerConfig +from ._resampling._config import ResamplerConfig, ResamplerConfig2, ResamplerConfig3 from ._resampling._resampler import Resampler from ._ringbuffer import OrderedRingBuffer @@ -135,7 +135,9 @@ def __init__( # pylint: disable=too-many-arguments size: timedelta, resampled_data_recv: Receiver[Sample[Quantity]], input_sampling_period: timedelta, - resampler_config: ResamplerConfig | None = None, + resampler_config: ( + ResamplerConfig3 | ResamplerConfig2 | ResamplerConfig | None + ) = None, align_to: datetime = UNIX_EPOCH, name: str | None = None, ) -> None: diff --git a/tests/timeseries/test_moving_window.py b/tests/timeseries/test_moving_window.py index 90751190e..276639557 100644 --- a/tests/timeseries/test_moving_window.py +++ b/tests/timeseries/test_moving_window.py @@ -20,7 +20,9 @@ MovingWindow, ResamplerConfig, ResamplerConfig2, + ResamplerConfig3, Sample, + WindowSide, ) @@ -64,7 +66,9 @@ async def push_logical_meter_data( def init_moving_window( size: timedelta, - resampler_config: ResamplerConfig | None = None, + resampler_config: ( + ResamplerConfig3 | ResamplerConfig2 | ResamplerConfig | None + ) = None, ) -> tuple[MovingWindow, Sender[Sample[Quantity]]]: """Initialize the moving window with given shape. @@ -457,13 +461,28 @@ async def test_wait_for_samples() -> None: assert task.done() -@pytest.mark.parametrize("config_class", [ResamplerConfig, ResamplerConfig2]) +@pytest.mark.parametrize( + "config_class", [ResamplerConfig, ResamplerConfig2, ResamplerConfig3] +) async def test_wait_for_samples_with_resampling( - config_class: type[ResamplerConfig], fake_time: time_machine.Coordinates + config_class: type[ResamplerConfig] | type[ResamplerConfig3], + fake_time: time_machine.Coordinates, ) -> None: """Test waiting for samples in a moving window with resampling.""" + resampling_period = timedelta(seconds=2) window, sender = init_moving_window( - timedelta(seconds=20), config_class(resampling_period=timedelta(seconds=2)) + timedelta(seconds=20), + ( + # Use the defaults of the other classes, so the expectations hold + ResamplerConfig3( + resampling_period, + max_data_age_in_periods=3.0, + closed=WindowSide.RIGHT, + label=WindowSide.RIGHT, + ) + if config_class is ResamplerConfig3 + else config_class(resampling_period=resampling_period) + ), ) async with window: task = asyncio.create_task(window.wait_for_samples(3)) @@ -523,7 +542,7 @@ async def test_wait_for_samples_with_resampling( # There is also an inconsistency here between the monotonic and wall clock, # the wall clock timer have less samples in the buffer at the end. This is # probably some border condition because of the way we fake time - is_wall_clock = config_class is ResamplerConfig2 + is_wall_clock = config_class is not ResamplerConfig assert window.count_valid() == (5 if is_wall_clock else 7) assert task.done() From c4044d4803192d402353fa1188c0afa91c426330 Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Thu, 26 Nov 2026 14:27:13 +0000 Subject: [PATCH 06/11] Add microgrid.latest_window_mean() To control a microgrid, a short gap in a data stream, or a device that sends data less often than the resampling period, should not make resampled values None. The old defaults covered this by averaging the last three periods, which also smoothed and delayed every value. latest_window_mean() averages only the samples in the newest window that has any, so each value covers a single window when there is data, and falls back to previous windows only when the newer ones are empty. With max_data_age_in_periods=3.0, two missing windows are covered. It lives in the microgrid package, and the setup for control is documented in initialize(), because the timeseries package should not know about microgrids or control. Signed-off-by: Leandro Lucarella --- src/frequenz/sdk/microgrid/__init__.py | 45 +++++++ .../sdk/microgrid/_resampling_functions.py | 76 +++++++++++ tests/microgrid/test_resampling_functions.py | 121 ++++++++++++++++++ 3 files changed, 242 insertions(+) create mode 100644 src/frequenz/sdk/microgrid/_resampling_functions.py create mode 100644 tests/microgrid/test_resampling_functions.py diff --git a/src/frequenz/sdk/microgrid/__init__.py b/src/frequenz/sdk/microgrid/__init__.py index 0d255b715..d4b62fe2d 100644 --- a/src/frequenz/sdk/microgrid/__init__.py +++ b/src/frequenz/sdk/microgrid/__init__.py @@ -408,6 +408,7 @@ voltage_per_phase, ) from ._power_managing import PowerManagerAlgorithm +from ._resampling_functions import latest_window_mean async def initialize( @@ -421,6 +422,49 @@ async def initialize( ) -> None: """Initialize the microgrid connection manager and the data pipeline. + The resampler configuration decides how the data of all the microgrid + timeseries is resampled, for example the data of component pools, formulas and + the grid. + + To control a microgrid, tolerating short gaps in the data is usually more + important than having each value cover only its own window. A small glitch in a + data stream, or a device that sends data less often than the resampling period, + should not make resampled values `None`. For this, we recommend using + [`latest_window_mean()`][frequenz.sdk.microgrid.latest_window_mean] with a + [`max_data_age_in_periods`][frequenz.sdk.timeseries.ResamplerConfig3.max_data_age_in_periods] + bigger than 1.0: + + ```python + from datetime import timedelta + + from frequenz.sdk import microgrid + from frequenz.sdk.timeseries import ResamplerConfig3 + + + async def main() -> None: + await microgrid.initialize( + "grpc://localhost:50051", + ResamplerConfig3( + timedelta(seconds=1), + max_data_age_in_periods=3.0, + resampling_function=microgrid.latest_window_mean, + ), + ) + ``` + + With this configuration, each value is the mean of the samples in its window. + If the window has no samples, the newest of the two previous windows with + samples is used instead, so its values are reused with a newer timestamp. The + maximum data age is relative to the input period for devices that send data + less often than the resampling period, so their last value is repeated while + it is not older than three input periods. + + The maximum data age doesn't guarantee that gaps of that size are covered. Until + the resampler has estimated the input period of a device, which needs + [`input_period_estimation_samples`][frequenz.sdk.timeseries.ResamplerConfig3.input_period_estimation_samples] + samples after a start, the maximum data age is relative to the resampling + period, so resampled values of slow devices can be `None`. + Args: server_url: The location of the microgrid API server in the form of a URL. The following format is expected: `grpc://hostname{:port}{?ssl=ssl}`, @@ -457,6 +501,7 @@ async def initialize( "FormulaOverrides", "PowerManagerAlgorithm", "initialize", + "latest_window_mean", "consumer", "grid", "frequency", diff --git a/src/frequenz/sdk/microgrid/_resampling_functions.py b/src/frequenz/sdk/microgrid/_resampling_functions.py new file mode 100644 index 000000000..3583902a9 --- /dev/null +++ b/src/frequenz/sdk/microgrid/_resampling_functions.py @@ -0,0 +1,76 @@ +# License: MIT +# Copyright © 2026 Frequenz Energy-as-a-Service GmbH + +"""Resampling functions for microgrid data.""" + +import statistics +from bisect import bisect_left, bisect_right +from collections.abc import Sequence +from datetime import datetime +from typing import assert_never + +from ..timeseries import ResamplingContext, WindowSide + + +def latest_window_mean( + input_samples: Sequence[tuple[datetime, float]], + context: ResamplingContext, + /, +) -> float: + """Return the mean of the samples in the newest window that has samples. + + Samples from older windows are only used when all newer windows are empty. This + way resampled values don't average several periods, but short gaps in a + timeseries are covered with the newest values available. How old these values + can be depends on + [`max_data_age_in_periods`][frequenz.sdk.timeseries.ResamplerConfig3.max_data_age_in_periods]. + See [`initialize()`][frequenz.sdk.microgrid.initialize] for how to use it to + control a microgrid. + + Windows are the resampling windows of the resampler, and + [`closed`][frequenz.sdk.timeseries.ResamplerConfig3.closed] decides to which + window a sample on a boundary belongs. The newest window with samples can have + only some of its samples, for example when a fractional + `max_data_age_in_periods` leaves out the oldest part of it. + + Warning: Limitation + The resampler currently expects the samples of each timeseries to arrive + in timestamp order. Samples that arrive out of order can make this + function use the wrong window. See + [frequenz-sdk-python#47](https://github.com/frequenz-floss/frequenz-sdk-python/issues/47). + + Example: + ```python + from datetime import timedelta + + from frequenz.sdk.microgrid import latest_window_mean + from frequenz.sdk.timeseries import ResamplerConfig3 + + config = ResamplerConfig3( + timedelta(seconds=1), + max_data_age_in_periods=3.0, + resampling_function=latest_window_mean, + ) + ``` + + Args: + input_samples: The samples to resample, sorted by timestamp. It must not + be empty. + context: The resampling window being calculated, the configuration of the + resampler and the properties of the timeseries being resampled. + + Returns: + The mean of the samples in the newest window that has samples. + """ + # The newest sample is in the newest window with samples, and every sample + # after the first one in that window is in it too, as samples are sorted and + # never newer than the end of the current window. + start, _ = context.window_bounds(context.window_offset(input_samples[-1][0])) + match context.config.closed: + case WindowSide.LEFT: + first = bisect_left(input_samples, start, key=lambda s: s[0]) + case WindowSide.RIGHT: + first = bisect_right(input_samples, start, key=lambda s: s[0]) + case unexpected: + assert_never(unexpected) + return statistics.fmean(s[1] for s in input_samples[first:]) diff --git a/tests/microgrid/test_resampling_functions.py b/tests/microgrid/test_resampling_functions.py new file mode 100644 index 000000000..08578f176 --- /dev/null +++ b/tests/microgrid/test_resampling_functions.py @@ -0,0 +1,121 @@ +# License: MIT +# Copyright © 2026 Frequenz Energy-as-a-Service GmbH + +"""Tests for the microgrid resampling functions.""" + +from collections.abc import Sequence +from datetime import datetime, timedelta, timezone + +import pytest +from frequenz.core.typing import FloatInt +from frequenz.quantities import Quantity + +from frequenz.sdk.microgrid import latest_window_mean +from frequenz.sdk.timeseries import ( + ResamplerConfig3, + ResamplingContext, + SourceProperties, + WindowSide, +) +from frequenz.sdk.timeseries._resampling._resampler import _ResamplingHelper + +_EPOCH = datetime(2026, 1, 1, tzinfo=timezone.utc) +_PERIOD = timedelta(seconds=10) + + +def _t(seconds: FloatInt) -> datetime: + """Return the timestamp of a number of seconds after the test epoch.""" + return _EPOCH + timedelta(seconds=seconds) + + +def _mean( + samples: Sequence[tuple[FloatInt, float]], + *, + window_start: float = 20.0, + closed: WindowSide = WindowSide.LEFT, +) -> float: + """Resample samples given in seconds after the epoch with `latest_window_mean`.""" + context = ResamplingContext( + window_start=_t(window_start), + config=ResamplerConfig3( + _PERIOD, max_data_age_in_periods=5.0, closed=closed, label=closed + ), + source_properties=SourceProperties(), + ) + return latest_window_mean([(_t(t), v) for t, v in samples], context) + + +def test_current_window_only() -> None: + """Test only the current window is used when it has samples.""" + assert _mean([(5, 100.0), (15, 100.0), (21, 1.0), (25, 2.0)]) == 1.5 + + +@pytest.mark.parametrize("gap", [1, 2], ids=["one window", "two windows"]) +def test_empty_windows_use_newest_previous_window(gap: int) -> None: + """Test the newest previous window with samples is used if newer ones are empty.""" + start = 20 - 10 * gap + samples = [(start - 5, 100.0), (start + 1, 1.0), (start + 9, 3.0)] + + assert _mean(samples) == 2.0 + + +@pytest.mark.parametrize( + "closed, samples, expected", + [ + # [10, 20) and [20, 30): the sample at 20 is in the current window + (WindowSide.LEFT, [(15, 100.0), (20, 1.0), (25, 3.0)], 2.0), + # [10, 20): the sample at 10 is in it + (WindowSide.LEFT, [(5, 100.0), (10, 1.0), (15, 3.0)], 2.0), + # (10, 20] and (20, 30]: the sample at 20 is in the previous window + (WindowSide.RIGHT, [(15, 1.0), (20, 3.0)], 2.0), + # (10, 20]: the sample at 10 is not in it + (WindowSide.RIGHT, [(10, 100.0), (15, 1.0), (20, 3.0)], 2.0), + # (20, 30]: the sample at 30 is in the current window + (WindowSide.RIGHT, [(20, 100.0), (25, 1.0), (30, 3.0)], 2.0), + ], +) +def test_samples_on_boundaries( + closed: WindowSide, samples: list[tuple[FloatInt, float]], expected: float +) -> None: + """Test samples on window boundaries are in the window on their closed side.""" + assert _mean(samples, closed=closed) == expected + + +def test_fractional_max_data_age_partial_window() -> None: + """Test a fractional maximum data age can leave only part of the window.""" + helper = _ResamplingHelper( + "test", + ResamplerConfig3( + _PERIOD, + max_data_age_in_periods=1.5, + resampling_function=latest_window_mean, + ), + ) + for t, v in [(2, 100.0), (6, 1.0), (8, 3.0)]: + helper.add_sample((_t(t), v)) + + # The current window [10, 20) is empty, and samples older than 5 are dropped + assert helper.resample(_t(20)).value == Quantity(2.0) + + +def test_upsampling_repeats_last_value() -> None: + """Test the last value of a slow source is repeated until a new one arrives.""" + helper = _ResamplingHelper( + "test", + ResamplerConfig3( + timedelta(seconds=1), + input_period_estimation_samples=2, + resampling_function=latest_window_mean, + ), + ) + + helper.add_sample((_t(0), 1.0)) + helper.add_sample((_t(3), 4.0)) + assert helper.resample(_t(4)).value == Quantity(4.0) + # The input period is estimated from 2 samples in 4 seconds + assert helper.source_properties.sampling_period == timedelta(seconds=2) + + assert helper.resample(_t(5)).value == Quantity(4.0) + + helper.add_sample((_t(5), 7.0)) + assert helper.resample(_t(6)).value == Quantity(7.0) From 8b5c8ba5e693f43f06462abd02b979fc2c771f4c Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Fri, 27 Nov 2026 09:56:07 +0000 Subject: [PATCH 07/11] Add microgrid.EXAMPLE_RESAMPLER_CONFIG Examples need a resampler configuration to call microgrid.initialize(), and repeating the values recommended for control in each of them, with the explanation of why they are used, is noisy and easy to get out of sync. EXAMPLE_RESAMPLER_CONFIG has those values, and its documentation explains why each one is used. That explanation moves there from the documentation of initialize(), which now links to it, so readers can find it from the constant, from initialize() and from latest_window_mean(). It is meant for examples and quick experiments, not as a default: applications should build their own configuration, using this one as a baseline. This is also why initialize() doesn't use it as the default for its resampler_config argument. Code examples in attribute docstrings are not linted by the docs examples checks, so a test checks the dataclasses.replace() example. Signed-off-by: Leandro Lucarella --- src/frequenz/sdk/microgrid/__init__.py | 44 ++----------- .../microgrid/_example_resampler_config.py | 65 +++++++++++++++++++ .../sdk/microgrid/_resampling_functions.py | 18 +---- .../test_example_resampler_config.py | 33 ++++++++++ 4 files changed, 106 insertions(+), 54 deletions(-) create mode 100644 src/frequenz/sdk/microgrid/_example_resampler_config.py create mode 100644 tests/microgrid/test_example_resampler_config.py diff --git a/src/frequenz/sdk/microgrid/__init__.py b/src/frequenz/sdk/microgrid/__init__.py index d4b62fe2d..44528026e 100644 --- a/src/frequenz/sdk/microgrid/__init__.py +++ b/src/frequenz/sdk/microgrid/__init__.py @@ -407,6 +407,7 @@ producer, voltage_per_phase, ) +from ._example_resampler_config import EXAMPLE_RESAMPLER_CONFIG from ._power_managing import PowerManagerAlgorithm from ._resampling_functions import latest_window_mean @@ -426,44 +427,10 @@ async def initialize( timeseries is resampled, for example the data of component pools, formulas and the grid. - To control a microgrid, tolerating short gaps in the data is usually more - important than having each value cover only its own window. A small glitch in a - data stream, or a device that sends data less often than the resampling period, - should not make resampled values `None`. For this, we recommend using - [`latest_window_mean()`][frequenz.sdk.microgrid.latest_window_mean] with a - [`max_data_age_in_periods`][frequenz.sdk.timeseries.ResamplerConfig3.max_data_age_in_periods] - bigger than 1.0: - - ```python - from datetime import timedelta - - from frequenz.sdk import microgrid - from frequenz.sdk.timeseries import ResamplerConfig3 - - - async def main() -> None: - await microgrid.initialize( - "grpc://localhost:50051", - ResamplerConfig3( - timedelta(seconds=1), - max_data_age_in_periods=3.0, - resampling_function=microgrid.latest_window_mean, - ), - ) - ``` - - With this configuration, each value is the mean of the samples in its window. - If the window has no samples, the newest of the two previous windows with - samples is used instead, so its values are reused with a newer timestamp. The - maximum data age is relative to the input period for devices that send data - less often than the resampling period, so their last value is repeated while - it is not older than three input periods. - - The maximum data age doesn't guarantee that gaps of that size are covered. Until - the resampler has estimated the input period of a device, which needs - [`input_period_estimation_samples`][frequenz.sdk.timeseries.ResamplerConfig3.input_period_estimation_samples] - samples after a start, the maximum data age is relative to the resampling - period, so resampled values of slow devices can be `None`. + Applications that control a microgrid can use + [`EXAMPLE_RESAMPLER_CONFIG`][frequenz.sdk.microgrid.EXAMPLE_RESAMPLER_CONFIG] as + a baseline for their configuration. Its documentation explains why it uses + those values. Args: server_url: The location of the microgrid API server in the form of a URL. @@ -498,6 +465,7 @@ async def main() -> None: __all__ = [ "ComponentGraphConfig", + "EXAMPLE_RESAMPLER_CONFIG", "FormulaOverrides", "PowerManagerAlgorithm", "initialize", diff --git a/src/frequenz/sdk/microgrid/_example_resampler_config.py b/src/frequenz/sdk/microgrid/_example_resampler_config.py new file mode 100644 index 000000000..30bb4fe1d --- /dev/null +++ b/src/frequenz/sdk/microgrid/_example_resampler_config.py @@ -0,0 +1,65 @@ +# License: MIT +# Copyright © 2026 Frequenz Energy-as-a-Service GmbH + +"""A resampler configuration for examples and quick experiments.""" + +from datetime import timedelta +from typing import Final + +from ..timeseries import ResamplerConfig3 +from ._resampling_functions import latest_window_mean + +EXAMPLE_RESAMPLER_CONFIG: Final[ResamplerConfig3] = ResamplerConfig3( + timedelta(seconds=1), + max_data_age_in_periods=3.0, + resampling_function=latest_window_mean, +) +"""A resampler configuration for examples and quick experiments. + +Applications should pass their own configuration to +[`initialize()`][frequenz.sdk.microgrid.initialize], but this one is a good +baseline for an application that controls a microgrid. + +To control a microgrid, tolerating short gaps in the data is usually more +important than having each value cover only its own window. A small glitch in a +data stream, or a device that sends data less often than the resampling period, +should not make resampled values `None`. This is why this configuration uses +[`latest_window_mean()`][frequenz.sdk.microgrid.latest_window_mean] with a +[`max_data_age_in_periods`][frequenz.sdk.timeseries.ResamplerConfig3.max_data_age_in_periods] +of 3: + +- Each value is the mean of the samples in its window. If the window has no + samples, the newest of the two previous windows with samples is used instead, + so its values are reused with a newer timestamp. +- The maximum data age is relative to the input period for devices that send + data less often than the resampling period, so their last value is repeated + while it is not older than three input periods. +- Values are noisier than the mean of several windows, as each value only uses + the samples of one window. + +The maximum data age doesn't guarantee that gaps of that size are covered. Until +the resampler has estimated the input period of a device, which needs +[`input_period_estimation_samples`][frequenz.sdk.timeseries.ResamplerConfig3.input_period_estimation_samples] +samples after a start, the maximum data age is relative to the resampling +period, so resampled values of slow devices can be `None`. + +The resampling period of 1 second keeps the resampled data close to real time. +The other settings are the defaults of +[`ResamplerConfig3`][frequenz.sdk.timeseries.ResamplerConfig3], so each value +covers its window from its start, included, to its end, excluded, and its +timestamp is the start of the window. + +To change some of the values, for example the resampling period, use +[`dataclasses.replace()`][dataclasses.replace]: + +```python +import dataclasses +from datetime import timedelta + +from frequenz.sdk import microgrid + +config = dataclasses.replace( + microgrid.EXAMPLE_RESAMPLER_CONFIG, resampling_period=timedelta(seconds=5) +) +``` +""" diff --git a/src/frequenz/sdk/microgrid/_resampling_functions.py b/src/frequenz/sdk/microgrid/_resampling_functions.py index 3583902a9..750d2d062 100644 --- a/src/frequenz/sdk/microgrid/_resampling_functions.py +++ b/src/frequenz/sdk/microgrid/_resampling_functions.py @@ -24,8 +24,8 @@ def latest_window_mean( timeseries are covered with the newest values available. How old these values can be depends on [`max_data_age_in_periods`][frequenz.sdk.timeseries.ResamplerConfig3.max_data_age_in_periods]. - See [`initialize()`][frequenz.sdk.microgrid.initialize] for how to use it to - control a microgrid. + [`EXAMPLE_RESAMPLER_CONFIG`][frequenz.sdk.microgrid.EXAMPLE_RESAMPLER_CONFIG] + uses it, and explains why it suits controlling a microgrid. Windows are the resampling windows of the resampler, and [`closed`][frequenz.sdk.timeseries.ResamplerConfig3.closed] decides to which @@ -39,20 +39,6 @@ def latest_window_mean( function use the wrong window. See [frequenz-sdk-python#47](https://github.com/frequenz-floss/frequenz-sdk-python/issues/47). - Example: - ```python - from datetime import timedelta - - from frequenz.sdk.microgrid import latest_window_mean - from frequenz.sdk.timeseries import ResamplerConfig3 - - config = ResamplerConfig3( - timedelta(seconds=1), - max_data_age_in_periods=3.0, - resampling_function=latest_window_mean, - ) - ``` - Args: input_samples: The samples to resample, sorted by timestamp. It must not be empty. diff --git a/tests/microgrid/test_example_resampler_config.py b/tests/microgrid/test_example_resampler_config.py new file mode 100644 index 000000000..451663180 --- /dev/null +++ b/tests/microgrid/test_example_resampler_config.py @@ -0,0 +1,33 @@ +# License: MIT +# Copyright © 2026 Frequenz Energy-as-a-Service GmbH + +"""Tests for the example resampler configuration.""" + +import dataclasses +from datetime import timedelta + +from frequenz.sdk import microgrid +from frequenz.sdk.timeseries import ResamplerConfig3 + + +def test_example_resampler_config_values() -> None: + """Test the configuration has the values its documentation explains.""" + assert microgrid.EXAMPLE_RESAMPLER_CONFIG == ResamplerConfig3( + timedelta(seconds=1), + max_data_age_in_periods=3.0, + resampling_function=microgrid.latest_window_mean, + ) + + +def test_example_resampler_config_can_be_changed_with_replace() -> None: + """Test the `dataclasses.replace()` example in the documentation. + + Code examples in attribute docstrings are not checked automatically. + """ + config = dataclasses.replace( + microgrid.EXAMPLE_RESAMPLER_CONFIG, resampling_period=timedelta(seconds=5) + ) + + assert config.resampling_period == timedelta(seconds=5) + assert config.max_data_age_in_periods == 3.0 + assert config.resampling_function is microgrid.latest_window_mean From f59af9ae27d2ffc0b8fa5621c73cf84e96c6f502 Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Thu, 26 Nov 2026 14:34:21 +0000 Subject: [PATCH 08/11] Use ResamplerConfig3 in the SDK's own code, docs and tests Docstring examples, the getting started tutorial, the examples and the benchmarks that call microgrid.initialize() now use microgrid.EXAMPLE_RESAMPLER_CONFIG. Microgrid tests use it too, with dataclasses.replace() when they need another resampling period. Tests that aren't about the old classes use ResamplerConfig3 too. Where their expectations depend on values labelled with the end of their window, they set the old window conventions explicitly. The tests that are about the monotonic timer, or that run with every configuration class, keep using the old classes until they are removed. Signed-off-by: Leandro Lucarella --- .../power_distribution/power_distributor.py | 3 +- benchmarks/timeseries/resampling.py | 13 ++++---- docs/tutorials/getting_started.md | 14 ++++---- examples/battery_pool.py | 4 +-- .../sdk/timeseries/_voltage_streamer.py | 5 +-- src/frequenz/sdk/timeseries/consumer.py | 5 +-- src/frequenz/sdk/timeseries/grid.py | 5 +-- .../logical_meter/_logical_meter.py | 5 +-- src/frequenz/sdk/timeseries/producer.py | 5 +-- tests/actor/test_resampling.py | 26 +++++++++++---- tests/microgrid/fixtures.py | 6 ++-- tests/microgrid/test_datapipeline.py | 5 ++- .../_battery_pool/test_battery_pool.py | 12 +++++-- .../test_battery_pool_control_methods.py | 5 +-- .../test_ev_charger_pool_control_methods.py | 7 ++-- .../_pv_pool/test_pv_pool_control_methods.py | 6 ++-- .../test_steam_boiler_pool_control_methods.py | 6 ++-- tests/timeseries/mock_microgrid.py | 4 +-- tests/timeseries/mock_resampler.py | 4 +-- tests/timeseries/test_moving_window.py | 7 +++- tests/timeseries/test_resampling.py | 32 +++++++++++-------- 21 files changed, 98 insertions(+), 81 deletions(-) diff --git a/benchmarks/power_distribution/power_distributor.py b/benchmarks/power_distribution/power_distributor.py index 08880d173..d4f4fd769 100644 --- a/benchmarks/power_distribution/power_distributor.py +++ b/benchmarks/power_distribution/power_distributor.py @@ -28,7 +28,6 @@ Result, Success, ) -from frequenz.sdk.timeseries import ResamplerConfig2 HOST = "microgrid.sandbox.api.frequenz.io" PORT = 62060 @@ -139,7 +138,7 @@ async def run() -> None: """Create microgrid api and run tests.""" await microgrid.initialize( "grpc://microgrid.sandbox.api.frequenz.io:62060", - ResamplerConfig2(resampling_period=timedelta(seconds=1.0)), + microgrid.EXAMPLE_RESAMPLER_CONFIG, ) all_batteries = connection_manager.get().component_graph.components( diff --git a/benchmarks/timeseries/resampling.py b/benchmarks/timeseries/resampling.py index 673e73aef..570251c3e 100644 --- a/benchmarks/timeseries/resampling.py +++ b/benchmarks/timeseries/resampling.py @@ -7,15 +7,14 @@ from datetime import datetime, timedelta, timezone from timeit import timeit -from frequenz.sdk.timeseries import ResamplerConfig, ResamplerConfig2 -from frequenz.sdk.timeseries._resampling._base_types import SourceProperties +from frequenz.sdk.timeseries import ResamplerConfig3, ResamplingContext from frequenz.sdk.timeseries._resampling._resampler import _ResamplingHelper def nop( # pylint: disable=unused-argument samples: Sequence[tuple[datetime, float]], - resampler_config: ResamplerConfig, - source_properties: SourceProperties, + context: ResamplingContext, + /, ) -> float: """Return 0.0.""" return 0.0 @@ -25,11 +24,11 @@ def _benchmark_resampling_helper(resamples: int, samples: int) -> None: """Benchmark the resampling helper.""" helper = _ResamplingHelper( "benchmark", - ResamplerConfig2( - resampling_period=timedelta(seconds=1.0), + ResamplerConfig3( + timedelta(seconds=1.0), max_data_age_in_periods=3.0, resampling_function=nop, - initial_buffer_len=samples * 3, + input_period_estimation_samples=samples * 3, warn_buffer_len=samples * 3 + 2, max_buffer_len=samples * 3 + 3, ), diff --git a/docs/tutorials/getting_started.md b/docs/tutorials/getting_started.md index ddeed9d00..94d59bc51 100644 --- a/docs/tutorials/getting_started.md +++ b/docs/tutorials/getting_started.md @@ -30,16 +30,18 @@ importing the necessary libraries. ```python import asyncio -from datetime import timedelta from frequenz.sdk import microgrid -from frequenz.sdk.timeseries import ResamplerConfig2 ``` ## Create the application skeleton The main logic of your application will run within an async function. Let's create a skeleton that contains all the necessary code to initialize a -microgrid. +microgrid. It uses +[`microgrid.EXAMPLE_RESAMPLER_CONFIG`][frequenz.sdk.microgrid.EXAMPLE_RESAMPLER_CONFIG], +a resampler configuration for examples. A real application should use its own +configuration, and the documentation of `EXAMPLE_RESAMPLER_CONFIG` explains how +to choose one. ```python async def run() -> None: @@ -49,7 +51,7 @@ async def run() -> None: # Initialize the microgrid await microgrid.initialize( server_url, - ResamplerConfig2(resampling_period=timedelta(seconds=1)), + microgrid.EXAMPLE_RESAMPLER_CONFIG, ) # Define your application logic here @@ -98,9 +100,7 @@ Here is the full version of your first Frequenz SDK application. ```python import asyncio -from datetime import timedelta from frequenz.sdk import microgrid -from frequenz.sdk.timeseries import ResamplerConfig2 async def run() -> None: # This points to the default Frequenz microgrid sandbox @@ -109,7 +109,7 @@ async def run() -> None: # Initialize the microgrid await microgrid.initialize( server_url, - ResamplerConfig2(resampling_period=timedelta(seconds=1)), + microgrid.EXAMPLE_RESAMPLER_CONFIG, ) # Define your application logic here diff --git a/examples/battery_pool.py b/examples/battery_pool.py index 971256c37..c235db003 100644 --- a/examples/battery_pool.py +++ b/examples/battery_pool.py @@ -5,12 +5,10 @@ import asyncio import logging -from datetime import timedelta from frequenz.channels import merge from frequenz.sdk import microgrid -from frequenz.sdk.timeseries import ResamplerConfig2 MICROGRID_API_URL = "grpc://microgrid.sandbox.api.frequenz.io:62060" @@ -23,7 +21,7 @@ async def main() -> None: await microgrid.initialize( MICROGRID_API_URL, - resampler_config=ResamplerConfig2(resampling_period=timedelta(seconds=1.0)), + resampler_config=microgrid.EXAMPLE_RESAMPLER_CONFIG, ) battery_pool = microgrid.new_battery_pool(priority=5) diff --git a/src/frequenz/sdk/timeseries/_voltage_streamer.py b/src/frequenz/sdk/timeseries/_voltage_streamer.py index 4759b362f..f24ab7c0c 100644 --- a/src/frequenz/sdk/timeseries/_voltage_streamer.py +++ b/src/frequenz/sdk/timeseries/_voltage_streamer.py @@ -34,14 +34,11 @@ class VoltageStreamer: Example: ```python - from datetime import timedelta - from frequenz.sdk import microgrid - from frequenz.sdk.timeseries import ResamplerConfig2 await microgrid.initialize( "grpc://127.0.0.1:50051", - ResamplerConfig2(resampling_period=timedelta(seconds=1)) + microgrid.EXAMPLE_RESAMPLER_CONFIG, ) # Get a receiver for the phase-to-neutral voltage. diff --git a/src/frequenz/sdk/timeseries/consumer.py b/src/frequenz/sdk/timeseries/consumer.py index 0376c0444..84fcda121 100644 --- a/src/frequenz/sdk/timeseries/consumer.py +++ b/src/frequenz/sdk/timeseries/consumer.py @@ -33,14 +33,11 @@ class Consumer: Example: ```python - from datetime import timedelta - from frequenz.sdk import microgrid - from frequenz.sdk.timeseries import ResamplerConfig2 await microgrid.initialize( "grpc://127.0.0.1:50051", - ResamplerConfig2(resampling_period=timedelta(seconds=1.0)) + microgrid.EXAMPLE_RESAMPLER_CONFIG, ) consumer = microgrid.consumer() diff --git a/src/frequenz/sdk/timeseries/grid.py b/src/frequenz/sdk/timeseries/grid.py index 9640ee4bf..69a2f8094 100644 --- a/src/frequenz/sdk/timeseries/grid.py +++ b/src/frequenz/sdk/timeseries/grid.py @@ -39,14 +39,11 @@ class Grid: Example: ```python - from datetime import timedelta - from frequenz.sdk import microgrid - from frequenz.sdk.timeseries import ResamplerConfig2 await microgrid.initialize( "grpc://127.0.0.1:50051", - ResamplerConfig2(resampling_period=timedelta(seconds=1)) + microgrid.EXAMPLE_RESAMPLER_CONFIG, ) grid = microgrid.grid() diff --git a/src/frequenz/sdk/timeseries/logical_meter/_logical_meter.py b/src/frequenz/sdk/timeseries/logical_meter/_logical_meter.py index 44c45ad8b..54897d421 100644 --- a/src/frequenz/sdk/timeseries/logical_meter/_logical_meter.py +++ b/src/frequenz/sdk/timeseries/logical_meter/_logical_meter.py @@ -31,16 +31,13 @@ class LogicalMeter: Example: ```python - from datetime import timedelta - from frequenz.sdk import microgrid - from frequenz.sdk.timeseries import ResamplerConfig2 from frequenz.client.microgrid.metrics import Metric await microgrid.initialize( "grpc://microgrid.sandbox.api.frequenz.io:62060", - ResamplerConfig2(resampling_period=timedelta(seconds=1)), + microgrid.EXAMPLE_RESAMPLER_CONFIG, ) logical_meter = ( diff --git a/src/frequenz/sdk/timeseries/producer.py b/src/frequenz/sdk/timeseries/producer.py index 0c82ae16c..563bfb94e 100644 --- a/src/frequenz/sdk/timeseries/producer.py +++ b/src/frequenz/sdk/timeseries/producer.py @@ -33,14 +33,11 @@ class Producer: Example: ```python - from datetime import timedelta - from frequenz.sdk import microgrid - from frequenz.sdk.timeseries import ResamplerConfig2 await microgrid.initialize( "grpc://127.0.0.1:50051", - ResamplerConfig2(resampling_period=timedelta(seconds=1.0)) + microgrid.EXAMPLE_RESAMPLER_CONFIG, ) producer = microgrid.producer() diff --git a/tests/actor/test_resampling.py b/tests/actor/test_resampling.py index 2f0dc2c26..a08a30ac4 100644 --- a/tests/actor/test_resampling.py +++ b/tests/actor/test_resampling.py @@ -18,7 +18,7 @@ from frequenz.sdk._internal._channels import ChannelRegistry from frequenz.sdk.microgrid._data_sourcing import ComponentMetricRequest from frequenz.sdk.microgrid._resampling import ComponentMetricsResamplingActor -from frequenz.sdk.timeseries import ResamplerConfig2, Sample +from frequenz.sdk.timeseries import ResamplerConfig3, Sample, WindowSide @pytest.fixture(autouse=True) @@ -114,9 +114,13 @@ async def test_single_request( channel_registry=channel_registry, data_sourcing_request_sender=data_source_req_chan.new_sender(), resampling_request_receiver=resampling_req_chan.new_receiver(), - config=ResamplerConfig2( - resampling_period=timedelta(seconds=0.2), + config=ResamplerConfig3( + timedelta(seconds=0.2), max_data_age_in_periods=2, + # _assert_resampling_works() expects samples labelled with the + # end of their window + closed=WindowSide.RIGHT, + label=WindowSide.RIGHT, ), ) as resampling_actor: subs_req = ComponentMetricRequest( @@ -157,9 +161,13 @@ async def test_duplicate_request( channel_registry=channel_registry, data_sourcing_request_sender=data_source_req_chan.new_sender(), resampling_request_receiver=resampling_req_chan.new_receiver(), - config=ResamplerConfig2( - resampling_period=timedelta(seconds=0.2), + config=ResamplerConfig3( + timedelta(seconds=0.2), max_data_age_in_periods=2, + # _assert_resampling_works() expects samples labelled with the + # end of their window + closed=WindowSide.RIGHT, + label=WindowSide.RIGHT, ), ) as resampling_actor: subs_req = ComponentMetricRequest( @@ -199,9 +207,13 @@ async def test_stalled_request_does_not_block_later_subscriptions() -> None: channel_registry=channel_registry, data_sourcing_request_sender=data_source_req_chan.new_sender(), resampling_request_receiver=resampling_req_chan.new_receiver(), - config=ResamplerConfig2( - resampling_period=timedelta(seconds=0.2), + config=ResamplerConfig3( + timedelta(seconds=0.2), max_data_age_in_periods=2, + # _assert_resampling_works() expects samples labelled with the + # end of their window + closed=WindowSide.RIGHT, + label=WindowSide.RIGHT, ), ): first_request = ComponentMetricRequest( diff --git a/tests/microgrid/fixtures.py b/tests/microgrid/fixtures.py index f1c6b0f12..a1ad2bcf6 100644 --- a/tests/microgrid/fixtures.py +++ b/tests/microgrid/fixtures.py @@ -23,7 +23,6 @@ from frequenz.sdk import microgrid from frequenz.sdk.microgrid._power_distributing import ComponentPoolStatus -from frequenz.sdk.timeseries import ResamplerConfig2 from ..timeseries.mock_microgrid import MockMicrogrid from ..utils.component_data_streamer import MockComponentDataStreamer @@ -62,7 +61,10 @@ async def new( if microgrid._data_pipeline._DATA_PIPELINE is not None: microgrid._data_pipeline._DATA_PIPELINE = None await microgrid._data_pipeline.initialize( - ResamplerConfig2(resampling_period=timedelta(seconds=0.1)) + dataclasses.replace( + microgrid.EXAMPLE_RESAMPLER_CONFIG, + resampling_period=timedelta(seconds=0.1), + ), ) streamer = MockComponentDataStreamer(mockgrid.mock_client) diff --git a/tests/microgrid/test_datapipeline.py b/tests/microgrid/test_datapipeline.py index fea4876c5..86c41e5eb 100644 --- a/tests/microgrid/test_datapipeline.py +++ b/tests/microgrid/test_datapipeline.py @@ -29,7 +29,6 @@ from frequenz.sdk import microgrid from frequenz.sdk.microgrid import _data_pipeline from frequenz.sdk.microgrid._data_pipeline import _DataPipeline -from frequenz.sdk.timeseries import ResamplerConfig2 from frequenz.sdk.timeseries.component_pool import ComponentPool from ..timeseries.mock_microgrid import MockMicrogrid @@ -51,7 +50,7 @@ async def test_actors_started( ) -> None: """Test that the datasourcing, resampling and power distributing actors are started.""" datapipeline = _DataPipeline( - resampler_config=ResamplerConfig2(resampling_period=timedelta(seconds=1)) + resampler_config=microgrid.EXAMPLE_RESAMPLER_CONFIG, ) await asyncio.sleep(1) @@ -154,7 +153,7 @@ async def test_empty_component_ids_matches_none_in_either_call_order( what BOTH calls got. """ datapipeline = _DataPipeline( - resampler_config=ResamplerConfig2(resampling_period=timedelta(seconds=1)) + resampler_config=microgrid.EXAMPLE_RESAMPLER_CONFIG, ) grid_1 = GridConnectionPoint( diff --git a/tests/timeseries/_battery_pool/test_battery_pool.py b/tests/timeseries/_battery_pool/test_battery_pool.py index 510d47dcd..10b8a2dac 100644 --- a/tests/timeseries/_battery_pool/test_battery_pool.py +++ b/tests/timeseries/_battery_pool/test_battery_pool.py @@ -37,7 +37,7 @@ _get_battery_inverter_mappings, ) from frequenz.sdk.microgrid._power_managing import ReportRequest, _Report -from frequenz.sdk.timeseries import Bounds, ResamplerConfig2, Sample +from frequenz.sdk.timeseries import Bounds, Sample from frequenz.sdk.timeseries._base_types import SystemBounds from frequenz.sdk.timeseries.battery_pool import BatteryPool from frequenz.sdk.timeseries.battery_pool._battery_pool_reference_store import ( @@ -148,7 +148,10 @@ async def setup_all_batteries(mocker: MockerFixture) -> AsyncIterator[SetupArgs] # pylint: disable=protected-access microgrid._data_pipeline._DATA_PIPELINE = None await microgrid._data_pipeline.initialize( - ResamplerConfig2(resampling_period=timedelta(seconds=min_update_interval)) + dataclasses.replace( + microgrid.EXAMPLE_RESAMPLER_CONFIG, + resampling_period=timedelta(seconds=min_update_interval), + ) ) streamer = MockComponentDataStreamer(mock_microgrid) @@ -199,7 +202,10 @@ async def setup_batteries_pool(mocker: MockerFixture) -> AsyncIterator[SetupArgs # pylint: disable=protected-access microgrid._data_pipeline._DATA_PIPELINE = None await microgrid._data_pipeline.initialize( - ResamplerConfig2(resampling_period=timedelta(seconds=min_update_interval)) + dataclasses.replace( + microgrid.EXAMPLE_RESAMPLER_CONFIG, + resampling_period=timedelta(seconds=min_update_interval), + ) ) # We don't use status channel from the sdk interface to limit diff --git a/tests/timeseries/_battery_pool/test_battery_pool_control_methods.py b/tests/timeseries/_battery_pool/test_battery_pool_control_methods.py index c2b5947c8..244dfc66e 100644 --- a/tests/timeseries/_battery_pool/test_battery_pool_control_methods.py +++ b/tests/timeseries/_battery_pool/test_battery_pool_control_methods.py @@ -22,7 +22,6 @@ from frequenz.sdk.microgrid._power_distributing._component_pool_status_tracker import ( ComponentPoolStatusTracker, ) -from frequenz.sdk.timeseries import ResamplerConfig2 from frequenz.sdk.timeseries.battery_pool._metric_calculator import ( PowerBoundsCalculator, ) @@ -69,7 +68,9 @@ async def mocks(mocker: MockerFixture) -> AsyncIterator[Mocks]: if microgrid._data_pipeline._DATA_PIPELINE is not None: microgrid._data_pipeline._DATA_PIPELINE = None await microgrid._data_pipeline.initialize( - ResamplerConfig2(resampling_period=timedelta(seconds=0.1)) + dataclasses.replace( + microgrid.EXAMPLE_RESAMPLER_CONFIG, resampling_period=timedelta(seconds=0.1) + ), ) streamer = MockComponentDataStreamer(mockgrid.mock_client) diff --git a/tests/timeseries/_ev_charger_pool/test_ev_charger_pool_control_methods.py b/tests/timeseries/_ev_charger_pool/test_ev_charger_pool_control_methods.py index 8c2a90d81..74895098e 100644 --- a/tests/timeseries/_ev_charger_pool/test_ev_charger_pool_control_methods.py +++ b/tests/timeseries/_ev_charger_pool/test_ev_charger_pool_control_methods.py @@ -4,6 +4,7 @@ """Test the EV charger pool control methods.""" import asyncio +import dataclasses from collections.abc import AsyncIterator, Callable from datetime import datetime, timedelta, timezone from typing import cast @@ -24,7 +25,7 @@ from frequenz.sdk.microgrid._power_distributing._component_pool_status_tracker import ( ComponentPoolStatusTracker, ) -from frequenz.sdk.timeseries import ResamplerConfig2, Sample3Phase +from frequenz.sdk.timeseries import Sample3Phase from frequenz.sdk.timeseries.ev_charger_pool import EVChargerPoolReport from ...microgrid.fixtures import _Mocks @@ -52,7 +53,9 @@ async def mocks(mocker: MockerFixture) -> AsyncIterator[_Mocks]: if microgrid._data_pipeline._DATA_PIPELINE is not None: microgrid._data_pipeline._DATA_PIPELINE = None await microgrid._data_pipeline.initialize( - ResamplerConfig2(resampling_period=timedelta(seconds=0.1)) + dataclasses.replace( + microgrid.EXAMPLE_RESAMPLER_CONFIG, resampling_period=timedelta(seconds=0.1) + ), ) streamer = MockComponentDataStreamer(mockgrid.mock_client) diff --git a/tests/timeseries/_pv_pool/test_pv_pool_control_methods.py b/tests/timeseries/_pv_pool/test_pv_pool_control_methods.py index 701d508b8..b27f03ca6 100644 --- a/tests/timeseries/_pv_pool/test_pv_pool_control_methods.py +++ b/tests/timeseries/_pv_pool/test_pv_pool_control_methods.py @@ -4,6 +4,7 @@ """Test the PV pool control methods.""" import asyncio +import dataclasses import typing from datetime import datetime, timedelta, timezone from unittest.mock import AsyncMock @@ -19,7 +20,6 @@ from frequenz.sdk import microgrid from frequenz.sdk.microgrid import _power_distributing from frequenz.sdk.microgrid._data_pipeline import _DataPipeline -from frequenz.sdk.timeseries import ResamplerConfig2 from frequenz.sdk.timeseries.pv_pool import PVPoolReport from ...microgrid.fixtures import _Mocks @@ -48,7 +48,9 @@ async def mocks(mocker: MockerFixture) -> typing.AsyncIterator[_Mocks]: if microgrid._data_pipeline._DATA_PIPELINE is not None: microgrid._data_pipeline._DATA_PIPELINE = None await microgrid._data_pipeline.initialize( - ResamplerConfig2(resampling_period=timedelta(seconds=0.1)) + dataclasses.replace( + microgrid.EXAMPLE_RESAMPLER_CONFIG, resampling_period=timedelta(seconds=0.1) + ), ) streamer = MockComponentDataStreamer(mockgrid.mock_client) diff --git a/tests/timeseries/_steam_boiler_pool/test_steam_boiler_pool_control_methods.py b/tests/timeseries/_steam_boiler_pool/test_steam_boiler_pool_control_methods.py index 4e79f77d9..b4382e5e0 100644 --- a/tests/timeseries/_steam_boiler_pool/test_steam_boiler_pool_control_methods.py +++ b/tests/timeseries/_steam_boiler_pool/test_steam_boiler_pool_control_methods.py @@ -4,6 +4,7 @@ """Test the steam boiler pool control methods.""" import asyncio +import dataclasses import typing from datetime import datetime, timedelta, timezone from unittest.mock import AsyncMock @@ -19,7 +20,6 @@ from frequenz.sdk import microgrid from frequenz.sdk.microgrid import _power_distributing from frequenz.sdk.microgrid._data_pipeline import _DataPipeline -from frequenz.sdk.timeseries import ResamplerConfig2 from frequenz.sdk.timeseries.steam_boiler_pool import SteamBoilerPoolReport from ...microgrid.fixtures import _Mocks @@ -48,7 +48,9 @@ async def mocks(mocker: MockerFixture) -> typing.AsyncIterator[_Mocks]: if microgrid._data_pipeline._DATA_PIPELINE is not None: microgrid._data_pipeline._DATA_PIPELINE = None await microgrid._data_pipeline.initialize( - ResamplerConfig2(resampling_period=timedelta(seconds=0.1)) + dataclasses.replace( + microgrid.EXAMPLE_RESAMPLER_CONFIG, resampling_period=timedelta(seconds=0.1) + ), ) streamer = MockComponentDataStreamer(mockgrid.mock_client) diff --git a/tests/timeseries/mock_microgrid.py b/tests/timeseries/mock_microgrid.py index 248cace17..ec8311b4d 100644 --- a/tests/timeseries/mock_microgrid.py +++ b/tests/timeseries/mock_microgrid.py @@ -36,7 +36,7 @@ from frequenz.sdk._internal._asyncio import cancel_and_await from frequenz.sdk.microgrid import _data_pipeline from frequenz.sdk.microgrid._old_component_data import ComponentData -from frequenz.sdk.timeseries import ResamplerConfig2 +from frequenz.sdk.timeseries import ResamplerConfig3 from ..utils import MockMicrogridClient from ..utils.component_data_wrapper import ( @@ -211,7 +211,7 @@ async def start(self, mocker: MockerFixture | None = None) -> None: self.init_mock_client(lambda mock_client: mock_client.initialize(local_mocker)) self.mock_resampler = MockResampler( mocker, - ResamplerConfig2(timedelta(seconds=self._sample_rate_s)), + ResamplerConfig3(timedelta(seconds=self._sample_rate_s)), bat_inverter_ids=self.battery_inverter_ids, pv_inverter_ids=self.pv_inverter_ids, evc_ids=self.evc_ids, diff --git a/tests/timeseries/mock_resampler.py b/tests/timeseries/mock_resampler.py index ee09c9834..97336a63f 100644 --- a/tests/timeseries/mock_resampler.py +++ b/tests/timeseries/mock_resampler.py @@ -16,7 +16,7 @@ from frequenz.sdk._internal._asyncio import cancel_and_await from frequenz.sdk.microgrid._data_pipeline import _DataPipeline from frequenz.sdk.microgrid._data_sourcing import ComponentMetricRequest -from frequenz.sdk.timeseries import ResamplerConfig2, Sample +from frequenz.sdk.timeseries import ResamplerConfig3, Sample from frequenz.sdk.timeseries.formulas._formula_pool import ( NON_EXISTING_COMPONENT_ID, ) @@ -30,7 +30,7 @@ class MockResampler: def __init__( # pylint: disable=too-many-arguments,too-many-positional-arguments self, mocker: MockerFixture, - resampler_config: ResamplerConfig2, + resampler_config: ResamplerConfig3, bat_inverter_ids: list[ComponentId], pv_inverter_ids: list[ComponentId], evc_ids: list[ComponentId], diff --git a/tests/timeseries/test_moving_window.py b/tests/timeseries/test_moving_window.py index 276639557..1098e14ab 100644 --- a/tests/timeseries/test_moving_window.py +++ b/tests/timeseries/test_moving_window.py @@ -556,7 +556,12 @@ async def test_resampling_window(fake_time: time_machine.Coordinates) -> None: window_size = timedelta(seconds=16) input_sampling = timedelta(seconds=1) output_sampling = timedelta(seconds=2) - resampler_config = ResamplerConfig(resampling_period=output_sampling) + resampler_config = ResamplerConfig3( + output_sampling, + max_data_age_in_periods=3.0, + closed=WindowSide.RIGHT, + label=WindowSide.RIGHT, + ) async with MovingWindow( size=window_size, diff --git a/tests/timeseries/test_resampling.py b/tests/timeseries/test_resampling.py index af6fc59d2..7346bc4bd 100644 --- a/tests/timeseries/test_resampling.py +++ b/tests/timeseries/test_resampling.py @@ -488,11 +488,12 @@ async def tick_delay_resampler( async def timer() -> AsyncIterator[TickInfo]: yield TickInfo(expected_tick_time=window_end, sleep_infos=[]) - config = ResamplerConfig2( - resampling_period=resampling_period, + config = ResamplerConfig3( + resampling_period, max_data_age_in_periods=1.0, - resampling_function=resampling_fun_mock, + resampling_function=_with_old_signature(resampling_fun_mock), closed=WindowSide.LEFT, + label=WindowSide.RIGHT, tick_delay=tick_delay, ) resampler = Resampler(config) @@ -622,11 +623,12 @@ async def test_without_tick_delay_late_window_samples_are_missed( async def timer() -> AsyncIterator[TickInfo]: yield TickInfo(expected_tick_time=window_end, sleep_infos=[]) - config = ResamplerConfig2( - resampling_period=resampling_period, + config = ResamplerConfig3( + resampling_period, max_data_age_in_periods=1.0, - resampling_function=resampling_fun_mock, + resampling_function=_with_old_signature(resampling_fun_mock), closed=WindowSide.LEFT, + label=WindowSide.RIGHT, tick_delay=timedelta(0), ) resampler = Resampler(config) @@ -2070,7 +2072,7 @@ async def test_resampler_closed_option( fake_time: time_machine.Coordinates, source_chan: Broadcast[Sample[Quantity]], ) -> None: - """Test the `closed` option in ResamplerConfig.""" + """Test the `closed` option in ResamplerConfig3.""" timestamp = datetime.now(timezone.utc) resampling_period_s = 2 @@ -2079,11 +2081,12 @@ async def test_resampler_closed_option( resampling_fun_mock = MagicMock( spec=ResamplingFunction, return_value=expected_resampled_value ) - config = ResamplerConfig( - resampling_period=timedelta(seconds=resampling_period_s), + config = ResamplerConfig3( + timedelta(seconds=resampling_period_s), max_data_age_in_periods=1.0, - resampling_function=resampling_fun_mock, + resampling_function=_with_old_signature(resampling_fun_mock), closed=closed, + label=WindowSide.RIGHT, ) resampler = Resampler(config) @@ -2191,7 +2194,7 @@ async def test_resampler_label_option( fake_time: time_machine.Coordinates, source_chan: Broadcast[Sample[Quantity]], ) -> None: - """Test the `label` option in ResamplerConfig.""" + """Test the `label` option in ResamplerConfig3.""" timestamp = datetime.now(timezone.utc) resampling_period_s = 2 @@ -2200,10 +2203,11 @@ async def test_resampler_label_option( resampling_fun_mock = MagicMock( spec=ResamplingFunction, return_value=expected_resampled_value ) - config = ResamplerConfig( - resampling_period=timedelta(seconds=resampling_period_s), + config = ResamplerConfig3( + timedelta(seconds=resampling_period_s), max_data_age_in_periods=1.0, - resampling_function=resampling_fun_mock, + resampling_function=_with_old_signature(resampling_fun_mock), + closed=WindowSide.RIGHT, label=label, ) resampler = Resampler(config) From 56cd79a12f60cff349a5ec5fe85d20fcf78ca25c Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Thu, 26 Nov 2026 14:39:56 +0000 Subject: [PATCH 09/11] Deprecate ResamplerConfig and ResamplingFunction ResamplerConfig makes the resampler use a monotonic timer, which is not suitable for resampling, as it drifts away from the wall clock. The wall clock timer has been available for a long time through ResamplerConfig2, and ResamplerConfig3 uses it too. The warning says the replacement uses a wall clock timer and has different defaults, so users don't replace one class with the other without checking how their results change. ResamplerConfig2 still inherits from ResamplerConfig, so isinstance() checks and code typed as ResamplerConfig keep working. Subclassing a deprecated class warns when the subclass is defined, which would happen every time the SDK is imported, so ResamplerConfig2 is defined while ignoring deprecations. Signed-off-by: Leandro Lucarella --- RELEASE_NOTES.md | 8 + .../sdk/timeseries/_resampling/_config.py | 283 ++++++++++-------- .../_resampling/test_deprecations.py | 84 ++++++ tests/timeseries/test_moving_window.py | 11 +- tests/timeseries/test_resampling.py | 17 +- 5 files changed, 280 insertions(+), 123 deletions(-) create mode 100644 tests/timeseries/_resampling/test_deprecations.py diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 7a75629d5..775b7bdbe 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -8,6 +8,14 @@ +- `ResamplerConfig` and `ResamplingFunction` are deprecated. Use `ResamplerConfig3` and `ResamplingFunction3` instead. This is not a search and replace: + + - The resampler uses a wall clock timer with `ResamplerConfig3`, so `align_to` moves to `timer_config=WallClockTimerConfig.from_interval(resampling_period, align_to=...)`. The wall clock timer also resamples the incomplete window after a start ([#1472](https://github.com/frequenz-floss/frequenz-sdk-python/issues/1472)), and can skip or repeat timestamps when the wall clock jumps ([#1478](https://github.com/frequenz-floss/frequenz-sdk-python/issues/1478)). + - `ResamplerConfig3` has different defaults, see below. + - Only `resampling_period` can be passed by position. + - `initial_buffer_len` is called `input_period_estimation_samples`. + - Resampling functions receive a `ResamplingContext` instead of the configuration, which is now `context.config`. + ## New Features diff --git a/src/frequenz/sdk/timeseries/_resampling/_config.py b/src/frequenz/sdk/timeseries/_resampling/_config.py index f033fff53..432fc19ec 100644 --- a/src/frequenz/sdk/timeseries/_resampling/_config.py +++ b/src/frequenz/sdk/timeseries/_resampling/_config.py @@ -15,6 +15,8 @@ from frequenz.core.datetime import UNIX_EPOCH from frequenz.core.typing import FloatInt +from frequenz.core.warnings import ignoring_deprecations +from typing_extensions import deprecated from ._base_types import SourceProperties from ._wall_clock_timer import WallClockTimerConfig @@ -49,9 +51,18 @@ class WindowSide(Enum): """The right side of the resampling window.""" +@deprecated( + "frequenz.sdk.timeseries.ResamplingFunction is deprecated. " + "Use frequenz.sdk.timeseries.ResamplingFunction3 instead, which receives a " + "resampling context instead of the configuration." +) class ResamplingFunction(Protocol): """Combine multiple samples into a new one. + Deprecated: + Deprecated since v1.0.0-rc2217. Use + [`ResamplingFunction3`][frequenz.sdk.timeseries.ResamplingFunction3] instead. + A resampling function produces a new sample based on a list of pre-existing samples. It can do "upsampling" when the data rate of the `input_samples` period is smaller than the `resampling_period`, or "downsampling" if it is @@ -62,6 +73,10 @@ class ResamplingFunction(Protocol): enable extrapolation, but no samples from the future (so the timestamp of the new sample that is going to be produced will always be bigger than the biggest timestamp in the input data). + + A [`ResamplingFunction3`][frequenz.sdk.timeseries.ResamplingFunction3] receives + a [`ResamplingContext`][frequenz.sdk.timeseries.ResamplingContext] with the + configuration and the window being resampled, instead of the configuration. """ def __call__( @@ -87,9 +102,30 @@ def __call__( ... # pylint: disable=unnecessary-ellipsis +@deprecated( + "frequenz.sdk.timeseries.ResamplerConfig is deprecated. " + "Use frequenz.sdk.timeseries.ResamplerConfig3 instead, but note it uses a " + "wall clock timer and has different defaults, so resampled values can change." +) @dataclass(frozen=True) class ResamplerConfig: - """Resampler configuration.""" + """Resampler configuration. + + Deprecated: + Deprecated since v1.0.0-rc2217. Use + [`ResamplerConfig3`][frequenz.sdk.timeseries.ResamplerConfig3] instead. + + With a [`ResamplerConfig3`][frequenz.sdk.timeseries.ResamplerConfig3], the + resampler uses a [`WallClockTimer`][frequenz.sdk.timeseries.WallClockTimer] + instead of a monotonic timer, so the alignment is set with + [`timer_config`][frequenz.sdk.timeseries.ResamplerConfig3.timer_config] + instead of `align_to`. It also has different defaults, and its resampling + function receives a + [`ResamplingContext`][frequenz.sdk.timeseries.ResamplingContext] instead of + the configuration. To keep the results of this class, pass + `max_data_age_in_periods=3.0`, `closed=WindowSide.RIGHT` and + `label=WindowSide.RIGHT`. + """ resampling_period: timedelta """The resampling period. @@ -313,151 +349,158 @@ def __call__( ... # pylint: disable=unnecessary-ellipsis -@dataclass(frozen=True) -class ResamplerConfig2(ResamplerConfig): - """Resampler configuration.""" +# Subclassing the deprecated ResamplerConfig warns, but users can't do anything +# about it, as it happens when the SDK is imported. +with ignoring_deprecations(): - resampling_period: timedelta - """The resampling period. + @dataclass(frozen=True) + class ResamplerConfig2(ResamplerConfig): + """Resampler configuration.""" - This is the time it passes between resampled data should be calculated. + resampling_period: timedelta + """The resampling period. - It must be a positive time span. - """ - - max_data_age_in_periods: float = 3.0 - """The maximum age a sample can have to be considered *relevant* for resampling. + This is the time it passes between resampled data should be calculated. - Expressed in number of periods, where period is the `resampling_period` - if we are downsampling (resampling period bigger than the input period) or - the *input sampling period* if we are upsampling (input period bigger than - the resampling period). + It must be a positive time span. + """ - It must be bigger than 1.0. + max_data_age_in_periods: float = 3.0 + """The maximum age a sample can have to be considered *relevant* for resampling. - Example: - If `resampling_period` is 3 seconds, the input sampling period is - 1 and `max_data_age_in_periods` is 2, then data older than 3*2 - = 6 seconds will be discarded when creating a new sample and never - passed to the resampling function. + Expressed in number of periods, where period is the `resampling_period` + if we are downsampling (resampling period bigger than the input period) or + the *input sampling period* if we are upsampling (input period bigger than + the resampling period). - If `resampling_period` is 3 seconds, the input sampling period is - 5 and `max_data_age_in_periods` is 2, then data older than 5*2 - = 10 seconds will be discarded when creating a new sample and never - passed to the resampling function. - """ + It must be bigger than 1.0. - resampling_function: ResamplingFunction2 = lambda samples, _, __: statistics.fmean( - s[1] for s in samples - ) - """The resampling function. + Example: + If `resampling_period` is 3 seconds, the input sampling period is + 1 and `max_data_age_in_periods` is 2, then data older than 3*2 + = 6 seconds will be discarded when creating a new sample and never + passed to the resampling function. - This function will be applied to the sequence of relevant samples at - a given time. The result of the function is what is sent as the resampled - value. - """ + If `resampling_period` is 3 seconds, the input sampling period is + 5 and `max_data_age_in_periods` is 2, then data older than 5*2 + = 10 seconds will be discarded when creating a new sample and never + passed to the resampling function. + """ - initial_buffer_len: int = DEFAULT_BUFFER_LEN_INIT - """The number of samples to receive before estimating the input sampling period. + resampling_function: ResamplingFunction2 = ( + lambda samples, _, __: statistics.fmean(s[1] for s in samples) + ) + """The resampling function. - The input sampling period is estimated once, at the first resampling after - receiving enough samples, and decides how old the relevant samples can be - when upsampling (see `max_data_age_in_periods`). Until it is known, samples - are not removed from the resampling buffer, except when it is full. + This function will be applied to the sequence of relevant samples at + a given time. The result of the function is what is sent as the resampled + value. + """ - The number of received samples must also be at least the number of seconds - in `max_data_age_in_periods` resampling periods. For example, with a - resampling period of 60 seconds and a `max_data_age_in_periods` of 3, the - input sampling period is estimated after receiving at least 180 samples (see - [frequenz-sdk-python#1497](https://github.com/frequenz-floss/frequenz-sdk-python/issues/1497)). + initial_buffer_len: int = DEFAULT_BUFFER_LEN_INIT + """The number of samples to receive before estimating the input sampling period. - It must be at least 1 and at most `max_buffer_len`. - """ + The input sampling period is estimated once, at the first resampling after + receiving enough samples, and decides how old the relevant samples can be + when upsampling (see `max_data_age_in_periods`). Until it is known, samples + are not removed from the resampling buffer, except when it is full. - warn_buffer_len: int = DEFAULT_BUFFER_LEN_WARN - """The number of samples above which a resampling buffer logs a warning. + The number of received samples must also be at least the number of seconds + in `max_data_age_in_periods` resampling periods. For example, with a + resampling period of 60 seconds and a `max_data_age_in_periods` of 3, the + input sampling period is estimated after receiving at least 180 samples (see + [frequenz-sdk-python#1497](https://github.com/frequenz-floss/frequenz-sdk-python/issues/1497)). - Old samples are removed from the buffer when resampling, so it only holds - the samples that are still relevant and the ones received since. If it - holds more samples than this value after removing old ones, a warning is - logged once, so buffers don't grow too big inadvertently. + It must be at least 1 and at most `max_buffer_len`. + """ - It must be at least 1 and at most `max_buffer_len`. - """ + warn_buffer_len: int = DEFAULT_BUFFER_LEN_WARN + """The number of samples above which a resampling buffer logs a warning. - max_buffer_len: int = DEFAULT_BUFFER_LEN_MAX - """The maximum number of samples a resampling buffer can hold. + Old samples are removed from the buffer when resampling, so it only holds + the samples that are still relevant and the ones received since. If it + holds more samples than this value after removing old ones, a warning is + logged once, so buffers don't grow too big inadvertently. - When the buffer is full, the oldest sample is dropped when a new one is - added, even if it would be needed to resample. An error is logged once if - samples needed to resample may have been dropped. + It must be at least 1 and at most `max_buffer_len`. + """ - It must be bigger than `warn_buffer_len`. - """ + max_buffer_len: int = DEFAULT_BUFFER_LEN_MAX + """The maximum number of samples a resampling buffer can hold. - align_to: datetime | None = field(default=None, init=False) - """Deprecated: Use timer_config.align_to instead.""" + When the buffer is full, the oldest sample is dropped when a new one is + added, even if it would be needed to resample. An error is logged once if + samples needed to resample may have been dropped. - timer_config: WallClockTimerConfig | None = None - """The custom configuration of the wall clock timer used to keep track of time. + It must be bigger than `warn_buffer_len`. + """ - If not provided or `None`, a configuration will be created by passing the - [`resampling_period`][frequenz.sdk.timeseries.ResamplerConfig2.resampling_period] to - the [`from_interval()`][frequenz.sdk.timeseries.WallClockTimerConfig.from_interval] - method. - """ + align_to: datetime | None = field(default=None, init=False) + """Deprecated: Use timer_config.align_to instead.""" - def __post_init__(self) -> None: - """Check that config values are valid. + timer_config: WallClockTimerConfig | None = None + """The custom configuration of the wall clock timer used to keep track of time. - Raises: - ValueError: If any value is out of range. + If not provided or `None`, a configuration will be created by passing the + [`resampling_period`][frequenz.sdk.timeseries.ResamplerConfig2.resampling_period] to + the [`from_interval()`][frequenz.sdk.timeseries.WallClockTimerConfig.from_interval] + method. """ - if self.resampling_period.total_seconds() < 0.0: - raise ValueError( - f"resampling_period ({self.resampling_period}) must be positive" - ) - if self.max_data_age_in_periods < 1.0: - raise ValueError( - f"max_data_age_in_periods ({self.max_data_age_in_periods}) should be at least 1.0" - ) - if self.warn_buffer_len < 1: - raise ValueError( - f"warn_buffer_len ({self.warn_buffer_len}) should be at least 1" - ) - if self.max_buffer_len <= self.warn_buffer_len: - raise ValueError( - f"max_buffer_len ({self.max_buffer_len}) should " - f"be bigger than warn_buffer_len ({self.warn_buffer_len})" - ) - if self.initial_buffer_len < 1: - raise ValueError( - f"initial_buffer_len ({self.initial_buffer_len}) should at least 1" - ) - if self.initial_buffer_len > self.max_buffer_len: - raise ValueError( - f"initial_buffer_len ({self.initial_buffer_len}) is bigger " - f"than max_buffer_len ({self.max_buffer_len}), use a smaller " - "initial_buffer_len or a bigger max_buffer_len" - ) - if self.initial_buffer_len > self.warn_buffer_len: - _logger.warning( - "initial_buffer_len (%s) is bigger than warn_buffer_len (%s)", - self.initial_buffer_len, - self.warn_buffer_len, - ) - if self.align_to is not None: - raise ValueError( - f"align_to ({self.align_to}) must be specified via timer_config" - ) - if self.tick_delay < timedelta(0): - raise ValueError(f"tick_delay ({self.tick_delay}) should be non-negative") - if self.tick_delay >= self.resampling_period: - raise ValueError( - f"tick_delay ({self.tick_delay}) should be smaller than " - f"resampling_period ({self.resampling_period})" - ) + def __post_init__(self) -> None: + """Check that config values are valid. + + Raises: + ValueError: If any value is out of range. + """ + if self.resampling_period.total_seconds() < 0.0: + raise ValueError( + f"resampling_period ({self.resampling_period}) must be positive" + ) + if self.max_data_age_in_periods < 1.0: + raise ValueError( + f"max_data_age_in_periods ({self.max_data_age_in_periods}) " + "should be at least 1.0" + ) + if self.warn_buffer_len < 1: + raise ValueError( + f"warn_buffer_len ({self.warn_buffer_len}) should be at least 1" + ) + if self.max_buffer_len <= self.warn_buffer_len: + raise ValueError( + f"max_buffer_len ({self.max_buffer_len}) should " + f"be bigger than warn_buffer_len ({self.warn_buffer_len})" + ) + + if self.initial_buffer_len < 1: + raise ValueError( + f"initial_buffer_len ({self.initial_buffer_len}) should at least 1" + ) + if self.initial_buffer_len > self.max_buffer_len: + raise ValueError( + f"initial_buffer_len ({self.initial_buffer_len}) is bigger " + f"than max_buffer_len ({self.max_buffer_len}), use a smaller " + "initial_buffer_len or a bigger max_buffer_len" + ) + if self.initial_buffer_len > self.warn_buffer_len: + _logger.warning( + "initial_buffer_len (%s) is bigger than warn_buffer_len (%s)", + self.initial_buffer_len, + self.warn_buffer_len, + ) + if self.align_to is not None: + raise ValueError( + f"align_to ({self.align_to}) must be specified via timer_config" + ) + if self.tick_delay < timedelta(0): + raise ValueError( + f"tick_delay ({self.tick_delay}) should be non-negative" + ) + if self.tick_delay >= self.resampling_period: + raise ValueError( + f"tick_delay ({self.tick_delay}) should be smaller than " + f"resampling_period ({self.resampling_period})" + ) @dataclass(frozen=True, kw_only=True) diff --git a/tests/timeseries/_resampling/test_deprecations.py b/tests/timeseries/_resampling/test_deprecations.py new file mode 100644 index 000000000..602df6ea4 --- /dev/null +++ b/tests/timeseries/_resampling/test_deprecations.py @@ -0,0 +1,84 @@ +# License: MIT +# Copyright © 2026 Frequenz Energy-as-a-Service GmbH + +"""Tests for the deprecated resampler configuration classes.""" + +import subprocess +import sys +import textwrap +from datetime import timedelta + +import pytest +from frequenz.core.warnings import asserting_no_deprecations + +from frequenz.sdk.timeseries import ( + ResamplerConfig, + ResamplerConfig2, + ResamplingFunction, +) + +_PERIOD = timedelta(seconds=1) + +_RESAMPLER_CONFIG_MESSAGE = ( + "frequenz.sdk.timeseries.ResamplerConfig is deprecated. " + "Use frequenz.sdk.timeseries.ResamplerConfig3 instead, but note it uses a " + "wall clock timer and has different defaults, so resampled values can change." +) + +_RESAMPLING_FUNCTION_MESSAGE = ( + "frequenz.sdk.timeseries.ResamplingFunction is deprecated. " + "Use frequenz.sdk.timeseries.ResamplingFunction3 instead, which receives a " + "resampling context instead of the configuration." +) + + +def test_resampler_config_is_deprecated() -> None: + """Test creating a `ResamplerConfig` warns once.""" + with pytest.deprecated_call() as record: + ResamplerConfig(_PERIOD) + + assert [str(w.message) for w in record] == [_RESAMPLER_CONFIG_MESSAGE] + + +def test_resampling_function_is_deprecated() -> None: + """Test subclassing `ResamplingFunction` warns once.""" + with pytest.deprecated_call() as record: + + class _Function(ResamplingFunction): # pylint: disable=unused-variable + pass + + assert [str(w.message) for w in record] == [_RESAMPLING_FUNCTION_MESSAGE] + + +def test_resampler_config2_does_not_warn_about_resampler_config() -> None: + """Test creating a `ResamplerConfig2` doesn't warn about its base class.""" + with asserting_no_deprecations(): + ResamplerConfig2(_PERIOD) + + +def test_import_does_not_warn() -> None: + """Test importing the SDK doesn't emit the SDK's own deprecation warnings. + + `ResamplerConfig2` subclasses the deprecated `ResamplerConfig`, which warns + when the subclass is defined. It runs in a new interpreter, as the modules are + already imported here. + """ + code = textwrap.dedent("""\ + import warnings + + with warnings.catch_warnings(record=True) as record: + warnings.simplefilter("always") + import frequenz.sdk.actor + import frequenz.sdk.microgrid + import frequenz.sdk.timeseries + + for warning in record: + if "frequenz.sdk." in str(warning.message): + print(warning.message) + """) + + result = subprocess.run( + [sys.executable, "-c", code], capture_output=True, text=True, check=True + ) + + assert result.stdout == "" diff --git a/tests/timeseries/test_moving_window.py b/tests/timeseries/test_moving_window.py index 1098e14ab..6d06edc82 100644 --- a/tests/timeseries/test_moving_window.py +++ b/tests/timeseries/test_moving_window.py @@ -462,7 +462,16 @@ async def test_wait_for_samples() -> None: @pytest.mark.parametrize( - "config_class", [ResamplerConfig, ResamplerConfig2, ResamplerConfig3] + "config_class", + [ + pytest.param( + ResamplerConfig, + id="ResamplerConfig", + marks=pytest.mark.filterwarnings("once::DeprecationWarning"), + ), + ResamplerConfig2, + ResamplerConfig3, + ], ) async def test_wait_for_samples_with_resampling( config_class: type[ResamplerConfig] | type[ResamplerConfig3], diff --git a/tests/timeseries/test_resampling.py b/tests/timeseries/test_resampling.py index 7346bc4bd..3d580ab09 100644 --- a/tests/timeseries/test_resampling.py +++ b/tests/timeseries/test_resampling.py @@ -49,8 +49,19 @@ _ConfigClass = type[ResamplerConfig] | type[ResamplerConfig3] """A resampler configuration class.""" -_CONFIG_CLASSES = [ResamplerConfig, ResamplerConfig2, ResamplerConfig3] -"""All the resampler configuration classes, to parametrize tests.""" +_CONFIG_CLASSES = [ + pytest.param( + ResamplerConfig, + id="ResamplerConfig", + marks=pytest.mark.filterwarnings("once::DeprecationWarning"), + ), + ResamplerConfig2, + ResamplerConfig3, +] +"""All the resampler configuration classes, to parametrize tests. + +Deprecated classes are still tested until they are removed. +""" def _make_config( @@ -778,6 +789,7 @@ async def send_samples_after_tick_delay() -> None: ), ), ) +@pytest.mark.filterwarnings("once::DeprecationWarning") async def test_calculate_window_end_trivial_cases( fake_time: time_machine.Coordinates, resampling_period_s: float, @@ -916,6 +928,7 @@ async def test_resampling_window_size_is_constant( # Not parametrized because now warnings are handled by the wall clock timer when the # wall clock timer is used, not the resampler, so it should be tested in the wall clock # timer tests. +@pytest.mark.filterwarnings("once::DeprecationWarning") async def test_timer_errors_are_logged( # pylint: disable=too-many-statements fake_time: time_machine.Coordinates, source_chan: Broadcast[Sample[Quantity]], From 84b5561ec9f506fc8912c59a106308b677f5be4d Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Thu, 26 Nov 2026 14:43:34 +0000 Subject: [PATCH 10/11] Deprecate ResamplerConfig2 and ResamplingFunction2 ResamplerConfig3 replaces ResamplerConfig2 with defaults that don't average several periods and that label values like reporting data, and with resampling functions that know the window they resample. The warning says the replacement has different defaults and a different resampling function signature, so users don't replace one class with the other without checking how their results change. Creating a ResamplerConfig2 only warns about ResamplerConfig2, not about its deprecated base class. Signed-off-by: Leandro Lucarella --- RELEASE_NOTES.md | 4 +- .../sdk/timeseries/_resampling/_config.py | 34 ++++++++++++- .../_resampling/test_deprecations.py | 51 +++++++++++++++++-- tests/timeseries/test_moving_window.py | 6 ++- tests/timeseries/test_resampling.py | 6 ++- 5 files changed, 93 insertions(+), 8 deletions(-) diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 775b7bdbe..f36d56cc5 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -14,7 +14,9 @@ - `ResamplerConfig3` has different defaults, see below. - Only `resampling_period` can be passed by position. - `initial_buffer_len` is called `input_period_estimation_samples`. - - Resampling functions receive a `ResamplingContext` instead of the configuration, which is now `context.config`. + - Resampling functions receive a `ResamplingContext` instead of the configuration and the source properties, which are now `context.config` and `context.source_properties`. + +- `ResamplerConfig2` and `ResamplingFunction2` are deprecated. Use `ResamplerConfig3` and `ResamplingFunction3` instead. `ResamplerConfig3` uses the same wall clock timer, but it has different defaults (see below), only `resampling_period` can be passed by position, `initial_buffer_len` is called `input_period_estimation_samples`, and resampling functions receive a `ResamplingContext` instead of the configuration and the source properties. Keep any `timer_config` and `tick_delay` you pass. Subclassing `ResamplerConfig2` also shows the deprecation warning of `ResamplerConfig`, whose advice about the timer doesn't apply to it. ## New Features diff --git a/src/frequenz/sdk/timeseries/_resampling/_config.py b/src/frequenz/sdk/timeseries/_resampling/_config.py index 432fc19ec..d22c9cea7 100644 --- a/src/frequenz/sdk/timeseries/_resampling/_config.py +++ b/src/frequenz/sdk/timeseries/_resampling/_config.py @@ -311,9 +311,18 @@ def __post_init__(self) -> None: ) +@deprecated( + "frequenz.sdk.timeseries.ResamplingFunction2 is deprecated. " + "Use frequenz.sdk.timeseries.ResamplingFunction3 instead, which receives a " + "resampling context instead of the configuration." +) class ResamplingFunction2(Protocol): """Combine multiple samples into a new one. + Deprecated: + Deprecated since v1.0.0-rc2217. Use + [`ResamplingFunction3`][frequenz.sdk.timeseries.ResamplingFunction3] instead. + A resampling function produces a new sample based on a list of pre-existing samples. It can do "upsampling" when the data rate of the `input_samples` period is smaller than the `resampling_period`, or "downsampling" if it is @@ -324,6 +333,10 @@ class ResamplingFunction2(Protocol): enable extrapolation, but no samples from the future (so the timestamp of the new sample that is going to be produced will always be bigger than the biggest timestamp in the input data). + + A [`ResamplingFunction3`][frequenz.sdk.timeseries.ResamplingFunction3] receives + a [`ResamplingContext`][frequenz.sdk.timeseries.ResamplingContext] with the + configuration and the window being resampled, instead of the configuration. """ def __call__( @@ -353,9 +366,28 @@ def __call__( # about it, as it happens when the SDK is imported. with ignoring_deprecations(): + @deprecated( + "frequenz.sdk.timeseries.ResamplerConfig2 is deprecated. " + "Use frequenz.sdk.timeseries.ResamplerConfig3 instead, but note it has " + "different defaults and resampling function signature, so resampled " + "values can change." + ) @dataclass(frozen=True) class ResamplerConfig2(ResamplerConfig): - """Resampler configuration.""" + """Resampler configuration. + + Deprecated: + Deprecated since v1.0.0-rc2217. Use + [`ResamplerConfig3`][frequenz.sdk.timeseries.ResamplerConfig3] instead. + + A [`ResamplerConfig3`][frequenz.sdk.timeseries.ResamplerConfig3] has + different defaults, and its resampling function receives a + [`ResamplingContext`][frequenz.sdk.timeseries.ResamplingContext] instead + of the configuration. To keep the results of this class, pass + `max_data_age_in_periods=3.0`, `closed=WindowSide.RIGHT` and + `label=WindowSide.RIGHT`, together with any `timer_config` and + `tick_delay`. + """ resampling_period: timedelta """The resampling period. diff --git a/tests/timeseries/_resampling/test_deprecations.py b/tests/timeseries/_resampling/test_deprecations.py index 602df6ea4..c720755c8 100644 --- a/tests/timeseries/_resampling/test_deprecations.py +++ b/tests/timeseries/_resampling/test_deprecations.py @@ -6,7 +6,7 @@ import subprocess import sys import textwrap -from datetime import timedelta +from datetime import datetime, timedelta, timezone import pytest from frequenz.core.warnings import asserting_no_deprecations @@ -14,7 +14,11 @@ from frequenz.sdk.timeseries import ( ResamplerConfig, ResamplerConfig2, + ResamplerConfig3, + ResamplingContext, ResamplingFunction, + ResamplingFunction2, + SourceProperties, ) _PERIOD = timedelta(seconds=1) @@ -25,12 +29,25 @@ "wall clock timer and has different defaults, so resampled values can change." ) +_RESAMPLER_CONFIG2_MESSAGE = ( + "frequenz.sdk.timeseries.ResamplerConfig2 is deprecated. " + "Use frequenz.sdk.timeseries.ResamplerConfig3 instead, but note it has " + "different defaults and resampling function signature, so resampled " + "values can change." +) + _RESAMPLING_FUNCTION_MESSAGE = ( "frequenz.sdk.timeseries.ResamplingFunction is deprecated. " "Use frequenz.sdk.timeseries.ResamplingFunction3 instead, which receives a " "resampling context instead of the configuration." ) +_RESAMPLING_FUNCTION2_MESSAGE = ( + "frequenz.sdk.timeseries.ResamplingFunction2 is deprecated. " + "Use frequenz.sdk.timeseries.ResamplingFunction3 instead, which receives a " + "resampling context instead of the configuration." +) + def test_resampler_config_is_deprecated() -> None: """Test creating a `ResamplerConfig` warns once.""" @@ -50,11 +67,37 @@ class _Function(ResamplingFunction): # pylint: disable=unused-variable assert [str(w.message) for w in record] == [_RESAMPLING_FUNCTION_MESSAGE] -def test_resampler_config2_does_not_warn_about_resampler_config() -> None: - """Test creating a `ResamplerConfig2` doesn't warn about its base class.""" - with asserting_no_deprecations(): +def test_resampler_config2_is_deprecated() -> None: + """Test creating a `ResamplerConfig2` warns once, and not about its base class.""" + with pytest.deprecated_call() as record: ResamplerConfig2(_PERIOD) + assert [str(w.message) for w in record] == [_RESAMPLER_CONFIG2_MESSAGE] + + +def test_resampling_function2_is_deprecated() -> None: + """Test subclassing `ResamplingFunction2` warns once.""" + with pytest.deprecated_call() as record: + + class _Function(ResamplingFunction2): # pylint: disable=unused-variable + pass + + assert [str(w.message) for w in record] == [_RESAMPLING_FUNCTION2_MESSAGE] + + +def test_resampler_config3_does_not_warn() -> None: + """Test the replacement doesn't warn, nor its default resampling function.""" + with asserting_no_deprecations(): + config = ResamplerConfig3(_PERIOD) + config.resampling_function( + [(datetime(2026, 1, 1, tzinfo=timezone.utc), 1.0)], + ResamplingContext( + window_start=datetime(2026, 1, 1, tzinfo=timezone.utc), + config=config, + source_properties=SourceProperties(), + ), + ) + def test_import_does_not_warn() -> None: """Test importing the SDK doesn't emit the SDK's own deprecation warnings. diff --git a/tests/timeseries/test_moving_window.py b/tests/timeseries/test_moving_window.py index 6d06edc82..e238d1988 100644 --- a/tests/timeseries/test_moving_window.py +++ b/tests/timeseries/test_moving_window.py @@ -469,7 +469,11 @@ async def test_wait_for_samples() -> None: id="ResamplerConfig", marks=pytest.mark.filterwarnings("once::DeprecationWarning"), ), - ResamplerConfig2, + pytest.param( + ResamplerConfig2, + id="ResamplerConfig2", + marks=pytest.mark.filterwarnings("once::DeprecationWarning"), + ), ResamplerConfig3, ], ) diff --git a/tests/timeseries/test_resampling.py b/tests/timeseries/test_resampling.py index 3d580ab09..7ab113688 100644 --- a/tests/timeseries/test_resampling.py +++ b/tests/timeseries/test_resampling.py @@ -55,7 +55,11 @@ id="ResamplerConfig", marks=pytest.mark.filterwarnings("once::DeprecationWarning"), ), - ResamplerConfig2, + pytest.param( + ResamplerConfig2, + id="ResamplerConfig2", + marks=pytest.mark.filterwarnings("once::DeprecationWarning"), + ), ResamplerConfig3, ] """All the resampler configuration classes, to parametrize tests. From c883e176fc6adee351a629faf5b4a3815312ad15 Mon Sep 17 00:00:00 2001 From: Leandro Lucarella Date: Thu, 26 Nov 2026 14:44:01 +0000 Subject: [PATCH 11/11] Complete the release notes Add the summary, the new defaults with the configuration that keeps the old results, the ways changing closed and label can break code without any error, and the new features. Signed-off-by: Leandro Lucarella --- RELEASE_NOTES.md | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index f36d56cc5..8b525d9f5 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -4,6 +4,8 @@ +This release adds `ResamplerConfig3`, a resampler configuration with defaults that don't surprise data analysis: when downsampling, each resampled value is the mean of its own window, labelled with the start of the window. It deprecates `ResamplerConfig` and `ResamplerConfig2`. For controlling a microgrid, the new `microgrid.latest_window_mean()` resampling function covers short gaps in the data without averaging several periods. + ## Upgrading @@ -18,10 +20,41 @@ - `ResamplerConfig2` and `ResamplingFunction2` are deprecated. Use `ResamplerConfig3` and `ResamplingFunction3` instead. `ResamplerConfig3` uses the same wall clock timer, but it has different defaults (see below), only `resampling_period` can be passed by position, `initial_buffer_len` is called `input_period_estimation_samples`, and resampling functions receive a `ResamplingContext` instead of the configuration and the source properties. Keep any `timer_config` and `tick_delay` you pass. Subclassing `ResamplerConfig2` also shows the deprecation warning of `ResamplerConfig`, whose advice about the timer doesn't apply to it. +- `ResamplerConfig3` has new defaults: `max_data_age_in_periods=1.0`, `closed=WindowSide.LEFT` and `label=WindowSide.LEFT`. The old classes use `3.0`, `RIGHT` and `RIGHT`. When downsampling, each value is now the mean of the samples in its own window only, instead of the last three periods, and it is labelled with the start of its window instead of its end, so timestamps are one period earlier. To keep the aggregation and the window conventions of the old classes, pass the old defaults explicitly: + + ```python + from datetime import timedelta + + from frequenz.sdk.timeseries import ResamplerConfig3, WindowSide + + config = ResamplerConfig3( + timedelta(seconds=1), + max_data_age_in_periods=3.0, + closed=WindowSide.RIGHT, + label=WindowSide.RIGHT, + ) + ``` + +- Changing `closed` and `label` can break code in subtle ways, without any error: + + - Timeseries resampled with different `label` values are off by one period, and with different `closed` values, samples exactly on a window boundary go to different windows. When they are combined, for example in a formula or when the output of a resampler is resampled again (like a `MovingWindow` with its own resampler fed by microgrid data), values from adjacent windows are silently paired. Use the same values for all resamplers whose output is combined, also while migrating only part of an application. + - Code that compares the timestamps of resampled values with the current time sees values one period older, as values are still sent at the end of their window, or later with `tick_delay`. + - Stored or exported values are labelled one period earlier after changing `label`, and the timestamp of the last value before the change is repeated by the first one after it. + +- Applications that control a microgrid and relied on the 3-period mean of the old defaults to tolerate gaps in the data should use the new `microgrid.latest_window_mean()` with a `max_data_age_in_periods` bigger than 1.0. Its values are noisier than the old 3-period mean, as they are not averaged over several periods anymore, so controllers that relied on that smoothing will see more noise. `microgrid.EXAMPLE_RESAMPLER_CONFIG` shows a configuration like this. + ## New Features +- `ResamplerConfig3` is a new resampler configuration. It always uses the wall clock timer, and has new defaults, see the upgrading notes. + +- Resampling functions for `ResamplerConfig3` (`ResamplingFunction3`) receive a `ResamplingContext`, with the window being resampled, the configuration and the source properties. Its `window_end` property, and `window_bounds()` and `window_offset()` methods, give the boundaries of the current and previous windows and the window a sample belongs to. + +- `microgrid.latest_window_mean()` is a resampling function that averages the samples in the newest window that has any. Older windows are only used when newer ones are empty, so short gaps in the data and devices that send data less often than the resampling period don't produce `None` values, as long as some samples are not older than `max_data_age_in_periods`. + +- `microgrid.EXAMPLE_RESAMPLER_CONFIG` is a resampler configuration for examples and quick experiments. Applications that control a microgrid can use it as a baseline for their own configuration: it uses `microgrid.latest_window_mean()` with a `max_data_age_in_periods` of 3, and its documentation explains why. + - `SourceProperties` has a new `dropped_samples` field, with the number of samples the resampler dropped because its buffer was full. - `SourceProperties` has new `total_windows_without_samples` and `current_windows_without_samples` fields, with the number of resampling windows without relevant samples in total and in the current gap in the data. They tell how healthy a timeseries is, and whether it is in a gap right now. The windows before the first sample was received are counted too.