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
+25 -281
View File
@@ -1,27 +1,23 @@
"""Regression test suite for the repaired HomeAppliance module.
TODO: fix this import to match wherever HomeApplianceParameters / HomeAppliance
actually live in the repo.
"""
"""Regression test suite for the repaired GENETIC home appliance simulation."""
from typing import Any
from unittest.mock import Mock
import numpy as np
import pendulum
import pytest
from akkudoktoreos.config.configabc import CycleTimeWindowSequence, ValueTimeWindow
from akkudoktoreos.devices.genetic.homeappliance import (
HomeAppliance,
HomeApplianceParameters,
from akkudoktoreos.optimization.genetic.devices.genetichomeappliance import (
GeneticHomeAppliance,
)
from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration, to_time
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticHomeApplianceRequest,
)
from akkudoktoreos.utils.datetimeutil import to_datetime
# ---------------------------------------------------------------------------
# Fixtures / factories
# ---------------------------------------------------------------------------
def make_params(**overrides) -> HomeApplianceParameters:
def make_params(**overrides) -> GeneticHomeApplianceRequest:
defaults: dict[str, Any] = dict(
device_id="dishwasher",
consumption_wh=2000,
@@ -31,76 +27,34 @@ def make_params(**overrides) -> HomeApplianceParameters:
time_windows=None,
)
defaults.update(overrides)
return HomeApplianceParameters(**defaults)
return GeneticHomeApplianceRequest(**defaults)
def make_appliance(
prediction_hours: int = 24,
optimization_hours: int = 24,
**param_overrides,
) -> HomeAppliance:
) -> GeneticHomeAppliance:
"""Build the simulated appliance from a request."""
params = make_params(**param_overrides)
return HomeAppliance(
parameters=params,
return GeneticHomeAppliance(
parameters=params.to_parameters(),
optimization_hours=optimization_hours,
prediction_hours=prediction_hours,
)
def cycle_window(cycle: int, start: str, duration: str) -> CycleTimeWindowSequence:
"""Build a CycleTimeWindowSequence with a single window for one cycle."""
return CycleTimeWindowSequence(
windows=[
ValueTimeWindow(
start_time=to_time(start),
duration=to_duration(duration),
value=float(cycle),
)
]
)
def mock_cycle_windows(cycle_matrix: dict[int, np.ndarray]) -> Mock:
"""Build a Mock standing in for CycleTimeWindowSequence.
``Mock(spec=CycleTimeWindowSequence)`` satisfies both the pydantic
field-type check on ``HomeApplianceParameters.time_windows`` and any
isinstance check in the module, without needing real windows/pendulum
datetimes -- useful for isolating _build_duration_feasibility and the
scheduling/repair logic from the real cycles_to_matrix() implementation.
"""
cycle_indices = list(cycle_matrix.keys())
matrix = np.array([cycle_matrix[c] for c in cycle_indices])
mock = Mock(spec=CycleTimeWindowSequence)
mock.cycles_to_matrix = Mock(return_value=(cycle_indices, matrix))
return mock
# ---------------------------------------------------------------------------
# Setup / defaults
# ---------------------------------------------------------------------------
class TestSetup:
def test_default_time_windows_created_when_none_given(self):
appliance = make_appliance(time_windows=None, num_cycles=1)
assert appliance.parameters.time_windows is not None
assert isinstance(appliance.parameters.time_windows, CycleTimeWindowSequence)
"""Building the appliance."""
def test_default_time_window_value_left_unset(self):
# A None-valued window is invisible to cycles_to_matrix() and so
# never masquerades as a real per-cycle window; every remaining
# cycle instead falls through to the "unconstrained" fallback.
appliance = make_appliance(time_windows=None, num_cycles=3)
assert appliance.parameters.time_windows is not None
windows = appliance.parameters.time_windows.windows
assert len(windows) == 1
assert windows[0].value is None
def test_default_time_window_serializes_without_a_cycle_value(self):
appliance = make_appliance(time_windows=None, num_cycles=1)
assert appliance.parameters.time_windows is not None
dumped = appliance.parameters.time_windows.model_dump()
assert dumped["windows"][0]["value"] is None
def test_simulation_leaves_the_request_unchanged(self):
params = make_params(time_windows=None, num_cycles=1)
GeneticHomeAppliance(params.to_parameters(), 24, 24)
assert params.time_windows is None
def test_num_remaining_cycles_initial(self):
appliance = make_appliance(num_cycles=3)
@@ -113,76 +67,9 @@ class TestSetup:
# ---------------------------------------------------------------------------
# Allowed-start computation: default (unconstrained) per-cycle windows
# Allowed start slots: daylight saving time
# ---------------------------------------------------------------------------
class TestDefaultStartAllowed:
def test_starts_allowed_up_to_horizon_minus_duration(self):
appliance = make_appliance(prediction_hours=10, duration_h=3)
max_start = 10 - 3
allowed = appliance.start_allowed[0]
assert allowed[: max_start + 1].all()
def test_starts_beyond_horizon_minus_duration_forbidden(self):
appliance = make_appliance(prediction_hours=10, duration_h=3)
max_start = 10 - 3
allowed = appliance.start_allowed[0]
assert not allowed[max_start + 1 :].any()
def test_start_earliest_and_latest(self):
appliance = make_appliance(prediction_hours=10, duration_h=3)
assert appliance.start_earliest[0] == 0
assert appliance.start_latest[0] == 10 - 3
def test_each_cycle_gets_its_own_unconstrained_mask(self):
appliance = make_appliance(prediction_hours=10, duration_h=2, num_cycles=2)
max_start = 10 - 2
assert appliance.start_allowed[0][: max_start + 1].all()
assert appliance.start_allowed[1][: max_start + 1].all()
# ---------------------------------------------------------------------------
# Allowed-start computation: explicit single-cycle window
# ---------------------------------------------------------------------------
class TestExplicitCycleWindow:
def test_only_hours_inside_window_allowed(self):
appliance = make_appliance(
prediction_hours=24,
duration_h=2,
num_cycles=1,
time_windows=cycle_window(0, "10:00", "3 hours"),
)
allowed = appliance.start_allowed[0]
# Window is 10:00-13:00, appliance needs 2h -> valid starts 10, 11.
assert allowed[10] and allowed[11]
assert not allowed[9]
assert not allowed[12]
def test_earliest_latest_reflect_window(self):
appliance = make_appliance(
prediction_hours=24,
duration_h=2,
num_cycles=1,
time_windows=cycle_window(0, "10:00", "3 hours"),
)
assert appliance.start_earliest[0] == 10
assert appliance.start_latest[0] == 11
def test_window_with_no_valid_start_falls_back(self):
# Window shorter than the appliance's own duration -> nothing fits.
appliance = make_appliance(
prediction_hours=24,
duration_h=3,
num_cycles=1,
time_windows=cycle_window(0, "10:00", "1 hour"),
)
allowed = appliance.start_allowed[0]
assert not allowed.any()
assert appliance.start_earliest[0] == 0
assert appliance.start_latest[0] == 24 - 3
class TestDSTAllowedStartSlots:
"""The optimizer must distinguish both occurrences of the autumn hour."""
@@ -190,15 +77,15 @@ class TestDSTAllowedStartSlots:
def _appliance(window_field, windows, run_minutes=15):
if window_field == "time_windows":
windows = [{**window, "value": 0} for window in windows]
return HomeAppliance(
parameters=HomeApplianceParameters.model_validate(
return GeneticHomeAppliance(
parameters=GeneticHomeApplianceRequest.model_validate(
{
"device_id": "dishwasher",
"load_profile_power_w": [1000],
"load_profile_interval_seconds": run_minutes * 60,
window_field: {"windows": windows},
}
),
).to_parameters(),
optimization_hours=25,
prediction_hours=100,
slot_duration_h=0.25,
@@ -260,52 +147,6 @@ class TestDSTAllowedStartSlots:
assert allowed == expected
# ---------------------------------------------------------------------------
# Allowed-start computation: mocked per-cycle windows (CycleTimeWindowSequence)
# ---------------------------------------------------------------------------
class TestCycleStartAllowed:
def test_missing_cycle_row_is_unconstrained(self):
# num_cycles=2 but the mock only provides a window for cycle 0.
prediction_hours = 10
duration_h = 2
steps = np.zeros(prediction_hours)
steps[2:6] = 1.0
windows = mock_cycle_windows({0: steps})
appliance = make_appliance(
prediction_hours=prediction_hours,
duration_h=duration_h,
num_cycles=2,
time_windows=windows,
)
max_start = prediction_hours - duration_h
# Cycle 1 has no matrix row -> should be allowed everywhere it fits.
assert appliance.start_allowed[1][: max_start + 1].all()
def test_duration_feasibility_uses_correct_window(self):
# Steps 2,3,4,5 are inside the window (1.0); everything else is 0.
# duration_h=2 -> valid starts are 2, 3, 4 (each 2h block fully inside).
prediction_hours = 10
duration_h = 2
steps = np.zeros(prediction_hours)
steps[2:6] = 1.0
windows = mock_cycle_windows({0: steps})
appliance = make_appliance(
prediction_hours=prediction_hours,
duration_h=duration_h,
num_cycles=1,
time_windows=windows,
)
allowed = appliance.start_allowed[0]
expected = np.zeros(prediction_hours, dtype=bool)
expected[2:5] = True # starts 2, 3, 4
np.testing.assert_array_equal(allowed, expected)
# ---------------------------------------------------------------------------
# set_completed_cycles
# ---------------------------------------------------------------------------
@@ -321,12 +162,6 @@ class TestSetCompletedCycles:
assert appliance.start_hours == []
assert (appliance.load_curve == 0).all()
def test_remaining_cycle_indices_updated(self):
appliance = make_appliance(num_cycles=4)
appliance.set_completed_cycles(2)
assert appliance.remaining_cycle_indices == [2, 3]
assert appliance.num_remaining_cycles == 2
def test_clamped_to_valid_range(self):
appliance = make_appliance(num_cycles=3)
appliance.set_completed_cycles(-5)
@@ -335,97 +170,6 @@ class TestSetCompletedCycles:
assert appliance.completed_cycles == 3
# ---------------------------------------------------------------------------
# set_starting_times -- the core scheduling / repair logic
# ---------------------------------------------------------------------------
class TestSetStartingTimes:
def test_single_cycle_schedule_returns_requested_start(self):
appliance = make_appliance(prediction_hours=24, duration_h=2, num_cycles=1)
result = appliance.set_starting_times([5])
assert result == [5]
def test_two_cycles_enforce_minimum_gap(self):
appliance = make_appliance(
prediction_hours=24, duration_h=2, num_cycles=2, min_cycle_gap_h=1
)
# Requested starts overlap; cycle 1 must be pushed to start >= 0+2+1=3.
result = appliance.set_starting_times([0, 1])
assert result[0] == 0
assert result[1] >= 3
def test_three_cycles_are_all_gap_repaired(self):
appliance = make_appliance(
prediction_hours=24, duration_h=1, num_cycles=3, min_cycle_gap_h=0
)
result = appliance.set_starting_times([0, 0, 0])
# Each cycle is 1h with no gap -> expect 0, 1, 2.
assert result == [0, 1, 2]
def test_load_curve_reflects_final_start_hours(self):
appliance = make_appliance(
prediction_hours=10, duration_h=2, consumption_wh=2000, num_cycles=1
)
appliance.set_starting_times([3])
expected = np.zeros(10)
expected[3:5] = 1000 # 2000 Wh over 2h
np.testing.assert_array_equal(appliance.get_load_curve(), expected)
def test_sorting_preserves_per_cycle_window_alignment(self):
prediction_hours = 24
duration_h = 1
# Cycle 0 only allowed late (hour 20), cycle 1 only allowed early (hour 2).
steps0 = np.zeros(prediction_hours)
steps0[20] = 1.0
steps1 = np.zeros(prediction_hours)
steps1[2] = 1.0
windows = mock_cycle_windows({0: steps0, 1: steps1})
appliance = make_appliance(
prediction_hours=prediction_hours,
duration_h=duration_h,
num_cycles=2,
time_windows=windows,
)
result = appliance.set_starting_times([20, 2])
# Cycle 0 must land at 20 (its only allowed hour), cycle 1 at 2,
# regardless of chronological sorting during repair.
assert 20 in result
assert 2 in result
def test_raises_on_wrong_number_of_start_times(self):
appliance = make_appliance(prediction_hours=24, duration_h=2, num_cycles=2)
with pytest.raises(ValueError):
appliance.set_starting_times([5])
def test_no_remaining_cycles_returns_empty_list(self):
appliance = make_appliance(prediction_hours=24, duration_h=2, num_cycles=1)
appliance.completed_cycles = 1
result = appliance.set_starting_times([])
assert result == []
assert (appliance.load_curve == 0).all()
# ---------------------------------------------------------------------------
# Backwards-compatible single-cycle interface
# ---------------------------------------------------------------------------
class TestSetStartingTimeBackCompat:
def test_single_cycle_wrapper_returns_int(self):
appliance = make_appliance(prediction_hours=24, duration_h=2, num_cycles=1)
result = appliance.set_starting_time(5)
assert isinstance(result, int)
assert result == 5
def test_no_remaining_cycles_returns_input_unchanged(self):
appliance = make_appliance(prediction_hours=24, duration_h=2, num_cycles=1)
appliance.completed_cycles = 1 # nothing left to schedule
result = appliance.set_starting_time(7)
assert result == 7
assert (appliance.load_curve == 0).all()
# ---------------------------------------------------------------------------
# Load curve utilities
# ---------------------------------------------------------------------------
@@ -459,7 +203,7 @@ class TestRunInProgress:
SLOT0 = "2026-11-14T01:00:00+01:00"
def pinned(self, started: str, now: str, slot0: str = SLOT0, **overrides) -> HomeAppliance:
def pinned(self, started: str, now: str, slot0: str = SLOT0, **overrides) -> GeneticHomeAppliance:
appliance = make_appliance(
prediction_hours=overrides.pop("prediction_hours", 6),
run_started_datetime=started,
@@ -488,8 +232,8 @@ class TestRunInProgress:
load_profile_interval_seconds=900,
run_started_datetime="2026-11-14T00:00:00+01:00",
)
appliance = HomeAppliance(
parameters=params, optimization_hours=4, prediction_hours=16, slot_duration_h=0.25
appliance = GeneticHomeAppliance(
parameters=params.to_parameters(), optimization_hours=4, prediction_hours=16, slot_duration_h=0.25
)
appliance.pin_run_in_progress(
to_datetime("2026-11-14T00:15:00+01:00"), to_datetime("2026-11-14T00:20:00+01:00")