fix(genetic): include DAILY appliance load in tail and terminal value

With terminal_value_mode AUTO, the tail and the continuation curve only
saw the base load: appliance load is added to consumption inside
simulate() but never reached either curve. Stored battery energy was
therefore valued at 0 ct/kWh over a wide SoC range, and the optimizer
drained the battery to run scheduled appliances instead of using cheap
night grid energy.

Both curves now include the expected load of DAILY home appliances: one
run per local day and cycle at its earliest allowed start within its
window, with the minimum cycle gap. Days whose run is already planned in
the control horizon are not counted again in the tail. ONCE appliances
are left out.

Squashed from PR #1540 (6 commits) onto main e40ff7f.

Closes: #1495
Signed-off-by: SchaafAlexander <86607129+SchaafAlexander@users.noreply.github.com>
This commit is contained in:
ChenYi-Nnergy
2026-11-15 15:10:57 +01:00
committed by Bobby Noelte
parent ebb440238a
commit a344e04ca5
2 changed files with 215 additions and 2 deletions
@@ -1341,6 +1341,84 @@ class GeneticOptimization(OptimizationBase):
) )
logger.warning(self._forecast_reason) logger.warning(self._forecast_reason)
def _estimated_daily_appliance_load(
self, start_slot: int, end_slot: int, skip_planned_days: bool = False
) -> np.ndarray:
"""Expected per-slot load of DAILY home appliances over a slot range.
DAILY appliances repeat once per local calendar day, so their load is
part of the demand beyond the control horizon even though the optimizer
never schedules it there. Each (day, cycle) run is placed at its
earliest allowed start inside its time window; cycles of one appliance
on one day keep their configured minimum gap. ONCE appliances have no
recurring schedule and are left out (see #1495).
Args:
start_slot: First slot of the estimated range (absolute slot index).
end_slot: Exclusive end slot of the estimated range.
skip_planned_days: Leave out local days whose run is already
scheduled in the control horizon, so a day that straddles the
control end is not counted twice.
Returns:
Per-slot appliance load [Wh] over ``[start_slot, end_slot)``.
"""
estimate = np.zeros(max(end_slot - start_slot, 0), dtype=float)
slot0 = self._slot0_datetime
if slot0 is None or start_slot >= end_slot:
return estimate
slot_seconds = self.slot_duration_h * 3600
first_date = slot0.date()
for appliance in self.simulation.home_appliances or []:
if appliance.schedule_mode != ConsumerScheduleMode.DAILY:
continue
# The configured appliance only spans the control horizon, so its
# window logic cannot see the tail. Query a throwaway copy sized to
# the estimated range instead; it shares the same parameters, so the
# time windows, earliest start and deadline bounds all still apply.
probe = HomeAppliance(
parameters=appliance.parameters,
optimization_hours=self._genetic_cfg.horizon_hours,
prediction_hours=end_slot,
slot_duration_h=self.slot_duration_h,
)
by_date: dict[Any, dict[int, list[int]]] = {}
for cycle in range(appliance.num_cycles):
allowed = probe.allowed_start_slots(
slot0_datetime=slot0,
earliest_slot=start_slot,
horizon_end_slot=end_slot,
cycle_index=cycle,
)
for slot in allowed:
date = slot0.add(seconds=slot * slot_seconds).date()
if date == first_date and cycle < appliance.completed_cycles:
continue
by_date.setdefault(date, {}).setdefault(cycle, []).append(slot)
if skip_planned_days and self.appliance_layout is not None:
planned = {
gene.run_date
for gene in self.appliance_layout.genes
if gene.device_id == appliance.device_id
}
by_date = {d: c for d, c in by_date.items() if d not in planned}
gap_slots = appliance.run_slots + math.ceil(
appliance.min_cycle_gap_h / self.slot_duration_h
)
for cycle_slots in by_date.values():
earliest = start_slot
for cycle in sorted(cycle_slots, key=lambda c: cycle_slots[c][0]):
starts = [slot for slot in cycle_slots[cycle] if slot >= earliest]
if not starts:
continue
start = starts[0]
run_end = min(start + appliance.run_slots, end_slot)
estimate[start - start_slot : run_end - start_slot] += appliance.run_energy_wh[
: run_end - start
]
earliest = start + gap_slots
return estimate
def _build_terminal_value_curve( def _build_terminal_value_curve(
self, self,
battery: Optional[Battery], battery: Optional[Battery],
@@ -1382,11 +1460,19 @@ class GeneticOptimization(OptimizationBase):
window_slots = max(int(window_hours) * self.slots_per_hour, 1) window_slots = max(int(window_hours) * self.slots_per_hour, 1)
end_slot = self.control_end_slot + getattr(self, "_effective_tail_slots", 0) end_slot = self.control_end_slot + getattr(self, "_effective_tail_slots", 0)
# DAILY home appliances keep running after the horizon: their expected
# load is part of the demand the tail and the continuation curve
# evaluate (#1495). Without it the tail sees the base load only and
# values stored energy at 0 ct/kWh over a wide SoC range.
base_window = trailing_window(self.simulation.load_energy_array, end_slot, window_slots)
appliance_window = self._estimated_daily_appliance_load(
end_slot - len(base_window), end_slot
)
curve = build_terminal_value_curve( curve = build_terminal_value_curve(
prices_euro_per_wh=trailing_window( prices_euro_per_wh=trailing_window(
self.simulation.elect_price_hourly, end_slot, window_slots self.simulation.elect_price_hourly, end_slot, window_slots
), ),
load_wh=trailing_window(self.simulation.load_energy_array, end_slot, window_slots), load_wh=base_window + appliance_window,
pv_wh=trailing_window(self.simulation.pv_prediction_wh, end_slot, window_slots), pv_wh=trailing_window(self.simulation.pv_prediction_wh, end_slot, window_slots),
feed_in_euro_per_wh=trailing_window( feed_in_euro_per_wh=trailing_window(
self.simulation.elect_revenue_per_hour_arr, end_slot, window_slots self.simulation.elect_revenue_per_hour_arr, end_slot, window_slots
@@ -1435,7 +1521,10 @@ class GeneticOptimization(OptimizationBase):
battery=battery, battery=battery,
inverter=inverter, inverter=inverter,
prices_euro_per_wh=prices[tail], prices_euro_per_wh=prices[tail],
load_wh=loads[tail], load_wh=loads[tail]
+ self._estimated_daily_appliance_load(
self.control_end_slot, end_slot, skip_planned_days=True
),
pv_wh=pv[tail], pv_wh=pv[tail],
feed_in_euro_per_wh=tariffs[tail], feed_in_euro_per_wh=tariffs[tail],
continuation=curve, continuation=curve,
+124
View File
@@ -9,6 +9,7 @@ import pytest
from akkudoktoreos.config.config import SettingsEOSDefaults from akkudoktoreos.config.config import SettingsEOSDefaults
from akkudoktoreos.core.coreabc import get_ems from akkudoktoreos.core.coreabc import get_ems
from akkudoktoreos.devices.genetic.battery import Battery, SolarPanelBatteryParameters from akkudoktoreos.devices.genetic.battery import Battery, SolarPanelBatteryParameters
from akkudoktoreos.devices.genetic.homeappliance import HomeApplianceParameters
from akkudoktoreos.devices.genetic.inverter import Inverter, InverterParameters from akkudoktoreos.devices.genetic.inverter import Inverter, InverterParameters
from akkudoktoreos.optimization.genetic.forecast import bounded_forecast_array from akkudoktoreos.optimization.genetic.forecast import bounded_forecast_array
from akkudoktoreos.optimization.genetic.genetic import GeneticOptimization from akkudoktoreos.optimization.genetic.genetic import GeneticOptimization
@@ -436,3 +437,126 @@ def test_short_prediction_horizon_shortens_the_tail(config_eos):
assert result.terminal_value.mode == "TAIL" assert result.terminal_value.mode == "TAIL"
assert result.terminal_value.requested_tail_hours == 48 assert result.terminal_value.requested_tail_hours == 48
assert result.terminal_value.effective_tail_hours == 12 assert result.terminal_value.effective_tail_hours == 12
def test_daily_appliance_load_values_stored_energy_in_tail(config_eos):
"""#1495: a DAILY appliance's expected load belongs to the tail demand.
With a flat 20 ct/kWh import price, zero base load, no PV and no feed-in
value, stored energy is worth exactly 0 ct/kWh without the appliance. The
same run with a DAILY water heater (6 kWh every night) must value the
15-50 % SoC range at the import price instead.
"""
def run(with_appliance: bool):
opt, params = setup_run(config_eos, hours=72)
config_eos.feedintariff.direct_marketing_enabled = False
params.ems.feed_in_tariff_per_wh = [0.0] * 72
if with_appliance:
params.home_appliances = [
HomeApplianceParameters.model_validate(
dict(
device_id="water_heater",
consumption_wh=6000,
duration_h=3,
num_cycles=1,
schedule_mode="DAILY",
time_windows={
"windows": [{"start_time": "00:00", "duration": "5 hours", "value": 0}]
},
)
)
]
def choose(*args, **kwargs):
genome = opt.create_individual()
genome[:] = [0] * len(genome)
return genome, {}
with patch.object(opt, "optimize", side_effect=choose):
return opt.optimize_ems(params)
plain = run(with_appliance=False)
assert plain.terminal_value.mode == "TAIL"
assert plain.terminal_value.curve is not None
assert plain.terminal_value.curve.value(500) == pytest.approx(0.0)
with_appliance = run(with_appliance=True)
assert with_appliance.terminal_value.mode == "TAIL"
curve = with_appliance.terminal_value.curve
assert curve is not None
# The tail value includes the unavoidable cost of serving the tail load,
# so the absolute level is negative; what the optimizer acts on is the
# value of stored energy relative to an empty battery. 500 Wh of stored
# energy serves 500 Wh of night appliance load at 20 ct.
assert curve.value(500) - curve.value(0) == pytest.approx(0.10, abs=0.005)
# The 15-50 % SoC band (150-500 Wh of a 1000 Wh battery) is no longer 0.
marginals = [
marginal
for energy, marginal in zip(curve.energy_wh, curve.marginal_euro_per_kwh)
if 150 <= energy <= 500
]
assert marginals
assert all(marginal == pytest.approx(0.2, abs=0.01) for marginal in marginals)
@pytest.mark.parametrize(
"start_hour,window_start,window_duration,duration_h",
[
(15, "14:00", "4 hours", 1), # control ends inside the afternoon window
(2, "00:00", "5 hours", 2), # control ends inside the night window
],
)
def test_daily_appliance_day_planned_in_control_is_not_counted_again_in_tail(
config_eos, start_hour, window_start, window_duration, duration_h
):
"""#1495: a day whose run is already scheduled in control is not repeated in the tail.
When the control horizon ends inside an appliance window, the optimizer
schedules that day's run before the control end. The tail must only add
the following days, otherwise the day's energy is counted twice.
"""
opt, params = setup_run(config_eos, start_hour=start_hour, hours=72 + start_hour)
params.home_appliances = [
HomeApplianceParameters.model_validate(
dict(
device_id="water_heater",
consumption_wh=3000,
duration_h=duration_h,
num_cycles=1,
schedule_mode="DAILY",
time_windows={
"windows": [
{"start_time": window_start, "duration": window_duration, "value": 0}
]
},
)
)
]
def choose(*args, **kwargs):
genome = opt.create_individual()
genome[:] = [0] * len(genome)
return genome, {}
with (
patch.object(opt, "optimize", side_effect=choose),
patch(
"akkudoktoreos.optimization.genetic.genetic.build_tail_value_curve",
wraps=build_tail_value_curve,
) as builder,
):
opt.optimize_ems(params)
planned_days = {gene.run_date for gene in opt.appliance_layout.genes}
tail_load = builder.call_args.kwargs["load_wh"]
slot0 = opt._slot0_datetime
tail_days = {
slot0.add(hours=opt.control_end_slot + index).date()
for index, energy in enumerate(tail_load)
if energy > 0
}
assert tail_days
assert not planned_days & tail_days
# Base load is zero: the tail holds exactly one 3 kWh run per remaining day.
assert float(np.sum(tail_load)) == pytest.approx(3000 * len(tail_days))