Files
EOS/tests/test_geneticacchargetotallimit.py
T
Bobby NoelteandClaude Opus 5.5 b3d5334d3e refactor(genetic): refactor GENETIC to the consolidated optimizer architecture
Pin result, conversion, plan and visualization of golden runs.
Drive GENETIC through the optimizer interface and registry.
Move GENETIC into one directory with role-named modules.
Prepare every run input once, run from the parameters.
Fall back instead of cancelling the optimization run.
Simulate battery, EV and inverter from frozen dataclasses.
Simulate the home appliance from frozen dataclasses.
Convert and visualize from the parameters and result only.
Serve GENETIC from its own router.
Return a frozen result, build responses in the API.
Echo the request as sent, not with an invented time window.

Additional changes
- Pin that the result does not depend on the number of evaluation workers.
- Run the golden module in UTC: until the request date-times are held in UTC they render in the host time zone.
- Add Optimizer.run_clock(), so the EMS gets slot length and time zone without GENETIC settings.
- Rename ConfigOptimizationRequest, RuntimeForecasts and GeneticCommonSettings as ADR 0010 asks.
- Correct the request example in ADR 0010.
- Record the renamed OpenAPI schemas in CHANGELOG.md and the upgrade guide.
- Add replay files that reproduce each golden result from its parameters.
- Drop OptimizationBase from the algorithm.
- Give the replay and worker tests own review files against xdist races.
- Handle a failing preparation in the EMS like a failing run, no separate cancel path.
- Record the fallbacks in CHANGELOG.md and the upgrade guide.
- Without an inverter, buy the whole load from the grid instead of planning it at no cost.
- Do not charge from the grid without any known price.
- Treat an infinite value after the control horizon as a gap.
- Correct the documentation that said missing forecasts cancel the run.
- Copy the efficiency helpers and the self-consumption table evaluation into GENETIC.
- Add CycleTimeWindowSequence, ConsumerScheduleMode and ConsumerDeadlinePolicy as contract names.
- Hold the date-times of battery, EV and home appliance requests in UTC, so they render the same on every host.
- Drop the UTC pin of the GENETIC golden module; the request date-times no longer depend on the host.
- Copy the time window logic GENETIC needs into genetictimewindow.py.
- Add ValueTimeWindow as a contract name.
- Move the settings' to_genetic_*() converters into the preparation.
- Drop the conversion's prediction reads and configuration fallbacks, which runs never reached.
- Make the moved docstrings valid reST.
- Remove the generic optimization solution route; each optimizer serves its own path.
- Import the GENETIC settings from the package.
- Record the removed route in CHANGELOG.md and the upgrade guide.
- Make the terminal and tail value models frozen dataclasses.
- Move the response models into geneticapi; remove geneticsolution and geneticabc.
- Remove the legacy appliance start arrays and API, which read the wall clock.
- Remove the time window helpers only they used.
- Echo a start_solution without start_solution_datetime as sent.
- Carry the previous solution's start in the run parameters.
- Plan the home appliance cycles that fit, or leave the appliance out, instead of failing.
- Move the appliance layout rules into geneticappliancelayout for the preparation.
- Leave out a DAILY home appliance whose open windows leave no room for a run, with an error log, instead of silently.
- Name the reason of the SoC fallback instead of Python's exception text.
- Answer a solution request for an unknown algorithm with a 404 problem response.
- Record the fixes in CHANGELOG.md and the upgrade guide.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Assisted-by: Claude Code (claude-opus-5-5)
2026-11-27 13:55:41 +01:00

266 lines
11 KiB
Python

"""Tests for inverters whose AC charge setpoint caps the total battery charge.
With ``ac_charge_limits_total_charge`` an AC slot charges the battery with at
most ``ac_charge x max_charge_power_w``, PV included (e.g. Deye time-of-use grid
charging). PV surplus above that cap is exported; the grid only fills what PV
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
import pytest
from akkudoktoreos.devices.profile.inverterprofile import InverterProfileSettings
from akkudoktoreos.devices.profile.profilestore import get_profile_store
from akkudoktoreos.devices.settings.invertersettings import (
InverterCommonSettings,
InverterProfileAdjustment,
)
from akkudoktoreos.optimization.genetic import geneticprepare
from akkudoktoreos.optimization.genetic.devices.geneticbattery import (
GeneticBattery,
)
from akkudoktoreos.optimization.genetic.devices.geneticinverter import (
GeneticInverter,
)
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticBatteryRequest,
GeneticInverterRequest,
)
MAX_CHARGE_W = 5000
def _build(limits_total: bool, max_ac_charge_power_w=None) -> tuple[GeneticInverter, GeneticBattery]:
battery = GeneticBattery(
GeneticBatteryRequest(
device_id="battery1",
capacity_wh=20000,
initial_soc_percentage=20,
charging_efficiency=0.9,
discharging_efficiency=0.9,
min_soc_percentage=0,
max_soc_percentage=100,
max_charge_power_w=MAX_CHARGE_W,
).to_parameters(),
prediction_hours=4,
)
battery.reset()
# reset() creates an integer array; charge factors are fractions.
battery.charge_array = np.zeros(4)
predictor = Mock()
predictor.calculate_expected_direct_consumption.side_effect = min
with patch(
"akkudoktoreos.optimization.genetic.devices.geneticinverter.get_genetic_load_interpolator",
return_value=predictor,
):
inverter = GeneticInverter(
GeneticInverterRequest(
device_id="inverter1",
max_power_wh=10000,
battery_id="battery1",
ac_to_dc_efficiency=1.0,
max_ac_charge_power_w=max_ac_charge_power_w,
ac_charge_limits_total_charge=limits_total,
).to_parameters(),
battery=battery,
)
return inverter, battery
def _run_ac_slot(inverter: GeneticInverter, battery: GeneticBattery, pv_wh: float, factor: float):
"""Run one AC slot the way GeneticSimulation.simulate() does."""
battery.charge_array[0] = factor
battery.discharge_array[0] = 0
rate = inverter.ac_charge_factor(factor)
inverter.begin_ac_charge_slot(0, rate)
export, grid_import, _, _ = inverter.process_energy(pv_wh, 0.0, 0)
ac_wh, _ = inverter.charge_battery_from_grid(0, rate)
return export, grid_import + ac_wh, battery._charged_raw_wh_per_slot[0]
class TestPvSurplusAboveCap:
"""PV alone exceeds the AC setpoint - the Deye situation that exported PV."""
def test_total_limit_exports_pv_above_the_cap(self):
inverter, battery = _build(limits_total=True)
export, grid, charged_raw = _run_ac_slot(inverter, battery, pv_wh=6000, factor=0.5)
assert charged_raw == pytest.approx(0.5 * MAX_CHARGE_W)
assert export == pytest.approx(6000 - 0.5 * MAX_CHARGE_W)
assert grid == pytest.approx(0.0)
def test_default_model_stores_pv_up_to_full_charge_power(self):
inverter, battery = _build(limits_total=False)
export, grid, charged_raw = _run_ac_slot(inverter, battery, pv_wh=6000, factor=0.5)
assert charged_raw == pytest.approx(MAX_CHARGE_W)
assert export == pytest.approx(6000 - MAX_CHARGE_W)
assert grid == pytest.approx(0.0)
class TestPvSurplusBelowCap:
"""PV does not reach the setpoint - the grid tops up."""
def test_total_limit_grid_fills_up_to_the_cap(self):
inverter, battery = _build(limits_total=True)
export, grid, charged_raw = _run_ac_slot(inverter, battery, pv_wh=1000, factor=0.5)
assert charged_raw == pytest.approx(0.5 * MAX_CHARGE_W)
assert grid == pytest.approx(0.5 * MAX_CHARGE_W - 1000)
assert export == pytest.approx(0.0)
def test_default_model_grid_adds_factor_of_remaining_power(self):
inverter, battery = _build(limits_total=False)
export, grid, charged_raw = _run_ac_slot(inverter, battery, pv_wh=1000, factor=0.5)
assert grid == pytest.approx(0.5 * (MAX_CHARGE_W - 1000))
assert charged_raw == pytest.approx(1000 + 0.5 * (MAX_CHARGE_W - 1000))
assert export == pytest.approx(0.0)
def test_max_ac_charge_power_caps_the_total_charge():
"""max_ac_charge_power_w lowers the setpoint and with it the total cap."""
inverter, battery = _build(limits_total=True, max_ac_charge_power_w=2000)
export, grid, charged_raw = _run_ac_slot(inverter, battery, pv_wh=6000, factor=1.0)
assert charged_raw == pytest.approx(2000)
assert export == pytest.approx(4000)
assert grid == pytest.approx(0.0)
def test_dc_slot_is_not_capped():
"""Only AC slots are capped: a DC slot takes PV up to max_charge_power_w."""
inverter, battery = _build(limits_total=True)
battery.charge_array[0] = 1
battery.discharge_array[0] = 0
export, _, _, _ = inverter.process_energy(6000, 0.0, 0)
assert battery._charged_raw_wh_per_slot[0] == pytest.approx(MAX_CHARGE_W)
assert export == pytest.approx(1000)
def test_reset_lifts_the_slot_cap():
inverter, battery = _build(limits_total=True)
_run_ac_slot(inverter, battery, pv_wh=6000, factor=0.5)
battery.reset()
battery.charge_array = np.zeros(4)
battery.charge_array[0] = 1
inverter.process_energy(6000, 0.0, 0)
assert battery._charged_raw_wh_per_slot[0] == pytest.approx(MAX_CHARGE_W)
class TestGeneticSimulation:
"""The flag changes the simulated plan, so the optimizer can prefer DC."""
@pytest.fixture
def simulate(self, config_eos):
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticEnergyManagementRequest,
)
from akkudoktoreos.optimization.genetic.geneticsimulation import (
GeneticSimulation,
)
config_eos.merge_settings_from_dict(
{"prediction": {"hours": 48}, "optimization": {"hours": 24}}
)
hours = config_eos.prediction.hours
def _simulate(limits_total: bool, ac_factor: float, dc_factor: float):
battery = GeneticBattery(
GeneticBatteryRequest(
device_id="battery1",
capacity_wh=30000,
initial_soc_percentage=20,
charging_efficiency=0.9,
discharging_efficiency=0.9,
min_soc_percentage=0,
max_soc_percentage=100,
max_charge_power_w=MAX_CHARGE_W,
).to_parameters(),
prediction_hours=hours,
)
battery.reset()
inverter = GeneticInverter(
GeneticInverterRequest(
device_id="inverter1",
max_power_wh=10000,
battery_id="battery1",
ac_charge_limits_total_charge=limits_total,
).to_parameters(),
battery=battery,
)
sim = GeneticSimulation()
sim.prepare(
GeneticEnergyManagementRequest.model_validate(
dict(
pv_prognose_wh=[8000.0] * hours,
strompreis_euro_pro_wh=[0.0003] * hours,
einspeiseverguetung_euro_pro_wh=0.00008,
preis_euro_pro_wh_akku=0.0001,
gesamtlast=[0.0] * hours,
)
).to_parameters(),
optimization_hours=config_eos.optimization.genetic.horizon_hours,
prediction_hours=hours,
inverter=inverter,
ev=None,
home_appliance=None,
)
ac_hours, dc_hours = sim.ac_charge_hours, sim.dc_charge_hours
discharge_hours = sim.bat_discharge_hours
assert ac_hours is not None and dc_hours is not None and discharge_hours is not None
ac_hours[:] = 0
dc_hours[:] = 0
discharge_hours[:] = 0
ac_hours[1] = ac_factor
dc_hours[1] = dc_factor
return sim.simulate(start_hour=0)
return _simulate
def test_ac_slot_under_pv_surplus_exports_more_than_dc(self, simulate):
ac = simulate(limits_total=True, ac_factor=0.5, dc_factor=0)
dc = simulate(limits_total=True, ac_factor=0, dc_factor=1)
assert ac["Netzeinspeisung_Wh_pro_Stunde"][1] == pytest.approx(
dc["Netzeinspeisung_Wh_pro_Stunde"][1] + 0.5 * MAX_CHARGE_W
)
assert ac["akku_soc_pro_stunde"][2] < dc["akku_soc_pro_stunde"][2]
def test_default_model_treats_ac_slot_like_dc_under_pv_surplus(self, simulate):
ac = simulate(limits_total=False, ac_factor=0.5, dc_factor=0)
dc = simulate(limits_total=False, ac_factor=0, dc_factor=1)
assert ac["Netzeinspeisung_Wh_pro_Stunde"][1] == pytest.approx(
dc["Netzeinspeisung_Wh_pro_Stunde"][1]
)
class TestConfigOption:
"""The flag is a property of the inverter profile that reaches the GENETIC optimizer."""
@pytest.mark.parametrize("enabled", [False, True])
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",
battery_id="battery1",
profile_adjustment=InverterProfileAdjustment(nominal_power_w=10000),
)
assert geneticprepare.inverter_request(settings).ac_charge_limits_total_charge is enabled
def test_default_profile_keeps_the_existing_model(self, config_eos):
settings = InverterCommonSettings(
device_id="inverter",
profile_adjustment=InverterProfileAdjustment(nominal_power_w=10000),
)
assert geneticprepare.inverter_request(settings).ac_charge_limits_total_charge is False