From fc722ff150e010b5005a4f0d73afee3be0fa4eea Mon Sep 17 00:00:00 2001 From: cwasicki <126617870+cwasicki@users.noreply.github.com> Date: Tue, 1 Dec 2026 01:41:54 +0100 Subject: [PATCH] Add rated power bounds of a microgrid's assets Batteries gain a rated power, so every asset type can be summed. Returns directional bounds, so a site's feed-in and draw headroom stay separate; a symmetric band is their difference. It lives on `AssetsConfig` so it can later count assets filed under the microgrid's market locations without a new API. Signed-off-by: cwasicki <126617870+cwasicki@users.noreply.github.com> --- RELEASE_NOTES.md | 4 + src/frequenz/gridpool/config/__init__.py | 2 + src/frequenz/gridpool/config/_assets.py | 47 ++++++++- src/frequenz/gridpool/config/_microgrid.py | 107 ++++++++++++++++----- tests/test_config.py | 99 +++++++++++++++++++ 5 files changed, 233 insertions(+), 26 deletions(-) diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 1f1a0a1..9555d66 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -10,12 +10,16 @@ and producer formulas. `ComponentGraph.consumer_formula()` and `ComponentGraph.producer_formula()` can now return values previously pinned to zero: a negative consumer total, or a positive producer total. +- `PVConfig`, `WindConfig` and `BatteryConfig` take keyword arguments only. ## New Features - `generate-config` now derives a `generation` component type, with its `AC_POWER_ACTIVE` formula taken from `ComponentGraph.producer_formula()`, so the aggregated producer power is emitted alongside `consumption`. +- `BatteryConfig` gains an optional `rated_power`: the inverters' rated power in Watt. +- `MicrogridConfig.assets(asset_type)` returns the PV, wind or battery entries of a microgrid. +- `AssetsConfig.rated_power(asset_types, at=..., microgrid_id=...)` returns the summed rated power bounds of a microgrid's PV, wind or battery assets installed at `at`, or `None` if the microgrid is unknown or a rating is missing. `AssetType` names the asset types. ## Bug Fixes diff --git a/src/frequenz/gridpool/config/__init__.py b/src/frequenz/gridpool/config/__init__.py index 05c671f..61edda3 100644 --- a/src/frequenz/gridpool/config/__init__.py +++ b/src/frequenz/gridpool/config/__init__.py @@ -9,6 +9,7 @@ from ._gridpool import GridpoolConfig from ._load import load_configs from ._microgrid import ( + AssetType, BatteryConfig, ComponentCategory, ComponentType, @@ -25,6 +26,7 @@ ) __all__ = [ + "AssetType", "AssetsConfig", "BatteryConfig", "ComponentCategory", diff --git a/src/frequenz/gridpool/config/_assets.py b/src/frequenz/gridpool/config/_assets.py index d5b0b87..9d8acc9 100644 --- a/src/frequenz/gridpool/config/_assets.py +++ b/src/frequenz/gridpool/config/_assets.py @@ -5,6 +5,7 @@ import logging import tomllib +from collections.abc import Iterable from dataclasses import field from datetime import datetime from pathlib import Path @@ -12,11 +13,12 @@ import marshmallow from frequenz.client.assets import MarketParticipationType +from frequenz.client.assets.metrics import Bounds from marshmallow import Schema from marshmallow_dataclass import dataclass from ._gridpool import GridpoolConfig -from ._microgrid import MicrogridConfig +from ._microgrid import AssetType, MicrogridConfig from ._migrations import _CURRENT_VERSION, migrate from ._topology import DeliveryAreaConfig, MarketLocationConfig, RelationConfig @@ -133,6 +135,49 @@ def __post_init__(self) -> None: f"Gridpool ID mismatch: key {gpid} != {gridpool.gridpool_id}" ) + def rated_power( + self, + asset_types: AssetType | Iterable[AssetType], + *, + at: datetime, + microgrid_id: int, + ) -> Bounds | None: + """Get the rated power bounds of a microgrid's assets of the given types. + + Bounds follow the passive sign convention: consumption is positive. PV + and wind span `[-rated, 0]`, batteries `[-rated, rated]`. Wind + ratings count once per turbine. Only assets installed at `at` count. + + Args: + asset_types: The asset type or types to sum over. + at: The instant the assets must be installed at. + microgrid_id: The microgrid whose assets to sum. + + Returns: + The summed bounds, zero if there are no such assets, or `None` if + the microgrid is unknown, an installed asset has no rating, or + a type has a `ctype` entry but no assets. + """ + microgrid = self.microgrids.get(microgrid_id) + if microgrid is None: + return None + types = [asset_types] if isinstance(asset_types, str) else asset_types + lower = upper = 0.0 + for asset_type in types: + assets = microgrid.assets(asset_type) + if not assets and asset_type in microgrid.ctype: + return None + for asset in assets.values(): + if not asset.is_installed(at): + continue + rated = asset.total_rated_power + if rated is None: + return None + lower -= rated + if asset_type == "battery": + upper += rated + return Bounds(lower=lower, upper=upper) + def check(self) -> None: """Check the document as a whole, once every layer has been merged. diff --git a/src/frequenz/gridpool/config/_microgrid.py b/src/frequenz/gridpool/config/_microgrid.py index a3d9390..43e53e0 100644 --- a/src/frequenz/gridpool/config/_microgrid.py +++ b/src/frequenz/gridpool/config/_microgrid.py @@ -4,9 +4,19 @@ """Data model for microgrid configurations.""" import re -from dataclasses import field +from collections.abc import Mapping +from dataclasses import KW_ONLY, field from datetime import datetime -from typing import Any, ClassVar, Literal, Self, Type, cast, get_args +from typing import ( + Any, + ClassVar, + Literal, + Self, + Type, + assert_never, + cast, + get_args, +) from marshmallow import Schema from marshmallow_dataclass import dataclass @@ -21,6 +31,9 @@ ComponentCategory = Literal["meter", "inverter", "component"] """Valid component categories.""" +AssetType = Literal["pv", "wind", "battery"] +"""Asset types that carry a rated power.""" + @dataclass class ComponentTypeConfig: @@ -99,47 +112,67 @@ def is_valid_type(cls, ctype: str) -> bool: @dataclass(frozen=True) -class PVConfig: - """Configuration of a PV system in a microgrid.""" +class _AssetBase: + """Installation period and rating shared by all asset configurations.""" + + _: KW_ONLY start_time: datetime | None = field(default=None, metadata=toml_datetime_metadata()) - """Start time of the PV system installation.""" + """Start time of the installation.""" end_time: datetime | None = field(default=None, metadata=toml_datetime_metadata()) - """End time of the PV system installation.""" + """End time of the installation, exclusive.""" + + rated_power: float | None = None + """Rated AC power in Watt.""" + + @property + def total_rated_power(self) -> float | None: + """The rated power of the whole asset in Watt, `None` if unrated.""" + return self.rated_power + + def is_installed(self, at: datetime) -> bool: + """Check whether the asset is installed at `at`. + + Args: + at: The instant to check. + + Returns: + Whether `at` lies in the installation period. + """ + if self.start_time is not None and at < self.start_time: + return False + return self.end_time is None or at < self.end_time + + +@dataclass(frozen=True) +class PVConfig(_AssetBase): + """Configuration of a PV system in a microgrid.""" + + _: KW_ONLY peak_power: float | None = None """Peak power of the PV system in Watt.""" - rated_power: float | None = None - """Rated power of the inverters in Watt.""" - curtailable: bool | None = None """Flag to indicate if PV system can be curtailed.""" @dataclass(frozen=True) -class WindConfig: +class WindConfig(_AssetBase): # pylint: disable=too-many-instance-attributes """Configuration of a wind turbine in a microgrid.""" - start_time: datetime | None = field(default=None, metadata=toml_datetime_metadata()) - """Start time of the wind turbine installation.""" - - end_time: datetime | None = field(default=None, metadata=toml_datetime_metadata()) - """End time of the wind turbine installation.""" + _: KW_ONLY turbine_model: str | None = None """Model name of the wind turbine.""" - rated_power: float | None = None - """Rated power of the wind turbine in Watt.""" - turbine_height: float | None = None """Height of the wind turbine in meters.""" number_of_turbines: int = 1 - """Number of wind turbines.""" + """Number of wind turbines, each rated at `rated_power`.""" hellmann_exponent: float | None = None """Hellmann exponent for wind speed extrapolation. See: https://w.wiki/FMw9""" @@ -150,16 +183,19 @@ class WindConfig: latitude: float | None = None """Geographic latitude of the wind turbine.""" + @property + def total_rated_power(self) -> float | None: + """The rated power of all turbines in Watt, `None` if unrated.""" + if self.rated_power is None: + return None + return self.rated_power * self.number_of_turbines + @dataclass(frozen=True) -class BatteryConfig: +class BatteryConfig(_AssetBase): """Configuration of a battery in a microgrid.""" - start_time: datetime | None = field(default=None, metadata=toml_datetime_metadata()) - """Start time of the battery installation.""" - - end_time: datetime | None = field(default=None, metadata=toml_datetime_metadata()) - """End time of the battery installation.""" + _: KW_ONLY capacity: float | None = None """Capacity of the battery in Wh.""" @@ -209,6 +245,27 @@ class MicrogridConfig: ctype: dict[str, ComponentTypeConfig] = field(default_factory=dict) """Mapping of component category types to ac power component config.""" + def assets( + self, asset_type: AssetType + ) -> Mapping[str, PVConfig | WindConfig | BatteryConfig]: + """Get the asset entries of one type. + + Args: + asset_type: The asset type. + + Returns: + The entries by label, empty if there are none. + """ + match asset_type: + case "pv": + return self.pv or {} + case "wind": + return self.wind or {} + case "battery": + return self.battery or {} + case _ as unreachable: + assert_never(unreachable) + def component_types(self) -> list[str]: """Get a list of all component types in the configuration.""" return list(self.ctype.keys()) diff --git a/tests/test_config.py b/tests/test_config.py index 0e57b87..20723b0 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -4,10 +4,12 @@ """Tests for the frequenz.lib.notebooks.config module.""" import logging +from datetime import datetime, timezone from pathlib import Path from typing import Any import pytest +from frequenz.client.assets.metrics import Bounds from marshmallow import ValidationError from pytest_mock import MockerFixture @@ -132,6 +134,7 @@ def test_load_configs(mocker: MockerFixture) -> None: assets.microgrids.1.pv.PV2.peak_power = 8000 assets.microgrids.1.pv.PV2.rated_power = 7000 assets.microgrids.1.battery.BAT1.capacity = 10000 + assets.microgrids.1.battery.BAT1.rated_power = 5000 """ mock_file = mocker.mock_open(read_data=toml_data.encode("utf-8")) mocker.patch("pathlib.Path.open", mock_file) @@ -152,6 +155,7 @@ def test_load_configs(mocker: MockerFixture) -> None: battery_system = battery_config.get("BAT1") assert battery_system is not None assert battery_system.capacity == 10000 + assert battery_system.rated_power == 5000 def _assert_optional_field(value: float | None, expected: float) -> None: @@ -391,3 +395,98 @@ def test_assets_config_warns_on_unknown_entities( assert sorted(config.microgrids) == [1] assert "gridpool" in caplog.text + + +_AT = datetime(2026, 6, 1, tzinfo=timezone.utc) + + +def _assets(**entry: Any) -> AssetsConfig: + """Build a config holding microgrid 1 from its table entry fields.""" + # pylint: disable=protected-access + microgrids = MicrogridConfig._load_table_entries( + {"1": {"microgrid_id": 1, **entry}} + ) + return AssetsConfig(microgrids=microgrids) + + +def test_assets() -> None: + """Asset entries are looked up by type, empty if unset.""" + microgrid = _assets(pv={"1": {"rated_power": 500}}).microgrids[1] + assert list(microgrid.assets("pv")) == ["1"] + assert not microgrid.assets("battery") + + +def test_rated_power_unknown_microgrid() -> None: + """An unknown microgrid has no known rating.""" + assert _assets().rated_power("pv", at=_AT, microgrid_id=2) is None + + +def test_rated_power_none() -> None: + """A site without the asset types has zero bounds.""" + assert _assets().rated_power(["pv", "battery"], at=_AT, microgrid_id=1) == Bounds( + lower=0.0, upper=0.0 + ) + + +def test_rated_power_all_rated() -> None: + """Generators bound feed-in only, batteries both directions.""" + assets = _assets( + pv={"1": {"rated_power": 500}, "2": {"rated_power": 100}}, + battery={"1": {"rated_power": 200}}, + ) + assert assets.rated_power("pv", at=_AT, microgrid_id=1) == Bounds( + lower=-600.0, upper=0.0 + ) + assert assets.rated_power("battery", at=_AT, microgrid_id=1) == Bounds( + lower=-200.0, upper=200.0 + ) + assert assets.rated_power(["pv", "battery"], at=_AT, microgrid_id=1) == Bounds( + lower=-800.0, upper=200.0 + ) + + +def test_rated_power_one_unrated() -> None: + """One installed asset without a rating makes the result unknown.""" + assets = _assets( + pv={"1": {"rated_power": 500}}, + battery={"1": {"rated_power": 200}, "2": {"capacity": 400}}, + ) + assert assets.rated_power("pv", at=_AT, microgrid_id=1) is not None + assert assets.rated_power(["pv", "battery"], at=_AT, microgrid_id=1) is None + + +def test_rated_power_ctype_without_assets() -> None: + """A component type without assets makes the result unknown.""" + assets = _assets(ctype={"battery": {"meter": [1]}}) + assert assets.rated_power("pv", at=_AT, microgrid_id=1) == Bounds( + lower=0.0, upper=0.0 + ) + assert assets.rated_power("battery", at=_AT, microgrid_id=1) is None + + +def test_rated_power_installed_at() -> None: + """Only assets installed at the instant count, unrated or not.""" + assets = _assets( + pv={ + "old": { + "rated_power": 100, + "end_time": datetime(2026, 1, 1, tzinfo=timezone.utc), + }, + "now": { + "rated_power": 200, + "start_time": datetime(2026, 1, 1, tzinfo=timezone.utc), + }, + "new": {"start_time": datetime(2027, 1, 1, tzinfo=timezone.utc)}, + }, + ) + assert assets.rated_power("pv", at=_AT, microgrid_id=1) == Bounds( + lower=-200.0, upper=0.0 + ) + + +def test_rated_power_wind_turbines() -> None: + """A wind entry's rating counts once per turbine.""" + assets = _assets(wind={"1": {"rated_power": 3000, "number_of_turbines": 2}}) + assert assets.rated_power("wind", at=_AT, microgrid_id=1) == Bounds( + lower=-6000.0, upper=0.0 + )