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
@@ -466,3 +466,232 @@ async def test_meter_only_record_does_not_hide_completed_cycles(
|
||||
).resolve()
|
||||
assert prepared.home_appliances is not None
|
||||
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,
|
||||
HomeApplianceParameters,
|
||||
)
|
||||
from akkudoktoreos.utils.datetimeutil import to_duration, to_time
|
||||
from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration, to_time
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Fixtures / factories
|
||||
@@ -448,3 +448,121 @@ class TestLoadCurve:
|
||||
appliance = make_appliance(prediction_hours=6)
|
||||
with pytest.raises(ValueError):
|
||||
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