mirror of
https://github.com/Akkudoktor-EOS/EOS.git
synced 2026-11-25 15:06:20 +01:00
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:
committed by
Bobby Noelte
co-authored by
Claude Opus 5.5
parent
0bf9f50b97
commit
4693e1fa97
@@ -129,6 +129,7 @@ config path from ``self.device_id`` without needing an external index.
|
|||||||
"cycle_time_windows": null,
|
"cycle_time_windows": null,
|
||||||
"min_cycle_gap_h": 0,
|
"min_cycle_gap_h": 0,
|
||||||
"cycles_completed_measurement_key": null,
|
"cycles_completed_measurement_key": null,
|
||||||
|
"run_started_measurement_key": null,
|
||||||
"load_profile_power_w": null,
|
"load_profile_power_w": null,
|
||||||
"load_profile_interval_seconds": null,
|
"load_profile_interval_seconds": null,
|
||||||
"schedule_mode": "ONCE",
|
"schedule_mode": "ONCE",
|
||||||
@@ -303,6 +304,7 @@ config path from ``self.device_id`` without needing an external index.
|
|||||||
"cycle_time_windows": null,
|
"cycle_time_windows": null,
|
||||||
"min_cycle_gap_h": 0,
|
"min_cycle_gap_h": 0,
|
||||||
"cycles_completed_measurement_key": null,
|
"cycles_completed_measurement_key": null,
|
||||||
|
"run_started_measurement_key": null,
|
||||||
"load_profile_power_w": null,
|
"load_profile_power_w": null,
|
||||||
"load_profile_interval_seconds": null,
|
"load_profile_interval_seconds": null,
|
||||||
"schedule_mode": "ONCE",
|
"schedule_mode": "ONCE",
|
||||||
@@ -312,7 +314,8 @@ config path from ``self.device_id`` without needing an external index.
|
|||||||
"deadline_policy": "BEST_EFFORT",
|
"deadline_policy": "BEST_EFFORT",
|
||||||
"effective_num_cycles": 1,
|
"effective_num_cycles": 1,
|
||||||
"measurement_keys": [
|
"measurement_keys": [
|
||||||
"dishwasher.cycles_completed"
|
"dishwasher.cycles_completed",
|
||||||
|
"dishwasher.run_started_at"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -334,7 +337,8 @@ config path from ``self.device_id`` without needing an external index.
|
|||||||
"ev0-power-l2-w",
|
"ev0-power-l2-w",
|
||||||
"ev0-power-l3-w",
|
"ev0-power-l3-w",
|
||||||
"ev0-power-3-phase-sym-w",
|
"ev0-power-3-phase-sym-w",
|
||||||
"dishwasher.cycles_completed"
|
"dishwasher.cycles_completed",
|
||||||
|
"dishwasher.run_started_at"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -133,6 +133,7 @@
|
|||||||
"cycle_time_windows": null,
|
"cycle_time_windows": null,
|
||||||
"min_cycle_gap_h": 0,
|
"min_cycle_gap_h": 0,
|
||||||
"cycles_completed_measurement_key": null,
|
"cycles_completed_measurement_key": null,
|
||||||
|
"run_started_measurement_key": null,
|
||||||
"load_profile_power_w": null,
|
"load_profile_power_w": null,
|
||||||
"load_profile_interval_seconds": null,
|
"load_profile_interval_seconds": null,
|
||||||
"schedule_mode": "ONCE",
|
"schedule_mode": "ONCE",
|
||||||
|
|||||||
@@ -512,6 +512,22 @@ the measurement store, under the key configured in `cycles_completed_measurement
|
|||||||
to `{device_id}.cycles_completed`). This lets the optimizer skip cycles the appliance has already
|
to `{device_id}.cycles_completed`). This lets the optimizer skip cycles the appliance has already
|
||||||
completed earlier the same day.
|
completed earlier the same day.
|
||||||
|
|
||||||
|
A run that has started is kept until the device reports it as finished. The executor writes the
|
||||||
|
start of the run as UNIX time in seconds to the key configured in `run_started_measurement_key`
|
||||||
|
(defaults to `{device_id}.run_started_at`) when it switches the appliance on for a planned run.
|
||||||
|
When the device reports the run as finished, the executor writes `0` and increments the completed
|
||||||
|
cycles. The device decides when that is: a water heater may finish early because its thermostat
|
||||||
|
reached the temperature, a dishwasher may run longer than its profile. Until then, every re-plan:
|
||||||
|
|
||||||
|
- places the remaining energy of the run from now on, independent of time windows and deadline,
|
||||||
|
- sends RUN for the appliance and does not move or stop the run,
|
||||||
|
- counts the run as a cycle of its start day and plans further cycles after its end and
|
||||||
|
`min_cycle_gap_h`.
|
||||||
|
|
||||||
|
A run past its configured duration keeps the current slot without extra energy. A start more than
|
||||||
|
two run durations ago is taken as a stale report and ignored, as are invalid values; both are
|
||||||
|
logged.
|
||||||
|
|
||||||
:::{admonition} Note
|
:::{admonition} Note
|
||||||
:class: note
|
:class: note
|
||||||
Unlike GENETIC0, the GENETIC algorithm can plan multiple cycles -- and therefore multiple starts
|
Unlike GENETIC0, the GENETIC algorithm can plan multiple cycles -- and therefore multiple starts
|
||||||
|
|||||||
@@ -96,6 +96,10 @@ time, charging power and supported charge rates.
|
|||||||
slots). The energies, costs and SoC change of that slot cover only that part, and its
|
slots). The energies, costs and SoC change of that slot cover only that part, and its
|
||||||
charge/discharge factors are the power for the remaining time. A run on a slot
|
charge/discharge factors are the power for the remaining time. A run on a slot
|
||||||
boundary plans a full first slot (`first_slot_fraction` 1.0).
|
boundary plans a full first slot (`first_slot_fraction` 1.0).
|
||||||
|
- Executors of household appliances should report a started run: write its start (UNIX
|
||||||
|
seconds) to `<device_id>.run_started_at` when switching the appliance on, and `0` when
|
||||||
|
the device reports it finished. Without it, a re-plan may move or stop a running
|
||||||
|
appliance.
|
||||||
- Runtime purchase and sale prices are **currency per Wh**: 0.30 EUR/kWh is 0.00030 EUR/Wh.
|
- Runtime purchase and sale prices are **currency per Wh**: 0.30 EUR/kWh is 0.00030 EUR/Wh.
|
||||||
Provider power forecasts are converted by EOS; do not convert them a second time.
|
Provider power forecasts are converted by EOS; do not convert them a second time.
|
||||||
- Read returned timestamps and interval information instead of assuming 24 hourly values
|
- Read returned timestamps and interval information instead of assuming 24 hourly values
|
||||||
|
|||||||
@@ -59,6 +59,8 @@ Request SoC values are integer percentages. Without an override, the measurement
|
|||||||
key `<device_id>-soc-factor` must contain a recent factor from 0 to 1. Invalid,
|
key `<device_id>-soc-factor` must contain a recent factor from 0 to 1. Invalid,
|
||||||
future or stale measurements never become an assumed zero SoC. Completed appliance
|
future or stale measurements never become an assumed zero SoC. Completed appliance
|
||||||
cycles use their configured measurement key, default `<device_id>.cycles_completed`.
|
cycles use their configured measurement key, default `<device_id>.cycles_completed`.
|
||||||
|
The start of a run in progress (UNIX seconds, `0` when finished) uses
|
||||||
|
`<device_id>.run_started_at`; such a run is kept until the device reports it finished.
|
||||||
|
|
||||||
Optional forecast arrays begin at local midnight, with one value per configured
|
Optional forecast arrays begin at local midnight, with one value per configured
|
||||||
slot: `pv_forecast_wh` and `total_load` are Wh per slot; `electricity_price_per_wh`
|
slot: `pv_forecast_wh` and `total_load` are Wh per slot; `electricity_price_per_wh`
|
||||||
|
|||||||
+56
-1
@@ -11044,7 +11044,7 @@
|
|||||||
},
|
},
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"title": "Appliance Starts",
|
"title": "Appliance Starts",
|
||||||
"description": "Scheduled run start times per appliance device_id as absolute local datetimes."
|
"description": "Scheduled run start times per appliance device_id as absolute local datetimes. A run in progress is listed first with its actual (past) start."
|
||||||
},
|
},
|
||||||
"appliance_deadline_missed": {
|
"appliance_deadline_missed": {
|
||||||
"additionalProperties": {
|
"additionalProperties": {
|
||||||
@@ -11299,6 +11299,25 @@
|
|||||||
"GENETIC"
|
"GENETIC"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
"run_started_measurement_key": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Run Started Measurement Key",
|
||||||
|
"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",
|
||||||
|
null
|
||||||
|
],
|
||||||
|
"x-scope": [
|
||||||
|
"GENETIC"
|
||||||
|
]
|
||||||
|
},
|
||||||
"load_profile_power_w": {
|
"load_profile_power_w": {
|
||||||
"anyOf": [
|
"anyOf": [
|
||||||
{
|
{
|
||||||
@@ -11572,6 +11591,25 @@
|
|||||||
"GENETIC"
|
"GENETIC"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
"run_started_measurement_key": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Run Started Measurement Key",
|
||||||
|
"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",
|
||||||
|
null
|
||||||
|
],
|
||||||
|
"x-scope": [
|
||||||
|
"GENETIC"
|
||||||
|
]
|
||||||
|
},
|
||||||
"load_profile_power_w": {
|
"load_profile_power_w": {
|
||||||
"anyOf": [
|
"anyOf": [
|
||||||
{
|
{
|
||||||
@@ -11810,6 +11848,23 @@
|
|||||||
"description": "Cycles already completed on the first planning day.",
|
"description": "Cycles already completed on the first planning day.",
|
||||||
"default": 0
|
"default": 0
|
||||||
},
|
},
|
||||||
|
"run_started_datetime": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "string",
|
||||||
|
"format": "date-time"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Run Started Datetime",
|
||||||
|
"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": [
|
||||||
|
null,
|
||||||
|
"2026-11-14T00:47:45+01:00"
|
||||||
|
]
|
||||||
|
},
|
||||||
"min_cycle_gap_h": {
|
"min_cycle_gap_h": {
|
||||||
"type": "integer",
|
"type": "integer",
|
||||||
"minimum": 0.0,
|
"minimum": 0.0,
|
||||||
|
|||||||
@@ -156,6 +156,18 @@ class HomeApplianceParameters(DeviceParameters):
|
|||||||
completed_cycles: int = Field(
|
completed_cycles: int = Field(
|
||||||
default=0, ge=0, description="Cycles already completed on the first planning day."
|
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(
|
min_cycle_gap_h: int = Field(
|
||||||
default=0,
|
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
|
@classmethod
|
||||||
def transform_to_datetime(cls, value: Any) -> Optional[DateTime]:
|
def transform_to_datetime(cls, value: Any) -> Optional[DateTime]:
|
||||||
"""Accept the usual date time representations, naive input is local time."""
|
"""Accept the usual date time representations, naive input is local time."""
|
||||||
@@ -304,6 +318,10 @@ class HomeAppliance:
|
|||||||
repair algorithm.
|
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__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
parameters: HomeApplianceParameters,
|
parameters: HomeApplianceParameters,
|
||||||
@@ -347,6 +365,14 @@ class HomeAppliance:
|
|||||||
|
|
||||||
self.load_curve = np.zeros(prediction_hours)
|
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.
|
# Start times for remaining cycles, in chronological order.
|
||||||
self.start_hours: list[int] = []
|
self.start_hours: list[int] = []
|
||||||
|
|
||||||
@@ -392,6 +418,108 @@ class HomeAppliance:
|
|||||||
power, float(input_interval), float(self.slot_interval_seconds)
|
power, float(input_interval), float(self.slot_interval_seconds)
|
||||||
)
|
)
|
||||||
self.run_slots: int = int(len(self.run_energy_wh))
|
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:
|
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.
|
"""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
|
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
|
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:
|
Args:
|
||||||
starts: Absolute start slots of the scheduled runs.
|
starts: Absolute start slots of the scheduled runs.
|
||||||
@@ -631,13 +760,16 @@ class HomeAppliance:
|
|||||||
"""
|
"""
|
||||||
if self.deadline_datetime is None:
|
if self.deadline_datetime is None:
|
||||||
return False
|
return False
|
||||||
if not starts:
|
|
||||||
return True
|
|
||||||
timezone = slot0_datetime.timezone
|
timezone = slot0_datetime.timezone
|
||||||
if timezone is None:
|
if timezone is None:
|
||||||
raise ValueError("The optimization slot origin must have a timezone.")
|
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)
|
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:
|
def build_load_curve(self, starts: list[int]) -> None:
|
||||||
"""Place the resampled run energy at each decoded start slot.
|
"""Place the resampled run energy at each decoded start slot.
|
||||||
@@ -878,7 +1010,7 @@ class HomeAppliance:
|
|||||||
|
|
||||||
if self.num_remaining_cycles == 0:
|
if self.num_remaining_cycles == 0:
|
||||||
self.start_hours = []
|
self.start_hours = []
|
||||||
self.reset_load_curve()
|
self._build_load_curve()
|
||||||
return []
|
return []
|
||||||
|
|
||||||
max_start = max(
|
max_start = max(
|
||||||
@@ -1058,8 +1190,10 @@ class HomeAppliance:
|
|||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
def _build_load_curve(self) -> None:
|
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()
|
self.reset_load_curve()
|
||||||
|
if self.run_in_progress:
|
||||||
|
self.load_curve += self.pinned_load
|
||||||
|
|
||||||
for start in self.start_hours:
|
for start in self.start_hours:
|
||||||
length = min(self.run_slots, self.total_slots - start)
|
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")
|
@model_validator(mode="before")
|
||||||
@classmethod
|
@classmethod
|
||||||
@@ -402,4 +420,7 @@ class HomeApplianceCommonSettings(DevicesBaseSettings):
|
|||||||
@property
|
@property
|
||||||
def measurement_keys(self) -> Optional[list[str]]:
|
def measurement_keys(self) -> Optional[list[str]]:
|
||||||
"""Measurement keys for the home appliance stati that are measurements."""
|
"""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,
|
GeneticEnergyManagementParameters,
|
||||||
GeneticOptimizationParameters,
|
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):
|
class RuntimeForecasts(GeneticParametersBaseModel):
|
||||||
@@ -72,6 +75,60 @@ class ConfigOptimizationRequest(
|
|||||||
"""Parse a previous-plan timestamp while retaining its explicit timezone."""
|
"""Parse a previous-plan timestamp while retaining its explicit timezone."""
|
||||||
return GeneticOptimizationParameters.transform_start_solution_datetime(value)
|
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:
|
async def resolve(self) -> GeneticOptimizationParameters:
|
||||||
"""Resolve inside the EMS lock after its slot start has been established."""
|
"""Resolve inside the EMS lock after its slot start has been established."""
|
||||||
config = self.config
|
config = self.config
|
||||||
@@ -256,6 +313,8 @@ class ConfigOptimizationRequest(
|
|||||||
):
|
):
|
||||||
raise ValueError(f"Invalid completed cycle count for {device.device_id}.")
|
raise ValueError(f"Invalid completed cycle count for {device.device_id}.")
|
||||||
appliance.completed_cycles = int(count)
|
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")
|
origin = start.start_of("day")
|
||||||
if config.prediction.hours is None or config.prediction.hours <= 0:
|
if config.prediction.hours is None or config.prediction.hours <= 0:
|
||||||
|
|||||||
@@ -1578,12 +1578,16 @@ class GeneticOptimization(OptimizationBase):
|
|||||||
first_date = slot0_datetime.date()
|
first_date = slot0_datetime.date()
|
||||||
for appliance_index, appliance in enumerate(appliances):
|
for appliance_index, appliance in enumerate(appliances):
|
||||||
cycles = range(appliance.num_cycles)
|
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]] = {}
|
allowed_by_cycle: dict[int, list[int]] = {}
|
||||||
relaxed_by_cycle: dict[int, bool] = {}
|
relaxed_by_cycle: dict[int, bool] = {}
|
||||||
for cycle in cycles:
|
for cycle in cycles:
|
||||||
allowed_by_cycle[cycle] = appliance.allowed_start_slots(
|
allowed_by_cycle[cycle] = appliance.allowed_start_slots(
|
||||||
slot0_datetime=slot0_datetime,
|
slot0_datetime=slot0_datetime,
|
||||||
earliest_slot=start_slot,
|
earliest_slot=earliest_slot,
|
||||||
horizon_end_slot=horizon_end_slot,
|
horizon_end_slot=horizon_end_slot,
|
||||||
cycle_index=cycle,
|
cycle_index=cycle,
|
||||||
)
|
)
|
||||||
@@ -1592,7 +1596,7 @@ class GeneticOptimization(OptimizationBase):
|
|||||||
groups = [
|
groups = [
|
||||||
(None, cycle, allowed_by_cycle[cycle])
|
(None, cycle, allowed_by_cycle[cycle])
|
||||||
for cycle in cycles
|
for cycle in cycles
|
||||||
if cycle >= appliance.completed_cycles
|
if cycle >= completed_cycles
|
||||||
]
|
]
|
||||||
else:
|
else:
|
||||||
by_date: dict[Any, dict[int, list[int]]] = {}
|
by_date: dict[Any, dict[int, list[int]]] = {}
|
||||||
@@ -1601,7 +1605,7 @@ class GeneticOptimization(OptimizationBase):
|
|||||||
date = slot0_datetime.add(
|
date = slot0_datetime.add(
|
||||||
seconds=slot * appliance.slot_interval_seconds
|
seconds=slot * appliance.slot_interval_seconds
|
||||||
).date()
|
).date()
|
||||||
if date == first_date and cycle < appliance.completed_cycles:
|
if date == first_date and cycle < completed_cycles:
|
||||||
continue
|
continue
|
||||||
by_date.setdefault(date, {}).setdefault(cycle, []).append(slot)
|
by_date.setdefault(date, {}).setdefault(cycle, []).append(slot)
|
||||||
groups = [
|
groups = [
|
||||||
@@ -1613,9 +1617,7 @@ class GeneticOptimization(OptimizationBase):
|
|||||||
# later complete planning days must retain all configured cycles.
|
# later complete planning days must retain all configured cycles.
|
||||||
for date, cycle_slots in by_date.items():
|
for date, cycle_slots in by_date.items():
|
||||||
expected = {
|
expected = {
|
||||||
cycle
|
cycle for cycle in cycles if date != first_date or cycle >= completed_cycles
|
||||||
for cycle in cycles
|
|
||||||
if date != first_date or cycle >= appliance.completed_cycles
|
|
||||||
}
|
}
|
||||||
if set(cycle_slots) != expected:
|
if set(cycle_slots) != expected:
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
@@ -4370,6 +4372,10 @@ class GeneticOptimization(OptimizationBase):
|
|||||||
)
|
)
|
||||||
for appliance_params in home_appliance_params
|
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)
|
self.appliance_layout = self._build_appliance_layout(home_appliances, self._slot0_datetime)
|
||||||
|
|
||||||
# EV charging deadline (departure). Resolved once per run; the seeding
|
# 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()
|
home_appliance_energy_wh[device_id] = appliance.get_load_curve()[start_slot:].tolist()
|
||||||
starts = sorted(starts_per_appliance.get(appliance_index, []))
|
starts = sorted(starts_per_appliance.get(appliance_index, []))
|
||||||
home_appliance_running[device_id] = [
|
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)
|
for slot in range(self.control_slots)
|
||||||
]
|
]
|
||||||
appliance_starts[device_id] = [
|
appliance_starts[device_id] = [
|
||||||
@@ -4497,6 +4504,10 @@ class GeneticOptimization(OptimizationBase):
|
|||||||
).in_timezone(timezone)
|
).in_timezone(timezone)
|
||||||
for start in starts
|
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,
|
# 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)
|
# or a run that ends late because a BEST_EFFORT deadline was dropped)
|
||||||
# so the caller can warn instead of silently trusting the schedule.
|
# so the caller can warn instead of silently trusting the schedule.
|
||||||
|
|||||||
@@ -455,6 +455,7 @@ class GeneticSolution(ConfigMixin, GeneticParametersBaseModel):
|
|||||||
json_schema_extra={
|
json_schema_extra={
|
||||||
"description": (
|
"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."
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -466,3 +466,232 @@ async def test_meter_only_record_does_not_hide_completed_cycles(
|
|||||||
).resolve()
|
).resolve()
|
||||||
assert prepared.home_appliances is not None
|
assert prepared.home_appliances is not None
|
||||||
assert prepared.home_appliances[0].completed_cycles == 1
|
assert prepared.home_appliances[0].completed_cycles == 1
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Run in progress (#1548): a started run is kept until the device reports it finished.
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def heater(**kwargs: Any) -> dict[str, Any]:
|
||||||
|
"""Water heater rod: 2 h at 1000 W, DAILY, window 00:00 + 5 h."""
|
||||||
|
return {
|
||||||
|
"device_id": "heater",
|
||||||
|
"consumption_wh": 2000,
|
||||||
|
"duration_h": 2,
|
||||||
|
"schedule_mode": "DAILY",
|
||||||
|
"shared_time_windows": {"windows": [{"start_time": "00:00", "duration": "5 hours"}]},
|
||||||
|
**kwargs,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def replan_at(config: ConfigEOS, moment: str, hours: int = 4) -> None:
|
||||||
|
"""Re-plan at a moment within a slot: slot start rounded down, observation kept."""
|
||||||
|
configure(config, hours=hours)
|
||||||
|
get_ems().set_start_datetime(to_datetime(moment), interval_seconds=900)
|
||||||
|
|
||||||
|
|
||||||
|
def run_zone() -> str:
|
||||||
|
timezone = get_ems().start_datetime.timezone_name
|
||||||
|
assert timezone is not None
|
||||||
|
return timezone
|
||||||
|
|
||||||
|
|
||||||
|
def heater_commands(solution: GeneticSolution) -> list[tuple[int, int, str]]:
|
||||||
|
timezone = run_zone()
|
||||||
|
return [
|
||||||
|
(
|
||||||
|
item.execution_time.in_timezone(timezone).hour,
|
||||||
|
item.execution_time.in_timezone(timezone).minute,
|
||||||
|
str(item.operation_mode_id),
|
||||||
|
)
|
||||||
|
for item in solution.energy_management_plan().instructions
|
||||||
|
if isinstance(item, DDBCInstruction) and item.resource_id == "heater"
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def heater_starts(solution: GeneticSolution) -> list[tuple[int, int]]:
|
||||||
|
timezone = run_zone()
|
||||||
|
return [
|
||||||
|
(moment.in_timezone(timezone).hour, moment.in_timezone(timezone).minute)
|
||||||
|
for moment in solution.appliance_starts["heater"]
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_run_in_progress_continues_after_its_start_slot(config_eos: ConfigEOS) -> None:
|
||||||
|
"""Started 00:47, re-plan 01:05: the run goes on until 02:47, no new start."""
|
||||||
|
replan_at(config_eos, "2026-09-16T01:05:00")
|
||||||
|
consumer = heater(run_started_datetime="2026-09-16T00:47:00")
|
||||||
|
_, solution = run(parameters(consumers=[consumer]))
|
||||||
|
|
||||||
|
assert heater_starts(solution) == [(0, 47)]
|
||||||
|
running = solution.result.home_appliance_running["heater"]
|
||||||
|
assert running[:8] == [True] * 8 and not any(running[8:])
|
||||||
|
assert sum(solution.result.home_appliance_energy_wh["heater"]) == pytest.approx(1700.0)
|
||||||
|
assert heater_commands(solution) == [(1, 0, "RUN"), (3, 0, "OFF")]
|
||||||
|
|
||||||
|
|
||||||
|
def test_run_in_progress_is_not_cut_by_the_window_end(config_eos: ConfigEOS) -> None:
|
||||||
|
"""Started 03:03, re-plan 04:06: no complete run fits before 05:00 any more."""
|
||||||
|
replan_at(config_eos, "2026-09-16T04:06:00")
|
||||||
|
consumer = heater(run_started_datetime="2026-09-16T03:03:00")
|
||||||
|
_, solution = run(parameters(consumers=[consumer]))
|
||||||
|
|
||||||
|
assert heater_starts(solution) == [(3, 3)]
|
||||||
|
assert sum(solution.result.home_appliance_energy_wh["heater"]) == pytest.approx(
|
||||||
|
2000 * 57 / 120
|
||||||
|
)
|
||||||
|
assert heater_commands(solution) == [(4, 0, "RUN"), (5, 15, "OFF")]
|
||||||
|
|
||||||
|
|
||||||
|
def test_run_in_progress_is_kept_by_a_replan_in_its_start_slot(config_eos: ConfigEOS) -> None:
|
||||||
|
"""Started 01:02, re-plan 01:12 with equal prices: still RUN from now."""
|
||||||
|
replan_at(config_eos, "2026-09-16T01:12:00")
|
||||||
|
consumer = heater(run_started_datetime="2026-09-16T01:02:00")
|
||||||
|
_, solution = run(parameters(consumers=[consumer]))
|
||||||
|
|
||||||
|
assert heater_starts(solution) == [(1, 2)]
|
||||||
|
assert heater_commands(solution) == [(1, 0, "RUN"), (3, 15, "OFF")]
|
||||||
|
|
||||||
|
|
||||||
|
def test_run_past_its_duration_runs_until_the_device_reports_finished(
|
||||||
|
config_eos: ConfigEOS,
|
||||||
|
) -> None:
|
||||||
|
"""A run longer than its profile keeps the current slot, without extra energy.
|
||||||
|
|
||||||
|
It is today's cycle, so no second run is planned for today.
|
||||||
|
"""
|
||||||
|
replan_at(config_eos, "2026-09-16T02:35:00")
|
||||||
|
consumer = heater(run_started_datetime="2026-09-16T00:15:00")
|
||||||
|
_, solution = run(parameters(consumers=[consumer]))
|
||||||
|
|
||||||
|
assert heater_starts(solution) == [(0, 15)]
|
||||||
|
assert sum(solution.result.home_appliance_energy_wh["heater"]) == pytest.approx(0.0)
|
||||||
|
assert heater_commands(solution) == [(2, 30, "RUN"), (2, 45, "OFF")]
|
||||||
|
|
||||||
|
|
||||||
|
def test_next_cycle_starts_after_the_run_in_progress_and_its_gap(config_eos: ConfigEOS) -> None:
|
||||||
|
replan_at(config_eos, "2026-09-16T01:05:00", hours=8)
|
||||||
|
consumer = heater(
|
||||||
|
num_cycles=2,
|
||||||
|
min_cycle_gap_h=1,
|
||||||
|
shared_time_windows={"windows": [{"start_time": "00:00", "duration": "9 hours"}]},
|
||||||
|
run_started_datetime="2026-09-16T00:47:00",
|
||||||
|
)
|
||||||
|
_, solution = run(parameters(hours=8, consumers=[consumer]))
|
||||||
|
|
||||||
|
starts = heater_starts(solution)
|
||||||
|
assert starts[0] == (0, 47) and len(starts) == 2
|
||||||
|
# The run ends 02:47 (slot until 03:00), then 1 h gap.
|
||||||
|
assert starts[1] >= (4, 0)
|
||||||
|
assert sum(solution.result.home_appliance_energy_wh["heater"]) == pytest.approx(
|
||||||
|
1700.0 + 2000.0
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_without_a_run_in_progress_the_plan_is_unchanged(config_eos: ConfigEOS) -> None:
|
||||||
|
replan_at(config_eos, "2026-09-16T01:05:00")
|
||||||
|
_, reference = run(parameters(consumers=[heater()]))
|
||||||
|
replan_at(config_eos, "2026-09-16T01:05:00")
|
||||||
|
_, solution = run(parameters(consumers=[heater(run_started_datetime=None)]))
|
||||||
|
|
||||||
|
assert solution.appliance_starts == reference.appliance_starts
|
||||||
|
assert solution.result.home_appliance_running == reference.result.home_appliance_running
|
||||||
|
assert sum(solution.result.home_appliance_energy_wh["heater"]) == pytest.approx(2000.0)
|
||||||
|
|
||||||
|
|
||||||
|
def configure_heater_device(config: ConfigEOS, **kwargs: Any) -> None:
|
||||||
|
config.merge_settings_from_dict(
|
||||||
|
{
|
||||||
|
"devices": {
|
||||||
|
"max_batteries": 0,
|
||||||
|
"batteries": {},
|
||||||
|
"max_electric_vehicles": 0,
|
||||||
|
"electric_vehicles": {},
|
||||||
|
"max_inverters": 1,
|
||||||
|
"inverters": {"inv": {"profile_adjustment": {"nominal_power_w": 10000}}},
|
||||||
|
"max_home_appliances": 1,
|
||||||
|
"home_appliances": {
|
||||||
|
"heater": {
|
||||||
|
"consumption_wh": 2000,
|
||||||
|
"duration_h": 2,
|
||||||
|
"schedule_mode": "DAILY",
|
||||||
|
"time_windows": {
|
||||||
|
"windows": [{"start_time": "00:00", "duration": "5 hours"}]
|
||||||
|
},
|
||||||
|
**kwargs,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def resolve_heater() -> GeneticOptimizationParameters:
|
||||||
|
prepared = await ConfigOptimizationRequest.model_validate(
|
||||||
|
{
|
||||||
|
"forecasts": {
|
||||||
|
"pv_forecast_wh": [0.0] * 24,
|
||||||
|
"total_load": [0.0] * 24,
|
||||||
|
"electricity_price_per_wh": [0.0003] * 24,
|
||||||
|
"feed_in_tariff_per_wh": [0.0001] * 24,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
).resolve()
|
||||||
|
assert prepared.home_appliances is not None
|
||||||
|
return prepared
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
@pytest.mark.parametrize("custom_key", [None, "heater.on_since"])
|
||||||
|
async def test_measured_run_start_reaches_request_and_plan(
|
||||||
|
config_eos: ConfigEOS, custom_key: str | None, isolated_measurement: Measurement
|
||||||
|
) -> None:
|
||||||
|
replan_at(config_eos, "2026-09-16T01:05:00")
|
||||||
|
configure_heater_device(config_eos, run_started_measurement_key=custom_key)
|
||||||
|
key = custom_key or "heater.run_started_at"
|
||||||
|
assert key in config_eos.devices.measurement_keys
|
||||||
|
started = to_datetime("2026-09-16T00:47:00")
|
||||||
|
# Like a pusher that stamps its rows at the slot start: the value carries the start.
|
||||||
|
await isolated_measurement.update_value(
|
||||||
|
get_ems().start_datetime, key, float(started.timestamp())
|
||||||
|
)
|
||||||
|
|
||||||
|
prepared = await resolve_heater()
|
||||||
|
assert prepared.home_appliances is not None
|
||||||
|
assert prepared.home_appliances[0].run_started_datetime == started
|
||||||
|
_, solution = run(prepared)
|
||||||
|
assert heater_starts(solution) == [(0, 47)]
|
||||||
|
assert heater_commands(solution)[0] == (1, 0, "RUN")
|
||||||
|
|
||||||
|
# The device reports the run finished: no run in progress any more.
|
||||||
|
await isolated_measurement.update_value(
|
||||||
|
get_ems().observation_datetime.subtract(seconds=10), key, 0.0
|
||||||
|
)
|
||||||
|
prepared = await resolve_heater()
|
||||||
|
assert prepared.home_appliances is not None
|
||||||
|
assert prepared.home_appliances[0].run_started_datetime is None
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
@pytest.mark.parametrize("value", [float("nan"), -5.0, "future"])
|
||||||
|
async def test_invalid_run_start_is_logged_and_ignored(
|
||||||
|
config_eos: ConfigEOS,
|
||||||
|
isolated_measurement: Measurement,
|
||||||
|
caplog: pytest.LogCaptureFixture,
|
||||||
|
value: Any,
|
||||||
|
) -> None:
|
||||||
|
replan_at(config_eos, "2026-09-16T01:05:00")
|
||||||
|
configure_heater_device(config_eos)
|
||||||
|
if value == "future":
|
||||||
|
value = float(get_ems().observation_datetime.add(minutes=10).timestamp())
|
||||||
|
await isolated_measurement.update_value(
|
||||||
|
get_ems().start_datetime, "heater.run_started_at", value
|
||||||
|
)
|
||||||
|
|
||||||
|
with caplog.at_level("ERROR"):
|
||||||
|
prepared = await resolve_heater()
|
||||||
|
|
||||||
|
assert prepared.home_appliances is not None
|
||||||
|
assert prepared.home_appliances[0].run_started_datetime is None
|
||||||
|
assert "Invalid run start" in caplog.text
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ from akkudoktoreos.devices.genetic.homeappliance import (
|
|||||||
HomeAppliance,
|
HomeAppliance,
|
||||||
HomeApplianceParameters,
|
HomeApplianceParameters,
|
||||||
)
|
)
|
||||||
from akkudoktoreos.utils.datetimeutil import to_duration, to_time
|
from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration, to_time
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# Fixtures / factories
|
# Fixtures / factories
|
||||||
@@ -448,3 +448,121 @@ class TestLoadCurve:
|
|||||||
appliance = make_appliance(prediction_hours=6)
|
appliance = make_appliance(prediction_hours=6)
|
||||||
with pytest.raises(ValueError):
|
with pytest.raises(ValueError):
|
||||||
appliance.get_load_for_hour(hour)
|
appliance.get_load_for_hour(hour)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Run in progress (#1548)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
class TestRunInProgress:
|
||||||
|
"""A started run is kept: its remainder is fixed load from the observation on."""
|
||||||
|
|
||||||
|
SLOT0 = "2026-11-14T01:00:00+01:00"
|
||||||
|
|
||||||
|
def pinned(self, started: str, now: str, **overrides) -> HomeAppliance:
|
||||||
|
appliance = make_appliance(
|
||||||
|
prediction_hours=overrides.pop("prediction_hours", 6),
|
||||||
|
run_started_datetime=started,
|
||||||
|
**overrides,
|
||||||
|
)
|
||||||
|
appliance.pin_run_in_progress(to_datetime(self.SLOT0), to_datetime(now))
|
||||||
|
return appliance
|
||||||
|
|
||||||
|
def test_remaining_flat_run_is_placed_from_now(self):
|
||||||
|
# 2000 Wh in 2 h (1000 W), started 00:47, re-plan 01:05: 102 min left.
|
||||||
|
appliance = self.pinned("2026-11-14T00:47:00+01:00", "2026-11-14T01:05:00+01:00")
|
||||||
|
|
||||||
|
assert appliance.run_in_progress
|
||||||
|
assert appliance.pinned_load[0] == pytest.approx(1000 * 55 / 60)
|
||||||
|
assert appliance.pinned_load[1] == pytest.approx(1000 * 47 / 60)
|
||||||
|
assert appliance.pinned_load[2:].sum() == 0
|
||||||
|
assert appliance.pinned_load.sum() == pytest.approx(2000 * 102 / 120)
|
||||||
|
assert appliance.pinned_end_slot == 2
|
||||||
|
assert appliance.pinned_end_datetime == to_datetime("2026-11-14T02:47:00+01:00")
|
||||||
|
|
||||||
|
def test_remaining_profile_run_follows_the_profile(self):
|
||||||
|
params = make_params(
|
||||||
|
consumption_wh=None,
|
||||||
|
duration_h=None,
|
||||||
|
load_profile_power_w=[400.0, 2000.0, 100.0],
|
||||||
|
load_profile_interval_seconds=900,
|
||||||
|
run_started_datetime="2026-11-14T00:00:00+01:00",
|
||||||
|
)
|
||||||
|
appliance = HomeAppliance(
|
||||||
|
parameters=params, optimization_hours=4, prediction_hours=16, slot_duration_h=0.25
|
||||||
|
)
|
||||||
|
appliance.pin_run_in_progress(
|
||||||
|
to_datetime("2026-11-14T00:15:00+01:00"), to_datetime("2026-11-14T00:20:00+01:00")
|
||||||
|
)
|
||||||
|
|
||||||
|
# Step 2 (2000 W) has 10 of 15 min left, step 3 (100 W) is complete.
|
||||||
|
assert appliance.pinned_load[0] == pytest.approx(2000 * 10 / 60)
|
||||||
|
assert appliance.pinned_load[1] == pytest.approx(100 * 15 / 60)
|
||||||
|
assert appliance.pinned_load[2:].sum() == 0
|
||||||
|
assert appliance.pinned_end_slot == 2
|
||||||
|
|
||||||
|
def test_run_past_its_duration_keeps_slot_zero_without_energy(self):
|
||||||
|
# The device decides when the run ends: 2 h run started 2 h 30 min ago.
|
||||||
|
appliance = self.pinned("2026-11-13T22:35:00+01:00", "2026-11-14T01:05:00+01:00")
|
||||||
|
|
||||||
|
assert appliance.run_in_progress
|
||||||
|
assert appliance.pinned_load.sum() == 0
|
||||||
|
assert appliance.pinned_end_slot == 1
|
||||||
|
assert appliance.pinned_end_datetime == to_datetime("2026-11-14T01:05:00+01:00")
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"started",
|
||||||
|
[
|
||||||
|
"2026-11-13T21:04:00+01:00", # more than 2 run durations ago: stale report
|
||||||
|
"2026-11-14T01:06:00+01:00", # in the future
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_implausible_start_is_not_pinned(self, started):
|
||||||
|
appliance = self.pinned(started, "2026-11-14T01:05:00+01:00")
|
||||||
|
|
||||||
|
assert not appliance.run_in_progress
|
||||||
|
assert appliance.pinned_load.sum() == 0
|
||||||
|
assert appliance.pinned_end_slot == 0
|
||||||
|
|
||||||
|
def test_no_report_changes_nothing(self):
|
||||||
|
appliance = make_appliance(prediction_hours=6)
|
||||||
|
appliance.pin_run_in_progress(to_datetime(self.SLOT0), to_datetime(self.SLOT0))
|
||||||
|
|
||||||
|
assert not appliance.run_in_progress
|
||||||
|
assert appliance.next_cycle_earliest_slot() == 0
|
||||||
|
assert appliance.completed_cycles_on(to_datetime(self.SLOT0).date()) == 0
|
||||||
|
|
||||||
|
def test_load_curve_contains_the_remainder(self):
|
||||||
|
appliance = self.pinned("2026-11-14T00:47:00+01:00", "2026-11-14T01:05:00+01:00")
|
||||||
|
|
||||||
|
appliance.build_load_curve([])
|
||||||
|
np.testing.assert_allclose(appliance.get_load_curve(), appliance.pinned_load)
|
||||||
|
appliance.build_load_curve([4])
|
||||||
|
assert appliance.get_load_curve()[4] == pytest.approx(1000)
|
||||||
|
assert appliance.get_load_curve()[0] == pytest.approx(1000 * 55 / 60)
|
||||||
|
|
||||||
|
def test_counts_as_a_cycle_of_its_start_day_and_delays_the_next(self):
|
||||||
|
appliance = self.pinned(
|
||||||
|
"2026-11-14T00:47:00+01:00",
|
||||||
|
"2026-11-14T01:05:00+01:00",
|
||||||
|
num_cycles=2,
|
||||||
|
min_cycle_gap_h=1,
|
||||||
|
schedule_mode="DAILY",
|
||||||
|
)
|
||||||
|
today = to_datetime(self.SLOT0).date()
|
||||||
|
|
||||||
|
assert appliance.completed_cycles_on(today) == 1
|
||||||
|
assert appliance.completed_cycles_on(today.add(days=1)) == 0
|
||||||
|
# Ends 02:47 (slot 2 is the first free slot) plus 1 h gap.
|
||||||
|
assert appliance.next_cycle_earliest_slot() == 3
|
||||||
|
|
||||||
|
def test_deadline_counts_the_expected_end_of_the_run(self):
|
||||||
|
appliance = self.pinned(
|
||||||
|
"2026-11-14T00:47:00+01:00",
|
||||||
|
"2026-11-14T01:05:00+01:00",
|
||||||
|
deadline_datetime="2026-11-14T02:30:00+01:00",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert appliance.deadline_missed([], to_datetime(self.SLOT0))
|
||||||
|
appliance.deadline_datetime = to_datetime("2026-11-14T03:00:00+01:00")
|
||||||
|
assert not appliance.deadline_missed([], to_datetime(self.SLOT0))
|
||||||
|
|||||||
Reference in New Issue
Block a user