fix(genetic): plan the running slot only for the remaining time

A run within a slot (e.g. 10:45 with hourly slots) planned slot 0 as a
full slot, although the SoC is measured at the run time. Slot 0 now moves
only the remaining part of the slot energy: battery, EV and inverter
energy caps, SoC power limit tables and the slot's PV and load forecast
are scaled by first_slot_fraction; efficiency curves are read at the
power of that part. The plan's SoC headroom clamp of the AC charge factor
uses the same part, and the GENETIC result reports first_slot_fraction.
A run on a slot boundary is unchanged.

Additional changes
Pin GENETIC test start times to the full hour; their results now depend on seconds within the slot
Document first_slot_fraction for consumers of GENETIC results

Refs: #1543
Signed-off-by: SchaafAlexander <86607129+SchaafAlexander@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Assisted-by: Claude Code (claude-opus-5-5)
This commit is contained in:
SchaafAlexander
2026-11-15 12:45:56 +01:00
committed by Bobby Noelte
co-authored by Claude Opus 5.5
parent 7e10f64048
commit 0bf9f50b97
15 changed files with 495 additions and 60 deletions
+85
View File
@@ -760,3 +760,88 @@ 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})
class TestFirstSlotFraction:
"""A run within slot 0 simulates only the remaining part of that slot."""
@staticmethod
def _battery(first_slot_fraction=1.0, soc=50, **curves):
params = SolarPanelBatteryParameters(
device_id="battery1",
capacity_wh=40_000,
initial_soc_percentage=soc,
min_soc_percentage=0,
max_soc_percentage=100,
max_charge_power_w=8_000,
max_discharge_power_w=4_000,
charging_efficiency=1.0,
discharging_efficiency=1.0,
**curves,
)
battery = Battery(
params, 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))
return battery
def test_slot_0_charges_only_the_remaining_part(self):
battery = self._battery(first_slot_fraction=0.25)
stored, _ = battery.charge_energy(None, 0, charge_factor=1.0)
assert stored == pytest.approx(2_000.0)
# Mode 1 (a PV surplus) is capped the same way.
assert battery.charge_energy(5_000.0, 0) == pytest.approx((0.0, 0.0))
# Slot 1 is a full slot again.
stored, _ = battery.charge_energy(None, 1, charge_factor=1.0)
assert stored == pytest.approx(8_000.0)
def test_slot_0_discharges_only_the_remaining_part(self):
battery = self._battery(first_slot_fraction=0.25)
assert battery.remaining_discharge_energy_wh(0) == pytest.approx(1_000.0)
assert battery.rated_discharge_energy_wh(0) == pytest.approx(1_000.0)
assert battery.rated_discharge_energy_wh(1) == pytest.approx(4_000.0)
assert battery.rated_discharge_energy_wh() == pytest.approx(4_000.0)
delivered, _ = battery.discharge_energy(9_000.0, 0)
assert delivered == pytest.approx(1_000.0)
delivered, _ = battery.discharge_energy(9_000.0, 1)
assert delivered == pytest.approx(4_000.0)
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.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
)
def test_soc_power_limit_scales_with_the_remaining_part(self):
battery = self._battery(
first_slot_fraction=0.5,
charge_power_limit_w_by_soc=[6_000.0] * 101,
discharge_power_limit_w_by_soc=[2_000.0] * 101,
)
stored, _ = battery.charge_energy(None, 0, charge_factor=1.0)
assert stored == pytest.approx(3_000.0)
delivered, _ = battery.discharge_energy(9_000.0, 0)
assert delivered == pytest.approx(1_000.0)
def test_efficiency_curve_is_read_at_the_power_not_the_energy(self):
"""Full power for 15 min has the efficiency of full power, not of 25 %."""
curve = [(0.0, 0.95), (0.25, 0.95), (1.0, 0.80)]
battery = self._battery(
first_slot_fraction=0.25,
charging_efficiency_curve=curve,
discharging_efficiency_curve=curve,
)
stored, losses = battery.charge_energy(None, 0, charge_factor=1.0)
assert stored + losses == pytest.approx(2_000.0)
assert stored == pytest.approx(2_000.0 * 0.80)
delivered, losses = battery.discharge_energy(9_000.0, 0)
assert delivered + losses == pytest.approx(1_000.0)
assert delivered == pytest.approx(1_000.0 * 0.80)
@pytest.mark.parametrize("fraction", [0.0, -0.1, 1.5])
def test_invalid_fraction_is_rejected(self, fraction):
with pytest.raises(ValueError, match="first_slot_fraction"):
self._battery(first_slot_fraction=fraction)
+3 -3
View File
@@ -510,7 +510,7 @@ def _full_charge_parameters(hours: int, **battery_extra) -> GeneticOptimizationP
def test_full_charge_slot_resolution(config_eos: ConfigEOS):
_optimizer_config(config_eos, 24)
ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0))
ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0, second=0, microsecond=0))
optimization = GeneticOptimization(fixed_seed=1)
optimization._slot0_datetime = optimization.ems.start_datetime
slot0 = optimization._slot0_datetime
@@ -530,7 +530,7 @@ def test_full_charge_slot_resolution(config_eos: ConfigEOS):
def test_maximum_soc_before_deadline_counts(config_eos: ConfigEOS):
_optimizer_config(config_eos, 24)
ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0))
ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0, second=0, microsecond=0))
optimization = GeneticOptimization(fixed_seed=1)
optimization.simulation.battery = MagicMock(spec=Battery)
optimization.simulation.battery.current_soc_percentage.return_value = 40.0
@@ -555,7 +555,7 @@ def test_maximum_soc_before_deadline_counts(config_eos: ConfigEOS):
def _run(config_eos: ConfigEOS, **battery_extra) -> list[float]:
hours = 24
_optimizer_config(config_eos, hours)
ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0))
ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0, second=0, microsecond=0))
CacheEnergyManagementStore().clear()
solution = GeneticOptimization(fixed_seed=42).optimize_ems(
parameters=_full_charge_parameters(hours, **battery_extra), start_hour=0, ngen=40
+5 -5
View File
@@ -90,7 +90,7 @@ def test_grid_export_rates_reach_the_solution(config_eos: ConfigEOS):
},
}
)
ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0))
ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0, second=0, microsecond=0))
CacheEnergyManagementStore().clear()
hours = 24
@@ -172,7 +172,7 @@ def test_ev_deadline_slot_resolution(config_eos: ConfigEOS):
},
}
)
ems_eos.set_start_datetime(to_datetime().set(hour=10, minute=0))
ems_eos.set_start_datetime(to_datetime().set(hour=10, minute=0, second=0, microsecond=0))
optimization = GeneticOptimization(fixed_seed=1)
optimization._slot0_datetime = optimization.ems.start_datetime
slot0 = optimization._slot0_datetime
@@ -213,7 +213,7 @@ def test_ev_soc_penalty_reads_the_deadline_slot(config_eos: ConfigEOS):
},
}
)
ems_eos.set_start_datetime(to_datetime().set(hour=10, minute=0))
ems_eos.set_start_datetime(to_datetime().set(hour=10, minute=0, second=0, microsecond=0))
optimization = GeneticOptimization(fixed_seed=1)
simulation_result = {"EAuto_SoC_pro_Stunde": [20.0, 35.0, 50.0, 80.0]}
@@ -250,7 +250,7 @@ def test_ev_deadline_charges_before_departure(config_eos: ConfigEOS):
},
}
)
ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0))
ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0, second=0, microsecond=0))
CacheEnergyManagementStore().clear()
parameters = _ev_deadline_parameters(hours, min_soc_max_duration_h=6)
@@ -289,7 +289,7 @@ def _terminal_value_run(
},
}
)
ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0))
ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0, second=0, microsecond=0))
CacheEnergyManagementStore().clear()
if prices is None:
+116
View File
@@ -163,3 +163,119 @@ def test_snapshot_and_warm_start_preserve_aware_instants(
assert restored.start_solution_datetime is not None
assert restored.start_solution_datetime.timestamp() == expected.timestamp()
assert restored.start_solution_datetime.utcoffset() == expected.utcoffset()
def _partial_first_slot_run(config_eos, timestamp: str, initial_soc_percentage: int = 20):
"""Run GENETIC with AC charge at full power in slot 0 only.
1 h slots, 2 h control horizon, no tail. Battery 10 kWh (at 20 % unless
given), 2000 W charge power, ideal efficiencies; base load 400 Wh per hour,
no PV.
"""
config_eos.merge_settings_from_dict(
{
"general": {"latitude": 52.52, "longitude": 13.405},
"prediction": {"hours": 24},
"optimization": {
"genetic": {
"interval_sec": 3600,
"horizon_hours": 2,
"tail_horizon_hours": 0,
"terminal_value_mode": "FIXED",
}
},
}
)
start = to_datetime(timestamp).in_timezone("Europe/Berlin")
get_ems(init=True).set_start_datetime(start)
count = start.hour + 2
parameters = GeneticOptimizationParameters.model_validate(
{
"ems": {
"pv_forecast_wh": [0.0] * count,
"total_load": [400.0] * count,
"electricity_price_per_wh": [0.0001] * count,
"feed_in_tariff_per_wh": 0.0,
"price_per_wh_battery": 0.0,
},
"pv_battery": {
"device_id": "battery1",
"capacity_wh": 10000,
"initial_soc_percentage": initial_soc_percentage,
"min_soc_percentage": 0,
"max_soc_percentage": 100,
"max_charge_power_w": 2000,
"charging_efficiency": 1.0,
"discharging_efficiency": 1.0,
},
"inverter": {
"device_id": "inverter1",
"battery_id": "battery1",
"max_power_wh": 5000,
"ac_to_dc_efficiency": 1.0,
"dc_to_ac_efficiency": 1.0,
},
"ev": None,
}
)
optimizer = GeneticOptimization(fixed_seed=42)
def full_ac_charge_in_first_slot(*args, **kwargs):
genome = optimizer.create_individual()
genome[:] = [0] * len(genome)
genome[0] = 3 * len(optimizer.bat_possible_charge_values) - 1
return genome, {}
with patch.object(optimizer, "optimize", side_effect=full_ac_charge_in_first_slot):
solution = optimizer.optimize_ems(parameters)
return optimizer, solution
def test_running_slot_is_planned_for_the_remaining_time_only(config_eos):
"""A run at 10:45 has 15 min of slot 0 left, not a full hour.
Charge power, load and grid energy of slot 0 shrink to a quarter; slot 1
is a full slot again.
"""
optimizer, solution = _partial_first_slot_run(config_eos, "2026-09-16T10:45:00+02:00")
assert optimizer.first_slot_fraction == pytest.approx(0.25)
assert solution.first_slot_fraction == pytest.approx(0.25)
result = solution.result
# Slot 0: 15 min of 400 W base load and 2000 W charge power. The load of
# the result includes the AC charge energy.
assert result.grid_consumption_wh_per_hour[0] == pytest.approx(100.0 + 500.0)
assert result.load_wh_per_hour[0] == pytest.approx(100.0 + 500.0)
# SoC at the start of each slot: 500 Wh stored in 15 min, 20 % -> 25 %.
assert result.battery_soc_per_hour[:2] == pytest.approx([20.0, 25.0])
# Slot 1 is a full slot again.
assert result.grid_consumption_wh_per_hour[1] == pytest.approx(400.0)
def test_run_on_a_slot_boundary_plans_a_full_first_slot(config_eos):
"""A run exactly at the start of the slot keeps the full slot."""
optimizer, solution = _partial_first_slot_run(config_eos, "2026-09-16T10:00:00+02:00")
assert optimizer.first_slot_fraction == pytest.approx(1.0)
assert solution.first_slot_fraction == pytest.approx(1.0)
result = solution.result
assert result.grid_consumption_wh_per_hour[0] == pytest.approx(400.0 + 2000.0)
assert result.battery_soc_per_hour[:2] == pytest.approx([20.0, 40.0])
def test_running_slot_ac_charge_factor_is_not_cut_for_a_full_slot(config_eos):
"""The plan clamps the AC charge factor to the headroom of the remaining time.
At 90 % there are 1000 Wh of headroom. A full hour at 2000 W would exceed it
and the factor would be cut to 0.5; the 15 min left store only 500 Wh, so
full power is sent for the running slot.
"""
_, solution = _partial_first_slot_run(
config_eos, "2026-09-16T10:45:00+02:00", initial_soc_percentage=90
)
assert solution.result.battery_soc_per_hour[:2] == pytest.approx([90.0, 95.0])
plan = solution.energy_management_plan()
battery_instructions = [
instruction for instruction in plan.instructions if instruction.resource_id == "battery1"
]
assert battery_instructions[0].operation_mode_factor == pytest.approx(1.0)
+1 -1
View File
@@ -46,7 +46,7 @@ def _setup(config_eos: ConfigEOS, horizon_hours: int) -> GeneticOptimizationPara
},
}
)
ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0))
ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0, second=0, microsecond=0))
CacheEnergyManagementStore().clear()
return GeneticOptimizationParameters.model_validate(
dict(
+1 -1
View File
@@ -34,7 +34,7 @@ def _configure_hourly_grid(config_eos: ConfigEOS) -> None:
},
}
)
get_ems(init=True).set_start_datetime(to_datetime().set(hour=0, minute=0))
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():
+74
View File
@@ -541,3 +541,77 @@ def test_battery_discharge_limit_caps_load_and_grid_export():
assert initial_soc_wh - battery.soc_wh == pytest.approx(1000.0)
assert grid_import == pytest.approx(500.0)
assert grid_export == 0.0
class TestFirstSlotFraction:
"""A run within slot 0 simulates only the remaining part of that slot."""
@staticmethod
def _inverter(first_slot_fraction=0.25, battery=None, **parameters):
predictor = Mock()
predictor.calculate_expected_direct_consumption.side_effect = min
with patch(
"akkudoktoreos.devices.genetic.inverter.get_eos_load_interpolator",
return_value=predictor,
):
inverter = Inverter(
InverterParameters(
device_id="inverter1",
max_power_wh=4000.0,
battery_id=battery.parameters.device_id if battery else None,
**parameters,
),
battery=battery,
first_slot_fraction=first_slot_fraction,
)
return inverter, predictor
def test_slot_0_moves_only_the_remaining_part(self):
inverter, _ = self._inverter()
grid_export, _, losses, _ = inverter.process_energy(5000.0, 0.0, hour=0)
assert grid_export == pytest.approx(1000.0)
assert losses == pytest.approx(4000.0)
grid_export, _, losses, _ = inverter.process_energy(5000.0, 0.0, hour=1)
assert grid_export == pytest.approx(4000.0)
assert losses == pytest.approx(1000.0)
def test_self_consumption_table_gets_the_power_of_the_remaining_part(self):
"""250 Wh in 15 min is 1000 W, not 250 W."""
inverter, predictor = self._inverter()
inverter.process_energy(500.0, 250.0, hour=0)
predictor.calculate_expected_direct_consumption.assert_called_with(1000.0, 2000.0)
def test_efficiency_curve_is_read_at_the_power_of_the_remaining_part(self):
inverter, _ = self._inverter(
dc_to_ac_efficiency_curve=[(0.0, 0.97), (0.25, 0.97), (1.0, 0.90)]
)
# 1000 Wh in 15 min is the full 4000 W.
assert inverter.dc_to_ac_efficiency_at(1000.0, 0.25) == pytest.approx(0.90)
assert inverter.dc_to_ac_efficiency_at(1000.0) == pytest.approx(0.97)
def test_ac_charge_in_slot_0_uses_the_remaining_part(self):
battery = Battery(
SolarPanelBatteryParameters(
device_id="battery1",
capacity_wh=40_000,
initial_soc_percentage=0,
min_soc_percentage=0,
max_charge_power_w=8_000,
charging_efficiency=1.0,
),
prediction_hours=2,
first_slot_fraction=0.25,
)
battery.set_charge_per_hour(np.ones(2))
inverter, _ = self._inverter(
battery=battery, ac_to_dc_efficiency=1.0, ac_charge_limits_total_charge=True
)
inverter.begin_ac_charge_slot(0, 0.5)
ac_wh, _ = inverter.charge_battery_from_grid(0, 0.5)
# Half the charge power for 15 min.
assert ac_wh == pytest.approx(1000.0)
@pytest.mark.parametrize("fraction", [0.0, 1.01])
def test_invalid_fraction_is_rejected(self, fraction):
with pytest.raises(ValueError, match="first_slot_fraction"):
self._inverter(first_slot_fraction=fraction)
+1 -1
View File
@@ -74,7 +74,7 @@ def _parameters(
},
}
)
ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0))
ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0, second=0, microsecond=0))
CacheEnergyManagementStore().clear()
return GeneticOptimizationParameters.model_validate(
dict(
+1 -1
View File
@@ -30,7 +30,7 @@ def _configure_hourly_grid(config_eos: ConfigEOS, *, start_hour: int = 0) -> Non
},
}
)
get_ems(init=True).set_start_datetime(to_datetime().set(hour=start_hour, minute=0))
get_ems(init=True).set_start_datetime(to_datetime().set(hour=start_hour, minute=0, second=0, microsecond=0))
def test_ev_repair_is_resimulated_before_fitness_assignment(config_eos: ConfigEOS):