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)
This commit is contained in:
Bobby Noelte
2026-11-27 13:55:41 +01:00
co-authored by Claude Opus 5.5
parent b108335ee4
commit b3d5334d3e
156 changed files with 146594 additions and 7766 deletions
+60 -51
View File
@@ -20,19 +20,28 @@ from akkudoktoreos.devices.devicesabc import (
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,
InverterProfileAdjustment,
)
from akkudoktoreos.optimization.genetic import geneticprepare
from akkudoktoreos.optimization.genetic0 import genetic0prepare
from akkudoktoreos.optimization.genetic.genetic import GeneticSimulation
from akkudoktoreos.optimization.genetic.geneticparams import (
GeneticEnergyManagementParameters,
from akkudoktoreos.optimization.genetic.devices.geneticbattery import (
GeneticBattery,
)
from akkudoktoreos.optimization.genetic.tailvalue import build_tail_value_curve
from akkudoktoreos.optimization.genetic.terminalvalue import TerminalValueCurve
from akkudoktoreos.optimization.genetic.devices.geneticinverter import (
GeneticInverter,
)
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticBatteryRequest,
GeneticEnergyManagementRequest,
GeneticInverterRequest,
)
from akkudoktoreos.optimization.genetic.geneticsimulation import (
GeneticSimulation,
)
from akkudoktoreos.optimization.genetic.genetictailvalue import build_tail_value_curve
from akkudoktoreos.optimization.genetic.geneticterminalvalue import TerminalValueCurve
CURVE = [(0.05, 0.80), (0.20, 0.90), (0.50, 0.95), (1.0, 0.93)]
@@ -43,22 +52,22 @@ def _make_inverter(
battery=None,
dc_to_ac_efficiency: float = 1.0,
**kwargs,
) -> Inverter:
) -> GeneticInverter:
predictor = Mock()
predictor.calculate_expected_direct_consumption.side_effect = min
with patch(
"akkudoktoreos.devices.genetic.inverter.get_eos_load_interpolator",
"akkudoktoreos.optimization.genetic.devices.geneticinverter.get_genetic_load_interpolator",
return_value=predictor,
):
return Inverter(
InverterParameters(
return GeneticInverter(
GeneticInverterRequest(
device_id="inverter1",
max_power_wh=max_power_wh,
battery_id=battery.parameters.device_id if battery else None,
dc_to_ac_efficiency=dc_to_ac_efficiency,
dc_to_ac_efficiency_curve=curve,
**kwargs,
),
).to_parameters(),
battery=battery,
)
@@ -80,18 +89,18 @@ def _passthrough_battery() -> Mock:
class TestCurveValidation:
def test_none_is_allowed(self):
assert validate_efficiency_curve(None) is None
params = InverterParameters(device_id="inverter1", max_power_wh=1000)
params = GeneticInverterRequest(device_id="inverter1", max_power_wh=1000)
assert params.dc_to_ac_efficiency_curve is None
assert params.dc_to_ac_efficiency_reference_load_fraction == pytest.approx(0.06)
def test_valid_curve_is_accepted(self):
params = InverterParameters(
params = GeneticInverterRequest(
device_id="inverter1", max_power_wh=1000, dc_to_ac_efficiency_curve=CURVE
)
assert params.dc_to_ac_efficiency_curve == CURVE
def test_json_lists_are_accepted(self):
params = InverterParameters.model_validate(
params = GeneticInverterRequest.model_validate(
{
"device_id": "inverter1",
"max_power_wh": 1000,
@@ -116,14 +125,14 @@ class TestCurveValidation:
)
def test_invalid_curve_is_rejected(self, curve):
with pytest.raises(ValidationError):
InverterParameters(
GeneticInverterRequest(
device_id="inverter1", max_power_wh=1000, dc_to_ac_efficiency_curve=curve
)
@pytest.mark.parametrize("fraction", [-0.1, 1.1])
def test_reference_load_fraction_range(self, fraction):
with pytest.raises(ValidationError):
InverterParameters(
GeneticInverterRequest(
device_id="inverter1",
max_power_wh=1000,
dc_to_ac_efficiency_reference_load_fraction=fraction,
@@ -166,15 +175,15 @@ class TestInterpolation:
"""max_power_wh is scaled to the slot, so 250 Wh in 15 min is 1 kW."""
predictor = Mock()
with patch(
"akkudoktoreos.devices.genetic.inverter.get_eos_load_interpolator",
"akkudoktoreos.optimization.genetic.devices.geneticinverter.get_genetic_load_interpolator",
return_value=predictor,
):
inverter = Inverter(
InverterParameters(
inverter = GeneticInverter(
GeneticInverterRequest(
device_id="inverter1",
max_power_wh=5000.0,
dc_to_ac_efficiency_curve=CURVE,
),
).to_parameters(),
slot_duration_h=0.25,
)
# 1 kW of 5 kW -> load fraction 0.2
@@ -237,8 +246,8 @@ class TestProcessEnergyWithCurve:
def test_grid_export_uses_efficiency_at_export_level(self, config_eos):
"""A full-power export runs at the efficiency of the rated load."""
battery = Battery(
SolarPanelBatteryParameters(
battery = GeneticBattery(
GeneticBatteryRequest(
device_id="battery1",
capacity_wh=10000,
initial_soc_percentage=100,
@@ -246,7 +255,7 @@ class TestProcessEnergyWithCurve:
charging_efficiency=1.0,
discharging_efficiency=1.0,
max_charge_power_w=1000,
),
).to_parameters(),
prediction_hours=1,
)
battery.reset()
@@ -289,8 +298,8 @@ class TestReferenceEfficiency:
"""Stored energy is valued with the efficiency at the reference load."""
def tail_curve(efficiency_curve):
battery = Battery(
SolarPanelBatteryParameters(
battery = GeneticBattery(
GeneticBatteryRequest(
device_id="battery1",
capacity_wh=1000,
max_charge_power_w=1000,
@@ -298,16 +307,16 @@ class TestReferenceEfficiency:
discharging_efficiency=1.0,
initial_soc_percentage=50,
charge_rates=[0, 0.5, 1],
),
).to_parameters(),
prediction_hours=1,
)
inverter = Inverter(
InverterParameters(
inverter = GeneticInverter(
GeneticInverterRequest(
device_id="inverter1",
battery_id="battery1",
max_power_wh=5000,
dc_to_ac_efficiency_curve=efficiency_curve,
),
).to_parameters(),
battery=battery,
)
return build_tail_value_curve(
@@ -344,8 +353,8 @@ def _simulate(config_eos, efficiency_curve, dc_to_ac_efficiency=0.95):
"optimization": {"genetic": {"tail_horizon_hours": 0, "horizon_hours": hours}},
}
)
battery = Battery(
SolarPanelBatteryParameters(
battery = GeneticBattery(
GeneticBatteryRequest(
device_id="battery1",
capacity_wh=10000,
initial_soc_percentage=60,
@@ -353,25 +362,25 @@ def _simulate(config_eos, efficiency_curve, dc_to_ac_efficiency=0.95):
charging_efficiency=0.95,
discharging_efficiency=0.95,
max_charge_power_w=4000,
),
).to_parameters(),
prediction_hours=hours,
)
battery.reset()
inverter = Inverter(
InverterParameters(
inverter = GeneticInverter(
GeneticInverterRequest(
device_id="inverter1",
max_power_wh=5000,
battery_id="battery1",
dc_to_ac_efficiency=dc_to_ac_efficiency,
ac_to_dc_efficiency=0.95,
dc_to_ac_efficiency_curve=efficiency_curve,
),
).to_parameters(),
battery=battery,
)
rng = np.random.default_rng(42)
simulation = GeneticSimulation()
simulation.prepare(
GeneticEnergyManagementParameters.model_validate(
GeneticEnergyManagementRequest.model_validate(
dict(
pv_prognose_wh=list(np.maximum(rng.normal(1500, 1500, hours), 0.0)),
strompreis_euro_pro_wh=list(rng.uniform(0.0001, 0.0004, hours)),
@@ -379,7 +388,7 @@ def _simulate(config_eos, efficiency_curve, dc_to_ac_efficiency=0.95):
preis_euro_pro_wh_akku=0.0001,
gesamtlast=list(rng.uniform(100, 3000, hours)),
)
),
).to_parameters(),
optimization_hours=hours,
prediction_hours=hours,
inverter=inverter,
@@ -427,7 +436,7 @@ class TestSettings:
dc_to_ac_efficiency_reference_load_fraction=0.1,
)
profile = settings.get_inverter_profile()
params = settings.to_genetic_param()
params = geneticprepare.inverter_request(settings)
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))
@@ -464,9 +473,9 @@ def _real_battery(
max_power_w: float = 1000.0,
discharging_efficiency: float = 1.0,
slot_duration_h: float = 1.0,
) -> Battery:
battery = Battery(
SolarPanelBatteryParameters(
) -> GeneticBattery:
battery = GeneticBattery(
GeneticBatteryRequest(
device_id="battery1",
capacity_wh=capacity_wh,
initial_soc_percentage=soc_percentage,
@@ -474,7 +483,7 @@ def _real_battery(
charging_efficiency=1.0,
discharging_efficiency=discharging_efficiency,
max_charge_power_w=max_power_w,
),
).to_parameters(),
prediction_hours=1,
slot_duration_h=slot_duration_h,
)
@@ -483,21 +492,21 @@ def _real_battery(
return battery
def _real_inverter(battery: Battery, curve=None, slot_duration_h: float = 1.0, **kwargs) -> Inverter:
def _real_inverter(battery: GeneticBattery, curve=None, slot_duration_h: float = 1.0, **kwargs) -> GeneticInverter:
predictor = Mock()
predictor.calculate_expected_direct_consumption.side_effect = min
with patch(
"akkudoktoreos.devices.genetic.inverter.get_eos_load_interpolator",
"akkudoktoreos.optimization.genetic.devices.geneticinverter.get_genetic_load_interpolator",
return_value=predictor,
):
return Inverter(
InverterParameters(
return GeneticInverter(
GeneticInverterRequest(
device_id="inverter1",
max_power_wh=1000.0,
battery_id="battery1",
dc_to_ac_efficiency_curve=curve,
**kwargs,
),
).to_parameters(),
battery=battery,
slot_duration_h=slot_duration_h,
)
@@ -672,12 +681,12 @@ class TestSolveAcForChargeDcEnergy:
class TestChargeFromGridWithCurve:
def test_curve_is_validated(self):
with pytest.raises(ValidationError):
InverterParameters(
GeneticInverterRequest(
device_id="inverter1", max_power_wh=1000, ac_to_dc_efficiency_curve=[(0.5, 0.9)]
)
@staticmethod
def _empty_battery() -> Battery:
def _empty_battery() -> GeneticBattery:
battery = _real_battery(soc_percentage=0)
battery.charge_array = np.ones(1)
return battery
@@ -705,7 +714,7 @@ class TestChargeFromGridWithCurve:
profile_adjustment=InverterProfileAdjustment(nominal_power_w=5000),
)
profile = settings.get_inverter_profile()
params = settings.to_genetic_param()
params = geneticprepare.inverter_request(settings)
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)