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
+123
View File
@@ -16,6 +16,7 @@ from http import HTTPStatus
from pathlib import Path
from typing import (
TYPE_CHECKING,
Any,
Callable,
Generator,
Iterator,
@@ -43,6 +44,8 @@ from akkudoktoreos.server.server import get_default_host
if TYPE_CHECKING:
from playwright.sync_api import Browser
from akkudoktoreos.optimization.genetic.geneticalgorithm import GeneticOptimization
# -----------------------------------------------
# Adapt pytest logging handling to Loguru logging
# -----------------------------------------------
@@ -926,3 +929,123 @@ def set_other_timezone():
# Restore the original timezone
cast(Callable[[pendulum.Timezone | pendulum.FixedTimezone], None], pendulum.set_local_timezone)(original_timezone)
assert pendulum.local_timezone() == original_timezone
def genetic_optimization(seed: Optional[int] = None) -> "GeneticOptimization":
"""GENETIC algorithm with the run settings of the configuration and EMS run start.
Before migration step 3 the algorithm read the configuration and the run start of the
energy management itself; tests that build it directly get the same settings here.
Args:
seed: Random seed of the run; ``None`` gives a random seed.
Returns:
A ``GeneticOptimization`` for the current configuration and run start.
"""
from dataclasses import replace
from akkudoktoreos.core.coreabc import get_ems
from akkudoktoreos.optimization.genetic.geneticalgorithm import GeneticOptimization
from akkudoktoreos.optimization.genetic.geneticprepare import run_settings
ems = get_ems()
settings = run_settings(ems.start_datetime, ems.observation_datetime)
return GeneticOptimization(replace(settings, seed=seed, verbose=False))
def genetic_run_parameters(request: Any, optimization: Any = None) -> Any:
"""GENETIC optimization parameters for the conversion and visualization tests.
Args:
request: The forecast and device parameters (``GeneticOptimizationParameters``), e.g. the
ones a result echoes.
optimization: The ``GeneticOptimization`` of the run, whose settings are used; without it,
the settings of the configuration and EMS run start.
Returns:
A ``GeneticParameters``.
"""
from akkudoktoreos.core.coreabc import get_ems
from akkudoktoreos.optimization.genetic.geneticparameters import GeneticParameters
from akkudoktoreos.optimization.genetic.geneticprepare import run_settings
if optimization is not None:
settings = optimization.settings
else:
ems = get_ems()
settings = run_settings(ems.start_datetime, ems.observation_datetime)
return GeneticParameters(
request=request, start_hour=settings.start_datetime.hour, settings=settings
)
def genetic_result_of(solution: Any) -> Any:
"""The GENETIC result a public solution was built from.
Tests keep stored solutions (``GeneticSolution`` JSON); the conversion and the visualization
take the result of a run (``GeneticResult``).
Args:
solution: A ``GeneticSolution`` response.
Returns:
A ``GeneticResult`` with the solution's values; its request is the echoed ``parameters``.
"""
import dataclasses
from akkudoktoreos.optimization.genetic import geneticterminalvalue
from akkudoktoreos.optimization.genetic.geneticresult import (
GeneticElectricVehicleState,
GeneticResult,
GeneticSimulationOutput,
)
def curve(value: Any) -> Any:
if value is None:
return None
return geneticterminalvalue.TerminalValueCurve(**value.model_dump())
terminal_value = None
if solution.terminal_value is not None:
tv = solution.terminal_value
terminal_value = geneticterminalvalue.TerminalValueResult(
**{
name: getattr(tv, name)
for name in type(tv).model_fields
if name not in ("curve", "continuation_curve", "tail_diagnostics", "tail_plan")
},
curve=curve(tv.curve),
continuation_curve=curve(tv.continuation_curve),
tail_diagnostics=None
if tv.tail_diagnostics is None
else geneticterminalvalue.TailDiagnostics(**tv.tail_diagnostics.model_dump()),
tail_plan=[
geneticterminalvalue.TailPlanSlot(**slot.model_dump()) for slot in tv.tail_plan
],
)
simulation = GeneticSimulationOutput(
**{
field.name: getattr(solution.result, field.name)
for field in dataclasses.fields(GeneticSimulationOutput)
}
)
ev = None
if solution.ev_obj is not None:
ev = GeneticElectricVehicleState(
**{
field.name: getattr(solution.ev_obj, field.name)
for field in dataclasses.fields(GeneticElectricVehicleState)
}
)
return GeneticResult(
**{
field.name: getattr(solution, field.name)
for field in dataclasses.fields(GeneticResult)
if field.name not in ("request", "result", "ev_obj", "terminal_value")
},
request=solution.parameters,
result=simulation,
ev_obj=ev,
terminal_value=terminal_value,
)