fix(genetic): keep a started home appliance run until the device reports it finished

A re-plan treated a running home appliance as not started. In its start
slot it could pick another start of equal cost and switch the appliance
off; after the start slot it could only plan a new complete run later; and
when no complete run fitted into the rest of the window, the DAILY cycle
was dropped and the running appliance got OFF.

The executor now reports the start of a planned run as UNIX seconds under
`<device_id>.run_started_at` (setting `run_started_measurement_key`) and 0
when the device reports the run as finished. The device decides when that
is, also before or after the configured duration. Until then the GENETIC
optimizer places the remaining energy from now on as fixed load,
independent of windows, deadline and genes, sends RUN, counts the run as a
cycle of its start day and plans further cycles after its end and gap. A
run past its duration keeps the current slot without extra energy; a start
more than two run durations ago, or an invalid value, is logged and
ignored.

Refs: #1548
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 13:54:22 +01:00
committed by Bobby Noelte
co-authored by Claude Opus 5.5
parent 0bf9f50b97
commit 4693e1fa97
13 changed files with 676 additions and 21 deletions
@@ -25,7 +25,10 @@ from akkudoktoreos.optimization.genetic.geneticparams import (
GeneticEnergyManagementParameters,
GeneticOptimizationParameters,
)
from akkudoktoreos.utils.datetimeutil import DateTime, to_duration
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime, to_duration
# How far back the latest "run started" report of a home appliance is looked up.
RUN_STARTED_LOOKBACK_HOURS = 48
class RuntimeForecasts(GeneticParametersBaseModel):
@@ -72,6 +75,60 @@ class ConfigOptimizationRequest(
"""Parse a previous-plan timestamp while retaining its explicit timezone."""
return GeneticOptimizationParameters.transform_start_solution_datetime(value)
async def _run_started(self, device: Any, observation_time: DateTime) -> Optional[DateTime]:
"""Start of the appliance's run in progress from its measurement, or None.
The latest report at or before the observation time holds the run start
as UNIX seconds, 0 when the device reported the run as finished. An
invalid report is logged and treated as no run in progress, so the
preparation never fails on it.
Args:
device: Home appliance settings.
observation_time: Moment of the optimization run.
Returns:
The run start, or None when no run is in progress.
"""
key = device.run_started_measurement_key or f"{device.device_id}.run_started_at"
try:
dates, values = await self.measurement.key_to_lists(
key=key,
start_datetime=observation_time.subtract(hours=RUN_STARTED_LOOKBACK_HOURS),
end_datetime=observation_time.add(seconds=1),
dropna=False,
)
except KeyError:
return None
# Skip records without a value (e.g. an adapter's meter reading, #1447).
samples = [
(date, value)
for date, value in zip(dates, values)
if date.timestamp() <= observation_time.timestamp()
and value is not None
and value is not pd.NA
]
if not samples:
return None
value = max(samples, key=lambda sample: sample[0].timestamp())[1]
try:
seconds = float(value)
except (TypeError, ValueError):
seconds = math.nan
if seconds == 0:
return None
if not math.isfinite(seconds) or seconds < 0 or seconds > observation_time.timestamp():
logger.error(
"Invalid run start {!r} in '{}' for home appliance '{}'; planned as not running.",
value,
key,
device.device_id,
)
return None
started = to_datetime(seconds)
timezone = observation_time.timezone
return started.in_timezone(timezone) if timezone is not None else started
async def resolve(self) -> GeneticOptimizationParameters:
"""Resolve inside the EMS lock after its slot start has been established."""
config = self.config
@@ -256,6 +313,8 @@ class ConfigOptimizationRequest(
):
raise ValueError(f"Invalid completed cycle count for {device.device_id}.")
appliance.completed_cycles = int(count)
for device, appliance in zip(groups["home_appliances"], appliances):
appliance.run_started_datetime = await self._run_started(device, observation_time)
origin = start.start_of("day")
if config.prediction.hours is None or config.prediction.hours <= 0:
@@ -1578,12 +1578,16 @@ class GeneticOptimization(OptimizationBase):
first_date = slot0_datetime.date()
for appliance_index, appliance in enumerate(appliances):
cycles = range(appliance.num_cycles)
# A run in progress counts as done for its day and delays the next
# cycle until after its end and the minimum gap.
completed_cycles = appliance.completed_cycles_on(first_date)
earliest_slot = max(start_slot, appliance.next_cycle_earliest_slot())
allowed_by_cycle: dict[int, list[int]] = {}
relaxed_by_cycle: dict[int, bool] = {}
for cycle in cycles:
allowed_by_cycle[cycle] = appliance.allowed_start_slots(
slot0_datetime=slot0_datetime,
earliest_slot=start_slot,
earliest_slot=earliest_slot,
horizon_end_slot=horizon_end_slot,
cycle_index=cycle,
)
@@ -1592,7 +1596,7 @@ class GeneticOptimization(OptimizationBase):
groups = [
(None, cycle, allowed_by_cycle[cycle])
for cycle in cycles
if cycle >= appliance.completed_cycles
if cycle >= completed_cycles
]
else:
by_date: dict[Any, dict[int, list[int]]] = {}
@@ -1601,7 +1605,7 @@ class GeneticOptimization(OptimizationBase):
date = slot0_datetime.add(
seconds=slot * appliance.slot_interval_seconds
).date()
if date == first_date and cycle < appliance.completed_cycles:
if date == first_date and cycle < completed_cycles:
continue
by_date.setdefault(date, {}).setdefault(cycle, []).append(slot)
groups = [
@@ -1613,9 +1617,7 @@ class GeneticOptimization(OptimizationBase):
# later complete planning days must retain all configured cycles.
for date, cycle_slots in by_date.items():
expected = {
cycle
for cycle in cycles
if date != first_date or cycle >= appliance.completed_cycles
cycle for cycle in cycles if date != first_date or cycle >= completed_cycles
}
if set(cycle_slots) != expected:
raise ValueError(
@@ -4370,6 +4372,10 @@ class GeneticOptimization(OptimizationBase):
)
for appliance_params in home_appliance_params
]
# A run in progress keeps running until the device reports it as
# finished; its remainder is fixed load, not a gene.
for appliance in home_appliances:
appliance.pin_run_in_progress(self._slot0_datetime, self.ems.observation_datetime)
self.appliance_layout = self._build_appliance_layout(home_appliances, self._slot0_datetime)
# EV charging deadline (departure). Resolved once per run; the seeding
@@ -4488,7 +4494,8 @@ class GeneticOptimization(OptimizationBase):
home_appliance_energy_wh[device_id] = appliance.get_load_curve()[start_slot:].tolist()
starts = sorted(starts_per_appliance.get(appliance_index, []))
home_appliance_running[device_id] = [
any(run_start <= slot < run_start + appliance.run_slots for run_start in starts)
slot < appliance.pinned_end_slot
or any(run_start <= slot < run_start + appliance.run_slots for run_start in starts)
for slot in range(self.control_slots)
]
appliance_starts[device_id] = [
@@ -4497,6 +4504,10 @@ class GeneticOptimization(OptimizationBase):
).in_timezone(timezone)
for start in starts
]
if appliance.pinned_start_datetime is not None:
appliance_starts[device_id].insert(
0, appliance.pinned_start_datetime.in_timezone(timezone)
)
# Report a deadline that could not be kept (no run scheduled at all,
# or a run that ends late because a BEST_EFFORT deadline was dropped)
# so the caller can warn instead of silently trusting the schedule.
@@ -454,7 +454,8 @@ class GeneticSolution(ConfigMixin, GeneticParametersBaseModel):
default_factory=dict,
json_schema_extra={
"description": (
"Scheduled run start times per appliance device_id as absolute local datetimes."
"Scheduled run start times per appliance device_id as absolute local datetimes. "
"A run in progress is listed first with its actual (past) start."
)
},
)