mirror of
https://github.com/Akkudoktor-EOS/EOS.git
synced 2026-11-13 09:13:30 +01:00
feat(devices): add inverter profiles
An inverter profile describes the technical data of an inverter model: its nominal AC power, the DC→AC and AC→DC efficiency curves over the load fraction (AC power relative to the nominal power), the AC charge power limit of the model, whether that limit also limits PV charging, and an optional power derating over the ambient temperature. Curves are read linearly and clamped at their ends, so every lookup yields a value. The packaged profile generic-hybrid has typical hybrid inverter efficiencies, no nominal power (the inverter device has to provide it) and full power up to 45 degC. Inverter settings name their profile (inverter_profile, default generic-hybrid) and hold the differences of the unit in profile_adjustment: nominal_power_w (replaces the profile value, required for a generic profile), max_power_w and max_ac_charge_power_w (installation limits that can only lower; an AC charge limit of 0 disables AC charging). The effective parameters are resolved at the ambient temperature of the inverter, given by the new measurement key <device_id>-temperature-degc (45 degC without a fresh value); the power derating lowers the maximum power and the AC charge limit. Optimization parameters are always valid: the GENETIC and GENETIC0 parameter preparation resolve the inverter with resolve_current_operating_parameters_or_defaults, which never raises. An unusable profile gives the generic-hybrid profile, a missing nominal power the fallback of 10000 W, an inverter derated to zero power the parameters at 45 degC, and no usable profile at all the profile adjustment with constant efficiency; each is logged as error. The GENETIC inverter takes the AC→DC efficiency curve of the profile, solved exactly on each linear piece of the curve (about 2 % longer runs); GENETIC0 keeps constant efficiencies and no longer replaces the configured inverters with the demo inverter; a battery, electric vehicle or inverter that cannot be prepared is left out of the GENETIC0 run, never replaced by a demo device. Configurations migrate: max_power_w becomes profile_adjustment.nominal_power_w, max_ac_charge_power_w moves into the adjustment, an ac_to_dc_efficiency of 0 keeps AC charging disabled, and the efficiency fields are dropped with an error log, as for batteries, so the profile efficiencies apply. Home Assistant config paths follow. Additional changes - Move the curve algorithms of the battery profile into profilecurve, so battery and inverter profiles share them; the battery profile keeps its document format and classes. - Move ProfileBaseModel, the strict base of profile documents, into profilestore. - Serve inverter profiles through the profile REST API. Refuse to delete a profile that a configured device uses and that has no packaged profile to revert to (409). - Share the measurement access of the device settings in devicemeasurement. - Rename check_battery_profiles to check_device_profiles; the device profile check at configuration setup covers inverters, too. - Document inverter profiles, their configuration, defaults and sharing; regenerate the configuration and OpenAPI documentation. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Assisted-by: Claude Code (claude-opus-5-5)
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
e255f987bf
commit
faf37abfe7
+19
-5
@@ -855,7 +855,7 @@ class TestDeviceSettings:
|
||||
with pytest.raises(ValidationError, match="device_id"):
|
||||
DevicesCommonSettings.model_validate({"batteries": {"house": {"device_id": "other"}}})
|
||||
|
||||
def test_check_battery_profiles_names_unresolvable_devices(self, config_eos):
|
||||
def test_check_device_profiles_names_unresolvable_devices(self, config_eos):
|
||||
# generic-lfp provides no capacity: the house battery lacks it, the car has it.
|
||||
devices = DevicesCommonSettings.model_validate(
|
||||
{
|
||||
@@ -863,15 +863,29 @@ class TestDeviceSettings:
|
||||
"electric_vehicles": {"car": {"profile_adjustment": {"nominal_capacity_wh": 60000}}},
|
||||
}
|
||||
)
|
||||
errors, warnings = devices.check_battery_profiles()
|
||||
errors, warnings = devices.check_device_profiles()
|
||||
assert len(errors) == 1
|
||||
assert "Battery 'house'" in errors[0]
|
||||
assert warnings == []
|
||||
|
||||
def test_config_logs_battery_profile_problems_once(self, config_eos, monkeypatch):
|
||||
def test_check_device_profiles_covers_inverters(self, config_eos):
|
||||
# generic-hybrid provides no nominal power.
|
||||
devices = DevicesCommonSettings.model_validate(
|
||||
{
|
||||
"inverters": {
|
||||
"inv1": {},
|
||||
"inv2": {"profile_adjustment": {"nominal_power_w": 5000, "max_power_w": 8000}},
|
||||
}
|
||||
}
|
||||
)
|
||||
errors, warnings = devices.check_device_profiles()
|
||||
assert len(errors) == 1 and "Inverter 'inv1'" in errors[0]
|
||||
assert len(warnings) == 1 and "Inverter 'inv2'" in warnings[0]
|
||||
|
||||
def test_config_logs_device_profile_problems_once(self, config_eos, monkeypatch):
|
||||
from loguru import logger
|
||||
|
||||
monkeypatch.setattr(ConfigEOS, "_battery_profile_problems", ((), ()))
|
||||
monkeypatch.setattr(ConfigEOS, "_device_profile_problems", ((), ()))
|
||||
messages: list[str] = []
|
||||
sink_id = logger.add(
|
||||
lambda message: messages.append(message.record["message"]), level="WARNING"
|
||||
@@ -888,7 +902,7 @@ class TestDeviceSettings:
|
||||
"devices/batteries/house/profile_adjustment/nominal_capacity_wh", 10000
|
||||
)
|
||||
assert not [m for m in messages if "Battery 'house'" in m]
|
||||
assert ConfigEOS._battery_profile_problems == ((), ())
|
||||
assert ConfigEOS._device_profile_problems == ((), ())
|
||||
finally:
|
||||
logger.remove(sink_id)
|
||||
|
||||
|
||||
@@ -416,6 +416,85 @@ class TestDeviceMigration:
|
||||
),
|
||||
}
|
||||
|
||||
def test_migration_logs_dropped_inverter_efficiencies_as_error(self):
|
||||
"""Like battery efficiencies, dropped inverter efficiencies are logged as error."""
|
||||
from loguru import logger
|
||||
|
||||
messages: list[str] = []
|
||||
sink_id = logger.add(lambda message: messages.append(message.record["message"]), level="ERROR")
|
||||
try:
|
||||
inverter = {
|
||||
"device_id": "inv1",
|
||||
"max_power_w": 8000,
|
||||
"dc_to_ac_efficiency_curve": [[0.1, 0.9], [1.0, 0.97]],
|
||||
}
|
||||
migrate_config_data({"devices": {"inverters": {"inv1": inverter}}})
|
||||
finally:
|
||||
logger.remove(sink_id)
|
||||
assert len(messages) == 1
|
||||
assert "Inverter 'inv1'" in messages[0]
|
||||
assert "dc_to_ac_efficiency_curve" in messages[0]
|
||||
|
||||
def test_migration_of_legacy_inverter_fields(self):
|
||||
"""Inverter power limits move into the adjustment, efficiencies are dropped."""
|
||||
inverter = {
|
||||
"device_id": "inv1",
|
||||
"max_power_w": 8000,
|
||||
"max_ac_charge_power_w": 3000,
|
||||
"ac_to_dc_efficiency": 0.95,
|
||||
"dc_to_ac_efficiency": 0.96,
|
||||
"dc_to_ac_efficiency_curve": [[0.1, 0.9], [1.0, 0.96]],
|
||||
"ac_charge_limits_total_charge": True,
|
||||
"battery_id": "bat1",
|
||||
}
|
||||
migrated = migrate_config_data({"devices": {"inverters": {"inv1": inverter}}})
|
||||
assert migrated.devices.inverters is not None
|
||||
settings = migrated.devices.inverters["inv1"]
|
||||
assert settings.profile_adjustment.nominal_power_w == 8000
|
||||
assert settings.profile_adjustment.max_ac_charge_power_w == 3000
|
||||
assert settings.profile_adjustment.max_power_w is None
|
||||
assert settings.battery_id == "bat1"
|
||||
dumped = settings.model_dump(exclude_computed_fields=True)
|
||||
for legacy in ("max_power_w", "max_ac_charge_power_w", "ac_to_dc_efficiency",
|
||||
"dc_to_ac_efficiency", "dc_to_ac_efficiency_curve",
|
||||
"ac_charge_limits_total_charge"):
|
||||
assert legacy not in dumped
|
||||
|
||||
def test_migration_keeps_ac_charging_disabled(self):
|
||||
"""A legacy AC→DC efficiency of 0 disabled AC charging."""
|
||||
inverter = {"device_id": "inv1", "max_power_w": 8000, "ac_to_dc_efficiency": 0.0}
|
||||
migrated = migrate_config_data({"devices": {"inverters": [inverter]}})
|
||||
assert migrated.devices.inverters is not None
|
||||
assert migrated.devices.inverters["inv1"].profile_adjustment.max_ac_charge_power_w == 0
|
||||
|
||||
def test_migration_keeps_present_inverter_adjustment(self):
|
||||
inverter = {
|
||||
"device_id": "inv1",
|
||||
"max_power_w": 8000,
|
||||
"profile_adjustment": {"nominal_power_w": 6000},
|
||||
}
|
||||
migrated = migrate_config_data({"devices": {"inverters": {"inv1": inverter}}})
|
||||
assert migrated.devices.inverters is not None
|
||||
assert migrated.devices.inverters["inv1"].profile_adjustment.nominal_power_w == 6000
|
||||
|
||||
def test_migration_of_inverter_home_assistant_config_paths(self):
|
||||
raw = {
|
||||
"adapter": {
|
||||
"homeassistant": {
|
||||
"config_entity_ids": {
|
||||
"devices/inverters/inv1/max_power_w": "sensor.inverter_power",
|
||||
"devices/inverters/inv1/dc_to_ac_efficiency": "sensor.efficiency",
|
||||
"devices/inverters/inv1/battery_id": "sensor.battery",
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
migrated = migrate_config_data(raw)
|
||||
assert migrated.adapter.homeassistant.config_entity_ids == {
|
||||
"devices/inverters/inv1/profile_adjustment/nominal_power_w": "sensor.inverter_power",
|
||||
"devices/inverters/inv1/battery_id": "sensor.battery",
|
||||
}
|
||||
|
||||
def test_migration_keeps_a_migrated_battery(self):
|
||||
"""A battery in the current layout is not changed, e.g. on a version bump."""
|
||||
battery = {
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
"""Tests for the one-dimensional curves shared by the device profiles."""
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from akkudoktoreos.devices.profile.profilecurve import (
|
||||
CurveInterpolation,
|
||||
OutOfRangeBehavior,
|
||||
PrecomputedCurve,
|
||||
reference_curve_lookup,
|
||||
validate_curve_points,
|
||||
)
|
||||
|
||||
X = (0.0, 0.2, 0.5, 1.0)
|
||||
Y = (0.80, 0.95, 0.97, 0.96)
|
||||
|
||||
|
||||
class TestValidateCurvePoints:
|
||||
def test_accepts_increasing_points(self):
|
||||
validate_curve_points(X, Y, "load_fraction", "efficiency")
|
||||
|
||||
@pytest.mark.parametrize("x", [(0.0, 0.0, 1.0), (0.0, 0.5, 0.4)])
|
||||
def test_rejects_not_strictly_increasing(self, x):
|
||||
with pytest.raises(ValueError, match="load_fraction breakpoints must be strictly"):
|
||||
validate_curve_points(x, (1.0, 1.0, 1.0), "load_fraction", "efficiency")
|
||||
|
||||
def test_rejects_mismatched_lengths(self):
|
||||
with pytest.raises(ValueError, match="same number of values"):
|
||||
validate_curve_points(X, Y[:-1], "load_fraction", "efficiency")
|
||||
|
||||
|
||||
class TestPrecomputedCurve:
|
||||
@pytest.mark.parametrize("interpolation", list(CurveInterpolation))
|
||||
@pytest.mark.parametrize("behavior", list(OutOfRangeBehavior))
|
||||
def test_lookup_matches_reference(self, interpolation, behavior):
|
||||
curve = PrecomputedCurve.from_points(X, Y, interpolation, behavior)
|
||||
queries = [-0.5, 0.0, 0.1, 0.2, 0.35, 0.5, 0.75, 1.0, 1.5, 0.6]
|
||||
for query in queries:
|
||||
expected = reference_curve_lookup(X, Y, interpolation, behavior, query)
|
||||
actual = curve.lookup(query)
|
||||
if expected is None:
|
||||
assert actual is None
|
||||
else:
|
||||
assert actual == pytest.approx(expected)
|
||||
|
||||
def test_linear_interpolation(self):
|
||||
curve = PrecomputedCurve.from_points(X, Y)
|
||||
assert curve.lookup(0.1) == pytest.approx(0.875)
|
||||
assert curve.lookup(0.75) == pytest.approx(0.965)
|
||||
|
||||
def test_clamps_by_default(self):
|
||||
curve = PrecomputedCurve.from_points(X, Y)
|
||||
assert curve.lookup(-1.0) == pytest.approx(0.80)
|
||||
assert curve.lookup(2.0) == pytest.approx(0.96)
|
||||
|
||||
def test_nearest_tie_takes_lower_breakpoint(self):
|
||||
curve = PrecomputedCurve.from_points(X, Y, CurveInterpolation.NEAREST)
|
||||
assert curve.lookup(0.1) == pytest.approx(0.80)
|
||||
|
||||
def test_none_interpolation_only_at_breakpoints(self):
|
||||
curve = PrecomputedCurve.from_points(X, Y, CurveInterpolation.NONE)
|
||||
assert curve.lookup(0.5) == pytest.approx(0.97)
|
||||
assert curve.lookup(0.4) is None
|
||||
|
||||
def test_reject_out_of_range(self):
|
||||
curve = PrecomputedCurve.from_points(X, Y, out_of_range_behavior=OutOfRangeBehavior.REJECT)
|
||||
assert curve.lookup(-0.1) is None
|
||||
assert curve.lookup(1.1) is None
|
||||
|
||||
def test_precomputes_coefficients(self):
|
||||
curve = PrecomputedCurve.from_points(X, Y)
|
||||
assert len(curve.slopes) == len(X) - 1
|
||||
assert curve.midpoints == pytest.approx((0.1, 0.35, 0.75))
|
||||
for i, slope in enumerate(curve.slopes):
|
||||
assert slope * X[i] + curve.intercepts[i] == pytest.approx(Y[i])
|
||||
|
||||
def test_accepts_numpy_input(self):
|
||||
curve = PrecomputedCurve.from_points(np.array(X), np.array(Y))
|
||||
assert curve.x == X
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"x, y",
|
||||
[((0.0,), (1.0,)), ((0.0, 0.0), (1.0, 1.0)), ((0.0, 1.0), (1.0,))],
|
||||
)
|
||||
def test_rejects_invalid_points(self, x, y):
|
||||
with pytest.raises(ValueError):
|
||||
PrecomputedCurve.from_points(x, y)
|
||||
|
||||
def test_is_immutable(self):
|
||||
curve = PrecomputedCurve.from_points(X, Y)
|
||||
with pytest.raises(AttributeError):
|
||||
curve.x = (0.0, 1.0) # type: ignore[misc]
|
||||
@@ -0,0 +1,165 @@
|
||||
"""Tests for inverter profile documents and their runtime form."""
|
||||
|
||||
import copy
|
||||
from typing import Any, Iterator
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from akkudoktoreos.devices.profile.inverterprofile import (
|
||||
InverterProfile,
|
||||
InverterProfileSettings,
|
||||
)
|
||||
from akkudoktoreos.devices.profile.profilestore import (
|
||||
ProfileStore,
|
||||
get_profile_store,
|
||||
profile_type,
|
||||
)
|
||||
|
||||
DOCUMENT: dict[str, Any] = {
|
||||
"inverter_model": "Test inverter",
|
||||
"nominal_power_w": 10000.0,
|
||||
"max_ac_charge_power_w": 6000.0,
|
||||
"dc_to_ac_efficiency": {
|
||||
"load_fraction": [0.1, 0.5, 1.0],
|
||||
"efficiency": [0.90, 0.97, 0.96],
|
||||
},
|
||||
"ac_to_dc_efficiency": {
|
||||
"load_fraction": [0.1, 1.0],
|
||||
"efficiency": [0.88, 0.95],
|
||||
},
|
||||
"power_derating": {
|
||||
"temperature_degC": [40.0, 60.0],
|
||||
"power_fraction": [1.0, 0.5],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def make_document(**changes: Any) -> dict[str, Any]:
|
||||
document = copy.deepcopy(DOCUMENT)
|
||||
document.update(changes)
|
||||
return document
|
||||
|
||||
|
||||
def make_profile(**changes: Any) -> InverterProfile:
|
||||
return InverterProfileSettings.model_validate(make_document(**changes)).compile_profile()
|
||||
|
||||
|
||||
class TestDocument:
|
||||
def test_registered_as_inverter_kind(self):
|
||||
assert profile_type("inverter") is InverterProfileSettings
|
||||
|
||||
def test_minimal_generic_document(self):
|
||||
document = make_document(nominal_power_w=None, max_ac_charge_power_w=None)
|
||||
del document["power_derating"]
|
||||
settings = InverterProfileSettings.model_validate(document)
|
||||
assert settings.nominal_power_w is None
|
||||
assert settings.power_derating is None
|
||||
assert settings.ac_charge_limits_total_charge is False
|
||||
|
||||
@pytest.mark.parametrize("field", ["dc_to_ac_efficiency", "ac_to_dc_efficiency"])
|
||||
def test_efficiency_curves_are_required(self, field):
|
||||
document = make_document()
|
||||
del document[field]
|
||||
with pytest.raises(ValidationError, match=field):
|
||||
InverterProfileSettings.model_validate(document)
|
||||
|
||||
def test_rejects_unknown_keys(self):
|
||||
with pytest.raises(ValidationError, match="nominal_power_kw"):
|
||||
InverterProfileSettings.model_validate(make_document(nominal_power_kw=10.0))
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"curve",
|
||||
[
|
||||
{"load_fraction": [0.5, 0.1], "efficiency": [0.9, 0.9]},
|
||||
{"load_fraction": [-0.1, 1.0], "efficiency": [0.9, 0.9]},
|
||||
{"load_fraction": [0.1, 1.0], "efficiency": [0.0, 0.9]},
|
||||
{"load_fraction": [0.1, 1.0], "efficiency": [0.9, 1.1]},
|
||||
{"load_fraction": [0.1, 0.5, 1.0], "efficiency": [0.9, 0.9]},
|
||||
{"load_fraction": [0.1], "efficiency": [0.9]},
|
||||
],
|
||||
)
|
||||
def test_rejects_invalid_efficiency_curves(self, curve):
|
||||
with pytest.raises(ValidationError):
|
||||
InverterProfileSettings.model_validate(make_document(dc_to_ac_efficiency=curve))
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"curve",
|
||||
[
|
||||
{"temperature_degC": [60.0, 40.0], "power_fraction": [1.0, 0.5]},
|
||||
{"temperature_degC": [40.0, 60.0], "power_fraction": [1.0, 1.5]},
|
||||
{"temperature_degC": [40.0, 60.0], "power_fraction": [1.0, -0.1]},
|
||||
],
|
||||
)
|
||||
def test_rejects_invalid_derating(self, curve):
|
||||
with pytest.raises(ValidationError):
|
||||
InverterProfileSettings.model_validate(make_document(power_derating=curve))
|
||||
|
||||
@pytest.mark.parametrize("field", ["nominal_power_w", "max_ac_charge_power_w"])
|
||||
@pytest.mark.parametrize("value", [0.0, -1.0, float("inf")])
|
||||
def test_rejects_invalid_powers(self, field, value):
|
||||
with pytest.raises(ValidationError):
|
||||
InverterProfileSettings.model_validate(make_document(**{field: value}))
|
||||
|
||||
def test_compile_rejects_options(self):
|
||||
with pytest.raises(TypeError):
|
||||
InverterProfileSettings.model_validate(make_document()).compile_profile(t_step=1.0)
|
||||
|
||||
|
||||
class TestRuntime:
|
||||
def test_carries_the_model_data(self):
|
||||
profile = make_profile(ac_charge_limits_total_charge=True)
|
||||
assert profile.inverter_model == "Test inverter"
|
||||
assert profile.nominal_power_w == pytest.approx(10000.0)
|
||||
assert profile.max_ac_charge_power_w == pytest.approx(6000.0)
|
||||
assert profile.ac_charge_limits_total_charge is True
|
||||
|
||||
def test_efficiencies_interpolate_linearly(self):
|
||||
profile = make_profile()
|
||||
assert profile.dc_to_ac_efficiency_at(0.3) == pytest.approx(0.935)
|
||||
assert profile.ac_to_dc_efficiency_at(0.55) == pytest.approx(0.915)
|
||||
|
||||
def test_efficiencies_clamp_beyond_the_curve(self):
|
||||
profile = make_profile()
|
||||
assert profile.dc_to_ac_efficiency_at(0.0) == pytest.approx(0.90)
|
||||
assert profile.dc_to_ac_efficiency_at(1.5) == pytest.approx(0.96)
|
||||
|
||||
def test_derating(self):
|
||||
profile = make_profile()
|
||||
assert profile.power_fraction_at(20.0) == pytest.approx(1.0)
|
||||
assert profile.power_fraction_at(50.0) == pytest.approx(0.75)
|
||||
assert profile.power_fraction_at(80.0) == pytest.approx(0.5)
|
||||
|
||||
def test_without_derating_full_power(self):
|
||||
document = make_document()
|
||||
del document["power_derating"]
|
||||
profile = InverterProfileSettings.model_validate(document).compile_profile()
|
||||
assert profile.power_fraction_at(70.0) == pytest.approx(1.0)
|
||||
|
||||
def test_is_immutable(self):
|
||||
profile = make_profile()
|
||||
with pytest.raises(AttributeError):
|
||||
profile.nominal_power_w = 1.0 # type: ignore[misc]
|
||||
|
||||
|
||||
class TestPackagedGenericHybrid:
|
||||
@pytest.fixture
|
||||
def profile(self, config_eos) -> Iterator[InverterProfile]:
|
||||
ProfileStore.reset_instance()
|
||||
yield get_profile_store().get(InverterProfileSettings, "generic-hybrid")
|
||||
ProfileStore.reset_instance()
|
||||
|
||||
def test_is_generic(self, profile):
|
||||
assert profile.nominal_power_w is None
|
||||
assert profile.max_ac_charge_power_w is None
|
||||
|
||||
def test_full_power_up_to_45_degc(self, profile):
|
||||
assert profile.power_fraction_at(-30.0) == pytest.approx(1.0)
|
||||
assert profile.power_fraction_at(45.0) == pytest.approx(1.0)
|
||||
assert profile.power_fraction_at(60.0) == pytest.approx(0.6)
|
||||
assert profile.power_fraction_at(65.0) == pytest.approx(0.0)
|
||||
|
||||
def test_realistic_efficiencies(self, profile):
|
||||
for load_fraction in (0.05, 0.1, 0.3, 0.5, 1.0):
|
||||
assert 0.85 <= profile.dc_to_ac_efficiency_at(load_fraction) < 1.0
|
||||
assert 0.85 <= profile.ac_to_dc_efficiency_at(load_fraction) < 1.0
|
||||
@@ -0,0 +1,317 @@
|
||||
"""Tests for the inverter device settings resolved from inverter profiles."""
|
||||
|
||||
import dataclasses
|
||||
import math
|
||||
from typing import Any, Optional
|
||||
|
||||
import pytest
|
||||
|
||||
from akkudoktoreos.devices.profile.inverterprofile import (
|
||||
InverterProfile,
|
||||
InverterProfileSettings,
|
||||
)
|
||||
from akkudoktoreos.devices.profile.profilecurve import PrecomputedCurve
|
||||
from akkudoktoreos.devices.profile.profilestore import get_profile_store
|
||||
from akkudoktoreos.devices.settings import invertermeasurement
|
||||
from akkudoktoreos.devices.settings.inverterresolution import (
|
||||
INVERTER_DEFAULT_TEMPERATURE_DEGC,
|
||||
InverterOperatingPoint,
|
||||
InverterResolutionError,
|
||||
)
|
||||
from akkudoktoreos.devices.settings.invertersettings import (
|
||||
INVERTER_DEFAULT_PROFILE,
|
||||
InverterCommonSettings,
|
||||
InverterProfileAdjustment,
|
||||
)
|
||||
|
||||
|
||||
def make_settings(**adjustment: Any) -> InverterCommonSettings:
|
||||
return InverterCommonSettings(
|
||||
device_id="inverter1",
|
||||
battery_id="battery1",
|
||||
profile_adjustment=InverterProfileAdjustment(**adjustment),
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def generic(config_eos) -> InverterProfile:
|
||||
"""The packaged generic hybrid inverter profile."""
|
||||
return get_profile_store().get(InverterProfileSettings, "generic-hybrid")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def use_profile(monkeypatch):
|
||||
"""Let all inverter settings use the given compiled profile."""
|
||||
|
||||
def _use(profile: InverterProfile) -> None:
|
||||
monkeypatch.setattr(InverterCommonSettings, "get_inverter_profile", lambda self: profile)
|
||||
|
||||
return _use
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def measured(monkeypatch) -> dict[str, Optional[float]]:
|
||||
"""Measured values by key for the inverter measurement access."""
|
||||
values: dict[str, Optional[float]] = {}
|
||||
|
||||
async def fake_get_measured_value(key: str, target_datetime: Any) -> Optional[float]:
|
||||
return values.get(key)
|
||||
|
||||
monkeypatch.setattr(invertermeasurement, "get_measured_value", fake_get_measured_value)
|
||||
return values
|
||||
|
||||
|
||||
class TestDefaults:
|
||||
def test_default_profile(self):
|
||||
settings = InverterCommonSettings(device_id="inverter1")
|
||||
assert settings.inverter_profile == INVERTER_DEFAULT_PROFILE == "generic-hybrid"
|
||||
assert settings.profile_adjustment.model_dump() == InverterProfileAdjustment().model_dump()
|
||||
|
||||
def test_generic_profile_needs_a_nominal_power(self, generic):
|
||||
settings = InverterCommonSettings(device_id="inverter1")
|
||||
with pytest.raises(InverterResolutionError, match="inverter1.*nominal_power_w"):
|
||||
settings.resolve_operating_parameters()
|
||||
assert settings.effective_nominal_power_w is None
|
||||
assert settings.effective_max_power_w is None
|
||||
errors, warnings = settings.check_profile()
|
||||
assert len(errors) == 1 and "inverter1" in errors[0]
|
||||
assert warnings == []
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"adjustment",
|
||||
[{"nominal_power_w": 0}, {"max_power_w": 0}, {"max_ac_charge_power_w": -1}],
|
||||
)
|
||||
def test_rejects_invalid_adjustment(self, adjustment):
|
||||
with pytest.raises(ValueError):
|
||||
InverterProfileAdjustment(**adjustment)
|
||||
|
||||
|
||||
class TestResolution:
|
||||
def test_reference_point_is_45_degc(self, generic):
|
||||
settings = make_settings(nominal_power_w=10000)
|
||||
parameters = settings.resolve_operating_parameters()
|
||||
assert parameters.temperature_degC == INVERTER_DEFAULT_TEMPERATURE_DEGC == 45.0
|
||||
# The generic profile is not derated at 45 degC.
|
||||
assert parameters.power_fraction == pytest.approx(1.0)
|
||||
assert parameters.nominal_power_w == pytest.approx(10000)
|
||||
assert parameters.max_power_w == pytest.approx(10000)
|
||||
assert parameters.max_ac_charge_power_w == pytest.approx(10000)
|
||||
assert settings.effective_max_power_w == pytest.approx(10000)
|
||||
|
||||
def test_efficiencies_come_from_the_profile(self, generic):
|
||||
settings = make_settings(nominal_power_w=10000)
|
||||
parameters = settings.resolve_operating_parameters()
|
||||
# DC→AC at the reference load fraction 0.06 of the maximum power.
|
||||
assert parameters.dc_to_ac_efficiency == pytest.approx(generic.dc_to_ac_efficiency_at(0.06))
|
||||
# AC→DC at the AC charge limit, here the full nominal power.
|
||||
assert parameters.ac_to_dc_efficiency == pytest.approx(generic.ac_to_dc_efficiency_at(1.0))
|
||||
assert settings.effective_dc_to_ac_efficiency == pytest.approx(
|
||||
parameters.dc_to_ac_efficiency
|
||||
)
|
||||
assert settings.effective_ac_to_dc_efficiency == pytest.approx(
|
||||
parameters.ac_to_dc_efficiency
|
||||
)
|
||||
|
||||
def test_derating_at_the_operating_point(self, generic):
|
||||
settings = make_settings(nominal_power_w=10000)
|
||||
parameters = settings.resolve_operating_parameters(InverterOperatingPoint(60.0))
|
||||
assert parameters.power_fraction == pytest.approx(0.6)
|
||||
assert parameters.max_power_w == pytest.approx(6000)
|
||||
assert parameters.max_ac_charge_power_w == pytest.approx(6000)
|
||||
|
||||
def test_curves_are_over_the_load_fraction_of_the_maximum_power(self, generic):
|
||||
settings = make_settings(nominal_power_w=10000)
|
||||
parameters = settings.resolve_operating_parameters(InverterOperatingPoint(60.0))
|
||||
# 3000 W are 0.3 of the nominal and 0.5 of the derated maximum power.
|
||||
curve = PrecomputedCurve.from_points(
|
||||
[x for x, _ in parameters.dc_to_ac_efficiency_curve],
|
||||
[y for _, y in parameters.dc_to_ac_efficiency_curve],
|
||||
)
|
||||
assert curve.lookup(0.5) == pytest.approx(generic.dc_to_ac_efficiency_at(0.3))
|
||||
# The curve ends at the maximum power, 0.6 of the nominal power.
|
||||
assert parameters.dc_to_ac_efficiency_curve[-1] == pytest.approx(
|
||||
(1.0, generic.dc_to_ac_efficiency_at(0.6))
|
||||
)
|
||||
assert all(0.0 <= x <= 1.0 for x, _ in parameters.dc_to_ac_efficiency_curve)
|
||||
|
||||
def test_curve_keeps_two_points_when_heavily_limited(self, generic):
|
||||
# 400 W are below the first breakpoint (0.05 of 10 kW = 500 W).
|
||||
settings = make_settings(nominal_power_w=10000, max_power_w=400)
|
||||
curve = settings.resolve_operating_parameters().dc_to_ac_efficiency_curve
|
||||
assert [x for x, _ in curve] == [0.0, 1.0]
|
||||
assert [y for _, y in curve] == pytest.approx([0.88, 0.88])
|
||||
settings.to_genetic_param()
|
||||
|
||||
def test_no_power_at_the_operating_point(self, generic):
|
||||
settings = make_settings(nominal_power_w=10000)
|
||||
with pytest.raises(InverterResolutionError, match="allows no power"):
|
||||
settings.resolve_operating_parameters(InverterOperatingPoint(70.0))
|
||||
|
||||
def test_installation_limits_only_lower(self, generic):
|
||||
settings = make_settings(nominal_power_w=10000, max_power_w=8000, max_ac_charge_power_w=3000)
|
||||
parameters = settings.resolve_operating_parameters()
|
||||
assert parameters.max_power_w == pytest.approx(8000)
|
||||
assert parameters.max_ac_charge_power_w == pytest.approx(3000)
|
||||
assert parameters.ac_to_dc_efficiency == pytest.approx(generic.ac_to_dc_efficiency_at(0.3))
|
||||
assert settings.check_profile() == ([], [])
|
||||
|
||||
def test_derating_below_the_installation_limit(self, generic):
|
||||
settings = make_settings(nominal_power_w=10000, max_power_w=8000)
|
||||
parameters = settings.resolve_operating_parameters(InverterOperatingPoint(60.0))
|
||||
assert parameters.max_power_w == pytest.approx(6000)
|
||||
|
||||
def test_zero_ac_charge_limit_disables_ac_charging(self, generic):
|
||||
settings = make_settings(nominal_power_w=10000, max_ac_charge_power_w=0)
|
||||
parameters = settings.resolve_operating_parameters()
|
||||
assert parameters.max_ac_charge_power_w == 0
|
||||
assert math.isfinite(parameters.ac_to_dc_efficiency)
|
||||
assert settings.to_genetic_param().max_ac_charge_power_w == 0
|
||||
|
||||
def test_model_ac_charge_limit_is_derated(self, generic, use_profile):
|
||||
use_profile(dataclasses.replace(generic, nominal_power_w=10000, max_ac_charge_power_w=5000))
|
||||
settings = make_settings()
|
||||
assert settings.resolve_operating_parameters().max_ac_charge_power_w == pytest.approx(5000)
|
||||
derated = settings.resolve_operating_parameters(InverterOperatingPoint(60.0))
|
||||
assert derated.max_ac_charge_power_w == pytest.approx(3000)
|
||||
|
||||
def test_profile_nominal_power_and_adjustment(self, generic, use_profile):
|
||||
use_profile(dataclasses.replace(generic, nominal_power_w=6000))
|
||||
assert make_settings().effective_nominal_power_w == pytest.approx(6000)
|
||||
assert make_settings(nominal_power_w=8000).effective_nominal_power_w == pytest.approx(8000)
|
||||
|
||||
def test_missing_profile(self, config_eos):
|
||||
settings = InverterCommonSettings(
|
||||
device_id="inverter1",
|
||||
inverter_profile="does-not-exist",
|
||||
profile_adjustment=InverterProfileAdjustment(nominal_power_w=10000),
|
||||
)
|
||||
with pytest.raises(InverterResolutionError, match="does-not-exist.*not usable"):
|
||||
settings.resolve_operating_parameters()
|
||||
assert settings.effective_max_power_w is None
|
||||
errors, _ = settings.check_profile()
|
||||
assert "does-not-exist" in errors[0]
|
||||
|
||||
def test_warns_about_limits_without_effect(self, generic):
|
||||
settings = make_settings(nominal_power_w=5000, max_power_w=8000, max_ac_charge_power_w=6000)
|
||||
errors, warnings = settings.check_profile()
|
||||
assert errors == []
|
||||
assert len(warnings) == 2
|
||||
assert "profile_adjustment.max_power_w" in warnings[0]
|
||||
assert "profile_adjustment.max_ac_charge_power_w" in warnings[1]
|
||||
|
||||
|
||||
class TestMeasurement:
|
||||
def test_temperature_measurement_key(self):
|
||||
settings = make_settings(nominal_power_w=10000)
|
||||
assert settings.measurement_key_temperature_degc == "inverter1-temperature-degc"
|
||||
assert "inverter1-temperature-degc" in settings.measurement_keys
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_measured_temperature(self, measured):
|
||||
measured["inverter1-temperature-degc"] = 52.5
|
||||
point = await make_settings().measure_operating_point()
|
||||
assert point == InverterOperatingPoint(temperature_degC=52.5)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("value", [None, float("nan"), float("inf")])
|
||||
async def test_missing_temperature_defaults_to_45_degc(self, measured, value):
|
||||
measured["inverter1-temperature-degc"] = value
|
||||
point = await make_settings().measure_operating_point()
|
||||
assert point.temperature_degC == 45.0
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_resolution_at_the_measured_temperature(self, generic, measured):
|
||||
settings = make_settings(nominal_power_w=10000)
|
||||
measured["inverter1-temperature-degc"] = 60.0
|
||||
parameters = await settings.resolve_current_operating_parameters()
|
||||
assert parameters.max_power_w == pytest.approx(6000)
|
||||
|
||||
|
||||
class TestConversion:
|
||||
def test_genetic_parameters(self, generic):
|
||||
settings = make_settings(nominal_power_w=10000, max_ac_charge_power_w=4000)
|
||||
parameters = settings.resolve_operating_parameters(InverterOperatingPoint(60.0))
|
||||
genetic = settings.to_genetic_param(parameters)
|
||||
assert genetic.device_id == "inverter1"
|
||||
assert genetic.battery_id == "battery1"
|
||||
assert genetic.max_power_wh == pytest.approx(6000)
|
||||
assert genetic.max_ac_charge_power_w == pytest.approx(4000)
|
||||
assert genetic.dc_to_ac_efficiency == pytest.approx(parameters.dc_to_ac_efficiency)
|
||||
assert genetic.ac_to_dc_efficiency == pytest.approx(parameters.ac_to_dc_efficiency)
|
||||
assert genetic.dc_to_ac_efficiency_curve == [
|
||||
tuple(point) for point in parameters.dc_to_ac_efficiency_curve
|
||||
]
|
||||
assert genetic.ac_charge_limits_total_charge is False
|
||||
|
||||
def test_genetic0_parameters(self, generic):
|
||||
settings = make_settings(nominal_power_w=10000)
|
||||
genetic0 = settings.to_genetic0_param()
|
||||
assert genetic0.max_power_wh == pytest.approx(10000)
|
||||
assert genetic0.dc_to_ac_efficiency == pytest.approx(settings.effective_dc_to_ac_efficiency)
|
||||
assert genetic0.ac_to_dc_efficiency == pytest.approx(settings.effective_ac_to_dc_efficiency)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def logged_errors():
|
||||
"""Collect the messages logged at ERROR level."""
|
||||
from loguru import logger
|
||||
|
||||
messages: list[str] = []
|
||||
sink_id = logger.add(lambda message: messages.append(message.record["message"]), level="ERROR")
|
||||
yield messages
|
||||
logger.remove(sink_id)
|
||||
|
||||
|
||||
class TestOptimizationDefaults:
|
||||
"""The parameter preparation of the optimizations never fails (defaults with an error log)."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_derated_to_zero_uses_the_reference_temperature(
|
||||
self, generic, measured, logged_errors
|
||||
):
|
||||
"""generic-hybrid derates to 0 W at 65 degC; the run gets the 45 degC parameters."""
|
||||
settings = make_settings(nominal_power_w=10000)
|
||||
measured["inverter1-temperature-degc"] = 70.0
|
||||
parameters = await settings.resolve_current_operating_parameters_or_defaults()
|
||||
assert parameters.max_power_w == pytest.approx(10000)
|
||||
assert parameters.temperature_degC == INVERTER_DEFAULT_TEMPERATURE_DEGC
|
||||
assert len(logged_errors) == 1
|
||||
assert "allows no power at 70.0 degC" in logged_errors[0]
|
||||
# The conversion gets valid parameters.
|
||||
assert settings.to_genetic_param(parameters).max_power_wh == pytest.approx(10000)
|
||||
|
||||
def test_missing_nominal_power_gives_the_fallback(self, generic, logged_errors):
|
||||
parameters = make_settings().resolve_operating_parameters_or_defaults()
|
||||
assert parameters.nominal_power_w == pytest.approx(10000)
|
||||
assert len(logged_errors) == 1
|
||||
assert "nominal power 10000 W" in logged_errors[0]
|
||||
|
||||
def test_unusable_profile_uses_the_generic_profile(self, generic, logged_errors):
|
||||
settings = InverterCommonSettings(
|
||||
device_id="inverter1",
|
||||
battery_id="battery1",
|
||||
inverter_profile="does-not-exist",
|
||||
profile_adjustment=InverterProfileAdjustment(nominal_power_w=8000),
|
||||
)
|
||||
parameters = settings.resolve_operating_parameters_or_defaults()
|
||||
assert parameters.nominal_power_w == pytest.approx(8000)
|
||||
assert parameters.dc_to_ac_efficiency < 1.0 # from the generic profile curves
|
||||
assert len(logged_errors) == 1
|
||||
assert f"inverter profile '{INVERTER_DEFAULT_PROFILE}'" in logged_errors[0]
|
||||
|
||||
@pytest.mark.parametrize("error", [FileNotFoundError, PermissionError, IsADirectoryError])
|
||||
def test_without_any_usable_profile(self, monkeypatch, logged_errors, error):
|
||||
def missing(document_type, name, **options):
|
||||
raise error(f"Inverter profile '{name}' is not readable")
|
||||
|
||||
monkeypatch.setattr(get_profile_store(), "get", missing)
|
||||
settings = make_settings(nominal_power_w=8000, max_power_w=6000)
|
||||
parameters = settings.resolve_operating_parameters_or_defaults()
|
||||
assert parameters.max_power_w == pytest.approx(6000)
|
||||
assert parameters.dc_to_ac_efficiency == pytest.approx(1.0)
|
||||
assert len(logged_errors) == 1
|
||||
assert "constant efficiency 1" in logged_errors[0]
|
||||
|
||||
def test_report_false_logs_nothing(self, generic, logged_errors):
|
||||
make_settings().resolve_operating_parameters_or_defaults(report=False)
|
||||
assert logged_errors == []
|
||||
@@ -228,3 +228,74 @@ class TestGenetic0SocClampedOperationFactors:
|
||||
async def test_optimization_solution_with_configured_battery(self, solution):
|
||||
optimization_solution = await solution.optimization_solution()
|
||||
assert optimization_solution is not None
|
||||
|
||||
|
||||
class TestGenetic0SolutionWithProfileInverter:
|
||||
"""The solution uses the inverter parameters of the run, not the inverter settings.
|
||||
|
||||
Inverter settings no longer hold efficiencies or power fields (they come
|
||||
from the inverter profile), so reading them from the settings fails.
|
||||
"""
|
||||
|
||||
@pytest.fixture
|
||||
def solution(self, config_eos: ConfigEOS) -> Genetic0Solution:
|
||||
config_eos.merge_settings_from_dict(
|
||||
{
|
||||
"devices": {
|
||||
"max_batteries": 1,
|
||||
"batteries": {
|
||||
"battery1": {
|
||||
"device_id": "battery1",
|
||||
"profile_adjustment": {"nominal_capacity_wh": 8000},
|
||||
}
|
||||
},
|
||||
"max_inverters": 1,
|
||||
"inverters": {
|
||||
"inverter1": {
|
||||
"device_id": "inverter1",
|
||||
"battery_id": "battery1",
|
||||
"profile_adjustment": {
|
||||
"nominal_power_w": 10000,
|
||||
"max_ac_charge_power_w": 2000,
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
)
|
||||
data = json.loads((DIR_TESTDATA / "optimize_result_1.json").read_text())
|
||||
return Genetic0Solution.model_validate(data)
|
||||
|
||||
def test_uses_solution_inverter_parameters(self, solution):
|
||||
bat = solution.parameters.pv_battery
|
||||
inverter = solution.parameters.inverter
|
||||
assert bat is not None and inverter is not None
|
||||
# The stored inverter has no AC charge limit and efficiency 1.0, unlike
|
||||
# the configured one: the battery charge power limits the AC charge.
|
||||
headroom_wh = 0.01 * bat.capacity_wh
|
||||
expected = headroom_wh / (
|
||||
bat.max_charge_power_w * inverter.ac_to_dc_efficiency * bat.charging_efficiency
|
||||
)
|
||||
ac, _, _ = solution._soc_clamped_operation_factors(
|
||||
1.0, 1.0, True, float(bat.max_soc_percentage) - 1.0
|
||||
)
|
||||
assert ac == pytest.approx(expected)
|
||||
|
||||
def test_without_stored_parameters_the_configured_inverter_is_resolved(self, solution):
|
||||
inverter = solution._inverter_parameters(None)
|
||||
assert inverter is not None
|
||||
assert inverter.max_power_wh == pytest.approx(10000)
|
||||
assert inverter.max_ac_charge_power_w == pytest.approx(2000)
|
||||
assert 0.0 < inverter.ac_to_dc_efficiency < 1.0
|
||||
|
||||
def test_unresolvable_inverter_counts_as_no_inverter(self, solution, config_eos):
|
||||
config_eos.merge_settings_from_dict(
|
||||
{"devices": {"inverters": {"inverter1": {"profile_adjustment": {"nominal_power_w": None}}}}}
|
||||
)
|
||||
assert solution._inverter_parameters(None) is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_optimization_solution_with_configured_inverter(self, solution):
|
||||
"""Regression: AttributeError 'ac_to_dc_efficiency' on InverterCommonSettings."""
|
||||
optimization_solution = await solution.optimization_solution()
|
||||
assert optimization_solution is not None
|
||||
|
||||
@@ -161,7 +161,7 @@ class TestGenetic0MeasuredSOC:
|
||||
"batteries": {
|
||||
"storage": {"profile_adjustment": {"nominal_capacity_wh": 2000, "max_charge_power_w": 1000}}
|
||||
},
|
||||
"inverters": {"inverter": {"battery_id": "storage", "max_power_w": 1000}},
|
||||
"inverters": {"inverter": {"battery_id": "storage", "profile_adjustment": {"nominal_power_w": 1000}}},
|
||||
},
|
||||
}
|
||||
)
|
||||
@@ -208,7 +208,7 @@ class TestGenetic0MeasuredSOC:
|
||||
"batteries": {
|
||||
"storage": {"profile_adjustment": {"nominal_capacity_wh": 2000, "max_charge_power_w": 1000}}
|
||||
},
|
||||
"inverters": {"inverter": {"battery_id": "storage", "max_power_w": 1000}},
|
||||
"inverters": {"inverter": {"battery_id": "storage", "profile_adjustment": {"nominal_power_w": 1000}}},
|
||||
},
|
||||
}
|
||||
)
|
||||
@@ -254,7 +254,7 @@ class TestGenetic0MeasuredSOC:
|
||||
"batteries": {
|
||||
"storage": {"profile_adjustment": {"nominal_capacity_wh": 2000, "max_charge_power_w": 1000}}
|
||||
},
|
||||
"inverters": {"inverter": {"battery_id": "storage", "max_power_w": 1000}},
|
||||
"inverters": {"inverter": {"battery_id": "storage", "profile_adjustment": {"nominal_power_w": 1000}}},
|
||||
},
|
||||
}
|
||||
)
|
||||
@@ -386,3 +386,83 @@ class TestGenetic0DemoData:
|
||||
assert any(
|
||||
"Battery 'storage'" in m and "nominal capacity 8000 Wh" in m for m in messages
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"settings_class, method, field, device_id",
|
||||
[
|
||||
("BatteriesCommonSettings", "to_genetic0_pv_bat_param", "pv_battery", "storage"),
|
||||
("BatteriesCommonSettings", "to_genetic0_ev_bat_param", "ev", "car"),
|
||||
("InverterCommonSettings", "to_genetic0_param", "inverter", "hybrid"),
|
||||
],
|
||||
)
|
||||
async def test_device_that_cannot_be_prepared_is_left_out(
|
||||
self, config_eos, monkeypatch, settings_class, method, field, device_id
|
||||
):
|
||||
"""No demo device replaces a configured device that cannot be prepared."""
|
||||
from loguru import logger
|
||||
|
||||
from akkudoktoreos.devices.settings import batterysettings, invertersettings
|
||||
|
||||
config_eos.merge_settings_from_dict(
|
||||
{
|
||||
"prediction": {"hours": 48},
|
||||
"optimization": {"genetic0": {"horizon_hours": 24}},
|
||||
"elecfee": {"provider": None},
|
||||
"devices": {
|
||||
"max_batteries": 1,
|
||||
"max_electric_vehicles": 1,
|
||||
"max_inverters": 1,
|
||||
"max_home_appliances": 0,
|
||||
"batteries": {
|
||||
"storage": {"profile_adjustment": {"nominal_capacity_wh": 5000}}
|
||||
},
|
||||
"electric_vehicles": {
|
||||
"car": {"profile_adjustment": {"nominal_capacity_wh": 40000}}
|
||||
},
|
||||
"inverters": {
|
||||
"hybrid": {
|
||||
"battery_id": "storage",
|
||||
"profile_adjustment": {"nominal_power_w": 6000},
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
)
|
||||
configured = config_eos.devices.model_dump(exclude_computed_fields=True)
|
||||
module = batterysettings if settings_class == "BatteriesCommonSettings" else invertersettings
|
||||
|
||||
def broken(self, *args, **kwargs):
|
||||
raise RuntimeError("conversion failed")
|
||||
|
||||
monkeypatch.setattr(getattr(module, settings_class), method, broken)
|
||||
get_ems().set_start_datetime(to_datetime("2026-08-01T14:00:00+00:00"))
|
||||
tariff = pd.Series(
|
||||
0.00008, index=pd.date_range("2026-08-01T00:00:00Z", periods=72 * 4, freq="15min")
|
||||
)
|
||||
|
||||
async def read_array(**kwargs):
|
||||
return np.full(48, 0.0003)
|
||||
|
||||
prediction = Mock(
|
||||
update_data=AsyncMock(),
|
||||
key_to_array=AsyncMock(side_effect=read_array),
|
||||
key_to_raw_series=AsyncMock(return_value=tariff),
|
||||
)
|
||||
messages: list[str] = []
|
||||
sink_id = logger.add(
|
||||
lambda message: messages.append(message.record["message"]), level="ERROR"
|
||||
)
|
||||
try:
|
||||
with patch.object(Genetic0OptimizationParameters, "prediction", prediction):
|
||||
parameters = await Genetic0OptimizationParameters.prepare()
|
||||
finally:
|
||||
logger.remove(sink_id)
|
||||
assert parameters is not None
|
||||
assert getattr(parameters, field) is None
|
||||
assert any(f"'{device_id}'" in m and "left out" in m for m in messages)
|
||||
assert not any("demo" in m for m in messages)
|
||||
# The other devices are prepared, the configuration is unchanged.
|
||||
for other in {"pv_battery", "ev", "inverter"} - {field}:
|
||||
assert getattr(parameters, other) is not None
|
||||
assert config_eos.devices.model_dump(exclude_computed_fields=True) == configured
|
||||
|
||||
@@ -7,6 +7,7 @@ leaves of the cap. Without the flag the default model applies: PV charges first
|
||||
and the grid adds ``ac_charge`` of the remaining charge power on top.
|
||||
"""
|
||||
|
||||
import dataclasses
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import numpy as np
|
||||
@@ -14,7 +15,12 @@ import pytest
|
||||
|
||||
from akkudoktoreos.devices.genetic.battery import Battery, SolarPanelBatteryParameters
|
||||
from akkudoktoreos.devices.genetic.inverter import Inverter, InverterParameters
|
||||
from akkudoktoreos.devices.settings.invertersettings import InverterCommonSettings
|
||||
from akkudoktoreos.devices.profile.inverterprofile import InverterProfileSettings
|
||||
from akkudoktoreos.devices.profile.profilestore import get_profile_store
|
||||
from akkudoktoreos.devices.settings.invertersettings import (
|
||||
InverterCommonSettings,
|
||||
InverterProfileAdjustment,
|
||||
)
|
||||
|
||||
MAX_CHARGE_W = 5000
|
||||
|
||||
@@ -226,19 +232,23 @@ class TestGeneticSimulation:
|
||||
|
||||
|
||||
class TestConfigOption:
|
||||
"""The flag is a device config option that reaches the GENETIC optimizer."""
|
||||
"""The flag is a property of the inverter profile that reaches the GENETIC optimizer."""
|
||||
|
||||
@pytest.mark.parametrize("enabled", [False, True])
|
||||
def test_config_passes_the_flag_to_the_optimizer(self, enabled):
|
||||
def test_profile_passes_the_flag_to_the_optimizer(self, config_eos, monkeypatch, enabled):
|
||||
generic = get_profile_store().get(InverterProfileSettings, "generic-hybrid")
|
||||
profile = dataclasses.replace(generic, ac_charge_limits_total_charge=enabled)
|
||||
monkeypatch.setattr(InverterCommonSettings, "get_inverter_profile", lambda self: profile)
|
||||
settings = InverterCommonSettings(
|
||||
device_id="inverter",
|
||||
max_power_w=10000,
|
||||
battery_id="battery1",
|
||||
ac_charge_limits_total_charge=enabled,
|
||||
profile_adjustment=InverterProfileAdjustment(nominal_power_w=10000),
|
||||
)
|
||||
assert settings.to_genetic_param().ac_charge_limits_total_charge is enabled
|
||||
|
||||
def test_default_keeps_the_existing_model(self):
|
||||
settings = InverterCommonSettings(device_id="inverter", max_power_w=10000)
|
||||
assert settings.ac_charge_limits_total_charge is False
|
||||
def test_default_profile_keeps_the_existing_model(self, config_eos):
|
||||
settings = InverterCommonSettings(
|
||||
device_id="inverter",
|
||||
profile_adjustment=InverterProfileAdjustment(nominal_power_w=10000),
|
||||
)
|
||||
assert settings.to_genetic_param().ac_charge_limits_total_charge is False
|
||||
|
||||
@@ -266,7 +266,7 @@ def full_charge_request(config_eos, monkeypatch):
|
||||
}
|
||||
},
|
||||
"electric_vehicles": {},
|
||||
"inverters": {"inverter": {"battery_id": "storage", "max_power_w": 5000}},
|
||||
"inverters": {"inverter": {"battery_id": "storage", "profile_adjustment": {"nominal_power_w": 5000}}},
|
||||
"home_appliances": {},
|
||||
},
|
||||
}
|
||||
@@ -309,6 +309,26 @@ async def test_cold_battery_does_not_cancel_the_request(full_charge_request, mon
|
||||
assert parameters.pv_battery.max_discharge_power_w is not None
|
||||
assert parameters.pv_battery.max_discharge_power_w > 0.0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_hot_inverter_does_not_cancel_the_request(full_charge_request, monkeypatch):
|
||||
"""An inverter derated to zero power at its temperature still gets valid parameters."""
|
||||
from akkudoktoreos.devices.settings.inverterresolution import InverterOperatingPoint
|
||||
from akkudoktoreos.devices.settings.invertersettings import InverterCommonSettings
|
||||
|
||||
config, _, _, data = full_charge_request
|
||||
config.devices.batteries["storage"].profile_adjustment.full_charge_interval_days = None
|
||||
|
||||
async def hot(self, target_datetime=None):
|
||||
return InverterOperatingPoint(temperature_degC=70.0)
|
||||
|
||||
monkeypatch.setattr(InverterCommonSettings, "measure_operating_point", hot)
|
||||
|
||||
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
|
||||
|
||||
assert parameters.inverter is not None
|
||||
assert parameters.inverter.max_power_wh > 0.0
|
||||
|
||||
def _history(start: DateTime, full_days_ago: Optional[float]) -> tuple[list[DateTime], list[float]]:
|
||||
"""Hourly SoC history over 30 days, full once ``full_days_ago`` (if given)."""
|
||||
dates = [start.subtract(hours=hour) for hour in range(30 * 24, 0, -1)]
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Configuration-owned requests and the real automatic GENETIC path."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, Optional
|
||||
from unittest.mock import AsyncMock, Mock, patch
|
||||
|
||||
import httpx
|
||||
@@ -67,7 +68,12 @@ def configured_request(config_eos, monkeypatch):
|
||||
}
|
||||
},
|
||||
"electric_vehicles": {},
|
||||
"inverters": {"inverter": {"battery_id": "storage", "max_power_w": 1000}},
|
||||
"inverters": {
|
||||
"inverter": {
|
||||
"battery_id": "storage",
|
||||
"profile_adjustment": {"nominal_power_w": 1000},
|
||||
}
|
||||
},
|
||||
"home_appliances": {},
|
||||
},
|
||||
}
|
||||
@@ -758,3 +764,74 @@ async def test_battery_configuration_error_uses_defaults_and_logs_error(configur
|
||||
and "Using defaults for the optimization: battery profile 'generic-lfp'" in m
|
||||
for m in messages
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"temperature_degc, expected_max_power_w",
|
||||
[(None, 1000.0), (45.0, 1000.0), (60.0, 600.0)],
|
||||
)
|
||||
async def test_inverter_is_derated_at_measured_temperature(
|
||||
configured_request, monkeypatch, temperature_degc, expected_max_power_w
|
||||
):
|
||||
"""The generic profile derates above 45 degC; without a measurement 45 degC applies."""
|
||||
from akkudoktoreos.devices.settings import invertermeasurement
|
||||
|
||||
_, _, _, data = configured_request
|
||||
|
||||
async def measured(key: str, target_datetime: Any) -> Optional[float]:
|
||||
return temperature_degc if key == "inverter-temperature-degc" else None
|
||||
|
||||
monkeypatch.setattr(invertermeasurement, "get_measured_value", measured)
|
||||
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
|
||||
assert parameters.inverter is not None
|
||||
assert parameters.inverter.max_power_wh == pytest.approx(expected_max_power_w)
|
||||
assert parameters.inverter.max_ac_charge_power_w == pytest.approx(expected_max_power_w)
|
||||
assert parameters.inverter.ac_to_dc_efficiency_curve is not None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unusable_inverter_profile_falls_back_to_generic(configured_request):
|
||||
"""A missing inverter profile does not cancel the parameter preparation."""
|
||||
from loguru import logger
|
||||
|
||||
config, _, _, data = configured_request
|
||||
config.merge_settings_from_dict(
|
||||
{"devices": {"inverters": {"inverter": {"inverter_profile": "does-not-exist"}}}}
|
||||
)
|
||||
messages: list[str] = []
|
||||
sink_id = logger.add(lambda message: messages.append(message.record["message"]), level="ERROR")
|
||||
try:
|
||||
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
|
||||
finally:
|
||||
logger.remove(sink_id)
|
||||
assert parameters.inverter is not None
|
||||
assert parameters.inverter.max_power_wh == pytest.approx(1000.0)
|
||||
assert any(
|
||||
"Inverter 'inverter'" in m and "inverter profile 'generic-hybrid'" in m
|
||||
for m in messages
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_inverter_without_nominal_power_uses_the_fallback_power(configured_request):
|
||||
"""The run is not cancelled: the fallback nominal power applies, reported as error."""
|
||||
from loguru import logger
|
||||
|
||||
from akkudoktoreos.devices.settings.inverterresolution import (
|
||||
INVERTER_FALLBACK_NOMINAL_POWER_W,
|
||||
)
|
||||
|
||||
config, _, _, data = configured_request
|
||||
config.merge_settings_from_dict(
|
||||
{"devices": {"inverters": {"inverter": {"profile_adjustment": {"nominal_power_w": None}}}}}
|
||||
)
|
||||
messages: list[str] = []
|
||||
sink_id = logger.add(lambda message: messages.append(message.record["message"]), level="ERROR")
|
||||
try:
|
||||
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
|
||||
finally:
|
||||
logger.remove(sink_id)
|
||||
assert parameters.inverter is not None
|
||||
assert parameters.inverter.max_power_wh == pytest.approx(INVERTER_FALLBACK_NOMINAL_POWER_W)
|
||||
assert any("nominal_power_w" in m for m in messages)
|
||||
|
||||
@@ -318,7 +318,7 @@ async def test_real_measurement_completed_cycles_reach_request_and_optimizer(
|
||||
"max_electric_vehicles": 0,
|
||||
"electric_vehicles": {},
|
||||
"max_inverters": 1,
|
||||
"inverters": {"inv": {"max_power_w": 10000}},
|
||||
"inverters": {"inv": {"profile_adjustment": {"nominal_power_w": 10000}}},
|
||||
"max_home_appliances": 1,
|
||||
"home_appliances": {
|
||||
"washer": profile(
|
||||
@@ -432,7 +432,7 @@ async def test_meter_only_record_does_not_hide_completed_cycles(
|
||||
"max_electric_vehicles": 0,
|
||||
"electric_vehicles": {},
|
||||
"max_inverters": 1,
|
||||
"inverters": {"inv": {"max_power_w": 10000}},
|
||||
"inverters": {"inv": {"profile_adjustment": {"nominal_power_w": 10000}}},
|
||||
"max_home_appliances": 1,
|
||||
"home_appliances": {
|
||||
"washer": profile(
|
||||
|
||||
@@ -492,11 +492,12 @@ def test_process_energy_zero_generation_full_battery_high_consumption(inverter,
|
||||
|
||||
class TestInverterSettings:
|
||||
@pytest.mark.parametrize("converter", ["to_genetic_param", "to_genetic0_param"])
|
||||
def test_inverter_conversion_requires_output_limit(self, converter):
|
||||
def test_inverter_conversion_requires_nominal_power(self, config_eos, converter):
|
||||
# The generic inverter profile provides no nominal power.
|
||||
settings = InverterCommonSettings(device_id="inverter")
|
||||
with pytest.raises(ValueError, match="max_power_w"):
|
||||
with pytest.raises(ValueError, match="nominal_power_w"):
|
||||
getattr(settings, converter)()
|
||||
settings.max_power_w = 4200
|
||||
settings.profile_adjustment.nominal_power_w = 4200
|
||||
assert getattr(settings, converter)().max_power_wh == 4200
|
||||
|
||||
|
||||
|
||||
@@ -172,3 +172,28 @@ async def test_optimize(
|
||||
|
||||
reader = PdfReader(BytesIO(pdf))
|
||||
assert len(reader.pages) >= 6
|
||||
|
||||
|
||||
def test_solution_inverter_parameters_come_from_the_run_or_the_profile(config_eos: ConfigEOS):
|
||||
"""Inverter settings hold no efficiencies; the solution never reads them directly."""
|
||||
config_eos.merge_settings_from_dict(
|
||||
{
|
||||
"devices": {
|
||||
"max_inverters": 1,
|
||||
"inverters": {
|
||||
"inverter1": {
|
||||
"device_id": "inverter1",
|
||||
"profile_adjustment": {"nominal_power_w": 8000},
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
)
|
||||
with (DIR_TESTDATA / "optimize_result_1.json").open("r") as f_in:
|
||||
solution = GeneticSolution.model_validate(json.load(f_in))
|
||||
stored = solution._inverter_parameters_list(solution.parameters)
|
||||
assert stored == ([solution.parameters.inverter] if solution.parameters.inverter else [])
|
||||
resolved = solution._inverter_parameters_list(None)
|
||||
assert len(resolved) == 1
|
||||
assert resolved[0].max_power_wh == pytest.approx(8000)
|
||||
assert 0.0 < resolved[0].ac_to_dc_efficiency < 1.0
|
||||
|
||||
@@ -37,7 +37,7 @@ def prepare_tariffs(config_eos):
|
||||
"max_batteries": 0,
|
||||
"max_electric_vehicles": 0,
|
||||
"max_inverters": 1,
|
||||
"inverters": {"inverter1": {"max_power_w": 10000}},
|
||||
"inverters": {"inverter1": {"profile_adjustment": {"nominal_power_w": 10000}}},
|
||||
"max_home_appliances": 0,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
"""Tests for the load-dependent DC-to-AC efficiency curve of the GENETIC inverter.
|
||||
"""Tests for the load-dependent efficiency curves of the GENETIC inverter.
|
||||
|
||||
``dc_to_ac_efficiency_curve`` replaces the constant ``dc_to_ac_efficiency`` by a
|
||||
curve over the load fraction (AC power / rated power). Real inverters are much
|
||||
less efficient at low load, which matters for night-time discharge into a small
|
||||
base load. Without a curve the behaviour must stay exactly the legacy one.
|
||||
base load. ``ac_to_dc_efficiency_curve`` does the same for charging the battery
|
||||
from the grid. Without a curve the behaviour must stay exactly the legacy one.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
@@ -15,12 +16,16 @@ from pydantic import ValidationError
|
||||
|
||||
from akkudoktoreos.devices.devicesabc import (
|
||||
interpolate_efficiency_curve,
|
||||
solve_ac_for_charge_dc_energy,
|
||||
solve_ac_for_dc_energy,
|
||||
validate_efficiency_curve,
|
||||
)
|
||||
from akkudoktoreos.devices.genetic.battery import Battery, SolarPanelBatteryParameters
|
||||
from akkudoktoreos.devices.genetic.inverter import Inverter, InverterParameters
|
||||
from akkudoktoreos.devices.settings.invertersettings import InverterCommonSettings
|
||||
from akkudoktoreos.devices.settings.invertersettings import (
|
||||
InverterCommonSettings,
|
||||
InverterProfileAdjustment,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.genetic import GeneticSimulation
|
||||
from akkudoktoreos.optimization.genetic.geneticparams import (
|
||||
GeneticEnergyManagementParameters,
|
||||
@@ -113,10 +118,6 @@ class TestCurveValidation:
|
||||
InverterParameters(
|
||||
device_id="inverter1", max_power_wh=1000, dc_to_ac_efficiency_curve=curve
|
||||
)
|
||||
with pytest.raises(ValidationError):
|
||||
InverterCommonSettings(
|
||||
device_id="inverter1", max_power_w=1000, dc_to_ac_efficiency_curve=curve
|
||||
)
|
||||
|
||||
@pytest.mark.parametrize("fraction", [-0.1, 1.1])
|
||||
def test_reference_load_fraction_range(self, fraction):
|
||||
@@ -416,62 +417,36 @@ def test_low_load_curve_increases_losses(config_eos):
|
||||
|
||||
|
||||
class TestSettings:
|
||||
def test_settings_pass_curve_to_genetic_parameters(self):
|
||||
settings = InverterCommonSettings.model_validate(
|
||||
{
|
||||
"device_id": "inverter1",
|
||||
"max_power_w": 5000,
|
||||
"dc_to_ac_efficiency_curve": [[0.02, 0.8], [0.07, 0.93], [1.0, 0.95]],
|
||||
"dc_to_ac_efficiency_reference_load_fraction": 0.1,
|
||||
}
|
||||
)
|
||||
params = settings.to_genetic_param()
|
||||
assert params.dc_to_ac_efficiency_curve == [(0.02, 0.8), (0.07, 0.93), (1.0, 0.95)]
|
||||
assert params.dc_to_ac_efficiency_reference_load_fraction == 0.1
|
||||
"""The DC→AC curve of the GENETIC parameters comes from the inverter profile."""
|
||||
|
||||
def test_defaults_keep_constant_efficiency(self):
|
||||
params = InverterCommonSettings(device_id="inverter1", max_power_w=5000).to_genetic_param()
|
||||
assert params.dc_to_ac_efficiency_curve is None
|
||||
assert params.dc_to_ac_efficiency_reference_load_fraction == pytest.approx(0.06)
|
||||
|
||||
def test_genetic0_is_unaffected(self):
|
||||
def test_settings_pass_profile_curve_to_genetic_parameters(self, config_eos):
|
||||
settings = InverterCommonSettings(
|
||||
device_id="inverter1",
|
||||
max_power_w=5000,
|
||||
dc_to_ac_efficiency_curve=[(0.0, 0.8), (1.0, 0.95)],
|
||||
profile_adjustment=InverterProfileAdjustment(nominal_power_w=5000),
|
||||
dc_to_ac_efficiency_reference_load_fraction=0.1,
|
||||
)
|
||||
profile = settings.get_inverter_profile()
|
||||
params = settings.to_genetic_param()
|
||||
assert params.dc_to_ac_efficiency_curve is not None
|
||||
# Not derated at 45 degC: the curve is the profile curve over [0, 1].
|
||||
expected = list(zip(profile.dc_to_ac_efficiency.x, profile.dc_to_ac_efficiency.y))
|
||||
assert [x for x, _ in params.dc_to_ac_efficiency_curve] == pytest.approx(
|
||||
[x for x, _ in expected]
|
||||
)
|
||||
assert [y for _, y in params.dc_to_ac_efficiency_curve] == pytest.approx(
|
||||
[y for _, y in expected]
|
||||
)
|
||||
assert params.dc_to_ac_efficiency_reference_load_fraction == 0.1
|
||||
assert params.dc_to_ac_efficiency == pytest.approx(profile.dc_to_ac_efficiency_at(0.1))
|
||||
|
||||
def test_genetic0_has_no_curve(self, config_eos):
|
||||
settings = InverterCommonSettings(
|
||||
device_id="inverter1",
|
||||
profile_adjustment=InverterProfileAdjustment(nominal_power_w=5000),
|
||||
)
|
||||
params = settings.to_genetic0_param()
|
||||
assert not hasattr(params, "dc_to_ac_efficiency_curve")
|
||||
|
||||
def test_config_accepts_curve(self, config_eos):
|
||||
config_eos.merge_settings_from_dict(
|
||||
{
|
||||
"devices": {
|
||||
"inverters": {
|
||||
"inverter1": {
|
||||
"max_power_w": 5000,
|
||||
"dc_to_ac_efficiency_curve": [[0.02, 0.8], [0.07, 0.93], [1.0, 0.95]],
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
inverters = config_eos.devices.inverters
|
||||
assert inverters is not None
|
||||
assert inverters["inverter1"].dc_to_ac_efficiency_curve == [
|
||||
(0.02, 0.8),
|
||||
(0.07, 0.93),
|
||||
(1.0, 0.95),
|
||||
]
|
||||
config_eos.set_nested_value(
|
||||
"devices/inverters/inverter1/dc_to_ac_efficiency_curve", [[0.0, 0.85], [1.0, 0.95]]
|
||||
)
|
||||
assert inverters["inverter1"].dc_to_ac_efficiency_curve == [(0.0, 0.85), (1.0, 0.95)]
|
||||
with pytest.raises(ValueError, match="at least two points"):
|
||||
config_eos.set_nested_value(
|
||||
"devices/inverters/inverter1/dc_to_ac_efficiency_curve", [[0.5, 0.9]]
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Discharge limited by the battery (low state of charge, power limit)
|
||||
@@ -664,3 +639,75 @@ class TestBatteryLimitedDischarge:
|
||||
)
|
||||
ac, losses = inverter._discharge_battery_to_ac(500.0 * slot_duration_h, 0)
|
||||
assert ac == pytest.approx(200.0 * slot_duration_h * efficiency)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# AC→DC curve for charging the battery from the grid
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
CHARGE_CURVE = [(0.05, 0.86), (0.3, 0.96), (1.0, 0.95)]
|
||||
|
||||
|
||||
class TestSolveAcForChargeDcEnergy:
|
||||
@pytest.mark.parametrize("dc_wh", [1.0, 30.0, 100.0, 250.0, 500.0, 900.0, 2000.0])
|
||||
def test_solution_is_consistent(self, dc_wh):
|
||||
ac_wh = solve_ac_for_charge_dc_energy(CHARGE_CURVE, dc_wh, 1000.0)
|
||||
efficiency = interpolate_efficiency_curve(CHARGE_CURVE, ac_wh / 1000.0)
|
||||
assert ac_wh * efficiency == pytest.approx(dc_wh, rel=1e-9)
|
||||
|
||||
def test_clamped_ends(self):
|
||||
# Below the first point the first efficiency applies, above the last the last.
|
||||
assert solve_ac_for_charge_dc_energy(CHARGE_CURVE, 8.6, 1000.0) == pytest.approx(10.0)
|
||||
assert solve_ac_for_charge_dc_energy(CHARGE_CURVE, 1900.0, 1000.0) == pytest.approx(2000.0)
|
||||
|
||||
def test_flat_curve_equals_constant_efficiency(self):
|
||||
flat = [(0.0, 0.9), (1.0, 0.9)]
|
||||
assert solve_ac_for_charge_dc_energy(flat, 450.0, 1000.0) == pytest.approx(500.0)
|
||||
|
||||
def test_no_energy(self):
|
||||
assert solve_ac_for_charge_dc_energy(CHARGE_CURVE, 0.0, 1000.0) == 0.0
|
||||
|
||||
|
||||
class TestChargeFromGridWithCurve:
|
||||
def test_curve_is_validated(self):
|
||||
with pytest.raises(ValidationError):
|
||||
InverterParameters(
|
||||
device_id="inverter1", max_power_wh=1000, ac_to_dc_efficiency_curve=[(0.5, 0.9)]
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _empty_battery() -> Battery:
|
||||
battery = _real_battery(soc_percentage=0)
|
||||
battery.charge_array = np.ones(1)
|
||||
return battery
|
||||
|
||||
def test_low_load_charge_draws_more_ac(self):
|
||||
flat = _real_inverter(self._empty_battery(), ac_to_dc_efficiency=0.96)
|
||||
curved = _real_inverter(
|
||||
self._empty_battery(),
|
||||
ac_to_dc_efficiency=0.96,
|
||||
ac_to_dc_efficiency_curve=CHARGE_CURVE,
|
||||
)
|
||||
# 5 % of the 1 kW battery charge power: a low AC load, efficiency ~0.87.
|
||||
flat_ac, flat_losses = flat.charge_battery_from_grid(0, 0.05)
|
||||
curved_ac, curved_losses = curved.charge_battery_from_grid(0, 0.05)
|
||||
assert flat_ac == pytest.approx(50.0 / 0.96)
|
||||
assert curved_ac > flat_ac
|
||||
assert curved_ac * interpolate_efficiency_curve(
|
||||
CHARGE_CURVE, curved_ac / 1000.0
|
||||
) == pytest.approx(50.0)
|
||||
assert curved_losses == pytest.approx(curved_ac - 50.0)
|
||||
|
||||
def test_settings_pass_the_profile_curve(self, config_eos):
|
||||
settings = InverterCommonSettings(
|
||||
device_id="inverter1",
|
||||
profile_adjustment=InverterProfileAdjustment(nominal_power_w=5000),
|
||||
)
|
||||
profile = settings.get_inverter_profile()
|
||||
params = settings.to_genetic_param()
|
||||
assert params.ac_to_dc_efficiency_curve is not None
|
||||
assert [y for _, y in params.ac_to_dc_efficiency_curve] == pytest.approx(
|
||||
list(profile.ac_to_dc_efficiency.y)
|
||||
)
|
||||
# The constant is the efficiency at the AC charge limit, here the nominal power.
|
||||
assert params.ac_to_dc_efficiency == pytest.approx(profile.ac_to_dc_efficiency_at(1.0))
|
||||
|
||||
@@ -81,7 +81,7 @@ def test_device_maps_feed_algorithm_specific_converters(algorithm):
|
||||
"electric_vehicles": {
|
||||
"car": {"profile_adjustment": {"nominal_capacity_wh": 60000, "max_charge_power_w": 7000}}
|
||||
},
|
||||
"inverters": {"inverter": {"battery_id": "storage", "max_power_w": 5000}},
|
||||
"inverters": {"inverter": {"battery_id": "storage", "profile_adjustment": {"nominal_power_w": 5000}}},
|
||||
"home_appliances": {
|
||||
"washer": {
|
||||
"consumption_wh": 1800,
|
||||
|
||||
@@ -9,6 +9,7 @@ from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from akkudoktoreos.devices.profile.batteryprofile import BatteryProfileSettings
|
||||
from akkudoktoreos.devices.profile.inverterprofile import InverterProfileSettings
|
||||
from akkudoktoreos.devices.profile.profilestore import ProfileStore, get_profile_store
|
||||
from akkudoktoreos.server.rest.error import register_problem_handlers
|
||||
from akkudoktoreos.server.rest.profile import router
|
||||
@@ -60,6 +61,16 @@ class TestRead:
|
||||
assert response.json()["chemistry"] == "LFP"
|
||||
BatteryProfileSettings.model_validate(response.json())
|
||||
|
||||
def test_inverter_profiles(self, client):
|
||||
assert "inverter" in client.get("/v1/profile").json()
|
||||
listed = client.get("/v1/profile/inverter").json()
|
||||
assert {"name": "generic-hybrid", "source": "package", "packaged": True} in listed
|
||||
schema = client.get("/v1/profile/inverter/schema").json()
|
||||
assert "power_derating" in schema["properties"]
|
||||
response = client.get("/v1/profile/inverter/generic-hybrid")
|
||||
assert response.status_code == 200
|
||||
InverterProfileSettings.model_validate(response.json())
|
||||
|
||||
def test_errors_are_problem_details(self, client):
|
||||
response = client.get("/v1/profile/nope")
|
||||
assert response.headers["content-type"] == "application/problem+json"
|
||||
@@ -169,6 +180,48 @@ class TestDelete:
|
||||
def test_delete_of_a_missing_profile_is_404(self, client):
|
||||
assert client.delete("/v1/profile/battery/does-not-exist").status_code == 404
|
||||
|
||||
@pytest.mark.parametrize("devices", ["batteries", "electric_vehicles"])
|
||||
def test_delete_of_a_battery_profile_in_use_is_409(
|
||||
self, client, config_eos, generic_lfp, devices
|
||||
):
|
||||
client.put("/v1/profile/battery/my-battery", json=generic_lfp)
|
||||
config_eos.merge_settings_from_dict(
|
||||
{"devices": {devices: {"unit1": {"device_id": "unit1", "battery_profile": "my-battery"}}}}
|
||||
)
|
||||
response = client.delete("/v1/profile/battery/my-battery")
|
||||
assert response.status_code == 409
|
||||
assert response.json()["title"] == "Profile in use"
|
||||
assert "unit1" in response.json()["detail"]
|
||||
assert client.get("/v1/profile/battery/my-battery").status_code == 200
|
||||
|
||||
def test_delete_of_an_inverter_profile_in_use_is_409(self, client, config_eos):
|
||||
generic_hybrid = client.get("/v1/profile/inverter/generic-hybrid").json()
|
||||
client.put("/v1/profile/inverter/my-inverter", json=generic_hybrid)
|
||||
config_eos.merge_settings_from_dict(
|
||||
{
|
||||
"devices": {
|
||||
"inverters": {
|
||||
"inverter1": {"device_id": "inverter1", "inverter_profile": "my-inverter"}
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
response = client.delete("/v1/profile/inverter/my-inverter")
|
||||
assert response.status_code == 409
|
||||
assert "inverter1" in response.json()["detail"]
|
||||
# A battery profile of the same name is not in use.
|
||||
assert client.delete("/v1/profile/battery/my-inverter").status_code == 404
|
||||
|
||||
def test_delete_of_an_override_in_use_reverts_to_the_packaged_profile(
|
||||
self, client, config_eos, generic_lfp
|
||||
):
|
||||
client.put("/v1/profile/battery/generic-lfp", json=generic_lfp)
|
||||
config_eos.merge_settings_from_dict(
|
||||
{"devices": {"batteries": {"battery1": {"device_id": "battery1"}}}}
|
||||
)
|
||||
assert config_eos.devices.batteries["battery1"].battery_profile == "generic-lfp"
|
||||
assert client.delete("/v1/profile/battery/generic-lfp").status_code == 200
|
||||
|
||||
|
||||
def test_eos_app_serves_the_profile_api(config_eos):
|
||||
from akkudoktoreos.server.eos import app
|
||||
|
||||
+3
-1
@@ -29,7 +29,9 @@
|
||||
"inverters": {
|
||||
"inverter1": {
|
||||
"device_id": "inverter1",
|
||||
"max_power_w": 10000.0,
|
||||
"profile_adjustment": {
|
||||
"nominal_power_w": 10000.0
|
||||
},
|
||||
"battery_id": "battery1"
|
||||
}
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user