diff --git a/docs/_generated/configdevices.md b/docs/_generated/configdevices.md index fa80bf5b..768e7bc7 100644 --- a/docs/_generated/configdevices.md +++ b/docs/_generated/configdevices.md @@ -129,6 +129,7 @@ config path from ``self.device_id`` without needing an external index. "cycle_time_windows": null, "min_cycle_gap_h": 0, "cycles_completed_measurement_key": null, + "run_started_measurement_key": null, "load_profile_power_w": null, "load_profile_interval_seconds": null, "schedule_mode": "ONCE", @@ -303,6 +304,7 @@ config path from ``self.device_id`` without needing an external index. "cycle_time_windows": null, "min_cycle_gap_h": 0, "cycles_completed_measurement_key": null, + "run_started_measurement_key": null, "load_profile_power_w": null, "load_profile_interval_seconds": null, "schedule_mode": "ONCE", @@ -312,7 +314,8 @@ config path from ``self.device_id`` without needing an external index. "deadline_policy": "BEST_EFFORT", "effective_num_cycles": 1, "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-l3-w", "ev0-power-3-phase-sym-w", - "dishwasher.cycles_completed" + "dishwasher.cycles_completed", + "dishwasher.run_started_at" ] } } diff --git a/docs/_generated/configexample.md b/docs/_generated/configexample.md index 3ed59450..91b1845e 100644 --- a/docs/_generated/configexample.md +++ b/docs/_generated/configexample.md @@ -133,6 +133,7 @@ "cycle_time_windows": null, "min_cycle_gap_h": 0, "cycles_completed_measurement_key": null, + "run_started_measurement_key": null, "load_profile_power_w": null, "load_profile_interval_seconds": null, "schedule_mode": "ONCE", diff --git a/docs/akkudoktoreos/resource.md b/docs/akkudoktoreos/resource.md index 775d2403..1ddb5fd8 100644 --- a/docs/akkudoktoreos/resource.md +++ b/docs/akkudoktoreos/resource.md @@ -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 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 :class: note Unlike GENETIC0, the GENETIC algorithm can plan multiple cycles -- and therefore multiple starts diff --git a/docs/akkudoktoreos/upgrade-genetic.md b/docs/akkudoktoreos/upgrade-genetic.md index 6302efd6..f10baaf4 100644 --- a/docs/akkudoktoreos/upgrade-genetic.md +++ b/docs/akkudoktoreos/upgrade-genetic.md @@ -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 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). +- Executors of household appliances should report a started run: write its start (UNIX + seconds) to `.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. 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 diff --git a/docs/development/genetic-rollout.md b/docs/development/genetic-rollout.md index c02441f2..bb694cd0 100644 --- a/docs/development/genetic-rollout.md +++ b/docs/development/genetic-rollout.md @@ -59,6 +59,8 @@ Request SoC values are integer percentages. Without an override, the measurement key `-soc-factor` must contain a recent factor from 0 to 1. Invalid, future or stale measurements never become an assumed zero SoC. Completed appliance cycles use their configured measurement key, default `.cycles_completed`. +The start of a run in progress (UNIX seconds, `0` when finished) uses +`.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 slot: `pv_forecast_wh` and `total_load` are Wh per slot; `electricity_price_per_wh` diff --git a/openapi.json b/openapi.json index 954d0aa9..84c4e6bb 100644 --- a/openapi.json +++ b/openapi.json @@ -11044,7 +11044,7 @@ }, "type": "object", "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": { "additionalProperties": { @@ -11299,6 +11299,25 @@ "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": { "anyOf": [ { @@ -11572,6 +11591,25 @@ "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": { "anyOf": [ { @@ -11810,6 +11848,23 @@ "description": "Cycles already completed on the first planning day.", "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": { "type": "integer", "minimum": 0.0, diff --git a/src/akkudoktoreos/devices/genetic/homeappliance.py b/src/akkudoktoreos/devices/genetic/homeappliance.py index b9c16117..6ba3fd17 100644 --- a/src/akkudoktoreos/devices/genetic/homeappliance.py +++ b/src/akkudoktoreos/devices/genetic/homeappliance.py @@ -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) diff --git a/src/akkudoktoreos/devices/settings/homeappliancesettings.py b/src/akkudoktoreos/devices/settings/homeappliancesettings.py index 22e8606e..964bbc17 100644 --- a/src/akkudoktoreos/devices/settings/homeappliancesettings.py +++ b/src/akkudoktoreos/devices/settings/homeappliancesettings.py @@ -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", + ] diff --git a/src/akkudoktoreos/optimization/genetic/configrequest.py b/src/akkudoktoreos/optimization/genetic/configrequest.py index e4d5b43d..4b99d833 100644 --- a/src/akkudoktoreos/optimization/genetic/configrequest.py +++ b/src/akkudoktoreos/optimization/genetic/configrequest.py @@ -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: diff --git a/src/akkudoktoreos/optimization/genetic/genetic.py b/src/akkudoktoreos/optimization/genetic/genetic.py index b804f6bb..d65bc276 100644 --- a/src/akkudoktoreos/optimization/genetic/genetic.py +++ b/src/akkudoktoreos/optimization/genetic/genetic.py @@ -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. diff --git a/src/akkudoktoreos/optimization/genetic/geneticsolution.py b/src/akkudoktoreos/optimization/genetic/geneticsolution.py index 4db38c1a..2e67c1e1 100644 --- a/src/akkudoktoreos/optimization/genetic/geneticsolution.py +++ b/src/akkudoktoreos/optimization/genetic/geneticsolution.py @@ -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." ) }, ) diff --git a/tests/test_geneticendtoenddevices.py b/tests/test_geneticendtoenddevices.py index 8d97c31a..2ba6e2f0 100644 --- a/tests/test_geneticendtoenddevices.py +++ b/tests/test_geneticendtoenddevices.py @@ -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 diff --git a/tests/test_genetichomeappliance.py b/tests/test_genetichomeappliance.py index a0fbee98..a83d2afe 100644 --- a/tests/test_genetichomeappliance.py +++ b/tests/test_genetichomeappliance.py @@ -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))