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
+15 -11
View File
@@ -9,17 +9,21 @@ from unittest.mock import patch
import numpy as np
import pytest
from conftest import genetic_optimization
from deap import creator
from pydantic import ValidationError
from akkudoktoreos.config.config import ConfigEOS
from akkudoktoreos.core.cache import CacheEnergyManagementStore
from akkudoktoreos.core.coreabc import get_ems
from akkudoktoreos.optimization.genetic.genetic import GeneticOptimization
from akkudoktoreos.optimization.genetic.geneticparams import (
from akkudoktoreos.optimization.genetic import geneticapi
from akkudoktoreos.optimization.genetic.geneticalgorithm import (
GeneticOptimization,
)
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticOptimizationParameters,
)
from akkudoktoreos.optimization.genetic.geneticsettings import GeneticCommonSettings
from akkudoktoreos.optimization.genetic.geneticsettings import GeneticSettings
from akkudoktoreos.utils.datetimeutil import to_datetime
DIR_TESTDATA = Path(__file__).parent / "testdata" / "genetic"
@@ -38,17 +42,17 @@ def _configure_hourly_grid(config_eos: ConfigEOS) -> None:
def test_fitness_cache_max_entries_setting_defaults_to_unbounded():
assert GeneticCommonSettings().fitness_cache_max_entries is None
assert GeneticCommonSettings(fitness_cache_max_entries=0).fitness_cache_max_entries == 0
assert GeneticCommonSettings(fitness_cache_max_entries=5000).fitness_cache_max_entries == 5000
assert GeneticSettings().fitness_cache_max_entries is None
assert GeneticSettings(fitness_cache_max_entries=0).fitness_cache_max_entries == 0
assert GeneticSettings(fitness_cache_max_entries=5000).fitness_cache_max_entries == 5000
with pytest.raises(ValidationError):
GeneticCommonSettings(fitness_cache_max_entries=-1)
GeneticSettings(fitness_cache_max_entries=-1)
@pytest.mark.parametrize("max_entries", [1, 2, 3, 10])
def test_bounded_fitness_cache_evicts_oldest_keys(config_eos: ConfigEOS, max_entries: int):
_configure_hourly_grid(config_eos)
opt = GeneticOptimization(fixed_seed=42)
opt = genetic_optimization(seed=42)
opt.optimize_ev = False
opt.setup_deap_environment({"home_appliance": 0}, start_hour=0)
parameters = SimpleNamespace(ems=SimpleNamespace(price_per_wh_battery=0.0), ev=None)
@@ -80,7 +84,7 @@ def test_bounded_fitness_cache_evicts_oldest_keys(config_eos: ConfigEOS, max_ent
def test_evict_fitness_cache_also_bounds_a_plain_dict(config_eos: ConfigEOS):
opt = GeneticOptimization(fixed_seed=42)
opt = genetic_optimization(seed=42)
opt._fitness_cache = {(bytes([value]),): None for value in range(10)} # type: ignore[misc]
opt._evict_fitness_cache(3)
assert list(opt._fitness_cache) == [(bytes([value]),) for value in (7, 8, 9)]
@@ -121,7 +125,7 @@ def _run_optimization(
)
CacheEnergyManagementStore().clear()
opt = GeneticOptimization(fixed_seed=42)
opt = genetic_optimization(seed=42)
max_cache_size = 0
uncached = opt._evaluate_uncached
@@ -133,7 +137,7 @@ def _run_optimization(
with patch.object(opt, "_evaluate_uncached", side_effect=spy):
solution = opt.optimize_ems(parameters=parameters, start_hour=10, ngen=12)
dump = solution.model_dump(mode="json")
dump = geneticapi.solution_response(solution).model_dump(mode="json")
history = dump.pop("fitness_history")
cache_stats = history.pop("fitness_cache")
max_cache_size = max(max_cache_size, cache_stats["keys"])