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
+85 -65
View File
@@ -3,17 +3,20 @@
from asyncio import Lock
from types import SimpleNamespace
from typing import Any
from unittest.mock import AsyncMock, Mock
from unittest.mock import ANY, AsyncMock, Mock
import pytest
from akkudoktoreos.core import ems as ems_module
from akkudoktoreos.core.emsettings import EnergyManagementMode
from akkudoktoreos.optimization.genetic import geneticalgorithm as genetic_module
from akkudoktoreos.optimization.genetic import geneticconvert, geneticprepare
from akkudoktoreos.optimization.genetic0 import genetic0algorithm as genetic0_module
from akkudoktoreos.optimization.genetic0 import genetic0convert, genetic0prepare
from akkudoktoreos.optimization.genetic0.genetic0request import (
Genetic0Request,
)
from akkudoktoreos.optimization.genetic.geneticrequest import GeneticRequest
from akkudoktoreos.optimization.optimization import OptimizationAlgorithm
from akkudoktoreos.optimization.optimizer import OptimizerRun
from akkudoktoreos.utils.datetimeutil import to_datetime
@@ -21,20 +24,24 @@ from akkudoktoreos.utils.gridinterpolator import GridInterpolatorBackend
def _patch_optimizer(monkeypatch, prefix: str, constructor: Any) -> None:
"""Replace the optimizer class that EnergyManagement.run() instantiates.
"""Replace the optimizer class that the optimizer's ``run()`` instantiates.
GENETIC0 is imported on first use inside its optimizer, so it is patched at its source.
Both are imported on first use inside their optimizer, so they are patched at their source.
"""
module = genetic0_module if prefix == "Genetic0" else ems_module
module = genetic0_module if prefix == "Genetic0" else genetic_module
monkeypatch.setattr(module, prefix + "Optimization", constructor)
def _patch_prepare(monkeypatch, prefix: str, prepare: Any) -> None:
"""Replace the legacy parameter preparation of GENETIC or GENETIC0."""
"""Replace the forecast and device preparation of GENETIC or GENETIC0.
GENETIC resolves every request, the configured default one included, through
``resolve_request()``; GENETIC0's legacy preparation serves runs without a request only.
"""
if prefix == "Genetic0":
monkeypatch.setattr(genetic0prepare, "prepare_request", prepare)
else:
monkeypatch.setattr(ems_module.GeneticOptimizationParameters, "prepare", prepare)
monkeypatch.setattr(geneticprepare, "resolve_request", prepare)
def _warm_start_of(call: Any) -> Any:
@@ -44,12 +51,14 @@ def _warm_start_of(call: Any) -> Any:
def _assert_prepared_without_request(prefix: str, prepare: Any) -> None:
"""GENETIC0 passes start, observation time and warm start (none here) into its preparation."""
"""Both pass the warm start (none here) into their preparation; GENETIC a default request."""
prepare.assert_awaited_once()
if prefix == "Genetic0":
prepare.assert_awaited_once()
assert _warm_start_of(prepare.await_args) is None
else:
prepare.assert_awaited_once_with()
request, start, observation, warm_start = prepare.await_args.args
assert request.model_dump() == GeneticRequest().model_dump()
assert warm_start is None
def _conversion_arguments(prefix: str) -> dict[str, Any]:
@@ -59,31 +68,32 @@ def _conversion_arguments(prefix: str) -> dict[str, Any]:
def _native_solution(prefix: str) -> Any:
"""The native solution the latest run published for GENETIC or GENETIC0."""
cls = ems_module.EnergyManagement
if prefix == "Genetic0":
return cls.optimizer_result("GENETIC0")
return cls._genetic_solution
return ems_module.EnergyManagement.optimizer_result(prefix.upper())
def _set_native_solution(monkeypatch, prefix: str, solution: Any) -> None:
"""Publish ``solution`` as the result of a previous run of GENETIC or GENETIC0."""
cls = ems_module.EnergyManagement
if prefix == "Genetic0":
runs = {"GENETIC0": OptimizerRun(parameters=object(), result=solution)}
monkeypatch.setattr(cls, "_optimizer_runs", runs)
else:
monkeypatch.setattr(cls, "_genetic_solution", solution)
runs = {prefix.upper(): OptimizerRun(parameters=object(), result=solution)}
monkeypatch.setattr(ems_module.EnergyManagement, "_optimizer_runs", runs)
def _supplied(prefix: str, parameters: Any, generations: int, seed: int) -> dict[str, Any]:
def _stand_in_request() -> SimpleNamespace:
"""A request both preparations accept.
GENETIC0's preparation looks at its home appliance, GENETIC's at its start solution and its
home appliances.
"""
return SimpleNamespace(
dishwasher=None,
start_solution=None,
start_solution_datetime=None,
resolved_home_appliances=lambda: [],
)
def _supplied(parameters: Any, generations: int, seed: int) -> dict[str, Any]:
"""Run arguments that supply the parameters, generations and seed of a run."""
if prefix == "Genetic0":
return {"request": parameters, "overrides": {"generations": generations, "seed": seed}}
return {
"genetic_parameters": parameters,
"genetic_generations": generations,
"genetic_seed": seed,
}
return {"request": parameters, "overrides": {"generations": generations, "seed": seed}}
@pytest.fixture
@@ -96,7 +106,6 @@ def offline_ems(monkeypatch):
"_last_run_datetime",
"_plan",
"_optimization_solution",
"_genetic_solution",
):
monkeypatch.setattr(cls, name, None)
monkeypatch.setattr(cls, "_optimizer_runs", {})
@@ -109,12 +118,27 @@ def offline_ems(monkeypatch):
ems=SimpleNamespace(mode=EnergyManagementMode.OPTIMIZATION),
optimization=SimpleNamespace(
algorithm=OptimizationAlgorithm.GENETIC,
genetic=SimpleNamespace(generations=3, seed=17, interval_sec=3600, individuals=31),
self_consumption_interpolator="scipy",
genetic=SimpleNamespace(
generations=3,
seed=17,
interval_sec=3600,
individuals=31,
horizon_hours=24,
tail_horizon_hours=0,
penalties={},
workers=None,
pin_workers=True,
fitness_cache_max_entries=None,
terminal_value_mode="AUTO",
terminal_value_window_hours=24,
),
genetic0=SimpleNamespace(
generations=5, seed=29, horizon_hours=24, individuals=13, penalties={}
),
),
prediction=SimpleNamespace(hours=48),
feedintariff=SimpleNamespace(provider=None, direct_marketing_enabled=False),
devices=SimpleNamespace(
batteries=None, electric_vehicles=None, max_home_appliances=0
),
@@ -124,7 +148,12 @@ def offline_ems(monkeypatch):
adapter=SimpleNamespace(update_data=AsyncMock()),
set_start_datetime=cls.set_start_datetime,
)
# GENETIC0's parameter preparation reads the settings and predictions itself.
# The parameter preparations read the settings (and GENETIC0's the predictions) themselves.
monkeypatch.setattr(geneticprepare, "get_config", lambda: ems.config)
# Stand-in requests are already resolved.
monkeypatch.setattr(
geneticprepare, "resolve_request", AsyncMock(side_effect=lambda request, *args: request)
)
monkeypatch.setattr(genetic0prepare, "get_config", lambda: ems.config)
monkeypatch.setattr(
genetic0prepare, "get_prediction", lambda: SimpleNamespace(record_keys=[])
@@ -139,6 +168,12 @@ def offline_ems(monkeypatch):
return await result.optimization_solution()
monkeypatch.setattr(genetic0convert, "optimization_solution", optimization_solution)
monkeypatch.setattr(geneticconvert, "optimization_solution", optimization_solution)
monkeypatch.setattr(
geneticconvert,
"energy_management_plan",
lambda parameters, result: result.energy_management_plan(),
)
monkeypatch.setattr(
genetic0convert,
"energy_management_plan",
@@ -202,8 +237,7 @@ async def test_optimization_routes_only_selected_algorithm(
other_name = "Genetic0" if selected_name == "Genetic" else "Genetic"
suffix = "genetic" if algorithm == OptimizationAlgorithm.GENETIC else "genetic0"
other_suffix = "genetic0" if suffix == "genetic" else "genetic"
# GENETIC0's preparation looks at the request's home appliance.
sentinel_parameters = SimpleNamespace(dishwasher=None)
sentinel_parameters = _stand_in_request()
sentinel_result, sentinel_plan = object(), object()
solution = SimpleNamespace(
optimization_solution=AsyncMock(return_value=sentinel_result),
@@ -228,9 +262,9 @@ async def test_optimization_routes_only_selected_algorithm(
offline_ems.config.optimization.algorithm = OptimizationAlgorithm(other_suffix.upper())
kwargs["algorithm"] = algorithm
if supplied:
kwargs.update(_supplied(selected_name, sentinel_parameters, 7, 43))
kwargs.update(_supplied(sentinel_parameters, 7, 43))
if algorithm == OptimizationAlgorithm.GENETIC:
kwargs["genetic_individuals"] = 11
kwargs["overrides"]["individuals"] = 11
run_result = await ems_module.EnergyManagement.run(offline_ems, **kwargs)
assert run_result is solution
selected = constructors[selected_name]
@@ -241,19 +275,18 @@ async def test_optimization_routes_only_selected_algorithm(
"start_hour": expected_hour,
"parameters": sentinel_parameters,
}
# Both get their algorithm settings from the parameters (step 3).
(settings,) = selected.call_args.args
assert (settings.seed, settings.generations, settings.verbose) == (
expected_seed,
expected_generations,
False,
)
if algorithm == OptimizationAlgorithm.GENETIC:
selected.assert_called_once_with(verbose=False, fixed_seed=expected_seed)
expected_arguments["ngen"] = expected_generations
else:
# GENETIC0 gets its algorithm settings from the parameters (step 3).
(settings,) = selected.call_args.args
assert (settings.seed, settings.generations, settings.verbose) == (
expected_seed,
expected_generations,
False,
)
if algorithm == OptimizationAlgorithm.GENETIC:
expected_arguments["individuals"] = 11 if supplied else None
expected_arguments["individuals"] = 11 if supplied else expected_config.individuals
# The start of the start solution comes from the parameters, not their request.
expected_arguments["start_solution_datetime"] = None
selected.return_value.optimize_ems.assert_called_once_with(**expected_arguments)
else:
# GENETIC0 runs from its parameters, which carry the request and the start hour.
@@ -262,7 +295,12 @@ async def test_optimization_routes_only_selected_algorithm(
assert parameters.start_hour == expected_hour
constructors[other_name].assert_not_called()
preparers[other_name].assert_not_awaited()
if supplied:
if supplied and algorithm == OptimizationAlgorithm.GENETIC:
# GENETIC completes the supplied request.
preparers[selected_name].assert_awaited_once_with(
sentinel_parameters, ANY, ANY, None
)
elif supplied:
preparers[selected_name].assert_not_awaited()
else:
_assert_prepared_without_request(selected_name, preparers[selected_name])
@@ -298,24 +336,6 @@ async def test_non_optimization_modes_never_optimize(monkeypatch, offline_ems, m
assert ems_module.EnergyManagement.plan() is None
@pytest.mark.asyncio
@pytest.mark.parametrize("prefix", ["Genetic"])
async def test_missing_preparation_does_not_dispatch_controls(monkeypatch, offline_ems, prefix):
"""GENETIC may still cancel; GENETIC0's preparation never does (TestGenetic0AlwaysValid)."""
constructor = Mock()
_patch_optimizer(monkeypatch, prefix, constructor)
prepare = AsyncMock(return_value=None)
_patch_prepare(monkeypatch, prefix, prepare)
await ems_module.EnergyManagement.run(
offline_ems, algorithm=OptimizationAlgorithm(prefix.upper())
)
_assert_prepared_without_request(prefix, prepare)
constructor.assert_not_called()
assert offline_ems.adapter.update_data.await_count == 1 # acquisition only
assert ems_module.EnergyManagement.plan() is None
assert ems_module.EnergyManagement.stage() == ems_module.EnergyManagementStage.IDLE
@pytest.mark.asyncio
@pytest.mark.parametrize("start_hour", [None, 11])
async def test_legacy_optimize_explicitly_uses_genetic0(monkeypatch, start_hour):
@@ -434,7 +454,7 @@ async def test_conversion_failure_preserves_consistent_previous_results(
constructor = Mock()
constructor.return_value.optimize_ems.return_value = solution
_patch_optimizer(monkeypatch, prefix, constructor)
supplied_parameters = _supplied(prefix, SimpleNamespace(dishwasher=None), 3, 17)
supplied_parameters = _supplied(_stand_in_request(), 3, 17)
result = await cls.run(
offline_ems,
algorithm=OptimizationAlgorithm(prefix.upper()),