mirror of
https://github.com/Akkudoktor-EOS/EOS.git
synced 2026-12-02 18:36:28 +01:00
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)
161 lines
6.3 KiB
Python
161 lines
6.3 KiB
Python
"""Tests for the configurable size limit of the GENETIC fitness cache."""
|
|
|
|
import json
|
|
from collections import OrderedDict
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
from typing import Any, Optional
|
|
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 import geneticapi
|
|
from akkudoktoreos.optimization.genetic.geneticalgorithm import (
|
|
GeneticOptimization,
|
|
)
|
|
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
|
GeneticOptimizationParameters,
|
|
)
|
|
from akkudoktoreos.optimization.genetic.geneticsettings import GeneticSettings
|
|
from akkudoktoreos.utils.datetimeutil import to_datetime
|
|
|
|
DIR_TESTDATA = Path(__file__).parent / "testdata" / "genetic"
|
|
|
|
|
|
def _configure_hourly_grid(config_eos: ConfigEOS) -> None:
|
|
config_eos.merge_settings_from_dict(
|
|
{
|
|
"prediction": {"hours": 48},
|
|
"optimization": {
|
|
"genetic": {"tail_horizon_hours": 0, "horizon_hours": 48, "interval_sec": 3600}
|
|
},
|
|
}
|
|
)
|
|
get_ems(init=True).set_start_datetime(to_datetime().set(hour=0, minute=0, second=0, microsecond=0))
|
|
|
|
|
|
def test_fitness_cache_max_entries_setting_defaults_to_unbounded():
|
|
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):
|
|
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 = 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)
|
|
result = {
|
|
"Gesamtbilanz_Euro": 1.0,
|
|
"Gesamt_Verluste": 0.0,
|
|
"EAuto_SoC_pro_Stunde": np.zeros(opt.control_slots),
|
|
}
|
|
opt._fitness_cache = OrderedDict()
|
|
opt._fitness_cache_max_entries = max_entries
|
|
opt._fitness_cache_enabled = True
|
|
individuals = [
|
|
creator.Individual([value % 2] + [value // 2] + [0] * (opt.control_slots - 2))
|
|
for value in range(20)
|
|
]
|
|
|
|
with patch.object(opt, "evaluate_inner", return_value=result):
|
|
for individual in individuals:
|
|
opt.evaluate(individual, parameters, 0, False) # type: ignore[arg-type]
|
|
assert len(opt._fitness_cache) <= max_entries
|
|
|
|
# The most recent evaluation is still cached; the first one has been evicted.
|
|
newest_key = opt._fitness_key(individuals[-1])
|
|
oldest_key = opt._fitness_key(individuals[0])
|
|
assert newest_key in opt._fitness_cache
|
|
assert oldest_key not in opt._fitness_cache
|
|
assert opt._fitness_cache_misses == len(individuals)
|
|
assert opt._fitness_cache_hits == 0
|
|
|
|
|
|
def test_evict_fitness_cache_also_bounds_a_plain_dict(config_eos: ConfigEOS):
|
|
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)]
|
|
|
|
|
|
def _run_optimization(
|
|
config_eos: ConfigEOS, max_entries: Optional[int]
|
|
) -> tuple[dict[str, Any], dict[str, Any], int, int]:
|
|
"""Run a short, seeded GENETIC optimization with EV and return its result."""
|
|
config_eos.merge_settings_from_dict(
|
|
{
|
|
"prediction": {"hours": 48},
|
|
"optimization": {
|
|
"algorithm": "GENETIC",
|
|
"genetic": {
|
|
"horizon_hours": 38,
|
|
"tail_horizon_hours": 0,
|
|
"terminal_value_mode": "FIXED",
|
|
"individuals": 40,
|
|
"generations": 10,
|
|
"fitness_cache_max_entries": max_entries,
|
|
"penalties": {"ev_soc_miss": 10, "ac_charge_break_even": 1},
|
|
},
|
|
},
|
|
"devices": {
|
|
"max_electric_vehicles": 1,
|
|
"electric_vehicles": {
|
|
"ev1": {"charge_rates": [0.0, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0]}
|
|
},
|
|
},
|
|
}
|
|
)
|
|
assert config_eos.optimization.genetic.fitness_cache_max_entries == max_entries
|
|
with (DIR_TESTDATA / "optimize_input_2.json").open("r") as f_in:
|
|
parameters = GeneticOptimizationParameters(**json.load(f_in))
|
|
get_ems(init=True).set_start_datetime(
|
|
to_datetime("2026-09-16T10:00:00+02:00", in_timezone="Europe/Berlin")
|
|
)
|
|
CacheEnergyManagementStore().clear()
|
|
|
|
opt = genetic_optimization(seed=42)
|
|
max_cache_size = 0
|
|
uncached = opt._evaluate_uncached
|
|
|
|
def spy(*args: Any, **kwargs: Any) -> tuple[float]:
|
|
nonlocal max_cache_size
|
|
max_cache_size = max(max_cache_size, len(opt._fitness_cache))
|
|
return uncached(*args, **kwargs)
|
|
|
|
with patch.object(opt, "_evaluate_uncached", side_effect=spy):
|
|
solution = opt.optimize_ems(parameters=parameters, start_hour=10, ngen=12)
|
|
|
|
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"])
|
|
return dump, history, cache_stats["hits"], max_cache_size
|
|
|
|
|
|
def test_fitness_cache_limit_does_not_change_the_result(config_eos: ConfigEOS):
|
|
reference, reference_history, reference_hits, unbounded_size = _run_optimization(
|
|
config_eos, None
|
|
)
|
|
assert reference_hits > 0
|
|
assert unbounded_size > 20
|
|
|
|
for max_entries in (0, 1, 7, 20):
|
|
result, history, hits, max_size = _run_optimization(config_eos, max_entries)
|
|
assert result == reference, f"fitness_cache_max_entries={max_entries}"
|
|
assert history == reference_history, f"fitness_cache_max_entries={max_entries}"
|
|
assert max_size <= max_entries
|
|
if max_entries == 0:
|
|
assert hits == 0
|