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
5 changes: 4 additions & 1 deletion RELEASE_NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@

## New Features

<!-- Here goes the main new features and examples or instructions on how to use them -->
- Resolve the `AC_ENERGY_ACTIVE`, `AC_ENERGY_ACTIVE_CONSUMED`, and
`AC_ENERGY_ACTIVE_DELIVERED` formulas to `AC_POWER_ACTIVE` when no explicit
energy formula is configured. This avoids duplicating topology formulas in
generated microgrid configuration.

## Bug Fixes

Expand Down
7 changes: 4 additions & 3 deletions src/frequenz/gridpool/config/_load.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,9 +233,10 @@ def _derive_component_configs(
"""Build the component-type configs for a microgrid from its graph.

Derives, per component type, the `AC_POWER_ACTIVE` formula and the
meter/inverter/component ID lists straight from the component graph. A
component type only appears in the result if the graph yields a non-zero
formula or at least one ID for it.
meter/inverter/component ID lists straight from the component graph. Active
energy metrics reuse the active-power formula at lookup time. A component
type only appears in the result if the graph yields a non-zero formula or
at least one ID for it.

Args:
graph:
Expand Down
42 changes: 37 additions & 5 deletions src/frequenz/gridpool/config/_microgrid.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,15 @@
ComponentCategory = Literal["meter", "inverter", "component"]
"""Valid component categories."""

_POWER_FORMULA_METRIC = "AC_POWER_ACTIVE"
_ENERGY_FORMULA_METRICS = frozenset(
{
"AC_ENERGY_ACTIVE",
"AC_ENERGY_ACTIVE_CONSUMED",
"AC_ENERGY_ACTIVE_DELIVERED",
}
)


@dataclass
class ComponentTypeConfig:
Expand All @@ -40,6 +49,31 @@ def __post_init__(self) -> None:
"""Set the default formula if none is provided."""
self.formula = self.formula or {}

def formula_for_metric(self, metric: str) -> str | None:
"""Get a formula for a metric, falling back to active power for energy.

Explicit formulas always take precedence. The component IDs and
operations of the generated active-power formula also apply to the
active-energy metrics, so they do not need to be stored redundantly.

Args:
metric: Metric name of the formula.

Returns:
The explicitly configured formula, or the active-power formula for
an active-energy metric that has no explicit formula.

Raises:
ValueError: If the formulas are not configured as a dictionary.
"""
if not isinstance(self.formula, dict):
raise ValueError("Formula must be a dictionary.")

formula = self.formula.get(metric)
if not formula and metric in _ENERGY_FORMULA_METRICS:
formula = self.formula.get(_POWER_FORMULA_METRIC)
return formula

def cids(self, metric: str = "") -> list[int]:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should remove this, I am not aware if it is used anywhere.

"""Get component IDs for this component.

Expand All @@ -58,14 +92,12 @@ def cids(self, metric: str = "") -> list[int]:
ValueError: If the metric is not supported or improperly set.
"""
if metric:
if not isinstance(self.formula, dict):
raise ValueError("Formula must be a dictionary.")
formula = self.formula.get(metric)
formula = self.formula_for_metric(metric)
if not formula:
raise ValueError(f"{metric} does not have a formula")
# Extract component IDs from the formula which are given as e.g. #123
pattern = r"#(\d+)"
return [int(e) for e in re.findall(pattern, self.formula[metric])]
return [int(e) for e in re.findall(pattern, formula)]

return self._default_cids()

Expand Down Expand Up @@ -267,7 +299,7 @@ def formula(self, component_type: str, metric: str) -> str:
raise ValueError(f"{component_type} not found in config.")
if cfg.formula is None:
raise ValueError(f"No formula set for {component_type}")
formula = cfg.formula.get(metric)
formula = cfg.formula_for_metric(metric)
if not formula:
raise ValueError(f"{component_type} is missing formula for {metric}")

Expand Down
15 changes: 15 additions & 0 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,12 @@ def test_microgrid_config_component_type_ids(
305,
306,
]
assert valid_microgrid_config.component_type_ids(
"pv", metric="AC_ENERGY_ACTIVE"
) == [
12,
23,
]

with pytest.raises(ValueError):
valid_microgrid_config.component_type_ids("unknown")
Expand All @@ -113,6 +119,15 @@ def test_microgrid_config_component_type_ids(
def test_microgrid_config_formula(valid_microgrid_config: MicrogridConfig) -> None:
"""Test retrieval of formula for a given component type and metric."""
assert valid_microgrid_config.formula("pv", "AC_POWER_ACTIVE") == "#12+#23"
for metric in (
"AC_ENERGY_ACTIVE",
"AC_ENERGY_ACTIVE_CONSUMED",
"AC_ENERGY_ACTIVE_DELIVERED",
):
assert valid_microgrid_config.formula("pv", metric) == "#12+#23"

valid_microgrid_config.ctype["pv"].formula["AC_ENERGY_ACTIVE"] = "#34"
assert valid_microgrid_config.formula("pv", "AC_ENERGY_ACTIVE") == "#34"

with pytest.raises(ValueError):
valid_microgrid_config.formula("pv", "INVALID_METRIC")
Expand Down