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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions RELEASE_NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,57 @@

<!-- Here goes a general summary of what this release is about -->

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

<!-- Here goes notes on how to upgrade from previous versions, including deprecations and what they should be replaced with -->

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

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

<!-- Here goes the main new features and examples or instructions on how to use them -->

- `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.
Expand All @@ -27,3 +70,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.
3 changes: 1 addition & 2 deletions benchmarks/power_distribution/power_distributor.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@
Result,
Success,
)
from frequenz.sdk.timeseries import ResamplerConfig2

HOST = "microgrid.sandbox.api.frequenz.io"
PORT = 62060
Expand Down Expand Up @@ -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(
Expand Down
13 changes: 6 additions & 7 deletions benchmarks/timeseries/resampling.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
),
Expand Down
14 changes: 7 additions & 7 deletions docs/tutorials/getting_started.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
4 changes: 1 addition & 3 deletions examples/battery_pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand All @@ -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)
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
21 changes: 19 additions & 2 deletions src/frequenz/sdk/microgrid/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -403,12 +407,14 @@
producer,
voltage_per_phase,
)
from ._example_resampler_config import EXAMPLE_RESAMPLER_CONFIG
from ._power_managing import PowerManagerAlgorithm
from ._resampling_functions import latest_window_mean


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
Expand All @@ -417,6 +423,15 @@ 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.

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.
The following format is expected: `grpc://hostname{:port}{?ssl=ssl}`,
Expand Down Expand Up @@ -450,9 +465,11 @@ async def initialize(

__all__ = [
"ComponentGraphConfig",
"EXAMPLE_RESAMPLER_CONFIG",
"FormulaOverrides",
"PowerManagerAlgorithm",
"initialize",
"latest_window_mean",
"consumer",
"grid",
"frequency",
Expand Down
10 changes: 6 additions & 4 deletions src/frequenz/sdk/microgrid/_data_pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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"
Expand Down Expand Up @@ -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:
Expand Down
65 changes: 65 additions & 0 deletions src/frequenz/sdk/microgrid/_example_resampler_config.py
Original file line number Diff line number Diff line change
@@ -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)
)
```
"""
8 changes: 6 additions & 2 deletions src/frequenz/sdk/microgrid/_resampling.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand Down
Loading