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
+49 -40
View File
@@ -5,13 +5,22 @@ import pytest
from pydantic import ValidationError
from akkudoktoreos.devices.devices import BatteriesCommonSettings
from akkudoktoreos.devices.genetic.battery import (
Battery,
ElectricVehicleParameters,
SolarPanelBatteryParameters,
)
from akkudoktoreos.devices.settings.batterysettings import BatteryProfileAdjustment
from akkudoktoreos.optimization.genetic import geneticprepare
from akkudoktoreos.optimization.genetic0 import genetic0prepare
from akkudoktoreos.optimization.genetic.devices.geneticbattery import (
GeneticBattery,
)
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticBatteryRequest,
GeneticElectricVehicleRequest,
)
# GENETIC's conversions of the battery settings, in its parameter preparation.
CONVERSIONS = {
"to_genetic_pv_bat_param": "battery_request",
"to_genetic_ev_bat_param": "electric_vehicle_request",
}
@pytest.fixture
@@ -26,7 +35,7 @@ def setup_pv_battery():
max_charge_power_w=8000
hours=24
params = SolarPanelBatteryParameters(
params = GeneticBatteryRequest(
device_id=device_id,
capacity_wh=capacity_wh,
initial_soc_percentage=initial_soc_percentage,
@@ -37,8 +46,8 @@ def setup_pv_battery():
max_charge_power_w=max_charge_power_w,
hours=hours,
)
battery = Battery(
params,
battery = GeneticBattery(
params.to_parameters(),
prediction_hours=48,
)
battery.reset()
@@ -122,13 +131,13 @@ def test_battery_discharge_when_empty(setup_pv_battery):
def test_discharge_preserves_energy_at_or_below_min_soc(
slot_duration_h, initial_soc, requested_wh
):
battery = Battery(
SolarPanelBatteryParameters(
battery = GeneticBattery(
GeneticBatteryRequest(
device_id="battery1",
capacity_wh=26_400,
initial_soc_percentage=initial_soc,
min_soc_percentage=6,
),
).to_parameters(),
prediction_hours=2,
slot_duration_h=slot_duration_h,
)
@@ -278,11 +287,11 @@ def test_charge_energy_with_charge_factor(setup_pv_battery, wh, charge_factor, e
@pytest.fixture
def setup_car_battery():
from akkudoktoreos.optimization.genetic.geneticparams import (
ElectricVehicleParameters,
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticElectricVehicleRequest,
)
params = ElectricVehicleParameters(
params = GeneticElectricVehicleRequest(
device_id="ev1",
capacity_wh=40000,
initial_soc_percentage=60,
@@ -291,8 +300,8 @@ def setup_car_battery():
max_charge_power_w=7000,
hours=24,
)
battery = Battery(
params,
battery = GeneticBattery(
params.to_parameters(),
prediction_hours=48,
)
battery.reset()
@@ -332,7 +341,7 @@ def test_car_and_pv_battery_discharge_and_max_charge_power(setup_pv_battery, set
def test_quarter_hour_charge_calls_share_one_power_budget():
params = SolarPanelBatteryParameters(
params = GeneticBatteryRequest(
device_id="battery1",
capacity_wh=10_000,
initial_soc_percentage=0,
@@ -342,7 +351,7 @@ def test_quarter_hour_charge_calls_share_one_power_budget():
charging_efficiency=1.0,
discharging_efficiency=1.0,
)
battery = Battery(params, prediction_hours=4, slot_duration_h=0.25)
battery = GeneticBattery(params.to_parameters(), prediction_hours=4, slot_duration_h=0.25)
battery.set_charge_per_hour(np.ones(4))
first_stored, _ = battery.charge_energy(200.0, 0)
@@ -354,7 +363,7 @@ def test_quarter_hour_charge_calls_share_one_power_budget():
def test_quarter_hour_discharge_calls_share_one_power_budget():
params = SolarPanelBatteryParameters(
params = GeneticBatteryRequest(
device_id="battery1",
capacity_wh=10_000,
initial_soc_percentage=100,
@@ -364,7 +373,7 @@ def test_quarter_hour_discharge_calls_share_one_power_budget():
charging_efficiency=1.0,
discharging_efficiency=1.0,
)
battery = Battery(params, prediction_hours=4, slot_duration_h=0.25)
battery = GeneticBattery(params.to_parameters(), prediction_hours=4, slot_duration_h=0.25)
battery.set_discharge_per_hour(np.ones(4))
first_delivered, _ = battery.discharge_energy(200.0, 0)
@@ -425,12 +434,12 @@ def test_pv_converter_preserves_id_lcos_charge_and_export_rates():
levelized_cost_of_storage_amt_kwh=0.123,
)
assert isinstance(BatteriesCommonSettings.validate_and_sort_charge_rates(None), np.ndarray)
parameters = settings.to_genetic_pv_bat_param()
parameters = geneticprepare.battery_request(settings)
assert parameters.device_id == "house"
assert parameters.charge_rates == [0.0, 0.5, 1.0]
assert parameters.grid_export_rates == [0.25, 1.0]
assert parameters.levelized_cost_of_storage_kwh == pytest.approx(0.123)
battery = Battery(parameters, prediction_hours=4, slot_duration_h=0.25)
battery = GeneticBattery(parameters.to_parameters(), prediction_hours=4, slot_duration_h=0.25)
assert battery.levelized_cost_of_storage_kwh == pytest.approx(0.123)
@@ -439,7 +448,7 @@ def test_equal_soc_limits_are_valid(target):
settings = BatteriesCommonSettings(device_id="ev", min_soc_percentage=target,
max_soc_percentage=target,
profile_adjustment=BatteryProfileAdjustment(nominal_capacity_wh=8000))
assert settings.to_genetic_ev_bat_param().min_soc_percentage == target
assert geneticprepare.electric_vehicle_request(settings).min_soc_percentage == target
assert genetic0prepare.electric_vehicle_request(settings).min_soc_percentage == target
@@ -456,9 +465,9 @@ def test_full_target_charges_to_capacity_without_overcharge():
nominal_capacity_wh=1000, max_charge_power_w=1000
),
min_soc_percentage=100, max_soc_percentage=100)
params = settings.to_genetic_ev_bat_param()
params = geneticprepare.electric_vehicle_request(settings)
params.initial_soc_percentage = 70
battery = Battery(params, prediction_hours=4, slot_duration_h=0.25)
battery = GeneticBattery(params.to_parameters(), prediction_hours=4, slot_duration_h=0.25)
battery.charge_array = np.ones(4)
for slot in range(4):
battery.charge_energy(wh=1000, hour=slot)
@@ -470,14 +479,14 @@ def test_full_target_charges_to_capacity_without_overcharge():
_EV_CHARGE_RATES = [0.0] + [amps / 16 for amps in range(6, 17)]
def _minimum_current_battery(kind=ElectricVehicleParameters, soc=99, maximum=100):
def _minimum_current_battery(kind=GeneticElectricVehicleRequest, soc=99, maximum=100):
parameters = kind(
device_id="ev-test", capacity_wh=60000,
initial_soc_percentage=int(soc), charging_efficiency=0.95,
discharging_efficiency=1.0, max_charge_power_w=11040,
max_soc_percentage=maximum, charge_rates=_EV_CHARGE_RATES,
)
value = Battery(parameters, prediction_hours=4, slot_duration_h=0.25)
value = GeneticBattery(parameters.to_parameters(), prediction_hours=4, slot_duration_h=0.25)
value.reset()
value.soc_wh = soc / 100 * value.capacity_wh
value.charge_array = np.full(4, 0.375)
@@ -514,7 +523,7 @@ class TestEVMinimumCurrent(unittest.TestCase):
self.assertAlmostEqual(value.soc_wh, 60000 * 0.96)
def test_stationary_battery_keeps_discrete_rate_behavior(self):
value = _minimum_current_battery(SolarPanelBatteryParameters, soc=99)
value = _minimum_current_battery(GeneticBatteryRequest, soc=99)
self.assertEqual(value.charge_energy(None, 0, charge_factor=0.375), (0.0, 0.0))
self.assertEqual(value.soc_wh, 59400)
self.assertEqual(value.charge_array[0], 0)
@@ -538,7 +547,7 @@ class TestMaxDischargePower:
@staticmethod
def _battery(max_discharge_power_w=None, slot_duration_h=1.0):
params = SolarPanelBatteryParameters(
params = GeneticBatteryRequest(
device_id="battery1",
capacity_wh=10_000,
initial_soc_percentage=100,
@@ -548,7 +557,7 @@ class TestMaxDischargePower:
charging_efficiency=1.0,
discharging_efficiency=1.0,
)
battery = Battery(params, prediction_hours=4, slot_duration_h=slot_duration_h)
battery = GeneticBattery(params.to_parameters(), prediction_hours=4, slot_duration_h=slot_duration_h)
battery.set_discharge_per_hour(np.ones(4))
return battery
@@ -584,7 +593,7 @@ class TestMaxDischargePower:
def test_negative_is_rejected(self):
with pytest.raises(ValidationError):
SolarPanelBatteryParameters(
GeneticBatteryRequest(
device_id="battery1", capacity_wh=10_000, max_discharge_power_w=-1
)
@@ -598,7 +607,7 @@ class TestMaxDischargePower:
settings = BatteriesCommonSettings(
device_id="battery1", profile_adjustment=BatteryProfileAdjustment(nominal_capacity_wh=8_000)
)
parameters = getattr(settings, converter)()
parameters = getattr(geneticprepare, CONVERSIONS[converter])(settings)
assert parameters.max_charge_power_w == pytest.approx(5_000.0)
assert parameters.max_discharge_power_w == pytest.approx(4_000.0)
@@ -611,7 +620,7 @@ class TestMaxDischargePower:
nominal_capacity_wh=8_000, max_charge_power_w=10_000, max_discharge_power_w=10_000
),
)
parameters = getattr(settings, converter)()
parameters = getattr(geneticprepare, CONVERSIONS[converter])(settings)
assert parameters.max_charge_power_w == pytest.approx(8_000.0)
assert parameters.max_discharge_power_w == pytest.approx(4_000.0)
@@ -621,7 +630,7 @@ class TestPowerCurves:
@staticmethod
def _battery(soc_percentage=50, slot_duration_h=1.0, **curves):
params = SolarPanelBatteryParameters(
params = GeneticBatteryRequest(
device_id="battery1",
capacity_wh=10_000,
initial_soc_percentage=soc_percentage,
@@ -633,7 +642,7 @@ class TestPowerCurves:
discharging_efficiency=1.0,
**curves,
)
battery = Battery(params, prediction_hours=4, slot_duration_h=slot_duration_h)
battery = GeneticBattery(params.to_parameters(), prediction_hours=4, slot_duration_h=slot_duration_h)
battery.set_charge_per_hour(np.ones(4))
battery.set_discharge_per_hour(np.ones(4))
return battery
@@ -760,7 +769,7 @@ class TestPowerCurves:
)
def test_invalid_curves_are_rejected(self, field, value):
with pytest.raises(ValidationError):
SolarPanelBatteryParameters(device_id="battery1", capacity_wh=10_000, **{field: value})
GeneticBatteryRequest(device_id="battery1", capacity_wh=10_000, **{field: value})
class TestFirstSlotFraction:
@@ -768,7 +777,7 @@ class TestFirstSlotFraction:
@staticmethod
def _battery(first_slot_fraction=1.0, soc=50, **curves):
params = SolarPanelBatteryParameters(
params = GeneticBatteryRequest(
device_id="battery1",
capacity_wh=40_000,
initial_soc_percentage=soc,
@@ -780,8 +789,8 @@ class TestFirstSlotFraction:
discharging_efficiency=1.0,
**curves,
)
battery = Battery(
params, prediction_hours=4, slot_duration_h=1.0, first_slot_fraction=first_slot_fraction
battery = GeneticBattery(
params.to_parameters(), prediction_hours=4, slot_duration_h=1.0, first_slot_fraction=first_slot_fraction
)
battery.set_charge_per_hour(np.ones(4))
battery.set_discharge_per_hour(np.ones(4))
@@ -810,7 +819,7 @@ class TestFirstSlotFraction:
def test_full_fraction_is_the_plain_slot(self):
partial = self._battery(first_slot_fraction=1.0)
plain = Battery(partial.parameters, prediction_hours=4, slot_duration_h=1.0)
plain = GeneticBattery(partial.parameters, prediction_hours=4, slot_duration_h=1.0)
plain.set_charge_per_hour(np.ones(4))
assert partial.charge_energy(None, 0, charge_factor=1.0) == plain.charge_energy(
None, 0, charge_factor=1.0