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
@@ -156,6 +156,18 @@ class HomeApplianceParameters(DeviceParameters):
completed_cycles: int = Field(
default=0, ge=0, description="Cycles already completed on the first planning day."
)
run_started_datetime: Optional[DateTime] = Field(
default=None,
json_schema_extra={
"description": (
"Start of the run in progress, None when the appliance is not "
"running. The run is kept until the device reports it as finished: "
"its remaining load is fixed from now on, independent of windows, "
"deadline and gene, and it is not counted in 'completed_cycles' yet."
),
"examples": [None, "2026-11-14T00:47:45+01:00"],
},
)
min_cycle_gap_h: int = Field(
default=0,
@@ -263,7 +275,9 @@ class HomeApplianceParameters(DeviceParameters):
},
)
@field_validator("earliest_start_datetime", "deadline_datetime", mode="before")
@field_validator(
"earliest_start_datetime", "deadline_datetime", "run_started_datetime", mode="before"
)
@classmethod
def transform_to_datetime(cls, value: Any) -> Optional[DateTime]:
"""Accept the usual date time representations, naive input is local time."""
@@ -304,6 +318,10 @@ class HomeAppliance:
repair algorithm.
"""
# A run in progress whose start is more than this many run durations ago
# is taken as a stale report (the executor stopped updating it).
STALE_RUN_FACTOR: float = 2.0
def __init__(
self,
parameters: HomeApplianceParameters,
@@ -347,6 +365,14 @@ class HomeAppliance:
self.load_curve = np.zeros(prediction_hours)
# Run in progress, set by pin_run_in_progress(): its remaining energy
# per slot from now, the first slot after it, and its start/end.
self.pinned_load: np.ndarray = np.zeros(prediction_hours)
self.pinned_end_slot: int = 0
self.pinned_start_datetime: Optional[DateTime] = None
self.pinned_end_datetime: Optional[DateTime] = None
self.pinned_run_date: Any = None
# Start times for remaining cycles, in chronological order.
self.start_hours: list[int] = []
@@ -392,6 +418,108 @@ class HomeAppliance:
power, float(input_interval), float(self.slot_interval_seconds)
)
self.run_slots: int = int(len(self.run_energy_wh))
# The profile itself, for the remainder of a run in progress.
self.run_power_w: list[float] = power
self.run_power_interval_seconds: float = float(input_interval)
self.run_duration_seconds: float = len(power) * float(input_interval)
def pin_run_in_progress(self, slot0_datetime: DateTime, observation_datetime: DateTime) -> None:
"""Fix the remainder of the run in progress as load from now on.
A run in progress (``run_started_datetime``) is kept until the device
reports it as finished. Its remaining energy is placed from the
observation time on, independent of windows, deadline and genes. A run
past its configured duration still runs: slot 0 stays occupied without
extra energy. A start older than ``STALE_RUN_FACTOR`` run durations is
taken as a stale report and ignored.
Args:
slot0_datetime: Local, timezone-aware datetime of slot index 0.
observation_datetime: Moment of the optimization run (within slot 0).
"""
self.pinned_load = np.zeros(self.prediction_hours)
self.pinned_end_slot = 0
self.pinned_start_datetime = None
self.pinned_end_datetime = None
self.pinned_run_date = None
started = self.parameters.run_started_datetime
if started is None or self.prediction_hours <= 0:
return
timezone = slot0_datetime.timezone
if timezone is None:
raise ValueError("The optimization slot origin must have a timezone.")
started = started.in_timezone(timezone)
now = observation_datetime.in_timezone(timezone)
elapsed = (now - started).total_seconds()
if elapsed < 0 or elapsed > self.STALE_RUN_FACTOR * self.run_duration_seconds:
logger.error(
"Home appliance '{}': run start {} is not plausible at {} "
"(run duration {} s); planned as not running.",
self.device_id,
started,
now,
self.run_duration_seconds,
)
return
slot_seconds = self.slot_interval_seconds
now_offset = (now - slot0_datetime).total_seconds()
start_offset = (started - slot0_datetime).total_seconds()
end_offset = start_offset + self.run_duration_seconds
for index, power in enumerate(self.run_power_w):
segment_start = max(start_offset + index * self.run_power_interval_seconds, now_offset)
segment_end = start_offset + (index + 1) * self.run_power_interval_seconds
while power > 0 and segment_start < segment_end:
slot = int(segment_start // slot_seconds)
if slot >= self.prediction_hours:
break
part_end = min(segment_end, (slot + 1) * slot_seconds)
self.pinned_load[slot] += power * (part_end - segment_start) / 3600.0
segment_start = part_end
# Slot 0 stays occupied while the device runs, even past its duration.
self.pinned_end_slot = min(
self.prediction_hours,
max(1, math.ceil(end_offset / slot_seconds - 1e-9)),
)
self.pinned_start_datetime = started
self.pinned_end_datetime = max(started.add(seconds=self.run_duration_seconds), now)
self.pinned_run_date = started.date()
if elapsed >= self.run_duration_seconds:
logger.info(
"Home appliance '{}': run started {} is past its duration of {} s "
"and still running; kept until the device reports it finished.",
self.device_id,
started,
self.run_duration_seconds,
)
@property
def run_in_progress(self) -> bool:
"""bool: Whether a run in progress is pinned."""
return self.pinned_start_datetime is not None
def next_cycle_earliest_slot(self) -> int:
"""Earliest slot for the next cycle: after a pinned run and its gap."""
if not self.run_in_progress:
return 0
return self.pinned_end_slot + math.ceil(self.min_cycle_gap_h / self.slot_duration_h)
def completed_cycles_on(self, first_date: Any) -> int:
"""Cycles counted as done on the first planning day, incl. a pinned run.
Args:
first_date: Local date of slot 0.
Returns:
``completed_cycles`` plus one when a run in progress belongs to that
day (DAILY) or to the horizon (ONCE), capped to ``num_cycles``.
"""
pinned = 0
if self.run_in_progress and (
self.schedule_mode == ConsumerScheduleMode.ONCE or self.pinned_run_date == first_date
):
pinned = 1
return min(self.num_cycles, self.completed_cycles + pinned)
def _slot_offset(self, moment: DateTime, slot0_datetime: DateTime, *, round_up: bool) -> int:
"""Convert an absolute moment into a slot index relative to slot 0.
@@ -620,7 +748,8 @@ class HomeAppliance:
Without a deadline nothing can be missed. With one, a consumer that was
not scheduled at all, or whose run ends after the deadline (a relaxed
BEST_EFFORT deadline), counts as missed.
BEST_EFFORT deadline), counts as missed. A run in progress counts with
its expected end.
Args:
starts: Absolute start slots of the scheduled runs.
@@ -631,13 +760,16 @@ class HomeAppliance:
"""
if self.deadline_datetime is None:
return False
if not starts:
return True
timezone = slot0_datetime.timezone
if timezone is None:
raise ValueError("The optimization slot origin must have a timezone.")
ends = [self.run_end_datetime(start, slot0_datetime) for start in starts]
if self.pinned_end_datetime is not None:
ends.append(self.pinned_end_datetime)
if not ends:
return True
deadline = self.deadline_datetime.in_timezone(timezone)
return any(self.run_end_datetime(start, slot0_datetime) > deadline for start in starts)
return any(end > deadline for end in ends)
def build_load_curve(self, starts: list[int]) -> None:
"""Place the resampled run energy at each decoded start slot.
@@ -878,7 +1010,7 @@ class HomeAppliance:
if self.num_remaining_cycles == 0:
self.start_hours = []
self.reset_load_curve()
self._build_load_curve()
return []
max_start = max(
@@ -1058,8 +1190,10 @@ class HomeAppliance:
# ------------------------------------------------------------------
def _build_load_curve(self) -> None:
"""Builds the load curve from all scheduled cycles."""
"""Builds the load curve from all scheduled cycles and a pinned run."""
self.reset_load_curve()
if self.run_in_progress:
self.load_curve += self.pinned_load
for start in self.start_hours:
length = min(self.run_slots, self.total_slots - start)
@@ -202,6 +202,24 @@ class HomeApplianceCommonSettings(DevicesBaseSettings):
],
},
)
run_started_measurement_key: Optional[str] = Field(
default=None,
json_schema_extra={
"description": (
"Measurement store key holding the start of the run in progress as "
"UNIX time in seconds, 0 when no run is in progress. The executor "
"sets it when it switches the appliance on for a planned run and "
"sets 0 when the device reports the run as finished (then it also "
"increments the completed cycles). The GENETIC optimizer keeps a "
"run in progress until then. Defaults to "
"'{device_id}.run_started_at' when null."
),
"examples": ["dishwasher.run_started_at", None],
"x-scope": [
str(ConfigScope.GENETIC),
],
},
)
@model_validator(mode="before")
@classmethod
@@ -402,4 +420,7 @@ class HomeApplianceCommonSettings(DevicesBaseSettings):
@property
def measurement_keys(self) -> Optional[list[str]]:
"""Measurement keys for the home appliance stati that are measurements."""
return [self.cycles_completed_measurement_key or f"{self.device_id}.cycles_completed"]
return [
self.cycles_completed_measurement_key or f"{self.device_id}.cycles_completed",
self.run_started_measurement_key or f"{self.device_id}.run_started_at",
]
@@ -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."
)
},
)