From 0bf9f50b9769d29975a6c0c47f5ba54de9b3c401 Mon Sep 17 00:00:00 2001 From: SchaafAlexander <86607129+SchaafAlexander@users.noreply.github.com> Date: Fri, 13 Nov 2026 19:10:02 +0100 Subject: [PATCH] fix(genetic): plan the running slot only for the remaining time A run within a slot (e.g. 10:45 with hourly slots) planned slot 0 as a full slot, although the SoC is measured at the run time. Slot 0 now moves only the remaining part of the slot energy: battery, EV and inverter energy caps, SoC power limit tables and the slot's PV and load forecast are scaled by first_slot_fraction; efficiency curves are read at the power of that part. The plan's SoC headroom clamp of the AC charge factor uses the same part, and the GENETIC result reports first_slot_fraction. A run on a slot boundary is unchanged. Additional changes Pin GENETIC test start times to the full hour; their results now depend on seconds within the slot Document first_slot_fraction for consumers of GENETIC results Refs: #1543 Signed-off-by: SchaafAlexander <86607129+SchaafAlexander@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 Assisted-by: Claude Code (claude-opus-5-5) --- docs/akkudoktoreos/upgrade-genetic.md | 5 + openapi.json | 8 ++ src/akkudoktoreos/devices/genetic/battery.py | 82 +++++++++---- src/akkudoktoreos/devices/genetic/inverter.py | 74 ++++++++--- .../optimization/genetic/genetic.py | 66 +++++++++- .../optimization/genetic/geneticsolution.py | 21 +++- tests/test_geneticbattery.py | 85 +++++++++++++ tests/test_geneticbatteryfullcharge.py | 6 +- tests/test_geneticcompleteoptimization.py | 10 +- tests/test_geneticcompletetimegrid.py | 116 ++++++++++++++++++ tests/test_geneticconfigfrozenperrun.py | 2 +- tests/test_geneticfitnesscachelimit.py | 2 +- tests/test_geneticinverter.py | 74 +++++++++++ tests/test_geneticparallelevaluation.py | 2 +- tests/test_geneticseeding.py | 2 +- 15 files changed, 495 insertions(+), 60 deletions(-) diff --git a/docs/akkudoktoreos/upgrade-genetic.md b/docs/akkudoktoreos/upgrade-genetic.md index d103bf7f..6302efd6 100644 --- a/docs/akkudoktoreos/upgrade-genetic.md +++ b/docs/akkudoktoreos/upgrade-genetic.md @@ -91,6 +91,11 @@ time, charging power and supported charge rates. - Runtime forecast arrays start at local midnight and use the configured slot interval. Energy is **Wh per slot**, not W or kWh. A constant 1,000 W load uses 250 Wh in 15 minutes. +- A run within a slot plans the first slot only for the time left in it, given as + `first_slot_fraction` in the GENETIC result (0.25 for a run at 10:45 with hourly + 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). - 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/openapi.json b/openapi.json index 70f78a48..954d0aa9 100644 --- a/openapi.json +++ b/openapi.json @@ -11060,6 +11060,14 @@ "description": "Duration of one result/control slot in seconds.", "default": 3600 }, + "first_slot_fraction": { + "type": "number", + "maximum": 1.0, + "exclusiveMinimum": 0.0, + "title": "First Slot Fraction", + "description": "Part of the first control slot that was still ahead when the optimization ran (0.25 for a run at 10:45 with hourly slots). The results of the first slot cover only that part, and its factors are chosen for it. 1.0 for a run on a slot boundary.", + "default": 1.0 + }, "eautocharge_hours_float": { "anyOf": [ { diff --git a/src/akkudoktoreos/devices/genetic/battery.py b/src/akkudoktoreos/devices/genetic/battery.py index e053c3ca..d0b08449 100644 --- a/src/akkudoktoreos/devices/genetic/battery.py +++ b/src/akkudoktoreos/devices/genetic/battery.py @@ -406,17 +406,33 @@ class Battery: parameters: BaseBatteryParameters, prediction_hours: int, slot_duration_h: float = 1.0, + first_slot_fraction: float = 1.0, ): # `prediction_hours` is the number of optimization slots, not hours. At # the default optimization interval of 3600 s, slot_duration_h is 1.0 and # the slot count equals the hour count, so existing callers are # unaffected. At 900 s (15 min) slot_duration_h is 0.25 and there are 4x # as many slots, each able to move a quarter of the hourly energy. + # + # `first_slot_fraction` is the part of slot 0 still ahead when the + # optimization runs within that slot (0.25 at 10:45 with hourly slots). + # Slot 0 then moves only that fraction of the slot energy; the slot's + # power limits and power dependent efficiencies stay the same. + if not 0.0 < first_slot_fraction <= 1.0: + raise ValueError(f"first_slot_fraction must be in (0, 1], got {first_slot_fraction}.") self.parameters = parameters self.prediction_hours = prediction_hours self.slot_duration_h = slot_duration_h + self.first_slot_fraction = first_slot_fraction self._setup() + def slot_scale(self, hour: int) -> float: + """Return the part of the slot duration that is simulated for slot ``hour``. + + ``first_slot_fraction`` for slot 0, 1.0 for every later slot. + """ + return self.first_slot_fraction if hour == 0 else 1.0 + def _setup(self) -> None: """Sets up the battery parameters based on provided parameters.""" self.capacity_wh = self.parameters.capacity_wh @@ -548,24 +564,30 @@ class Battery: self._curves.reset(self.prediction_hours) self._charge_limit_raw_wh_per_slot = [float("inf")] * self.prediction_hours - def _discharge_slot_cap_wh(self) -> float: - """Return the raw discharge energy of one slot [Wh] at the current SoC.""" + def _discharge_slot_cap_wh(self, hour: int) -> float: + """Return the raw discharge energy of slot ``hour`` [Wh] at the current SoC.""" curves = self._curves if curves is None or curves.discharge_limit_wh_by_soc is None: - return self.max_discharge_power_w * self.slot_duration_h + return self.max_discharge_power_w * self.slot_duration_h * self.slot_scale(hour) return _table_entry( curves.discharge_limit_wh_by_soc, int(self.soc_wh * curves.soc_index_per_wh + 0.5), - ) + ) * self.slot_scale(hour) - def _discharging_efficiency_at(self, slot_raw_wh: float) -> float: - """Return the discharging efficiency at the slot power of ``slot_raw_wh``.""" + def _discharging_efficiency_at(self, slot_raw_wh: float, scale: float = 1.0) -> float: + """Return the discharging efficiency at the slot power of ``slot_raw_wh``. + + Args: + slot_raw_wh: Raw discharge energy of the slot [Wh]. + scale: Simulated part of the slot duration (see ``slot_scale``); the + power is the energy divided by that part of the slot. + """ curves = self._curves if curves is None or curves.discharging_efficiency_by_power is None: return self.discharging_efficiency return _table_entry( curves.discharging_efficiency_by_power, - int(slot_raw_wh * curves.discharge_index_per_wh + 0.5), + int(slot_raw_wh / scale * curves.discharge_index_per_wh + 0.5), ) def limit_slot_charge(self, hour: int, raw_wh: float) -> None: @@ -582,24 +604,29 @@ class Battery: self._charge_limit_raw_wh_per_slot[hour], max(float(raw_wh), 0.0) ) - def rated_discharge_energy_wh(self) -> float: - """Return the DC energy one full-power discharge slot delivers. + def rated_discharge_energy_wh(self, hour: Optional[int] = None) -> float: + """Return the DC energy a full-power discharge delivers in one slot. This is the reference a grid-export rate is applied to: a rate of 0.5 exports at most half the battery's rated discharge power, independent of how much of the slot budget self-consumption already used. + + Args: + hour: Slot index. Slot 0 delivers only ``first_slot_fraction`` of + the slot energy. None gives a full slot. """ - rated_slot_wh = self.max_discharge_power_w * self.slot_duration_h - return rated_slot_wh * self._discharging_efficiency_at(rated_slot_wh) + scale = 1.0 if hour is None else self.slot_scale(hour) + rated_slot_wh = self.max_discharge_power_w * self.slot_duration_h * scale + return rated_slot_wh * self._discharging_efficiency_at(rated_slot_wh, scale) def remaining_discharge_energy_wh(self, hour: int) -> float: """Return DC energy still deliverable within one optimization slot.""" discharged_raw_wh = self._discharged_raw_wh_per_slot[hour] - raw_power_remaining_wh = max(self._discharge_slot_cap_wh() - discharged_raw_wh, 0.0) + raw_power_remaining_wh = max(self._discharge_slot_cap_wh(hour) - discharged_raw_wh, 0.0) raw_soc_available_wh = max(self.soc_wh - self.min_soc_wh, 0.0) raw_remaining_wh = min(raw_power_remaining_wh, raw_soc_available_wh) return raw_remaining_wh * self._discharging_efficiency_at( - discharged_raw_wh + raw_remaining_wh + discharged_raw_wh + raw_remaining_wh, self.slot_scale(hour) ) def discharge_released(self, hour: int) -> bool: @@ -672,22 +699,26 @@ class Battery: # Maximum raw discharge due to power limit, scaled to the slot duration. # The power limit is a power [W]; energy movable in one slot is - # power x slot_duration_h. With a battery profile the limit and the - # efficiency are looked up inline (no calls): this runs for every slot - # of every candidate plan. + # power x slot_duration_h, and only the remaining part of slot 0 when + # the optimization runs within it. With a battery profile the limit and + # the efficiency are looked up inline (no calls): this runs for every + # slot of every candidate plan. discharged_raw_wh = self._discharged_raw_wh_per_slot[hour] discharging_efficiency = self.discharging_efficiency + scale = self.first_slot_fraction if hour == 0 else 1.0 curves = self._curves if curves is None: - slot_cap_wh = self.max_discharge_power_w * self.slot_duration_h + slot_cap_wh = self.max_discharge_power_w * self.slot_duration_h * scale raw_withdrawal_wh = min(raw_available_wh, max(slot_cap_wh - discharged_raw_wh, 0.0)) else: limits = curves.discharge_limit_wh_by_soc if limits is None: - slot_cap_wh = self.max_discharge_power_w * self.slot_duration_h + slot_cap_wh = self.max_discharge_power_w * self.slot_duration_h * scale else: index = int(self.soc_wh * curves.soc_index_per_wh + 0.5) - slot_cap_wh = limits[index] if 0 <= index <= 100 else _table_entry(limits, index) + slot_cap_wh = ( + limits[index] if 0 <= index <= 100 else _table_entry(limits, index) + ) * scale raw_withdrawal_wh = slot_cap_wh - discharged_raw_wh if raw_withdrawal_wh < 0.0: raw_withdrawal_wh = 0.0 @@ -702,7 +733,8 @@ class Battery: if raw_estimate_wh > raw_withdrawal_wh: raw_estimate_wh = raw_withdrawal_wh index = int( - (discharged_raw_wh + raw_estimate_wh) * curves.discharge_index_per_wh + 0.5 + (discharged_raw_wh + raw_estimate_wh) / scale * curves.discharge_index_per_wh + + 0.5 ) discharging_efficiency = efficiencies[index] if index <= 100 else efficiencies[-1] @@ -804,9 +836,11 @@ class Battery: charged_raw_wh = self._charged_raw_wh_per_slot[hour] # Scale the power cap [W] to a per-slot energy cap [Wh] (W x slot hours). # At slot_duration_h=1.0 (hourly) this equals the legacy power value. + # Slot 0 only has its remaining part when the run starts within it. + scale = self.first_slot_fraction if hour == 0 else 1.0 max_charge_per_slot_wh_fast = max( min( - self.max_charge_power_w * self.slot_duration_h, + self.max_charge_power_w * self.slot_duration_h * scale, self._charge_limit_raw_wh_per_slot[hour], ) - charged_raw_wh, @@ -824,7 +858,7 @@ class Battery: index = int(soc_wh_fast * curves.soc_index_per_wh + 0.5) soc_limit_raw_wh = ( limits[index] if 0 <= index <= 100 else _table_entry(limits, index) - ) - charged_raw_wh + ) * scale - charged_raw_wh if soc_limit_raw_wh < 0.0: soc_limit_raw_wh = 0.0 efficiencies = curves.charging_efficiency_by_power @@ -840,7 +874,9 @@ class Battery: intended_raw_wh = soc_limit_raw_wh if intended_raw_wh < 0.0: intended_raw_wh = 0.0 - index = int((charged_raw_wh + intended_raw_wh) * curves.charge_index_per_wh + 0.5) + index = int( + (charged_raw_wh + intended_raw_wh) / scale * curves.charge_index_per_wh + 0.5 + ) charging_efficiency_fast = efficiencies[index] if index <= 100 else efficiencies[-1] # Decide mode & determine raw_request_wh and raw_charge_wh diff --git a/src/akkudoktoreos/devices/genetic/inverter.py b/src/akkudoktoreos/devices/genetic/inverter.py index 9df9819a..49dce373 100644 --- a/src/akkudoktoreos/devices/genetic/inverter.py +++ b/src/akkudoktoreos/devices/genetic/inverter.py @@ -137,12 +137,26 @@ class Inverter: parameters: InverterParameters, battery: Optional[Battery] = None, slot_duration_h: float = 1.0, + first_slot_fraction: float = 1.0, ): + # `first_slot_fraction` is the part of slot 0 still ahead when the + # optimization runs within that slot; slot 0 then moves only that part + # of the slot energy (see Battery). + if not 0.0 < first_slot_fraction <= 1.0: + raise ValueError(f"first_slot_fraction must be in (0, 1], got {first_slot_fraction}.") self.parameters: InverterParameters = parameters self.battery: Optional[Battery] = battery self.slot_duration_h: float = slot_duration_h + self.first_slot_fraction: float = first_slot_fraction self._setup() + def slot_scale(self, hour: int) -> float: + """Return the part of the slot duration that is simulated for slot ``hour``. + + ``first_slot_fraction`` for slot 0, 1.0 for every later slot. + """ + return self.first_slot_fraction if hour == 0 else 1.0 + def _setup(self) -> None: if self.battery and self.parameters.battery_id != self.battery.parameters.device_id: error_msg = f"Battery ID mismatch - {self.parameters.battery_id} is configured; got {self.battery.parameters.device_id}." @@ -167,19 +181,24 @@ class Inverter: self.max_ac_charge_power_w = self.parameters.max_ac_charge_power_w self.ac_charge_limits_total_charge = self.parameters.ac_charge_limits_total_charge - def dc_to_ac_efficiency_at(self, ac_wh: float) -> float: + def dc_to_ac_efficiency_at(self, ac_wh: float, scale: float = 1.0) -> float: """Return the DC-to-AC efficiency of a conversion delivering ``ac_wh`` in one slot. Without ``dc_to_ac_efficiency_curve`` this is the constant ``dc_to_ac_efficiency``. With a curve, the efficiency is interpolated at - the load fraction ``ac_wh / max_power_wh`` of this slot. ``max_power_wh`` - is already scaled to the slot duration, so the fraction equals the mean - AC power relative to the rated power. + the load fraction ``ac_wh / (max_power_wh * scale)`` of this slot. + ``max_power_wh`` is already scaled to the slot duration, so the fraction + equals the mean AC power relative to the rated power. + + Args: + ac_wh: AC energy of the conversion in this slot [Wh]. + scale: Simulated part of the slot duration (see ``slot_scale``). """ if self.dc_to_ac_efficiency_curve is None: return self.dc_to_ac_efficiency curve: list[tuple[float, float]] = self.dc_to_ac_efficiency_curve - load_fraction = ac_wh / self.max_power_wh if self.max_power_wh > 0 else 0.0 + slot_max_power_wh = self.max_power_wh * scale + load_fraction = ac_wh / slot_max_power_wh if slot_max_power_wh > 0 else 0.0 # This runs for every battery discharge of every candidate plan. Find # the curve segment by bisection on the load fractions, split off once # per curve, instead of walking the points. The segment and the @@ -234,7 +253,11 @@ class Inverter: """ if self.ac_charge_limits_total_charge and self.battery and factor > 0.0: self.battery.limit_slot_charge( - hour, self.battery.max_charge_power_w * self.slot_duration_h * factor + hour, + self.battery.max_charge_power_w + * self.slot_duration_h + * self.slot_scale(hour) + * factor, ) def charge_battery_from_grid(self, hour: int, factor: float) -> tuple[float, float]: @@ -250,9 +273,10 @@ class Inverter: """ if not self.battery or factor <= 0.0: return 0.0, 0.0 + scale = self.slot_scale(hour) if self.ac_charge_limits_total_charge: stored, battery_losses = self.battery.charge_energy( - self.battery.max_charge_power_w * self.slot_duration_h * factor, hour + self.battery.max_charge_power_w * self.slot_duration_h * scale * factor, hour ) else: stored, battery_losses = self.battery.charge_energy(None, hour, charge_factor=factor) @@ -262,7 +286,7 @@ class Inverter: # curve the efficiency is the one at the AC load actually drawn. curve = self.ac_to_dc_efficiency_curve if curve is not None: - ac_energy = solve_ac_for_charge_dc_energy(curve, dc_energy, self.max_power_wh) + ac_energy = solve_ac_for_charge_dc_energy(curve, dc_energy, self.max_power_wh * scale) else: ac_energy = dc_energy / self.ac_to_dc_efficiency return ac_energy, battery_losses + (ac_energy - dc_energy) @@ -273,18 +297,20 @@ class Inverter: dc_request: float, requested_ac_wh: float, dc_to_ac_efficiency: float, + scale: float = 1.0, ) -> float: """Return the AC energy of a discharge that delivered ``battery_discharge_dc``. If the battery delivered less than requested (low state of charge or its power limit), the conversion runs at a lower AC load than requested. With an efficiency curve the efficiency must then be the one at the AC energy - that is actually delivered, not at the request. + that is actually delivered, not at the request. ``scale`` is the + simulated part of the slot duration (see ``slot_scale``). """ curve = self.dc_to_ac_efficiency_curve if curve is not None and battery_discharge_dc < dc_request * (1.0 - 1e-12): return solve_ac_for_dc_energy( - curve, battery_discharge_dc, self.max_power_wh, requested_ac_wh + curve, battery_discharge_dc, self.max_power_wh * scale, requested_ac_wh ) return battery_discharge_dc * dc_to_ac_efficiency @@ -293,15 +319,16 @@ class Inverter: battery = self.battery if not battery or requested_ac_wh <= 0.0: return 0.0, 0.0 + scale = self.first_slot_fraction if hour == 0 else 1.0 if type(battery) is not Battery: # Another battery implementation: ask it, step by step. if not battery.discharge_released(hour): return 0.0, 0.0 - dc_to_ac_efficiency = self.dc_to_ac_efficiency_at(requested_ac_wh) + dc_to_ac_efficiency = self.dc_to_ac_efficiency_at(requested_ac_wh, scale) dc_request = requested_ac_wh / dc_to_ac_efficiency battery_discharge_dc, discharge_losses = battery.discharge_energy(dc_request, hour) battery_discharge_ac = self._delivered_ac_wh( - battery_discharge_dc, dc_request, requested_ac_wh, dc_to_ac_efficiency + battery_discharge_dc, dc_request, requested_ac_wh, dc_to_ac_efficiency, scale ) inverter_discharge_losses = battery_discharge_dc - battery_discharge_ac return battery_discharge_ac, discharge_losses + inverter_discharge_losses @@ -319,7 +346,7 @@ class Inverter: if self.dc_to_ac_efficiency_curve is None: dc_to_ac_efficiency = self.dc_to_ac_efficiency else: - dc_to_ac_efficiency = self.dc_to_ac_efficiency_at(requested_ac_wh) + dc_to_ac_efficiency = self.dc_to_ac_efficiency_at(requested_ac_wh, scale) dc_request = requested_ac_wh / dc_to_ac_efficiency if battery._curves is not None: @@ -335,7 +362,10 @@ class Inverter: # Match Battery.discharge_energy(): preserve a SoC below the reserve. return 0.0, 0.0 max_raw_wh = max( - battery.max_discharge_power_w * battery.slot_duration_h - discharged_raw_wh[hour], + battery.max_discharge_power_w + * battery.slot_duration_h + * (battery.first_slot_fraction if hour == 0 else 1.0) + - discharged_raw_wh[hour], 0.0, ) max_deliverable_wh = min(raw_available_wh, max_raw_wh) * discharging_efficiency @@ -354,7 +384,7 @@ class Inverter: battery_discharge_ac = solve_ac_for_dc_energy( self.dc_to_ac_efficiency_curve, battery_discharge_dc, - self.max_power_wh, + self.max_power_wh * scale, requested_ac_wh, ) else: @@ -402,12 +432,16 @@ class Inverter: if consumption < 0.0: consumption = 0.0 battery = self.battery - max_power_wh = self.max_power_wh + # Slot 0 only has its remaining part when the run starts within it: + # the inverter moves that part of the slot energy, and the slot's + # energies are converted to power over that part of the slot. + scale = self.first_slot_fraction if hour == 0 else 1.0 + max_power_wh = self.max_power_wh * scale # Convert interval energy [Wh] to mean power [W] for the probability # lookup, then convert its expected direct power back to slot energy. if generation > 0.0 and consumption > 0.0: - slot_duration_h = self.slot_duration_h + slot_duration_h = self.slot_duration_h * scale expected_direct_power_w = ( self.self_consumption_predictor.calculate_expected_direct_consumption( consumption / slot_duration_h, @@ -504,14 +538,14 @@ class Inverter: # limited by the energy the battery can actually deliver. remaining_battery_dc = battery.remaining_discharge_energy_wh(hour) remaining_battery_ac = remaining_battery_dc * self.dc_to_ac_efficiency_at( - remaining_battery_dc + remaining_battery_dc, scale ) # The rate caps the export against the battery's *rated* discharge # power, so it stays a plain power setpoint ("export at 50 %") that # does not silently grow when self-consumption used less of the slot. # At factor 1.0 this bound never binds; behaviour is unchanged. - rated_export_dc = battery.rated_discharge_energy_wh() * export_factor - rated_export_ac = rated_export_dc * self.dc_to_ac_efficiency_at(rated_export_dc) + rated_export_dc = battery.rated_discharge_energy_wh(hour) * export_factor + rated_export_ac = rated_export_dc * self.dc_to_ac_efficiency_at(rated_export_dc, scale) export_capacity = remaining_inverter_ac_capacity if remaining_battery_ac < export_capacity: export_capacity = remaining_battery_ac diff --git a/src/akkudoktoreos/optimization/genetic/genetic.py b/src/akkudoktoreos/optimization/genetic/genetic.py index 1c552db3..b804f6bb 100644 --- a/src/akkudoktoreos/optimization/genetic/genetic.py +++ b/src/akkudoktoreos/optimization/genetic/genetic.py @@ -1056,6 +1056,37 @@ class GeneticOptimization(OptimizationBase): """Genomes and device arrays start at now, independently of wall-clock hour.""" return 0 + def _remaining_first_slot_fraction(self) -> float: + """Return the part of slot 0 that is still ahead of the run. + + The run start is rounded down to the slot (``ems.start_datetime``), + while the measurements and the plan apply from the unrounded run time + (``ems.observation_datetime``). A run at 10:45 with hourly slots has + a quarter of slot 0 left. A run on a slot boundary, or without a + usable run time, keeps the full slot (1.0). + """ + slot_seconds = self.slot_duration_h * 3600 + slot0 = self.ems.start_datetime + observed = self.ems.observation_datetime + elapsed_s = (observed - slot0).total_seconds() + if elapsed_s <= 0.0: + return 1.0 + if elapsed_s >= slot_seconds: + logger.debug( + "Run time {} is not within slot 0 starting {}; planning a full first slot.", + observed, + slot0, + ) + return 1.0 + fraction = (slot_seconds - elapsed_s) / slot_seconds + logger.debug( + "Run at {} within slot 0 starting {}: {:.3f} of slot 0 left.", + observed, + slot0, + fraction, + ) + return fraction + def _start_day_slot(self) -> int: """Offset used only to trim legacy midnight-indexed forecast inputs.""" sd = self.ems.start_datetime @@ -1085,6 +1116,9 @@ class GeneticOptimization(OptimizationBase): # Populated from parameters.pv_battery.grid_export_rates in optimize_ems; # the single full-power default keeps the all-or-nothing export. self.bat_possible_grid_export_values: list[float] = [1.0] + # Part of slot 0 still ahead of the run (1.0 on a slot boundary), set + # per run by optimize_ems(). + self.first_slot_fraction: float = 1.0 # Slot by which the EV has to reach its target SoC. None means the SoC is # only required at the end of the horizon (the behaviour without a deadline). self._ev_soc_deadline_slot: Optional[int] = None @@ -2524,15 +2558,18 @@ class GeneticOptimization(OptimizationBase): return schedule max_stored_wh = ev.max_charge_power_w * self.slot_duration_h * ev.charging_efficiency + first_slot_fraction = getattr(self, "first_slot_fraction", 1.0) remaining_wh = required_stored_wh for slot in candidates: - required_rate = remaining_wh / max(max_stored_wh, 1e-9) + # Slot 0 only has its remaining part when the run starts within it. + slot_stored_wh = max_stored_wh * (first_slot_fraction if slot == 0 else 1.0) + required_rate = remaining_wh / max(slot_stored_wh, 1e-9) rate, rate_index = next( (item for item in positive_rates if item[0] >= required_rate), positive_rates[-1], ) schedule[slot] = rate_index - remaining_wh -= max_stored_wh * rate + remaining_wh -= slot_stored_wh * rate if remaining_wh <= 1e-9: break return schedule @@ -3856,8 +3893,12 @@ class GeneticOptimization(OptimizationBase): # AC charging at this hour is economically unjustified. # Penalty = excess cost per Wh × DC energy requested this slot. # max_charge_power_w is a power [W]; the energy movable in - # one slot is power × slot_duration_h (¼ at 15 min). - dc_wh = bat.max_charge_power_w * self.slot_duration_h * ac_factor + # one slot is power × slot_duration_h (¼ at 15 min), and + # only the remaining part of slot 0 within that slot. + slot_scale = getattr(self, "first_slot_fraction", 1.0) if hour == 0 else 1.0 + dc_wh = ( + bat.max_charge_power_w * self.slot_duration_h * slot_scale * ac_factor + ) ac_wh = dc_wh / max(inv.ac_to_dc_efficiency, 1e-9) excess_cost_per_wh = break_even_price - best_uncovered_price gesamtbilanz += ac_wh * excess_cost_per_wh * ac_penalty_factor @@ -4215,6 +4256,9 @@ class GeneticOptimization(OptimizationBase): # break-even lookup must be rebuilt lazily on first evaluation. self._ac_break_even_best_prices = None + # A run within a slot plans slot 0 for the remaining time only. + self.first_slot_fraction = self._remaining_first_slot_fraction() + # Initialize PV and EV batteries. slot_duration_h lets the Battery scale # its power caps (max_charge_power_w) to a per-slot energy cap. akku: Optional[Battery] = None @@ -4223,6 +4267,7 @@ class GeneticOptimization(OptimizationBase): parameters.pv_battery, prediction_hours=self.control_end_slot, slot_duration_h=self.slot_duration_h, + first_slot_fraction=self.first_slot_fraction, ) akku.set_charge_per_hour(np.full(self.control_end_slot, 0)) @@ -4232,6 +4277,7 @@ class GeneticOptimization(OptimizationBase): parameters.ev, prediction_hours=self.control_end_slot, slot_duration_h=self.slot_duration_h, + first_slot_fraction=self.first_slot_fraction, ) eauto.set_charge_per_hour(np.full(self.control_end_slot, 1)) self.optimize_ev = ( @@ -4356,6 +4402,7 @@ class GeneticOptimization(OptimizationBase): parameters.inverter, battery=akku, slot_duration_h=self.slot_duration_h, + first_slot_fraction=self.first_slot_fraction, ) # Prepare device simulation @@ -4386,6 +4433,16 @@ class GeneticOptimization(OptimizationBase): "elect_revenue_per_hour_arr", ): setattr(self.simulation, name, getattr(self.simulation, name)[: self.control_slots]) + # Only the remaining part of slot 0 is ahead: its PV and load forecast + # shrink to that part (spread evenly over the slot). Prices are per Wh + # and stay. The terminal value curve above keeps the full forecasts. + if self.first_slot_fraction < 1.0: + for name in ("load_energy_array", "pv_prediction_wh"): + values = getattr(self.simulation, name) + if values is not None and len(values) > 0: + values = np.array(values, dtype=float) + values[0] *= self.first_slot_fraction + setattr(self.simulation, name, values) # Setup the DEAP environment and optimization process. The appliance # genome layout (built above) drives the appliance gene block; evaluate @@ -4481,6 +4538,7 @@ class GeneticOptimization(OptimizationBase): **{ "parameters": parameters, "interval_seconds": self._genetic_cfg.interval_sec, + "first_slot_fraction": self.first_slot_fraction, "start_hour": start_hour, "extra_data": extra_data, "fitness_history": self.fitness_history, diff --git a/src/akkudoktoreos/optimization/genetic/geneticsolution.py b/src/akkudoktoreos/optimization/genetic/geneticsolution.py index 21228bae..4db38c1a 100644 --- a/src/akkudoktoreos/optimization/genetic/geneticsolution.py +++ b/src/akkudoktoreos/optimization/genetic/geneticsolution.py @@ -474,6 +474,18 @@ class GeneticSolution(ConfigMixin, GeneticParametersBaseModel): default=3600, description="Duration of one result/control slot in seconds." ) + first_slot_fraction: float = Field( + default=1.0, + gt=0.0, + le=1.0, + description=( + "Part of the first control slot that was still ahead when the " + "optimization ran (0.25 for a run at 10:45 with hourly slots). The " + "results of the first slot cover only that part, and its factors are " + "chosen for it. 1.0 for a run on a slot boundary." + ), + ) + @field_validator("start_solution_datetime", mode="before") @classmethod def transform_start_solution_datetime(cls, value: Any) -> Optional[DateTime]: @@ -621,6 +633,7 @@ class GeneticSolution(ConfigMixin, GeneticParametersBaseModel): discharge_allowed: bool, soc_pct: float, battery_grid_export_allowed: bool = False, + slot_fraction: float = 1.0, ) -> tuple[float, float, bool, bool]: """Clamp raw genetic gene values by the battery's actual SOC at that hour. @@ -638,6 +651,10 @@ class GeneticSolution(ConfigMixin, GeneticParametersBaseModel): (the inverter curtails automatically, but this makes intent clear). - Discharge: blocked when SOC is at or below min SOC. - Battery grid export: blocked when SOC is at or below min SOC. + + ``slot_fraction`` is the part of the slot the factors apply to: + ``first_slot_fraction`` for the running first slot, else 1.0. The + headroom check of the AC charge factor uses only that part of the slot. """ parameters = getattr(self, "parameters", None) # Without parameters, convert the battery settings: they hold no @@ -679,7 +696,7 @@ class GeneticSolution(ConfigMixin, GeneticParametersBaseModel): ) # Energy storable in one optimization slot, not per hour: scale the # power [W] by the slot duration (1.0 hourly, 0.25 at 15 min). - slot_duration_h = float(self.interval_seconds) / 3600.0 + slot_duration_h = float(self.interval_seconds) / 3600.0 * slot_fraction max_dc_per_slot_wh = ( effective_ac * max_ac_cp_w * slot_duration_h * ac_to_dc_eff * ch_eff ) @@ -821,6 +838,7 @@ class GeneticSolution(ConfigMixin, GeneticParametersBaseModel): discharge_allowed_hour, soc_h_pct, battery_grid_export_allowed_hour, + self.first_slot_fraction if result_idx == 0 else 1.0, ) operation_mode, operation_mode_factor = self._battery_operation_from_solution( eff_ac, eff_dc, eff_dis, eff_grid_export, battery_grid_export_factor_hour @@ -1097,6 +1115,7 @@ class GeneticSolution(ConfigMixin, GeneticParametersBaseModel): bool(self.discharge_allowed[hour_idx]), soc_h_pct, battery_grid_export_allowed_hour, + self.first_slot_fraction if result_idx == 0 else 1.0, ) operation_mode, operation_mode_factor = self._battery_operation_from_solution( eff_ac, diff --git a/tests/test_geneticbattery.py b/tests/test_geneticbattery.py index a7b1c603..3a1a27d8 100644 --- a/tests/test_geneticbattery.py +++ b/tests/test_geneticbattery.py @@ -760,3 +760,88 @@ class TestPowerCurves: def test_invalid_curves_are_rejected(self, field, value): with pytest.raises(ValidationError): SolarPanelBatteryParameters(device_id="battery1", capacity_wh=10_000, **{field: value}) + + +class TestFirstSlotFraction: + """A run within slot 0 simulates only the remaining part of that slot.""" + + @staticmethod + def _battery(first_slot_fraction=1.0, soc=50, **curves): + params = SolarPanelBatteryParameters( + device_id="battery1", + capacity_wh=40_000, + initial_soc_percentage=soc, + min_soc_percentage=0, + max_soc_percentage=100, + max_charge_power_w=8_000, + max_discharge_power_w=4_000, + charging_efficiency=1.0, + discharging_efficiency=1.0, + **curves, + ) + battery = Battery( + params, prediction_hours=4, slot_duration_h=1.0, first_slot_fraction=first_slot_fraction + ) + battery.set_charge_per_hour(np.ones(4)) + battery.set_discharge_per_hour(np.ones(4)) + return battery + + def test_slot_0_charges_only_the_remaining_part(self): + battery = self._battery(first_slot_fraction=0.25) + stored, _ = battery.charge_energy(None, 0, charge_factor=1.0) + assert stored == pytest.approx(2_000.0) + # Mode 1 (a PV surplus) is capped the same way. + assert battery.charge_energy(5_000.0, 0) == pytest.approx((0.0, 0.0)) + # Slot 1 is a full slot again. + stored, _ = battery.charge_energy(None, 1, charge_factor=1.0) + assert stored == pytest.approx(8_000.0) + + def test_slot_0_discharges_only_the_remaining_part(self): + battery = self._battery(first_slot_fraction=0.25) + assert battery.remaining_discharge_energy_wh(0) == pytest.approx(1_000.0) + assert battery.rated_discharge_energy_wh(0) == pytest.approx(1_000.0) + assert battery.rated_discharge_energy_wh(1) == pytest.approx(4_000.0) + assert battery.rated_discharge_energy_wh() == pytest.approx(4_000.0) + delivered, _ = battery.discharge_energy(9_000.0, 0) + assert delivered == pytest.approx(1_000.0) + delivered, _ = battery.discharge_energy(9_000.0, 1) + assert delivered == pytest.approx(4_000.0) + + def test_full_fraction_is_the_plain_slot(self): + partial = self._battery(first_slot_fraction=1.0) + plain = Battery(partial.parameters, prediction_hours=4, slot_duration_h=1.0) + plain.set_charge_per_hour(np.ones(4)) + assert partial.charge_energy(None, 0, charge_factor=1.0) == plain.charge_energy( + None, 0, charge_factor=1.0 + ) + + def test_soc_power_limit_scales_with_the_remaining_part(self): + battery = self._battery( + first_slot_fraction=0.5, + charge_power_limit_w_by_soc=[6_000.0] * 101, + discharge_power_limit_w_by_soc=[2_000.0] * 101, + ) + stored, _ = battery.charge_energy(None, 0, charge_factor=1.0) + assert stored == pytest.approx(3_000.0) + delivered, _ = battery.discharge_energy(9_000.0, 0) + assert delivered == pytest.approx(1_000.0) + + def test_efficiency_curve_is_read_at_the_power_not_the_energy(self): + """Full power for 15 min has the efficiency of full power, not of 25 %.""" + curve = [(0.0, 0.95), (0.25, 0.95), (1.0, 0.80)] + battery = self._battery( + first_slot_fraction=0.25, + charging_efficiency_curve=curve, + discharging_efficiency_curve=curve, + ) + stored, losses = battery.charge_energy(None, 0, charge_factor=1.0) + assert stored + losses == pytest.approx(2_000.0) + assert stored == pytest.approx(2_000.0 * 0.80) + delivered, losses = battery.discharge_energy(9_000.0, 0) + assert delivered + losses == pytest.approx(1_000.0) + assert delivered == pytest.approx(1_000.0 * 0.80) + + @pytest.mark.parametrize("fraction", [0.0, -0.1, 1.5]) + def test_invalid_fraction_is_rejected(self, fraction): + with pytest.raises(ValueError, match="first_slot_fraction"): + self._battery(first_slot_fraction=fraction) diff --git a/tests/test_geneticbatteryfullcharge.py b/tests/test_geneticbatteryfullcharge.py index 4d543d4b..9cd8c23f 100644 --- a/tests/test_geneticbatteryfullcharge.py +++ b/tests/test_geneticbatteryfullcharge.py @@ -510,7 +510,7 @@ def _full_charge_parameters(hours: int, **battery_extra) -> GeneticOptimizationP def test_full_charge_slot_resolution(config_eos: ConfigEOS): _optimizer_config(config_eos, 24) - ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0)) + ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0, second=0, microsecond=0)) optimization = GeneticOptimization(fixed_seed=1) optimization._slot0_datetime = optimization.ems.start_datetime slot0 = optimization._slot0_datetime @@ -530,7 +530,7 @@ def test_full_charge_slot_resolution(config_eos: ConfigEOS): def test_maximum_soc_before_deadline_counts(config_eos: ConfigEOS): _optimizer_config(config_eos, 24) - ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0)) + ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0, second=0, microsecond=0)) optimization = GeneticOptimization(fixed_seed=1) optimization.simulation.battery = MagicMock(spec=Battery) optimization.simulation.battery.current_soc_percentage.return_value = 40.0 @@ -555,7 +555,7 @@ def test_maximum_soc_before_deadline_counts(config_eos: ConfigEOS): def _run(config_eos: ConfigEOS, **battery_extra) -> list[float]: hours = 24 _optimizer_config(config_eos, hours) - ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0)) + ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0, second=0, microsecond=0)) CacheEnergyManagementStore().clear() solution = GeneticOptimization(fixed_seed=42).optimize_ems( parameters=_full_charge_parameters(hours, **battery_extra), start_hour=0, ngen=40 diff --git a/tests/test_geneticcompleteoptimization.py b/tests/test_geneticcompleteoptimization.py index 5d867d64..4478f231 100644 --- a/tests/test_geneticcompleteoptimization.py +++ b/tests/test_geneticcompleteoptimization.py @@ -90,7 +90,7 @@ def test_grid_export_rates_reach_the_solution(config_eos: ConfigEOS): }, } ) - ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0)) + ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0, second=0, microsecond=0)) CacheEnergyManagementStore().clear() hours = 24 @@ -172,7 +172,7 @@ def test_ev_deadline_slot_resolution(config_eos: ConfigEOS): }, } ) - ems_eos.set_start_datetime(to_datetime().set(hour=10, minute=0)) + ems_eos.set_start_datetime(to_datetime().set(hour=10, minute=0, second=0, microsecond=0)) optimization = GeneticOptimization(fixed_seed=1) optimization._slot0_datetime = optimization.ems.start_datetime slot0 = optimization._slot0_datetime @@ -213,7 +213,7 @@ def test_ev_soc_penalty_reads_the_deadline_slot(config_eos: ConfigEOS): }, } ) - ems_eos.set_start_datetime(to_datetime().set(hour=10, minute=0)) + ems_eos.set_start_datetime(to_datetime().set(hour=10, minute=0, second=0, microsecond=0)) optimization = GeneticOptimization(fixed_seed=1) simulation_result = {"EAuto_SoC_pro_Stunde": [20.0, 35.0, 50.0, 80.0]} @@ -250,7 +250,7 @@ def test_ev_deadline_charges_before_departure(config_eos: ConfigEOS): }, } ) - ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0)) + ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0, second=0, microsecond=0)) CacheEnergyManagementStore().clear() parameters = _ev_deadline_parameters(hours, min_soc_max_duration_h=6) @@ -289,7 +289,7 @@ def _terminal_value_run( }, } ) - ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0)) + ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0, second=0, microsecond=0)) CacheEnergyManagementStore().clear() if prices is None: diff --git a/tests/test_geneticcompletetimegrid.py b/tests/test_geneticcompletetimegrid.py index 6711718a..79437d8a 100644 --- a/tests/test_geneticcompletetimegrid.py +++ b/tests/test_geneticcompletetimegrid.py @@ -163,3 +163,119 @@ def test_snapshot_and_warm_start_preserve_aware_instants( assert restored.start_solution_datetime is not None assert restored.start_solution_datetime.timestamp() == expected.timestamp() assert restored.start_solution_datetime.utcoffset() == expected.utcoffset() + + +def _partial_first_slot_run(config_eos, timestamp: str, initial_soc_percentage: int = 20): + """Run GENETIC with AC charge at full power in slot 0 only. + + 1 h slots, 2 h control horizon, no tail. Battery 10 kWh (at 20 % unless + given), 2000 W charge power, ideal efficiencies; base load 400 Wh per hour, + no PV. + """ + config_eos.merge_settings_from_dict( + { + "general": {"latitude": 52.52, "longitude": 13.405}, + "prediction": {"hours": 24}, + "optimization": { + "genetic": { + "interval_sec": 3600, + "horizon_hours": 2, + "tail_horizon_hours": 0, + "terminal_value_mode": "FIXED", + } + }, + } + ) + start = to_datetime(timestamp).in_timezone("Europe/Berlin") + get_ems(init=True).set_start_datetime(start) + count = start.hour + 2 + parameters = GeneticOptimizationParameters.model_validate( + { + "ems": { + "pv_forecast_wh": [0.0] * count, + "total_load": [400.0] * count, + "electricity_price_per_wh": [0.0001] * count, + "feed_in_tariff_per_wh": 0.0, + "price_per_wh_battery": 0.0, + }, + "pv_battery": { + "device_id": "battery1", + "capacity_wh": 10000, + "initial_soc_percentage": initial_soc_percentage, + "min_soc_percentage": 0, + "max_soc_percentage": 100, + "max_charge_power_w": 2000, + "charging_efficiency": 1.0, + "discharging_efficiency": 1.0, + }, + "inverter": { + "device_id": "inverter1", + "battery_id": "battery1", + "max_power_wh": 5000, + "ac_to_dc_efficiency": 1.0, + "dc_to_ac_efficiency": 1.0, + }, + "ev": None, + } + ) + optimizer = GeneticOptimization(fixed_seed=42) + + def full_ac_charge_in_first_slot(*args, **kwargs): + genome = optimizer.create_individual() + genome[:] = [0] * len(genome) + genome[0] = 3 * len(optimizer.bat_possible_charge_values) - 1 + return genome, {} + + with patch.object(optimizer, "optimize", side_effect=full_ac_charge_in_first_slot): + solution = optimizer.optimize_ems(parameters) + return optimizer, solution + + +def test_running_slot_is_planned_for_the_remaining_time_only(config_eos): + """A run at 10:45 has 15 min of slot 0 left, not a full hour. + + Charge power, load and grid energy of slot 0 shrink to a quarter; slot 1 + is a full slot again. + """ + optimizer, solution = _partial_first_slot_run(config_eos, "2026-09-16T10:45:00+02:00") + + assert optimizer.first_slot_fraction == pytest.approx(0.25) + assert solution.first_slot_fraction == pytest.approx(0.25) + result = solution.result + # Slot 0: 15 min of 400 W base load and 2000 W charge power. The load of + # the result includes the AC charge energy. + assert result.grid_consumption_wh_per_hour[0] == pytest.approx(100.0 + 500.0) + assert result.load_wh_per_hour[0] == pytest.approx(100.0 + 500.0) + # SoC at the start of each slot: 500 Wh stored in 15 min, 20 % -> 25 %. + assert result.battery_soc_per_hour[:2] == pytest.approx([20.0, 25.0]) + # Slot 1 is a full slot again. + assert result.grid_consumption_wh_per_hour[1] == pytest.approx(400.0) + + +def test_run_on_a_slot_boundary_plans_a_full_first_slot(config_eos): + """A run exactly at the start of the slot keeps the full slot.""" + optimizer, solution = _partial_first_slot_run(config_eos, "2026-09-16T10:00:00+02:00") + + assert optimizer.first_slot_fraction == pytest.approx(1.0) + assert solution.first_slot_fraction == pytest.approx(1.0) + result = solution.result + assert result.grid_consumption_wh_per_hour[0] == pytest.approx(400.0 + 2000.0) + assert result.battery_soc_per_hour[:2] == pytest.approx([20.0, 40.0]) + + +def test_running_slot_ac_charge_factor_is_not_cut_for_a_full_slot(config_eos): + """The plan clamps the AC charge factor to the headroom of the remaining time. + + At 90 % there are 1000 Wh of headroom. A full hour at 2000 W would exceed it + and the factor would be cut to 0.5; the 15 min left store only 500 Wh, so + full power is sent for the running slot. + """ + _, solution = _partial_first_slot_run( + config_eos, "2026-09-16T10:45:00+02:00", initial_soc_percentage=90 + ) + assert solution.result.battery_soc_per_hour[:2] == pytest.approx([90.0, 95.0]) + plan = solution.energy_management_plan() + battery_instructions = [ + instruction for instruction in plan.instructions if instruction.resource_id == "battery1" + ] + assert battery_instructions[0].operation_mode_factor == pytest.approx(1.0) diff --git a/tests/test_geneticconfigfrozenperrun.py b/tests/test_geneticconfigfrozenperrun.py index 87004409..7e7d1240 100644 --- a/tests/test_geneticconfigfrozenperrun.py +++ b/tests/test_geneticconfigfrozenperrun.py @@ -46,7 +46,7 @@ def _setup(config_eos: ConfigEOS, horizon_hours: int) -> GeneticOptimizationPara }, } ) - ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0)) + ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0, second=0, microsecond=0)) CacheEnergyManagementStore().clear() return GeneticOptimizationParameters.model_validate( dict( diff --git a/tests/test_geneticfitnesscachelimit.py b/tests/test_geneticfitnesscachelimit.py index eca51a05..46f78d62 100644 --- a/tests/test_geneticfitnesscachelimit.py +++ b/tests/test_geneticfitnesscachelimit.py @@ -34,7 +34,7 @@ def _configure_hourly_grid(config_eos: ConfigEOS) -> None: }, } ) - get_ems(init=True).set_start_datetime(to_datetime().set(hour=0, minute=0)) + get_ems(init=True).set_start_datetime(to_datetime().set(hour=0, minute=0, second=0, microsecond=0)) def test_fitness_cache_max_entries_setting_defaults_to_unbounded(): diff --git a/tests/test_geneticinverter.py b/tests/test_geneticinverter.py index b6c4f62b..7e042532 100644 --- a/tests/test_geneticinverter.py +++ b/tests/test_geneticinverter.py @@ -541,3 +541,77 @@ def test_battery_discharge_limit_caps_load_and_grid_export(): assert initial_soc_wh - battery.soc_wh == pytest.approx(1000.0) assert grid_import == pytest.approx(500.0) assert grid_export == 0.0 + + +class TestFirstSlotFraction: + """A run within slot 0 simulates only the remaining part of that slot.""" + + @staticmethod + def _inverter(first_slot_fraction=0.25, battery=None, **parameters): + predictor = Mock() + predictor.calculate_expected_direct_consumption.side_effect = min + with patch( + "akkudoktoreos.devices.genetic.inverter.get_eos_load_interpolator", + return_value=predictor, + ): + inverter = Inverter( + InverterParameters( + device_id="inverter1", + max_power_wh=4000.0, + battery_id=battery.parameters.device_id if battery else None, + **parameters, + ), + battery=battery, + first_slot_fraction=first_slot_fraction, + ) + return inverter, predictor + + def test_slot_0_moves_only_the_remaining_part(self): + inverter, _ = self._inverter() + grid_export, _, losses, _ = inverter.process_energy(5000.0, 0.0, hour=0) + assert grid_export == pytest.approx(1000.0) + assert losses == pytest.approx(4000.0) + grid_export, _, losses, _ = inverter.process_energy(5000.0, 0.0, hour=1) + assert grid_export == pytest.approx(4000.0) + assert losses == pytest.approx(1000.0) + + def test_self_consumption_table_gets_the_power_of_the_remaining_part(self): + """250 Wh in 15 min is 1000 W, not 250 W.""" + inverter, predictor = self._inverter() + inverter.process_energy(500.0, 250.0, hour=0) + predictor.calculate_expected_direct_consumption.assert_called_with(1000.0, 2000.0) + + def test_efficiency_curve_is_read_at_the_power_of_the_remaining_part(self): + inverter, _ = self._inverter( + dc_to_ac_efficiency_curve=[(0.0, 0.97), (0.25, 0.97), (1.0, 0.90)] + ) + # 1000 Wh in 15 min is the full 4000 W. + assert inverter.dc_to_ac_efficiency_at(1000.0, 0.25) == pytest.approx(0.90) + assert inverter.dc_to_ac_efficiency_at(1000.0) == pytest.approx(0.97) + + def test_ac_charge_in_slot_0_uses_the_remaining_part(self): + battery = Battery( + SolarPanelBatteryParameters( + device_id="battery1", + capacity_wh=40_000, + initial_soc_percentage=0, + min_soc_percentage=0, + max_charge_power_w=8_000, + charging_efficiency=1.0, + ), + prediction_hours=2, + first_slot_fraction=0.25, + ) + battery.set_charge_per_hour(np.ones(2)) + inverter, _ = self._inverter( + battery=battery, ac_to_dc_efficiency=1.0, ac_charge_limits_total_charge=True + ) + inverter.begin_ac_charge_slot(0, 0.5) + ac_wh, _ = inverter.charge_battery_from_grid(0, 0.5) + # Half the charge power for 15 min. + assert ac_wh == pytest.approx(1000.0) + + @pytest.mark.parametrize("fraction", [0.0, 1.01]) + def test_invalid_fraction_is_rejected(self, fraction): + with pytest.raises(ValueError, match="first_slot_fraction"): + self._inverter(first_slot_fraction=fraction) diff --git a/tests/test_geneticparallelevaluation.py b/tests/test_geneticparallelevaluation.py index 96ff66a6..cce61013 100644 --- a/tests/test_geneticparallelevaluation.py +++ b/tests/test_geneticparallelevaluation.py @@ -74,7 +74,7 @@ def _parameters( }, } ) - ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0)) + ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0, second=0, microsecond=0)) CacheEnergyManagementStore().clear() return GeneticOptimizationParameters.model_validate( dict( diff --git a/tests/test_geneticseeding.py b/tests/test_geneticseeding.py index 6d4af4df..71946490 100644 --- a/tests/test_geneticseeding.py +++ b/tests/test_geneticseeding.py @@ -30,7 +30,7 @@ def _configure_hourly_grid(config_eos: ConfigEOS, *, start_hour: int = 0) -> Non }, } ) - get_ems(init=True).set_start_datetime(to_datetime().set(hour=start_hour, minute=0)) + get_ems(init=True).set_start_datetime(to_datetime().set(hour=start_hour, minute=0, second=0, microsecond=0)) def test_ev_repair_is_resimulated_before_fitness_assignment(config_eos: ConfigEOS):