mirror of
https://github.com/Akkudoktor-EOS/EOS.git
synced 2026-12-02 18:36:28 +01:00
refactor(genetic): refactor GENETIC to the consolidated optimizer architecture
Pin result, conversion, plan and visualization of golden runs. Drive GENETIC through the optimizer interface and registry. Move GENETIC into one directory with role-named modules. Prepare every run input once, run from the parameters. Fall back instead of cancelling the optimization run. Simulate battery, EV and inverter from frozen dataclasses. Simulate the home appliance from frozen dataclasses. Convert and visualize from the parameters and result only. Serve GENETIC from its own router. Return a frozen result, build responses in the API. Echo the request as sent, not with an invented time window. Additional changes - Pin that the result does not depend on the number of evaluation workers. - Run the golden module in UTC: until the request date-times are held in UTC they render in the host time zone. - Add Optimizer.run_clock(), so the EMS gets slot length and time zone without GENETIC settings. - Rename ConfigOptimizationRequest, RuntimeForecasts and GeneticCommonSettings as ADR 0010 asks. - Correct the request example in ADR 0010. - Record the renamed OpenAPI schemas in CHANGELOG.md and the upgrade guide. - Add replay files that reproduce each golden result from its parameters. - Drop OptimizationBase from the algorithm. - Give the replay and worker tests own review files against xdist races. - Handle a failing preparation in the EMS like a failing run, no separate cancel path. - Record the fallbacks in CHANGELOG.md and the upgrade guide. - Without an inverter, buy the whole load from the grid instead of planning it at no cost. - Do not charge from the grid without any known price. - Treat an infinite value after the control horizon as a gap. - Correct the documentation that said missing forecasts cancel the run. - Copy the efficiency helpers and the self-consumption table evaluation into GENETIC. - Add CycleTimeWindowSequence, ConsumerScheduleMode and ConsumerDeadlinePolicy as contract names. - Hold the date-times of battery, EV and home appliance requests in UTC, so they render the same on every host. - Drop the UTC pin of the GENETIC golden module; the request date-times no longer depend on the host. - Copy the time window logic GENETIC needs into genetictimewindow.py. - Add ValueTimeWindow as a contract name. - Move the settings' to_genetic_*() converters into the preparation. - Drop the conversion's prediction reads and configuration fallbacks, which runs never reached. - Make the moved docstrings valid reST. - Remove the generic optimization solution route; each optimizer serves its own path. - Import the GENETIC settings from the package. - Record the removed route in CHANGELOG.md and the upgrade guide. - Make the terminal and tail value models frozen dataclasses. - Move the response models into geneticapi; remove geneticsolution and geneticabc. - Remove the legacy appliance start arrays and API, which read the wall clock. - Remove the time window helpers only they used. - Echo a start_solution without start_solution_datetime as sent. - Carry the previous solution's start in the run parameters. - Plan the home appliance cycles that fit, or leave the appliance out, instead of failing. - Move the appliance layout rules into geneticappliancelayout for the preparation. - Leave out a DAILY home appliance whose open windows leave no room for a run, with an error log, instead of silently. - Name the reason of the SoC fallback instead of Python's exception text. - Answer a solution request for an unknown algorithm with a 404 problem response. - Record the fixes in CHANGELOG.md and the upgrade guide. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Assisted-by: Claude Code (claude-opus-5-5)
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
b108335ee4
commit
b3d5334d3e
@@ -0,0 +1,30 @@
|
||||
"""GENETIC optimizer: the only module code outside the optimizer imports (ADR 0005).
|
||||
|
||||
``GeneticOptimizer``, ``GeneticSettings`` and ``normalize_genetic_settings`` are loaded on first
|
||||
access, so importing the package does not load the optimizer and its simulation.
|
||||
"""
|
||||
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from akkudoktoreos.optimization.genetic.geneticoptimizer import GeneticOptimizer
|
||||
from akkudoktoreos.optimization.genetic.geneticsettings import (
|
||||
GeneticSettings,
|
||||
normalize_genetic_settings,
|
||||
)
|
||||
|
||||
__all__ = ["GeneticOptimizer", "GeneticSettings", "normalize_genetic_settings"]
|
||||
|
||||
|
||||
def __getattr__(name: str) -> Any:
|
||||
if name == "GeneticOptimizer":
|
||||
from akkudoktoreos.optimization.genetic.geneticoptimizer import (
|
||||
GeneticOptimizer,
|
||||
)
|
||||
|
||||
return GeneticOptimizer
|
||||
if name in ("GeneticSettings", "normalize_genetic_settings"):
|
||||
from akkudoktoreos.optimization.genetic import geneticsettings
|
||||
|
||||
return getattr(geneticsettings, name)
|
||||
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
||||
@@ -1,398 +0,0 @@
|
||||
"""Configuration-owned GENETIC requests with fresh runtime observations."""
|
||||
|
||||
import math
|
||||
from typing import Annotated, Any, Optional
|
||||
|
||||
import pandas as pd
|
||||
from loguru import logger
|
||||
from pydantic import AliasChoices, Field, field_validator
|
||||
|
||||
from akkudoktoreos.core.coreabc import (
|
||||
ConfigMixin,
|
||||
MeasurementMixin,
|
||||
PredictionMixin,
|
||||
get_ems,
|
||||
)
|
||||
from akkudoktoreos.devices.settings.batteryresolution import BatteryFullCharge
|
||||
from akkudoktoreos.devices.settings.batterysettings import BatteriesCommonSettings
|
||||
from akkudoktoreos.optimization.genetic.forecast import bounded_forecast_array
|
||||
from akkudoktoreos.optimization.genetic.fullcharge import (
|
||||
enforced_full_charge_deadline,
|
||||
full_charge_deadline,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticabc import GeneticParametersBaseModel
|
||||
from akkudoktoreos.optimization.genetic.geneticparams import (
|
||||
GeneticEnergyManagementParameters,
|
||||
GeneticOptimizationParameters,
|
||||
)
|
||||
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):
|
||||
"""External series from local midnight, in slot Wh and currency per Wh.
|
||||
|
||||
The interval is configured in optimization.genetic.interval_sec. Omitted
|
||||
series are read from the configured providers, preserving their raw coverage.
|
||||
"""
|
||||
|
||||
pv_forecast_wh: Optional[list[float]] = Field(
|
||||
default=None, validation_alias=AliasChoices("pv_forecast_wh", "pv_prognose_wh")
|
||||
)
|
||||
total_load: Optional[list[float]] = Field(
|
||||
default=None, validation_alias=AliasChoices("total_load", "gesamtlast")
|
||||
)
|
||||
electricity_price_per_wh: Optional[list[float]] = Field(
|
||||
default=None,
|
||||
validation_alias=AliasChoices("electricity_price_per_wh", "strompreis_euro_pro_wh"),
|
||||
)
|
||||
feed_in_tariff_per_wh: Optional[list[float]] = Field(
|
||||
default=None,
|
||||
validation_alias=AliasChoices("feed_in_tariff_per_wh", "einspeiseverguetung_euro_pro_wh"),
|
||||
)
|
||||
temperature_forecast: Optional[list[Optional[float]]] = None
|
||||
|
||||
|
||||
class ConfigOptimizationRequest(
|
||||
ConfigMixin, MeasurementMixin, PredictionMixin, GeneticParametersBaseModel
|
||||
):
|
||||
"""Supply observations while hardware, tariffs and scheduling remain in config.
|
||||
|
||||
Explicit SoC values take precedence over fresh measurements. Without a usable
|
||||
measurement, assume 0% initial SoC for the affected device and continue.
|
||||
"""
|
||||
|
||||
soc: dict[str, Annotated[int, Field(ge=0, le=100)]] = Field(default_factory=dict)
|
||||
forecasts: RuntimeForecasts = Field(default_factory=RuntimeForecasts)
|
||||
start_solution: Optional[list[float]] = None
|
||||
start_solution_datetime: Optional[DateTime] = None
|
||||
|
||||
@field_validator("start_solution_datetime", mode="before")
|
||||
@classmethod
|
||||
def validate_start_solution_datetime(cls, value: Any) -> Optional[DateTime]:
|
||||
"""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
|
||||
settings = config.optimization.genetic
|
||||
config.validate_optimization_horizons()
|
||||
ems = get_ems()
|
||||
start = ems.start_datetime
|
||||
observation_time = ems.observation_datetime
|
||||
devices = config.devices
|
||||
groups: dict[str, list[Any]] = {}
|
||||
for name in ("batteries", "electric_vehicles", "inverters", "home_appliances"):
|
||||
entries = list((getattr(devices, name) or {}).values())
|
||||
maximum = getattr(devices, "max_" + name)
|
||||
if maximum is not None and len(entries) > maximum:
|
||||
raise ValueError(f"devices.{name} exceeds configured maximum {maximum}.")
|
||||
if name != "home_appliances" and len(entries) > 1:
|
||||
raise ValueError(f"GENETIC supports at most one device in devices.{name}.")
|
||||
groups[name] = entries
|
||||
ids = [device.device_id for entries in groups.values() for device in entries]
|
||||
if len(ids) != len(set(ids)):
|
||||
raise ValueError("Configured device IDs must be unique across device groups.")
|
||||
storage = groups["batteries"] + groups["electric_vehicles"]
|
||||
unknown = set(self.soc) - {device.device_id for device in storage}
|
||||
if unknown:
|
||||
raise ValueError(f"SoC supplied for unconfigured devices: {sorted(unknown)}.")
|
||||
|
||||
async def state(device: BatteriesCommonSettings) -> int:
|
||||
if device.device_id in self.soc:
|
||||
return self.soc[device.device_id]
|
||||
try:
|
||||
dates, values = await self.measurement.key_to_lists(
|
||||
key=device.measurement_key_soc_factor,
|
||||
start_datetime=observation_time.subtract(
|
||||
seconds=settings.measurement_max_age_seconds
|
||||
),
|
||||
end_datetime=observation_time.add(seconds=1),
|
||||
dropna=False,
|
||||
)
|
||||
# Records without a SoC value (e.g. a meter reading stored by an
|
||||
# adapter, or pandas NA) must not hide an older SoC within the age
|
||||
# limit (#1447). An explicit NaN stays an invalid sample.
|
||||
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
|
||||
]
|
||||
date, value = max(samples, key=lambda sample: sample[0].timestamp())
|
||||
if (
|
||||
observation_time.timestamp() - date.timestamp()
|
||||
> settings.measurement_max_age_seconds
|
||||
or not math.isfinite(value)
|
||||
or not 0 <= value <= 1
|
||||
):
|
||||
raise ValueError("Invalid or stale SoC factor")
|
||||
return int(value * 100)
|
||||
except (ValueError, KeyError) as exc:
|
||||
logger.warning(
|
||||
"No usable fresh SoC for {}; assuming 0% initial SoC for this "
|
||||
"optimization (not a measurement): {}",
|
||||
device.device_id,
|
||||
exc,
|
||||
)
|
||||
return 0
|
||||
|
||||
async def full_charge(
|
||||
device: BatteriesCommonSettings, policy: BatteryFullCharge
|
||||
) -> Optional[DateTime]:
|
||||
"""Deadline of the next periodic full charge, None if disabled or unknown."""
|
||||
interval_days = policy.interval_days
|
||||
if interval_days is None:
|
||||
return None
|
||||
try:
|
||||
dates, values = await self.measurement.key_to_lists(
|
||||
key=device.measurement_key_soc_factor,
|
||||
start_datetime=observation_time.subtract(days=math.ceil(interval_days)),
|
||||
end_datetime=observation_time.add(seconds=1),
|
||||
dropna=False,
|
||||
)
|
||||
except KeyError:
|
||||
dates, values = [], []
|
||||
deadline = full_charge_deadline(
|
||||
zip(dates, values),
|
||||
now=observation_time,
|
||||
interval_days=interval_days,
|
||||
detect_percentage=policy.detect_percentage,
|
||||
)
|
||||
if deadline is None:
|
||||
logger.warning(
|
||||
"No state of charge history for {}; cannot schedule its periodic full charge.",
|
||||
device.device_id,
|
||||
)
|
||||
return deadline
|
||||
|
||||
# A battery configuration error does not cancel the run: the battery gets
|
||||
# default values for what cannot be resolved, and an error is logged.
|
||||
battery = None
|
||||
if groups["batteries"]:
|
||||
device = groups["batteries"][0]
|
||||
(
|
||||
operating_parameters,
|
||||
use_profile_tables,
|
||||
) = await device.resolve_current_operating_parameters_or_defaults(observation_time)
|
||||
battery = device.to_genetic_pv_bat_param(operating_parameters, use_profile_tables)
|
||||
battery.initial_soc_percentage = await state(device)
|
||||
policy = device.resolve_full_charge()
|
||||
deadline = await full_charge(device, policy)
|
||||
horizon_end = start.add(seconds=settings.horizon * settings.interval_sec)
|
||||
if deadline is not None and deadline.timestamp() <= horizon_end.timestamp():
|
||||
# Due within the horizon: lift the upper limit so the battery may
|
||||
# reach the target, and enforce the target only if grid charging
|
||||
# is allowed for it. The target is within the technical SOC bounds.
|
||||
target = policy.soc_percentage
|
||||
battery.max_soc_percentage = max(battery.max_soc_percentage, target)
|
||||
if device.full_charge_allow_grid:
|
||||
enforced = enforced_full_charge_deadline(deadline, observation_time)
|
||||
battery.full_charge_soc_percentage = target
|
||||
battery.full_charge_deadline_datetime = enforced
|
||||
logger.info(
|
||||
"Periodic full charge of {} to {}% due by {}; enforced by {}.",
|
||||
device.device_id,
|
||||
target,
|
||||
deadline,
|
||||
enforced,
|
||||
)
|
||||
else:
|
||||
logger.info(
|
||||
"Periodic full charge of {} to {}% due by {}; PV surplus only.",
|
||||
device.device_id,
|
||||
target,
|
||||
deadline,
|
||||
)
|
||||
ev = None
|
||||
if groups["electric_vehicles"]:
|
||||
device = groups["electric_vehicles"][0]
|
||||
(
|
||||
operating_parameters,
|
||||
use_profile_tables,
|
||||
) = await device.resolve_current_operating_parameters_or_defaults(observation_time)
|
||||
ev = device.to_genetic_ev_bat_param(operating_parameters, use_profile_tables)
|
||||
ev.initial_soc_percentage = await state(device)
|
||||
inverter = None
|
||||
if groups["inverters"]:
|
||||
device = groups["inverters"][0]
|
||||
if device.battery_id != (battery.device_id if battery else None):
|
||||
raise ValueError("Inverter battery_id must match the configured battery.")
|
||||
# The derating of the inverter profile applies at the measured
|
||||
# ambient temperature, 45 degC without a measurement.
|
||||
inverter = device.to_genetic_param(
|
||||
await device.resolve_current_operating_parameters_or_defaults(observation_time)
|
||||
)
|
||||
if inverter is None:
|
||||
raise ValueError("Configure an inverter to model PV and grid energy flows.")
|
||||
appliances = [device.to_genetic_param() for device in groups["home_appliances"]]
|
||||
for device, appliance in zip(groups["home_appliances"], appliances):
|
||||
key = device.cycles_completed_measurement_key or f"{device.device_id}.cycles_completed"
|
||||
try:
|
||||
dates, counts = await self.measurement.key_to_lists(
|
||||
key=key,
|
||||
start_datetime=observation_time.start_of("day"),
|
||||
end_datetime=observation_time.add(seconds=1),
|
||||
dropna=False,
|
||||
)
|
||||
except KeyError:
|
||||
continue
|
||||
# Skip records without a count (e.g. an adapter's meter reading, #1447).
|
||||
samples = [
|
||||
(date, count)
|
||||
for date, count in zip(dates, counts)
|
||||
if date.timestamp() <= observation_time.timestamp()
|
||||
and count is not None
|
||||
and count is not pd.NA
|
||||
]
|
||||
if not samples:
|
||||
continue
|
||||
count = max(samples, key=lambda item: item[0].timestamp())[1]
|
||||
if (
|
||||
not math.isfinite(count)
|
||||
or int(count) != count
|
||||
or not 0 <= count <= appliance.num_cycles
|
||||
):
|
||||
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:
|
||||
raise ValueError("Configure a positive prediction horizon.")
|
||||
end = start.add(hours=config.prediction.hours)
|
||||
interval = to_duration(settings.interval_sec)
|
||||
updated = False
|
||||
|
||||
async def forecast(
|
||||
supplied: Optional[list[float]], key: str, energy: bool = False
|
||||
) -> list[float]:
|
||||
nonlocal updated
|
||||
if supplied is not None:
|
||||
return list(supplied)
|
||||
if not updated:
|
||||
await self.prediction.update_data()
|
||||
updated = True
|
||||
values = await bounded_forecast_array(
|
||||
self.prediction, key=key, start_datetime=origin, end_datetime=end, interval=interval
|
||||
)
|
||||
if energy:
|
||||
values = values * (settings.interval_sec / 3600)
|
||||
return values.tolist()
|
||||
|
||||
supplied = self.forecasts
|
||||
pv = await forecast(supplied.pv_forecast_wh, "pvforecast_ac_power", energy=True)
|
||||
load = await forecast(supplied.total_load, "loadforecast_power_w", energy=True)
|
||||
prices = await forecast(supplied.electricity_price_per_wh, "elecprice_marketprice_wh")
|
||||
tariffs = await forecast(supplied.feed_in_tariff_per_wh, "feed_in_tariff_wh")
|
||||
length = min(len(pv), len(load), len(prices), len(tariffs))
|
||||
if not length:
|
||||
raise ValueError("Forecast series must be nonempty.")
|
||||
pv, load, prices, tariffs = (values[:length] for values in (pv, load, prices, tariffs))
|
||||
first = int((start - origin).total_seconds() / settings.interval_sec)
|
||||
last = first + settings.horizon
|
||||
if settings.horizon <= 0 or len(pv) < last:
|
||||
raise ValueError("Forecast does not cover the positive GENETIC control horizon.")
|
||||
for key, values in (
|
||||
("PV", pv),
|
||||
("load", load),
|
||||
("prices", prices),
|
||||
("feed-in tariff", tariffs),
|
||||
):
|
||||
missing = [index for index in range(first, last) if not math.isfinite(values[index])]
|
||||
if missing:
|
||||
left = origin.add(seconds=missing[0] * settings.interval_sec)
|
||||
right = left.add(seconds=settings.interval_sec)
|
||||
raise ValueError(
|
||||
f"Missing or invalid {key} within the control horizon. "
|
||||
f"First invalid interval: [{left.isoformat()}, {right.isoformat()}); "
|
||||
f"{len(missing)} invalid interval(s)."
|
||||
)
|
||||
if any(value < 0 for values in (pv, load) for value in values[first:last]):
|
||||
raise ValueError("PV and load energy must be nonnegative.")
|
||||
previous = ems.genetic_solution()
|
||||
warm_start = self.start_solution
|
||||
warm_start_time = self.start_solution_datetime
|
||||
if warm_start is None and previous is not None:
|
||||
warm_start = previous.start_solution
|
||||
warm_start_time = previous.start_solution_datetime
|
||||
return GeneticOptimizationParameters(
|
||||
forecast_interval_seconds=settings.interval_sec,
|
||||
ems=GeneticEnergyManagementParameters(
|
||||
pv_forecast_wh=pv,
|
||||
total_load=load,
|
||||
electricity_price_per_wh=prices,
|
||||
feed_in_tariff_per_wh=tariffs,
|
||||
price_per_wh_battery=settings.terminal_value_euro_per_kwh / 1000,
|
||||
),
|
||||
pv_battery=battery,
|
||||
ev=ev,
|
||||
inverter=inverter,
|
||||
home_appliances=appliances,
|
||||
temperature_forecast=(
|
||||
(supplied.temperature_forecast[:length] + [None] * length)[:length]
|
||||
if supplied.temperature_forecast is not None
|
||||
else None
|
||||
),
|
||||
start_solution=warm_start,
|
||||
start_solution_datetime=warm_start_time,
|
||||
)
|
||||
@@ -0,0 +1,704 @@
|
||||
"""Battery and electric vehicle of the GENETIC simulation."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Iterator, Optional
|
||||
|
||||
import numpy as np
|
||||
|
||||
# Values of a power limit table: one per SoC percent, 0 % ... 100 %.
|
||||
SOC_TABLE_POINTS = 101
|
||||
# Charge rates of a battery that has none of its own.
|
||||
DEFAULT_CHARGE_RATES: tuple[float, ...] = (0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0)
|
||||
|
||||
# Resolution of the dense efficiency tables: one value per power percent.
|
||||
_EFFICIENCY_TABLE_POINTS = 101
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class GeneticBatteryParameters:
|
||||
"""A battery or electric vehicle of the simulation, derived from its request.
|
||||
|
||||
Attributes:
|
||||
device_id: ID of the battery.
|
||||
capacity_wh: Capacity [Wh].
|
||||
charging_efficiency: Charging efficiency (0, 1].
|
||||
discharging_efficiency: Discharging efficiency (0, 1].
|
||||
max_charge_power_w: Maximum charging power [W]; ``None`` is the capacity per hour.
|
||||
max_discharge_power_w: Maximum discharging power [W]; ``None`` is the charging power.
|
||||
initial_soc_percentage: State of charge at the start of the run [%].
|
||||
min_soc_percentage: Lowest state of charge the simulation allows [%]; 0 for an
|
||||
electric vehicle, whose minimum is a charging target instead.
|
||||
max_soc_percentage: Highest state of charge [%].
|
||||
charge_rates: Selectable charge rates; ``None`` or empty uses ``DEFAULT_CHARGE_RATES``.
|
||||
charge_power_limit_w_by_soc: Charging power limit per SoC percent [W].
|
||||
discharge_power_limit_w_by_soc: Discharging power limit per SoC percent [W].
|
||||
charging_efficiency_curve: Charging efficiency by power fraction.
|
||||
discharging_efficiency_curve: Discharging efficiency by power fraction.
|
||||
levelized_cost_of_storage_kwh: Wear cost of stored energy [currency/kWh]; 0 for an
|
||||
electric vehicle.
|
||||
electric_vehicle: The vehicle's BMS ends charging when full, even within a slot.
|
||||
"""
|
||||
|
||||
device_id: str
|
||||
capacity_wh: int
|
||||
charging_efficiency: float
|
||||
discharging_efficiency: float
|
||||
max_charge_power_w: Optional[float]
|
||||
max_discharge_power_w: Optional[float]
|
||||
initial_soc_percentage: int
|
||||
min_soc_percentage: int
|
||||
max_soc_percentage: int
|
||||
charge_rates: Optional[tuple[float, ...]]
|
||||
charge_power_limit_w_by_soc: Optional[tuple[float, ...]]
|
||||
discharge_power_limit_w_by_soc: Optional[tuple[float, ...]]
|
||||
charging_efficiency_curve: Optional[tuple[tuple[float, float], ...]]
|
||||
discharging_efficiency_curve: Optional[tuple[tuple[float, float], ...]]
|
||||
levelized_cost_of_storage_kwh: float
|
||||
electric_vehicle: bool
|
||||
|
||||
|
||||
def _dense_efficiency_table(
|
||||
curve: Optional[tuple[tuple[float, float], ...]],
|
||||
) -> Optional[list[float]]:
|
||||
"""Interpolate an efficiency curve at every power percent 0 % ... 100 %."""
|
||||
if curve is None:
|
||||
return None
|
||||
fractions, efficiencies = zip(*curve)
|
||||
grid = np.linspace(0.0, 1.0, _EFFICIENCY_TABLE_POINTS)
|
||||
return [float(value) for value in np.interp(grid, fractions, efficiencies)]
|
||||
|
||||
|
||||
class _PowerCurves:
|
||||
"""Battery profile data of a simulated battery, prepared for fast access.
|
||||
|
||||
All values are precomputed for the slot duration of the battery, so the
|
||||
simulation only scales and indexes per call. Every table has 101 entries
|
||||
(index 0 ... 100); the hot paths rely on that bound.
|
||||
|
||||
Attributes:
|
||||
charge_limit_wh_by_soc: Raw charge energy of one slot [Wh] per SoC
|
||||
percent, capped at the rated charge power. None without limit table.
|
||||
discharge_limit_wh_by_soc: Raw discharge energy of one slot [Wh] per
|
||||
SoC percent, capped at the rated discharge power. None without table.
|
||||
charging_efficiency_by_power: Charging efficiency per power percent of
|
||||
the rated charge power. None without curve.
|
||||
discharging_efficiency_by_power: Discharging efficiency per power
|
||||
percent of the rated discharge power. None without curve.
|
||||
soc_index_per_wh: Factor from stored energy [Wh] to SoC percent.
|
||||
charge_index_per_wh: Factor from raw charge energy of one slot [Wh] to
|
||||
power percent of the rated charge power.
|
||||
discharge_index_per_wh: Factor from raw discharge energy of one slot
|
||||
[Wh] to power percent of the rated discharge power.
|
||||
discharged_dc_wh_per_slot: Energy delivered by the battery per slot [Wh].
|
||||
charged_stored_wh_per_slot: Energy stored into the battery per slot [Wh].
|
||||
"""
|
||||
|
||||
__slots__ = (
|
||||
"charge_limit_wh_by_soc",
|
||||
"discharge_limit_wh_by_soc",
|
||||
"charging_efficiency_by_power",
|
||||
"discharging_efficiency_by_power",
|
||||
"soc_index_per_wh",
|
||||
"charge_index_per_wh",
|
||||
"discharge_index_per_wh",
|
||||
"discharged_dc_wh_per_slot",
|
||||
"charged_stored_wh_per_slot",
|
||||
)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parameters: GeneticBatteryParameters,
|
||||
capacity_wh: float,
|
||||
max_charge_power_w: float,
|
||||
max_discharge_power_w: float,
|
||||
slot_duration_h: float,
|
||||
slots: int,
|
||||
) -> None:
|
||||
rated_charge_wh = max_charge_power_w * slot_duration_h
|
||||
rated_discharge_wh = max_discharge_power_w * slot_duration_h
|
||||
self.charge_limit_wh_by_soc: Optional[list[float]] = (
|
||||
[min(limit_w * slot_duration_h, rated_charge_wh) for limit_w in limits]
|
||||
if (limits := parameters.charge_power_limit_w_by_soc) is not None
|
||||
else None
|
||||
)
|
||||
self.discharge_limit_wh_by_soc: Optional[list[float]] = (
|
||||
[min(limit_w * slot_duration_h, rated_discharge_wh) for limit_w in limits]
|
||||
if (limits := parameters.discharge_power_limit_w_by_soc) is not None
|
||||
else None
|
||||
)
|
||||
self.charging_efficiency_by_power = _dense_efficiency_table(
|
||||
parameters.charging_efficiency_curve
|
||||
)
|
||||
self.discharging_efficiency_by_power = _dense_efficiency_table(
|
||||
parameters.discharging_efficiency_curve
|
||||
)
|
||||
self.soc_index_per_wh = 100.0 / capacity_wh
|
||||
# A rated power of 0 W maps every energy to the 0 % entry.
|
||||
self.charge_index_per_wh = 100.0 / rated_charge_wh if rated_charge_wh > 0 else 0.0
|
||||
self.discharge_index_per_wh = 100.0 / rated_discharge_wh if rated_discharge_wh > 0 else 0.0
|
||||
self.discharged_dc_wh_per_slot = [0.0] * slots
|
||||
self.charged_stored_wh_per_slot = [0.0] * slots
|
||||
|
||||
def reset(self, slots: int) -> None:
|
||||
"""Clear the delivered and stored energy of all slots."""
|
||||
self.discharged_dc_wh_per_slot = [0.0] * slots
|
||||
self.charged_stored_wh_per_slot = [0.0] * slots
|
||||
|
||||
|
||||
def _table_entry(table: list[float], index: int) -> float:
|
||||
"""Return a table entry, with the index clamped to the table."""
|
||||
if index <= 0:
|
||||
return table[0]
|
||||
if index >= len(table):
|
||||
return table[-1]
|
||||
return table[index]
|
||||
|
||||
|
||||
class GeneticBattery:
|
||||
"""Represents a battery device with methods to simulate energy charging and discharging."""
|
||||
|
||||
# Battery profile data, set per instance only if the parameters provide it.
|
||||
# A class default keeps plain batteries small: the simulation reads their
|
||||
# attributes for every slot of every candidate plan, and CPython accesses
|
||||
# attributes of instances with 30 or more of them noticeably slower.
|
||||
_curves: Optional[_PowerCurves] = None
|
||||
|
||||
@property
|
||||
def has_power_curves(self) -> bool:
|
||||
"""Whether charging or discharging depends on SoC or power (battery profile)."""
|
||||
return self._curves is not None
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parameters: GeneticBatteryParameters,
|
||||
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
|
||||
self.initial_soc_percentage = self.parameters.initial_soc_percentage
|
||||
self.charging_efficiency = self.parameters.charging_efficiency
|
||||
self.discharging_efficiency = self.parameters.discharging_efficiency
|
||||
self.levelized_cost_of_storage_kwh = self.parameters.levelized_cost_of_storage_kwh
|
||||
|
||||
# Charge rates, in case of None use default
|
||||
self.charge_rates = np.array(DEFAULT_CHARGE_RATES, dtype=float)
|
||||
if self.parameters.charge_rates:
|
||||
charge_rates = np.array(self.parameters.charge_rates, dtype=float)
|
||||
charge_rates = np.unique(charge_rates)
|
||||
charge_rates.sort()
|
||||
self.charge_rates = charge_rates
|
||||
|
||||
self.min_soc_percentage = self.parameters.min_soc_percentage
|
||||
self.max_soc_percentage = self.parameters.max_soc_percentage
|
||||
|
||||
# Initialize state of charge
|
||||
if self.parameters.max_charge_power_w is not None:
|
||||
self.max_charge_power_w = self.parameters.max_charge_power_w
|
||||
else:
|
||||
self.max_charge_power_w = self.capacity_wh # TODO this should not be equal capacity_wh
|
||||
if self.parameters.max_discharge_power_w is not None:
|
||||
self.max_discharge_power_w = self.parameters.max_discharge_power_w
|
||||
else:
|
||||
self.max_discharge_power_w = self.max_charge_power_w
|
||||
|
||||
# Optional battery profile data: power limits per SoC percent and
|
||||
# efficiencies per power percent.
|
||||
parameters = self.parameters
|
||||
if (
|
||||
parameters.charge_power_limit_w_by_soc is not None
|
||||
or parameters.discharge_power_limit_w_by_soc is not None
|
||||
or parameters.charging_efficiency_curve is not None
|
||||
or parameters.discharging_efficiency_curve is not None
|
||||
):
|
||||
self._curves = _PowerCurves(
|
||||
parameters,
|
||||
self.capacity_wh,
|
||||
self.max_charge_power_w,
|
||||
self.max_discharge_power_w,
|
||||
self.slot_duration_h,
|
||||
self.prediction_hours,
|
||||
)
|
||||
|
||||
self.discharge_array = np.full(self.prediction_hours, 0)
|
||||
self.charge_array = np.full(self.prediction_hours, 0)
|
||||
# Discharged energy per slot, a plain list: it is read and written one
|
||||
# slot at a time for every candidate plan, where single NumPy elements
|
||||
# (and the NumPy scalars they return) are slow.
|
||||
self._discharged_raw_wh_per_slot: list[float] = [0.0] * self.prediction_hours
|
||||
self._charged_raw_wh_per_slot: list[float] = [0.0] * self.prediction_hours
|
||||
# Optional per-slot cap on the raw charge energy from all sources. It is
|
||||
# unbounded unless an inverter restricts a slot (see limit_slot_charge).
|
||||
# Like the charged energy it is kept in a plain list: both are read and
|
||||
# written one slot at a time for every candidate plan, where single
|
||||
# NumPy elements (and the NumPy scalars they return) are slow.
|
||||
self._charge_limit_raw_wh_per_slot: list[float] = [float("inf")] * self.prediction_hours
|
||||
self.soc_wh = (self.initial_soc_percentage / 100) * self.capacity_wh
|
||||
self.min_soc_wh = (self.min_soc_percentage / 100) * self.capacity_wh
|
||||
self.max_soc_wh = (self.max_soc_percentage / 100) * self.capacity_wh
|
||||
|
||||
def _lower_charge_rates_desc(self, start_rate: float) -> Iterator[float]:
|
||||
"""Yield all charge rates lower than a given rate in descending order.
|
||||
|
||||
Args:
|
||||
charge_rates (np.ndarray): Sorted 1D array of available charge rates.
|
||||
start_rate (float): The reference charge rate.
|
||||
|
||||
Yields:
|
||||
float: Charge rates lower than `start_rate`, in descending order.
|
||||
"""
|
||||
charge_rates_fast = self.charge_rates
|
||||
|
||||
# Find the insertion index for start_rate (left-most position)
|
||||
idx = np.searchsorted(charge_rates_fast, start_rate, side="left")
|
||||
|
||||
# Yield values before idx in reverse (descending)
|
||||
return (charge_rates_fast[j] for j in range(idx - 1, -1, -1))
|
||||
|
||||
def _charge_rates_descending(self) -> tuple[float, ...]:
|
||||
"""Return the charge rates from highest to lowest as plain numbers.
|
||||
|
||||
Built once per ``charge_rates`` array instead of searching and slicing
|
||||
the array for every charge request that does not fit.
|
||||
"""
|
||||
rates = self.charge_rates
|
||||
if rates is not getattr(self, "_charge_rates_desc_source", None):
|
||||
self._charge_rates_desc = tuple(float(rate) for rate in rates[::-1])
|
||||
self._charge_rates_desc_source = rates
|
||||
return self._charge_rates_desc
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
"""Converts the object to a dictionary representation."""
|
||||
return {
|
||||
"device_id": self.parameters.device_id,
|
||||
"capacity_wh": self.capacity_wh,
|
||||
"initial_soc_percentage": self.initial_soc_percentage,
|
||||
"soc_wh": self.soc_wh,
|
||||
"hours": self.prediction_hours,
|
||||
"discharge_array": self.discharge_array,
|
||||
"charge_array": self.charge_array,
|
||||
"charging_efficiency": self.charging_efficiency,
|
||||
"discharging_efficiency": self.discharging_efficiency,
|
||||
"max_charge_power_w": self.max_charge_power_w,
|
||||
"max_discharge_power_w": self.max_discharge_power_w,
|
||||
}
|
||||
|
||||
def reset(self) -> None:
|
||||
"""Resets the battery state to its initial values."""
|
||||
self.soc_wh = (self.initial_soc_percentage / 100) * self.capacity_wh
|
||||
self.soc_wh = min(self.soc_wh, self.max_soc_wh) # Only clamp to max
|
||||
self.discharge_array = np.zeros(self.prediction_hours, dtype=np.int_)
|
||||
self.charge_array = np.zeros(self.prediction_hours, dtype=np.int_)
|
||||
self._discharged_raw_wh_per_slot = [0.0] * self.prediction_hours
|
||||
self._charged_raw_wh_per_slot = [0.0] * self.prediction_hours
|
||||
if self._curves is not None:
|
||||
self._curves.reset(self.prediction_hours)
|
||||
self._charge_limit_raw_wh_per_slot = [float("inf")] * self.prediction_hours
|
||||
|
||||
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 * 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, 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 / scale * curves.discharge_index_per_wh + 0.5),
|
||||
)
|
||||
|
||||
def limit_slot_charge(self, hour: int, raw_wh: float) -> None:
|
||||
"""Cap the raw energy the battery may take in one slot, from all sources.
|
||||
|
||||
The cap covers PV and grid charging together and is not raised by later
|
||||
calls within the same slot. It is lifted again by ``reset()``.
|
||||
|
||||
Args:
|
||||
hour (int): Slot index.
|
||||
raw_wh (float): Maximum raw charge energy [Wh] before charging efficiency.
|
||||
"""
|
||||
self._charge_limit_raw_wh_per_slot[hour] = min(
|
||||
self._charge_limit_raw_wh_per_slot[hour], max(float(raw_wh), 0.0)
|
||||
)
|
||||
|
||||
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.
|
||||
"""
|
||||
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(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, self.slot_scale(hour)
|
||||
)
|
||||
|
||||
def discharge_released(self, hour: int) -> bool:
|
||||
"""Whether the plan lets the battery discharge in this slot."""
|
||||
return self.discharge_array[hour] != 0
|
||||
|
||||
def discharged_energy_wh(self, hour: int) -> float:
|
||||
"""Return DC energy delivered by the battery in one optimization slot."""
|
||||
if self._curves is not None:
|
||||
return self._curves.discharged_dc_wh_per_slot[hour]
|
||||
return self._discharged_raw_wh_per_slot[hour] * self.discharging_efficiency
|
||||
|
||||
def charged_energy_wh(self, hour: int) -> float:
|
||||
"""Return the energy stored into the battery in one optimization slot."""
|
||||
if self._curves is not None:
|
||||
return self._curves.charged_stored_wh_per_slot[hour]
|
||||
return self._charged_raw_wh_per_slot[hour] * self.charging_efficiency
|
||||
|
||||
def set_discharge_per_hour(self, discharge_array: np.ndarray) -> None:
|
||||
"""Sets the discharge values for each hour."""
|
||||
if len(discharge_array) != self.prediction_hours:
|
||||
raise ValueError(
|
||||
f"Discharge array must have exactly {self.prediction_hours} elements. Got {len(discharge_array)} elements."
|
||||
)
|
||||
self.discharge_array = np.array(discharge_array)
|
||||
|
||||
def set_charge_per_hour(self, charge_array: np.ndarray) -> None:
|
||||
"""Sets the charge values for each hour."""
|
||||
if len(charge_array) != self.prediction_hours:
|
||||
raise ValueError(
|
||||
f"Charge array must have exactly {self.prediction_hours} elements. Got {len(charge_array)} elements."
|
||||
)
|
||||
self.charge_array = np.array(charge_array)
|
||||
|
||||
def current_soc_percentage(self) -> float:
|
||||
"""Calculates the current state of charge in percentage."""
|
||||
return (self.soc_wh / self.capacity_wh) * 100
|
||||
|
||||
def discharge_energy(self, wh: float, hour: int) -> tuple[float, float]:
|
||||
"""Discharge energy from the battery.
|
||||
|
||||
Discharge is limited by:
|
||||
|
||||
* Requested delivered energy
|
||||
* Remaining energy above minimum SoC
|
||||
* Maximum discharge power, and the power limit at the current SoC if
|
||||
``discharge_power_limit_w_by_soc`` is given
|
||||
* Discharge efficiency, at the slot power if
|
||||
``discharging_efficiency_curve`` is given
|
||||
|
||||
Args:
|
||||
wh (float): Requested delivered energy in watt-hours.
|
||||
hour (int): Time index. If `self.discharge_array[hour] == 0`,
|
||||
no discharge occurs.
|
||||
|
||||
Returns:
|
||||
tuple[float, float]:
|
||||
delivered_wh (float): Actual delivered energy [Wh].
|
||||
losses_wh (float): Conversion losses [Wh].
|
||||
|
||||
"""
|
||||
if self.discharge_array[hour] == 0:
|
||||
return 0.0, 0.0
|
||||
|
||||
# Raw extractable energy above minimum SoC
|
||||
raw_available_wh = max(self.soc_wh - self.min_soc_wh, 0.0)
|
||||
if raw_available_wh == 0.0:
|
||||
# A measured SoC below the reserve must not be raised by discharging.
|
||||
return 0.0, 0.0
|
||||
|
||||
# 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, 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 * 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 * 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)
|
||||
) * scale
|
||||
raw_withdrawal_wh = slot_cap_wh - discharged_raw_wh
|
||||
if raw_withdrawal_wh < 0.0:
|
||||
raw_withdrawal_wh = 0.0
|
||||
if raw_available_wh < raw_withdrawal_wh:
|
||||
raw_withdrawal_wh = raw_available_wh
|
||||
efficiencies = curves.discharging_efficiency_by_power
|
||||
if efficiencies is not None:
|
||||
# Efficiency at the slot power: the energy already discharged
|
||||
# in this slot plus this request (estimated with the constant
|
||||
# efficiency), within the possible withdrawal.
|
||||
raw_estimate_wh = wh / discharging_efficiency
|
||||
if raw_estimate_wh > raw_withdrawal_wh:
|
||||
raw_estimate_wh = raw_withdrawal_wh
|
||||
index = int(
|
||||
(discharged_raw_wh + raw_estimate_wh) / scale * curves.discharge_index_per_wh
|
||||
+ 0.5
|
||||
)
|
||||
discharging_efficiency = efficiencies[index] if index <= 100 else efficiencies[-1]
|
||||
|
||||
# Convert raw to delivered
|
||||
max_deliverable_wh = raw_withdrawal_wh * discharging_efficiency
|
||||
|
||||
# Cap by requested delivered energy
|
||||
delivered_wh = min(wh, max_deliverable_wh)
|
||||
|
||||
# Effective raw withdrawal based on what is delivered
|
||||
raw_used_wh = delivered_wh / discharging_efficiency
|
||||
|
||||
# Update SoC
|
||||
self.soc_wh -= raw_used_wh
|
||||
self.soc_wh = max(self.soc_wh, self.min_soc_wh)
|
||||
self._discharged_raw_wh_per_slot[hour] = discharged_raw_wh + raw_used_wh
|
||||
if curves is not None:
|
||||
curves.discharged_dc_wh_per_slot[hour] += delivered_wh
|
||||
|
||||
# Losses
|
||||
losses_wh = raw_used_wh - delivered_wh
|
||||
|
||||
return delivered_wh, losses_wh
|
||||
|
||||
def charge_energy(
|
||||
self,
|
||||
wh: Optional[float],
|
||||
hour: int,
|
||||
charge_factor: float = 0.0,
|
||||
) -> tuple[float, float]:
|
||||
"""Charge energy into the battery.
|
||||
|
||||
Two **exclusive** modes:
|
||||
|
||||
**Mode 1:**
|
||||
|
||||
- `wh is not None` and `charge_factor == 0`
|
||||
- The raw requested charge energy is `wh` (pre-efficiency).
|
||||
- If remaining capacity is insufficient, charging is automatically limited.
|
||||
- No exception is raised due to capacity limits.
|
||||
|
||||
**Mode 2:**
|
||||
|
||||
- `wh is None` and `charge_factor > 0`
|
||||
- The raw requested energy is `max_charge_power_w * charge_factor`.
|
||||
- An electric vehicle may finish within a slot at the requested current;
|
||||
its accepted energy is capped at the remaining capacity.
|
||||
- For stationary batteries, requests above the remaining capacity try a lower
|
||||
compatible `charge_factor`, replacing this slot's factor.
|
||||
- If no charge factor can accommodate charging, the request is ignored (``(0.0, 0.0)`` is
|
||||
returned) and a penalty is applied elsewhere.
|
||||
|
||||
Charging is constrained by:
|
||||
|
||||
- Available SoC headroom (``max_soc_wh − soc_wh``)
|
||||
- ``max_charge_power_w``
|
||||
- The power limit at the current SoC, if ``charge_power_limit_w_by_soc``
|
||||
is given. It caps the accepted energy like a battery management system
|
||||
does; it does not scale the charge factor.
|
||||
- A slot limit set by ``limit_slot_charge()``, if any
|
||||
- ``charging_efficiency``, or the efficiency at the slot power if
|
||||
``charging_efficiency_curve`` is given
|
||||
|
||||
Args:
|
||||
wh (float | None):
|
||||
Requested raw energy [Wh] before efficiency.
|
||||
Must be provided only for Mode 1 (charge_factor must be 0).
|
||||
|
||||
hour (int):
|
||||
Time index. If charging is disabled at this hour (charge_array[hour] == 0),
|
||||
returns `(0.0, 0.0)`.
|
||||
|
||||
charge_factor (float):
|
||||
Fraction (0–1) of max charge power.
|
||||
Must be >0 only in Mode 2 (`wh is None`).
|
||||
|
||||
Returns:
|
||||
tuple[float, float]:
|
||||
stored_wh : float
|
||||
Energy stored after efficiency [Wh].
|
||||
losses_wh : float
|
||||
Conversion losses [Wh].
|
||||
|
||||
Raises:
|
||||
ValueError:
|
||||
- If the mode is ambiguous (neither Mode 1 nor Mode 2).
|
||||
- If the final new SoC would exceed capacity_wh.
|
||||
|
||||
Notes:
|
||||
stored_wh = raw_input_wh * charging_efficiency
|
||||
losses_wh = raw_input_wh − stored_wh
|
||||
"""
|
||||
# Charging allowed in this hour?
|
||||
if hour is not None and self.charge_array[hour] == 0:
|
||||
return 0.0, 0.0
|
||||
|
||||
# Provide fast (3x..5x) local read access (vs. self.xxx) for repetitive read access
|
||||
soc_wh_fast = self.soc_wh
|
||||
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 * scale,
|
||||
self._charge_limit_raw_wh_per_slot[hour],
|
||||
)
|
||||
- charged_raw_wh,
|
||||
0.0,
|
||||
)
|
||||
charging_efficiency_fast = self.charging_efficiency
|
||||
# Power limit at the current SoC (battery profile), as raw energy still
|
||||
# acceptable in this slot. None without SoC dependent limit. Looked up
|
||||
# inline (no calls): this runs for every slot of every candidate plan.
|
||||
soc_limit_raw_wh: Optional[float] = None
|
||||
curves = self._curves
|
||||
if curves is not None:
|
||||
limits = curves.charge_limit_wh_by_soc
|
||||
if limits is not None:
|
||||
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)
|
||||
) * scale - charged_raw_wh
|
||||
if soc_limit_raw_wh < 0.0:
|
||||
soc_limit_raw_wh = 0.0
|
||||
efficiencies = curves.charging_efficiency_by_power
|
||||
if efficiencies is not None:
|
||||
# Efficiency at the slot power: the energy already charged in
|
||||
# this slot plus the intended request within the limits.
|
||||
intended_raw_wh = (
|
||||
wh if wh is not None else max_charge_per_slot_wh_fast * charge_factor
|
||||
)
|
||||
if intended_raw_wh > max_charge_per_slot_wh_fast:
|
||||
intended_raw_wh = max_charge_per_slot_wh_fast
|
||||
if soc_limit_raw_wh is not None and soc_limit_raw_wh < intended_raw_wh:
|
||||
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) / 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
|
||||
if wh is not None and charge_factor == 0.0: # mode 1
|
||||
raw_request_wh = wh
|
||||
raw_charge_wh = max(self.max_soc_wh - soc_wh_fast, 0.0) / charging_efficiency_fast
|
||||
elif wh is None and charge_factor > 0.0: # mode 2
|
||||
raw_request_wh = max_charge_per_slot_wh_fast * charge_factor
|
||||
raw_charge_wh = max(self.max_soc_wh - soc_wh_fast, 0.0) / charging_efficiency_fast
|
||||
if self.parameters.electric_vehicle:
|
||||
# The vehicle BMS ends charging when full, even within a slot.
|
||||
# Keep the feasible pilot/current setting; cap only the energy
|
||||
# below instead of inventing a current below the EV minimum.
|
||||
if raw_charge_wh <= 0.0:
|
||||
self.charge_array[hour] = 0
|
||||
return 0.0, 0.0
|
||||
elif raw_request_wh > raw_charge_wh:
|
||||
# Use a lower charge factor: the rates below the requested
|
||||
# one, highest first (as _lower_charge_rates_desc yields them).
|
||||
requested_charge_factor = charge_factor
|
||||
for lower_charge_factor in self._charge_rates_descending():
|
||||
if lower_charge_factor >= requested_charge_factor:
|
||||
continue
|
||||
charge_factor = lower_charge_factor
|
||||
raw_request_wh = max_charge_per_slot_wh_fast * charge_factor
|
||||
if raw_request_wh <= raw_charge_wh:
|
||||
self.charge_array[hour] = charge_factor
|
||||
break
|
||||
if raw_request_wh > raw_charge_wh:
|
||||
# ignore request - penalty for missing SoC will be applied
|
||||
self.charge_array[hour] = 0
|
||||
return 0.0, 0.0
|
||||
else:
|
||||
raise ValueError(
|
||||
f"{self.parameters.device_id}: charge_energy must be called either "
|
||||
"with wh != None and charge_factor == 0, or with wh == None and charge_factor > 0."
|
||||
)
|
||||
|
||||
# Remaining capacity
|
||||
max_raw_wh = min(raw_charge_wh, max_charge_per_slot_wh_fast)
|
||||
if soc_limit_raw_wh is not None and soc_limit_raw_wh < max_raw_wh:
|
||||
max_raw_wh = soc_limit_raw_wh
|
||||
|
||||
# Actual raw intake
|
||||
raw_input_wh = raw_request_wh if raw_request_wh < max_raw_wh else max_raw_wh
|
||||
|
||||
# Apply efficiency
|
||||
stored_wh = raw_input_wh * charging_efficiency_fast
|
||||
new_soc = soc_wh_fast + stored_wh
|
||||
|
||||
if new_soc > self.capacity_wh:
|
||||
raise ValueError(
|
||||
f"{self.parameters.device_id}: SoC {new_soc} Wh exceeds capacity {self.capacity_wh} Wh"
|
||||
)
|
||||
|
||||
self.soc_wh = new_soc
|
||||
self._charged_raw_wh_per_slot[hour] = charged_raw_wh + raw_input_wh
|
||||
if curves is not None:
|
||||
curves.charged_stored_wh_per_slot[hour] += stored_wh
|
||||
losses_wh = raw_input_wh - stored_wh
|
||||
|
||||
return stored_wh, losses_wh
|
||||
|
||||
def current_energy_content(self) -> float:
|
||||
"""Returns the current usable energy in the battery."""
|
||||
usable_energy = (self.soc_wh - self.min_soc_wh) * self.discharging_efficiency
|
||||
return max(usable_energy, 0.0)
|
||||
@@ -0,0 +1,151 @@
|
||||
from typing import List, Sequence
|
||||
|
||||
from loguru import logger
|
||||
|
||||
|
||||
class GeneticHeatpump:
|
||||
MAX_HEAT_OUTPUT = 5000
|
||||
"""Maximum heating power in watts"""
|
||||
|
||||
BASE_HEAT_POWER = 235.0
|
||||
"""Base heating power value"""
|
||||
|
||||
TEMPERATURE_COEFFICIENT = -11.645
|
||||
"""Coefficient for temperature"""
|
||||
|
||||
COP_BASE = 3.0
|
||||
"""Base COP value"""
|
||||
|
||||
COP_COEFFICIENT = 0.1
|
||||
"""COP increase per degree"""
|
||||
|
||||
def __init__(self, max_heat_output: int, hours: int):
|
||||
self.max_heat_output = max_heat_output
|
||||
self.hours = hours
|
||||
|
||||
def __check_outside_temperature_range__(self, temp_celsius: float) -> bool:
|
||||
"""Check if temperature is in valid range between -100 and 100 degree Celsius.
|
||||
|
||||
Args:
|
||||
temp_celsius: Temperature in degree Celsius
|
||||
|
||||
Returns:
|
||||
bool: True if in range
|
||||
"""
|
||||
return -100 < temp_celsius < 100
|
||||
|
||||
def calculate_cop(self, outside_temperature_celsius: float) -> float:
|
||||
"""Calculate the coefficient of performance (COP) based on outside temperature.
|
||||
|
||||
Supported temperate range -100 degree Celsius to 100 degree Celsius.
|
||||
|
||||
Args:
|
||||
outside_temperature_celsius: Outside temperature in degree Celsius
|
||||
|
||||
Raise:
|
||||
ValueError: If outside temperature isn't range.
|
||||
|
||||
Return:
|
||||
cop: Calculated COP based on temperature
|
||||
"""
|
||||
# TODO: Support for other temperature units (e.g Fahrenheit, Kelvin)
|
||||
# Check for sensible temperature values
|
||||
if self.__check_outside_temperature_range__(outside_temperature_celsius):
|
||||
cop = self.COP_BASE + (outside_temperature_celsius * self.COP_COEFFICIENT)
|
||||
return max(cop, 1)
|
||||
else:
|
||||
err_msg = (
|
||||
f"Outside temperature '{outside_temperature_celsius}' not in range "
|
||||
"(min: -100 Celsius, max: 100 Celsius)"
|
||||
)
|
||||
logger.error(err_msg)
|
||||
raise ValueError(err_msg)
|
||||
|
||||
def calculate_heating_output(self, outside_temperature_celsius: float) -> float:
|
||||
"""Calculate the heating output in Watts based on outside temperature in degree Celsius.
|
||||
|
||||
Temperature range must be between -100 and 100 degree Celsius.
|
||||
|
||||
Args:
|
||||
outside_temperature_celsius: Outside temperature in degree Celsius
|
||||
|
||||
Raises:
|
||||
ValueError: Raised if outside temperature isn't in described range.
|
||||
|
||||
Returns:
|
||||
heating output: Calculated heating output in Watts.
|
||||
"""
|
||||
if self.__check_outside_temperature_range__(outside_temperature_celsius):
|
||||
heat_output = (
|
||||
(self.BASE_HEAT_POWER + outside_temperature_celsius * self.TEMPERATURE_COEFFICIENT)
|
||||
* 1000
|
||||
) / 24.0
|
||||
return min(self.max_heat_output, heat_output)
|
||||
else:
|
||||
err_msg = (
|
||||
f"Outside temperature '{outside_temperature_celsius}' not in range "
|
||||
"(min: -100 Celsius, max: 100 Celsius)"
|
||||
)
|
||||
logger.error(err_msg)
|
||||
raise ValueError(err_msg)
|
||||
|
||||
def calculate_heat_power(self, outside_temperature_celsius: float) -> float:
|
||||
"""Calculate electrical power based on outside temperature (degree Celsius).
|
||||
|
||||
Args:
|
||||
outside_temperature_celsius: Temperature in range -100 to 100 degree Celsius.
|
||||
|
||||
Raises:
|
||||
ValueError: Raised if temperature isn't in described range
|
||||
|
||||
Returns:
|
||||
power: Calculated electrical power in Watt.
|
||||
"""
|
||||
if self.__check_outside_temperature_range__(outside_temperature_celsius):
|
||||
return (
|
||||
1164 - 77.8 * outside_temperature_celsius + 1.62 * outside_temperature_celsius**2.0
|
||||
)
|
||||
else:
|
||||
err_msg = (
|
||||
f"Outside temperature '{outside_temperature_celsius}' not in range "
|
||||
"(min: -100 Celsius, max: 100 Celsius)"
|
||||
)
|
||||
logger.error(err_msg)
|
||||
raise ValueError(err_msg)
|
||||
|
||||
def simulate_24h(self, temperatures: Sequence[float]) -> List[float]:
|
||||
"""Simulate power data for 24 hours based on provided temperatures."""
|
||||
power_data: List[float] = []
|
||||
|
||||
if len(temperatures) != self.hours:
|
||||
raise ValueError(
|
||||
f"The temperature array must contain exactly {self.hours} entries, "
|
||||
"one for each hour of the day."
|
||||
)
|
||||
|
||||
for temp in temperatures:
|
||||
power = self.calculate_heat_power(temp)
|
||||
power_data.append(power)
|
||||
return power_data
|
||||
|
||||
|
||||
# Example usage of the class
|
||||
if __name__ == "__main__":
|
||||
max_heating_power = 5000 # 5 kW heating power
|
||||
initial_indoor_temperature = 15 # Initial indoor temperature
|
||||
insulation_efficiency = 0.8 # Insulation efficiency
|
||||
desired_indoor_temperature = 20 # Desired indoor temperature
|
||||
hp = GeneticHeatpump(max_heating_power, 24) # Initialize heat pump with prediction hours
|
||||
|
||||
# Print COP for various outside temperatures
|
||||
print(hp.calculate_cop(-10), " ", hp.calculate_cop(0), " ", hp.calculate_cop(10))
|
||||
|
||||
# 24 hours of outside temperatures (example values)
|
||||
temperatures = [
|
||||
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -5, -2, 5,
|
||||
] # fmt: skip
|
||||
|
||||
# Calculate the 24-hour power data
|
||||
power_data = hp.simulate_24h(temperatures)
|
||||
|
||||
print(power_data)
|
||||
@@ -0,0 +1,714 @@
|
||||
"""Simulation of a home appliance that runs one or more fixed-duration cycles.
|
||||
|
||||
This module models household devices such as dishwashers or washing
|
||||
machines that must run for a fixed duration, possibly multiple times
|
||||
(cycles), within one or more allowed time windows.
|
||||
|
||||
Time windows are expressed as cycle windows (``GeneticTimeWindow``, see
|
||||
``genetictimewindow``): each window's ``value`` encodes the 0-based cycle
|
||||
index it applies to, so different cycles of the same appliance can be
|
||||
constrained to different windows. A cycle without a window of its own is
|
||||
unconstrained.
|
||||
|
||||
The optimizer asks ``allowed_start_slots()`` for the start slots at which a
|
||||
complete run is allowed (windows, earliest start, deadline and horizon, from
|
||||
the run start as slot 0), decodes the starts of its genome from them, and the
|
||||
appliance builds the per-slot energy curve of those starts
|
||||
(``build_load_curve()``).
|
||||
"""
|
||||
|
||||
import math
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass
|
||||
from enum import StrEnum
|
||||
from typing import Any, Optional
|
||||
|
||||
import numpy as np
|
||||
from loguru import logger
|
||||
|
||||
from akkudoktoreos.optimization.genetic.devices.genetictimewindow import (
|
||||
GeneticTimeWindow,
|
||||
)
|
||||
from akkudoktoreos.utils.datetimeutil import (
|
||||
DateTime,
|
||||
Duration,
|
||||
to_duration,
|
||||
)
|
||||
|
||||
|
||||
class GeneticScheduleMode(StrEnum):
|
||||
"""How often an appliance's load profile is scheduled within the horizon."""
|
||||
|
||||
ONCE = "ONCE"
|
||||
DAILY = "DAILY"
|
||||
|
||||
|
||||
class GeneticDeadlinePolicy(StrEnum):
|
||||
"""Whether a deadline that cannot be kept may be dropped."""
|
||||
|
||||
BEST_EFFORT = "BEST_EFFORT"
|
||||
STRICT = "STRICT"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class GeneticHomeApplianceParameters:
|
||||
"""A home appliance of the simulation, derived from its request.
|
||||
|
||||
Attributes:
|
||||
device_id: ID of the appliance.
|
||||
consumption_wh: Energy of one run of the flat load [Wh]; with ``duration_h``.
|
||||
duration_h: Duration of one run of the flat load [h]; with ``consumption_wh``.
|
||||
num_cycles: Runs per schedule period.
|
||||
completed_cycles: Runs already completed.
|
||||
run_started_datetime: Start of a run in progress, if any.
|
||||
min_cycle_gap_h: Minimum idle time between two runs [h].
|
||||
time_windows: Cycle windows (``value`` is the cycle index); ``None`` unconstrained.
|
||||
shared_time_windows: Windows every run must lie within; ``None`` unconstrained.
|
||||
load_profile_power_w: Explicit power per profile step [W], instead of the flat load.
|
||||
load_profile_interval_seconds: Duration of one profile step [s].
|
||||
schedule_mode: How often the profile is scheduled.
|
||||
earliest_start_datetime: No run starts before this moment.
|
||||
deadline_datetime: Every run ends by this moment.
|
||||
deadline_policy: Whether a deadline that cannot be kept may be dropped.
|
||||
"""
|
||||
|
||||
device_id: str
|
||||
consumption_wh: Optional[int]
|
||||
duration_h: Optional[int]
|
||||
num_cycles: int
|
||||
completed_cycles: int
|
||||
run_started_datetime: Optional[DateTime]
|
||||
min_cycle_gap_h: int
|
||||
time_windows: Optional[tuple[GeneticTimeWindow, ...]]
|
||||
shared_time_windows: Optional[tuple[GeneticTimeWindow, ...]]
|
||||
load_profile_power_w: Optional[tuple[float, ...]]
|
||||
load_profile_interval_seconds: Optional[int]
|
||||
schedule_mode: GeneticScheduleMode
|
||||
earliest_start_datetime: Optional[DateTime]
|
||||
deadline_datetime: Optional[DateTime]
|
||||
deadline_policy: GeneticDeadlinePolicy
|
||||
|
||||
|
||||
def resample_power_to_slot_energy(
|
||||
power_w: list[float],
|
||||
input_interval_seconds: float,
|
||||
slot_interval_seconds: float,
|
||||
) -> np.ndarray:
|
||||
"""Resample a piecewise-constant power profile to per-slot energy.
|
||||
|
||||
Each input value ``power_w[i]`` is interpreted as a constant power [W] over
|
||||
the interval ``[i * input_interval_seconds, (i + 1) * input_interval_seconds)``.
|
||||
The energy of every output slot is the time-weighted integral of the input
|
||||
power over that slot::
|
||||
|
||||
E_j = sum_i P_i * overlap(i, j) / 3600 [Wh]
|
||||
|
||||
where ``overlap(i, j)`` is the temporal overlap (in seconds) between input
|
||||
interval ``i`` and output slot ``j``. This is exact for arbitrary (including
|
||||
non-integer) ratios such as 10 -> 15 or 20 -> 15 minutes and conserves
|
||||
energy within numerical tolerance::
|
||||
|
||||
sum_j E_j == sum_i P_i * input_interval_seconds / 3600
|
||||
|
||||
Args:
|
||||
power_w: Piecewise-constant power values [W] of a single run.
|
||||
input_interval_seconds: Duration of one input step [s] (> 0).
|
||||
slot_interval_seconds: Duration of one output slot [s] (> 0).
|
||||
|
||||
Returns:
|
||||
1-D array of per-slot energy [Wh]; length is the number of slots the run
|
||||
occupies (ceil of the total run duration divided by the slot duration).
|
||||
"""
|
||||
if not math.isfinite(input_interval_seconds) or input_interval_seconds <= 0:
|
||||
raise ValueError("Input interval must be finite and positive.")
|
||||
if not math.isfinite(slot_interval_seconds) or slot_interval_seconds <= 0:
|
||||
raise ValueError("Slot interval must be finite and positive.")
|
||||
if not power_w or any(not math.isfinite(p) or p < 0 for p in power_w):
|
||||
raise ValueError("Power profile must contain finite non-negative values.")
|
||||
n_in = len(power_w)
|
||||
total_seconds = n_in * input_interval_seconds
|
||||
n_slots = int(np.ceil(total_seconds / slot_interval_seconds - 1e-9))
|
||||
out = np.zeros(max(n_slots, 0), dtype=float)
|
||||
for i, power in enumerate(power_w):
|
||||
if power == 0.0:
|
||||
continue
|
||||
seg_start = i * input_interval_seconds
|
||||
seg_end = seg_start + input_interval_seconds
|
||||
first = int(seg_start // slot_interval_seconds)
|
||||
last = int((seg_end - 1e-9) // slot_interval_seconds)
|
||||
for j in range(first, last + 1):
|
||||
slot_start = j * slot_interval_seconds
|
||||
slot_end = slot_start + slot_interval_seconds
|
||||
overlap = min(seg_end, slot_end) - max(seg_start, slot_start)
|
||||
if overlap > 0:
|
||||
out[j] += power * overlap / 3600.0
|
||||
return out
|
||||
|
||||
|
||||
class GeneticHomeAppliance:
|
||||
"""Non-vectorized simulation of a multi-cycle home appliance.
|
||||
|
||||
A home appliance may execute multiple fixed-duration cycles during
|
||||
the simulation horizon. See the module docstring for how the optimizer
|
||||
schedules them.
|
||||
"""
|
||||
|
||||
# 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: GeneticHomeApplianceParameters,
|
||||
optimization_hours: int,
|
||||
prediction_hours: int,
|
||||
slot_duration_h: float = 1.0,
|
||||
) -> None:
|
||||
"""Initializes the appliance.
|
||||
|
||||
Args:
|
||||
parameters: The appliance's configuration.
|
||||
optimization_hours: Number of hours under active
|
||||
optimization.
|
||||
prediction_hours: Length of the simulation horizon, in
|
||||
slots.
|
||||
slot_duration_h: Physical duration of each slot, in hours.
|
||||
"""
|
||||
self.parameters = parameters
|
||||
self.optimization_hours = optimization_hours
|
||||
self.prediction_hours = prediction_hours
|
||||
|
||||
if not math.isfinite(slot_duration_h) or slot_duration_h <= 0:
|
||||
raise ValueError("Slot duration must be finite and positive.")
|
||||
self.total_slots = prediction_hours
|
||||
self.slot_duration_h = slot_duration_h
|
||||
self.slot_interval_seconds = slot_duration_h * 3600
|
||||
self.device_id = parameters.device_id
|
||||
self.schedule_mode = parameters.schedule_mode
|
||||
self.time_windows = parameters.shared_time_windows
|
||||
# Cycle windows; a cycle without a window of its own is unconstrained.
|
||||
self.cycle_windows: tuple[GeneticTimeWindow, ...] = parameters.time_windows or ()
|
||||
self.earliest_start_datetime = parameters.earliest_start_datetime
|
||||
self.deadline_datetime = parameters.deadline_datetime
|
||||
self.deadline_policy = parameters.deadline_policy
|
||||
self.deadline_relaxed = False
|
||||
self._build_run_profile()
|
||||
self.duration_h = self.run_slots * slot_duration_h
|
||||
self.consumption_wh = float(self.run_energy_wh.sum())
|
||||
self.num_cycles = parameters.num_cycles
|
||||
self.min_cycle_gap_h = parameters.min_cycle_gap_h
|
||||
|
||||
self.completed_cycles = parameters.completed_cycles
|
||||
|
||||
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] = []
|
||||
|
||||
def _build_run_profile(self) -> None:
|
||||
"""Build the per-slot energy [Wh] of a single complete run."""
|
||||
if self.parameters.load_profile_power_w is not None:
|
||||
power = [float(value) for value in self.parameters.load_profile_power_w]
|
||||
input_interval = (
|
||||
self.parameters.load_profile_interval_seconds or self.slot_interval_seconds
|
||||
)
|
||||
else:
|
||||
# Flat fallback: constant power over duration_h hours. Route it through
|
||||
# the same resampling path so hourly and sub-hourly grids behave
|
||||
# identically. Power [W] = energy per hour = consumption_wh / duration_h.
|
||||
duration_h = self.parameters.duration_h
|
||||
consumption_wh = self.parameters.consumption_wh
|
||||
if duration_h is None or consumption_wh is None:
|
||||
raise ValueError("Flat appliance load requires duration and consumption.")
|
||||
power = [consumption_wh / duration_h]
|
||||
input_interval = duration_h * 3600
|
||||
|
||||
self.run_energy_wh: np.ndarray = resample_power_to_slot_energy(
|
||||
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)
|
||||
# The start day in the time zone of the horizon, which also dates the cycles.
|
||||
horizon_timezone = slot0_datetime.timezone
|
||||
self.pinned_run_date = (
|
||||
started.in_timezone(horizon_timezone) if horizon_timezone is not None else 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 == GeneticScheduleMode.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.
|
||||
|
||||
Args:
|
||||
moment: Absolute moment; converted into ``slot0_datetime``'s timezone.
|
||||
slot0_datetime: Local, timezone-aware datetime of slot index 0.
|
||||
round_up: ``True`` returns the first slot boundary at or after
|
||||
``moment`` (lower bounds), ``False`` the last one at or before
|
||||
it (upper bounds).
|
||||
|
||||
Returns:
|
||||
Slot index (may be negative or beyond the grid; callers clamp).
|
||||
"""
|
||||
timezone = slot0_datetime.timezone
|
||||
if timezone is None:
|
||||
raise ValueError("The optimization slot origin must have a timezone.")
|
||||
seconds = (moment.in_timezone(timezone) - slot0_datetime).total_seconds()
|
||||
exact = seconds / self.slot_interval_seconds
|
||||
# Tolerance absorbs float noise so a moment that sits exactly on a slot
|
||||
# boundary is not pushed to the neighbouring slot.
|
||||
return math.ceil(exact - 1e-9) if round_up else math.floor(exact + 1e-9)
|
||||
|
||||
def allowed_start_slots(
|
||||
self,
|
||||
*,
|
||||
slot0_datetime: DateTime,
|
||||
earliest_slot: int,
|
||||
horizon_end_slot: int,
|
||||
cycle_index: Optional[int] = None,
|
||||
) -> list[int]:
|
||||
"""Return the sorted absolute start slots at which a full run is allowed.
|
||||
|
||||
A start slot ``s`` is allowed when the complete run fits the optimization
|
||||
horizon, both absolute bounds and (if configured) a single allowed time
|
||||
window:
|
||||
|
||||
- ``earliest_slot <= s`` and ``s + run_slots <= horizon_end_slot``
|
||||
- with ``earliest_start_datetime`` set, the run starts at or after it
|
||||
- with ``deadline_datetime`` set, the run *ends* at or before it
|
||||
- with ``time_windows`` set, the run's whole occupied span starting at
|
||||
``s`` is contained in one window (respecting weekday/date constraints)
|
||||
|
||||
When a deadline leaves no start at all and the policy is
|
||||
``BEST_EFFORT``, the deadline is dropped and only the earliest still
|
||||
possible start is offered (a warning is logged and ``deadline_relaxed``
|
||||
is set). Multiple cycles retain all relaxed choices for joint
|
||||
earliest-start repair by the optimizer, respecting per-cycle windows
|
||||
and minimum gaps.
|
||||
|
||||
No snapping is performed: every returned slot is a genuinely valid start.
|
||||
|
||||
Args:
|
||||
slot0_datetime: Local, timezone-aware datetime of slot index 0.
|
||||
earliest_slot: First slot the optimizer may schedule at ("now").
|
||||
horizon_end_slot: Exclusive upper bound; a run must end at or before.
|
||||
cycle_index: Global configured cycle index, independent of completed cycles.
|
||||
|
||||
Returns:
|
||||
Sorted list of allowed absolute start slots (may be empty).
|
||||
"""
|
||||
self.deadline_relaxed = False
|
||||
allowed = self._allowed_start_slots(
|
||||
slot0_datetime=slot0_datetime,
|
||||
earliest_slot=earliest_slot,
|
||||
horizon_end_slot=horizon_end_slot,
|
||||
apply_deadline=True,
|
||||
cycle_index=cycle_index,
|
||||
)
|
||||
if (
|
||||
allowed
|
||||
or self.deadline_datetime is None
|
||||
or self.deadline_policy == GeneticDeadlinePolicy.STRICT
|
||||
):
|
||||
return allowed
|
||||
|
||||
relaxed = self._allowed_start_slots(
|
||||
slot0_datetime=slot0_datetime,
|
||||
earliest_slot=earliest_slot,
|
||||
horizon_end_slot=horizon_end_slot,
|
||||
apply_deadline=False,
|
||||
cycle_index=cycle_index,
|
||||
)
|
||||
if not relaxed:
|
||||
return relaxed
|
||||
self.deadline_relaxed = True
|
||||
# Keep only the earliest possible start: the deadline is already missed,
|
||||
# so the run is scheduled as soon as possible rather than as cheap as
|
||||
# possible. Multiple cycles retain choices so the optimizer can find
|
||||
# the earliest joint schedule that respects idle gaps.
|
||||
earliest = relaxed[:1] if self.num_cycles == 1 else relaxed
|
||||
logger.warning(
|
||||
"Home appliance '{}': deadline {} can not be met - running as early as "
|
||||
"possible instead (BEST_EFFORT). Run ends {}.",
|
||||
self.device_id,
|
||||
self.deadline_datetime,
|
||||
self.run_end_datetime(earliest[0], slot0_datetime),
|
||||
)
|
||||
return earliest
|
||||
|
||||
def open_start_slots(
|
||||
self,
|
||||
*,
|
||||
slot0_datetime: DateTime,
|
||||
earliest_slot: int,
|
||||
horizon_end_slot: int,
|
||||
cycle_index: int,
|
||||
) -> list[int]:
|
||||
"""Return the start slots at which a run of one slot would be allowed.
|
||||
|
||||
Ignores the deadline; only starts that leave room for the full run before the horizon
|
||||
end count. Tells a horizon in which the windows and the earliest start allow no run at
|
||||
all (nothing to plan) from one in which they are open but leave no room for the
|
||||
appliance's full run (a configuration that cannot be scheduled).
|
||||
|
||||
Args:
|
||||
slot0_datetime: Local, timezone-aware datetime of slot index 0.
|
||||
earliest_slot: First slot the optimizer may schedule at ("now").
|
||||
horizon_end_slot: Exclusive upper bound; a run must end at or before.
|
||||
cycle_index: Global configured cycle index, independent of completed cycles.
|
||||
|
||||
Returns:
|
||||
Sorted list of absolute start slots (may be empty).
|
||||
"""
|
||||
return self._allowed_start_slots(
|
||||
slot0_datetime=slot0_datetime,
|
||||
earliest_slot=earliest_slot,
|
||||
horizon_end_slot=horizon_end_slot - self.run_slots + 1,
|
||||
cycle_index=cycle_index,
|
||||
apply_deadline=False,
|
||||
run_slots=1,
|
||||
)
|
||||
|
||||
def _allowed_start_slots(
|
||||
self,
|
||||
*,
|
||||
slot0_datetime: DateTime,
|
||||
earliest_slot: int,
|
||||
horizon_end_slot: int,
|
||||
cycle_index: Optional[int] = None,
|
||||
apply_deadline: bool,
|
||||
run_slots: Optional[int] = None,
|
||||
) -> list[int]:
|
||||
"""Compute the allowed start slots for one set of constraints.
|
||||
|
||||
Args:
|
||||
slot0_datetime: Local, timezone-aware datetime of slot index 0.
|
||||
earliest_slot: First slot the optimizer may schedule at ("now").
|
||||
horizon_end_slot: Exclusive upper bound; a run must end at or before.
|
||||
cycle_index: Global configured cycle index, independent of completed cycles.
|
||||
apply_deadline: Whether ``deadline_datetime`` restricts the run end.
|
||||
run_slots: Length of the run in slots; ``None`` is the appliance's run.
|
||||
|
||||
Returns:
|
||||
Sorted list of allowed absolute start slots (may be empty).
|
||||
"""
|
||||
if run_slots is None:
|
||||
run_slots = self.run_slots
|
||||
if run_slots <= 0:
|
||||
return []
|
||||
|
||||
first_start = max(earliest_slot, 0)
|
||||
if self.earliest_start_datetime is not None:
|
||||
first_start = max(
|
||||
first_start,
|
||||
self._slot_offset(self.earliest_start_datetime, slot0_datetime, round_up=True),
|
||||
)
|
||||
|
||||
end_bound = min(horizon_end_slot, self.total_slots)
|
||||
if apply_deadline and self.deadline_datetime is not None:
|
||||
end_bound = min(
|
||||
end_bound,
|
||||
self._slot_offset(self.deadline_datetime, slot0_datetime, round_up=False),
|
||||
)
|
||||
|
||||
last_start = end_bound - run_slots
|
||||
if last_start < first_start:
|
||||
return []
|
||||
|
||||
if cycle_index is not None and not 0 <= cycle_index < self.num_cycles:
|
||||
raise ValueError("Cycle index is outside the configured cycle range.")
|
||||
cycle_windows = [
|
||||
window
|
||||
for window in self.cycle_windows
|
||||
if window.value is not None and int(window.value) == cycle_index
|
||||
]
|
||||
|
||||
run_duration = to_duration(f"{run_slots * self.slot_interval_seconds} seconds")
|
||||
allowed: list[int] = []
|
||||
for slot in range(first_start, last_start + 1):
|
||||
start_dt = slot0_datetime.add(seconds=slot * self.slot_interval_seconds)
|
||||
if (
|
||||
self.time_windows is None
|
||||
or self._windows_allow_run(self.time_windows, start_dt, run_duration)
|
||||
) and (
|
||||
not cycle_windows
|
||||
or self._windows_allow_run(cycle_windows, start_dt, run_duration, merge=True)
|
||||
):
|
||||
allowed.append(slot)
|
||||
return allowed
|
||||
|
||||
@staticmethod
|
||||
def _windows_allow_run(
|
||||
windows: Sequence[GeneticTimeWindow],
|
||||
start: DateTime,
|
||||
duration: Duration,
|
||||
*,
|
||||
merge: bool = False,
|
||||
) -> bool:
|
||||
"""Check full coverage including windows anchored on previous local dates.
|
||||
|
||||
Date, weekday, and month restrictions belong to the window's opening day.
|
||||
Per-cycle windows retain their existing union semantics; shared windows
|
||||
require one complete containing occurrence.
|
||||
"""
|
||||
# Compare elapsed offsets from the run start, including when sorting
|
||||
# and merging intervals. Wall-clock ordering cannot distinguish the
|
||||
# two occurrences of an hour repeated during a DST transition.
|
||||
intervals: list[tuple[float, float]] = []
|
||||
run_end = start + duration
|
||||
run_seconds = (run_end - start).total_seconds()
|
||||
for window in windows:
|
||||
days_back = math.ceil(window.duration.total_seconds() / 86400) + 1
|
||||
for offset in range(days_back + 1):
|
||||
anchor = start.subtract(days=offset)
|
||||
if window.date is not None and anchor.date() != window.date:
|
||||
continue
|
||||
if window.day_of_week is not None and anchor.day_of_week != window.day_of_week:
|
||||
continue
|
||||
if window.month is not None and anchor.month != window.month:
|
||||
continue
|
||||
opening, closing = window.start_end(anchor)
|
||||
opening_offset = (opening - start).total_seconds()
|
||||
closing_offset = (closing - start).total_seconds()
|
||||
if opening_offset <= 0 and run_seconds <= closing_offset:
|
||||
return True
|
||||
if merge and opening_offset < run_seconds and closing_offset > 0:
|
||||
intervals.append((opening_offset, closing_offset))
|
||||
covered_until = 0.0
|
||||
for opening_offset, closing_offset in sorted(intervals):
|
||||
if opening_offset > covered_until:
|
||||
break
|
||||
covered_until = max(covered_until, closing_offset)
|
||||
if covered_until >= run_seconds:
|
||||
return True
|
||||
return False
|
||||
|
||||
def run_end_datetime(self, start_slot: int, slot0_datetime: DateTime) -> DateTime:
|
||||
"""Absolute local moment at which a run started at ``start_slot`` finishes.
|
||||
|
||||
Args:
|
||||
start_slot: Absolute start slot of the run.
|
||||
slot0_datetime: Local, timezone-aware datetime of slot index 0.
|
||||
|
||||
Returns:
|
||||
End datetime of the run (exclusive, i.e. the first free moment).
|
||||
"""
|
||||
return slot0_datetime.add(
|
||||
seconds=(start_slot + self.run_slots) * self.slot_interval_seconds
|
||||
)
|
||||
|
||||
def deadline_missed(self, starts: list[int], slot0_datetime: DateTime) -> bool:
|
||||
"""Whether the scheduled runs violate the configured deadline.
|
||||
|
||||
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. A run in progress counts with
|
||||
its expected end.
|
||||
|
||||
Args:
|
||||
starts: Absolute start slots of the scheduled runs.
|
||||
slot0_datetime: Local, timezone-aware datetime of slot index 0.
|
||||
|
||||
Returns:
|
||||
True if the deadline is set and not met.
|
||||
"""
|
||||
if self.deadline_datetime is None:
|
||||
return False
|
||||
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(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.
|
||||
|
||||
Multiple runs may overlap; their per-slot energies are summed.
|
||||
|
||||
Args:
|
||||
starts: Absolute start slots of the scheduled runs.
|
||||
"""
|
||||
if any(start < 0 or start + self.run_slots > self.total_slots for start in starts):
|
||||
raise ValueError("A complete appliance run must fit inside the slot horizon.")
|
||||
self.start_hours = list(starts)
|
||||
self._build_load_curve()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Setup
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def num_remaining_cycles(self) -> int:
|
||||
"""int: Number of cycles which still have to be scheduled."""
|
||||
return max(0, self.num_cycles - self.completed_cycles)
|
||||
|
||||
def set_completed_cycles(self, completed_cycles: int) -> None:
|
||||
"""Sets the number of cycles already completed.
|
||||
|
||||
Clears any previously scheduled start times and load curve.
|
||||
|
||||
Args:
|
||||
completed_cycles: Number of cycles completed so far.
|
||||
Clamped to ``[0, num_cycles]``.
|
||||
"""
|
||||
self.completed_cycles = max(
|
||||
0,
|
||||
min(completed_cycles, self.num_cycles),
|
||||
)
|
||||
|
||||
self.start_hours = []
|
||||
self.reset_load_curve()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Load curve
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _build_load_curve(self) -> None:
|
||||
"""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)
|
||||
if 0 <= start and length > 0:
|
||||
self.load_curve[start : start + length] += self.run_energy_wh[:length]
|
||||
|
||||
def reset_load_curve(self) -> None:
|
||||
"""Resets the load curve to all zeros."""
|
||||
self.load_curve = np.zeros(self.prediction_hours)
|
||||
|
||||
def get_load_curve(self) -> np.ndarray:
|
||||
"""Returns the current per-slot load curve, in watt-hours."""
|
||||
return self.load_curve
|
||||
|
||||
def get_load_for_hour(self, hour: int) -> float:
|
||||
"""Returns the load for a specific hour.
|
||||
|
||||
Args:
|
||||
hour: Hour of the prediction horizon to look up.
|
||||
|
||||
Returns:
|
||||
The energy, in watt-hours, at slot ``hour``.
|
||||
|
||||
Raises:
|
||||
ValueError: If ``hour`` is outside
|
||||
``[0, prediction_hours)``.
|
||||
"""
|
||||
if hour < 0 or hour >= self.prediction_hours:
|
||||
raise ValueError(
|
||||
f"The specified hour {hour} is outside the available "
|
||||
f"time frame {self.prediction_hours}."
|
||||
)
|
||||
|
||||
return float(self.load_curve[hour])
|
||||
@@ -0,0 +1,484 @@
|
||||
"""Inverter of the GENETIC simulation."""
|
||||
|
||||
from bisect import bisect_left
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from akkudoktoreos.optimization.genetic.devices.geneticbattery import GeneticBattery
|
||||
from akkudoktoreos.optimization.genetic.geneticefficiency import (
|
||||
interpolate_efficiency_curve,
|
||||
solve_ac_for_charge_dc_energy,
|
||||
solve_ac_for_dc_energy,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticloadinterpolator import (
|
||||
get_genetic_load_interpolator,
|
||||
)
|
||||
from akkudoktoreos.utils.gridinterpolator import GridInterpolatorBackend
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class GeneticInverterParameters:
|
||||
"""An inverter of the simulation, derived from its request.
|
||||
|
||||
Attributes:
|
||||
device_id: ID of the inverter.
|
||||
max_power_wh: Maximum power [W], the energy per hour it can convert.
|
||||
battery_id: ID of the battery behind the inverter, if any.
|
||||
ac_to_dc_efficiency: Efficiency of AC to DC conversion (grid charging).
|
||||
dc_to_ac_efficiency: Efficiency of DC to AC conversion.
|
||||
dc_to_ac_efficiency_curve: DC to AC efficiency by load fraction.
|
||||
dc_to_ac_efficiency_reference_load_fraction: Load fraction at which stored energy is
|
||||
valued with the DC to AC curve.
|
||||
ac_to_dc_efficiency_curve: AC to DC efficiency by load fraction.
|
||||
max_ac_charge_power_w: Maximum AC charging power [W]; ``None`` is no extra limit.
|
||||
ac_charge_limits_total_charge: The AC charge setpoint caps the total charge power.
|
||||
"""
|
||||
|
||||
device_id: str
|
||||
max_power_wh: float
|
||||
battery_id: Optional[str]
|
||||
ac_to_dc_efficiency: float
|
||||
dc_to_ac_efficiency: float
|
||||
dc_to_ac_efficiency_curve: Optional[tuple[tuple[float, float], ...]]
|
||||
dc_to_ac_efficiency_reference_load_fraction: float
|
||||
ac_to_dc_efficiency_curve: Optional[tuple[tuple[float, float], ...]]
|
||||
max_ac_charge_power_w: Optional[float]
|
||||
ac_charge_limits_total_charge: bool
|
||||
|
||||
|
||||
class GeneticInverter:
|
||||
"""Inverter of the simulation: converts PV, battery and grid energy within its power."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parameters: GeneticInverterParameters,
|
||||
battery: Optional[GeneticBattery] = None,
|
||||
slot_duration_h: float = 1.0,
|
||||
first_slot_fraction: float = 1.0,
|
||||
self_consumption_backend: GridInterpolatorBackend = GridInterpolatorBackend.SCIPY,
|
||||
):
|
||||
# `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: GeneticInverterParameters = parameters
|
||||
self.battery: Optional[GeneticBattery] = battery
|
||||
self.self_consumption_backend = self_consumption_backend
|
||||
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}."
|
||||
logger.error(error_msg)
|
||||
raise ValueError(error_msg)
|
||||
self.self_consumption_predictor = get_genetic_load_interpolator(
|
||||
self.self_consumption_backend
|
||||
)
|
||||
# max_power_wh is supplied as power [W] but used as the maximum energy
|
||||
# the inverter can move during one optimization slot.
|
||||
self.max_power_wh = self.parameters.max_power_wh * self.slot_duration_h
|
||||
self.dc_to_ac_efficiency = self.parameters.dc_to_ac_efficiency
|
||||
self.ac_to_dc_efficiency = self.parameters.ac_to_dc_efficiency
|
||||
self.dc_to_ac_efficiency_curve = self.parameters.dc_to_ac_efficiency_curve
|
||||
self.ac_to_dc_efficiency_curve = self.parameters.ac_to_dc_efficiency_curve
|
||||
# DC-to-AC efficiency used to value stored battery energy where no single
|
||||
# conversion is known (end-of-horizon value, AC charge break-even). With
|
||||
# a curve it is the efficiency at the configured reference load.
|
||||
self.reference_dc_to_ac_efficiency = self.dc_to_ac_efficiency_at(
|
||||
self.parameters.dc_to_ac_efficiency_reference_load_fraction * self.max_power_wh
|
||||
)
|
||||
# This value remains a power [W]. GeneticSimulation converts it into a
|
||||
# slot-independent charge-factor limit.
|
||||
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, 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 * 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: tuple[tuple[float, float], ...] = self.dc_to_ac_efficiency_curve
|
||||
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
|
||||
# interpolation are those of interpolate_efficiency_curve().
|
||||
if curve is not getattr(self, "_curve_source", None):
|
||||
self._curve_fractions = [point[0] for point in curve]
|
||||
self._curve_efficiencies = [point[1] for point in curve]
|
||||
self._curve_source = curve
|
||||
fractions = self._curve_fractions
|
||||
if load_fraction != load_fraction or len(fractions) != len(curve):
|
||||
# NaN, or a curve changed in place: the plain walk.
|
||||
return interpolate_efficiency_curve(curve, load_fraction)
|
||||
efficiencies = self._curve_efficiencies
|
||||
index = bisect_left(fractions, load_fraction)
|
||||
if index == 0:
|
||||
return efficiencies[0]
|
||||
if index == len(fractions):
|
||||
return efficiencies[-1]
|
||||
lower_fraction = fractions[index - 1]
|
||||
lower_efficiency = efficiencies[index - 1]
|
||||
return lower_efficiency + (load_fraction - lower_fraction) / (
|
||||
fractions[index] - lower_fraction
|
||||
) * (efficiencies[index] - lower_efficiency)
|
||||
|
||||
def ac_charge_factor(self, factor: float) -> float:
|
||||
"""Return the AC charge factor the inverter can actually execute.
|
||||
|
||||
The factor is a fraction of the battery's ``max_charge_power_w``. It is
|
||||
capped so that the AC input stays within ``max_ac_charge_power_w`` and
|
||||
is 0.0 when AC charging is impossible.
|
||||
"""
|
||||
if factor <= 0.0 or not self.battery or self.ac_to_dc_efficiency <= 0.0:
|
||||
return 0.0
|
||||
if self.max_ac_charge_power_w is not None and self.battery.max_charge_power_w > 0:
|
||||
# DC power = max_charge_power_w * factor
|
||||
# AC power = DC power / ac_to_dc_eff <= max_ac_charge_power_w
|
||||
factor = min(
|
||||
factor,
|
||||
self.max_ac_charge_power_w
|
||||
* self.ac_to_dc_efficiency
|
||||
/ self.battery.max_charge_power_w,
|
||||
)
|
||||
return max(factor, 0.0)
|
||||
|
||||
def begin_ac_charge_slot(self, hour: int, factor: float) -> None:
|
||||
"""Apply the AC charge setpoint of a slot before its PV is processed.
|
||||
|
||||
On inverters whose grid charge setpoint caps the total charge power, the
|
||||
battery takes at most ``factor`` of its rated charge power in this slot,
|
||||
PV included. Call ``process_energy`` afterwards so PV surplus above the
|
||||
cap is exported, as the inverter does.
|
||||
"""
|
||||
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
|
||||
* self.slot_scale(hour)
|
||||
* factor,
|
||||
)
|
||||
|
||||
def charge_battery_from_grid(self, hour: int, factor: float) -> tuple[float, float]:
|
||||
"""Charge the battery from the grid after PV was processed in this slot.
|
||||
|
||||
Default model: the grid adds ``factor`` of the rated charge power on top
|
||||
of the PV charge. With ``ac_charge_limits_total_charge`` the grid only
|
||||
fills what PV left of the slot cap set by ``begin_ac_charge_slot``.
|
||||
|
||||
Returns:
|
||||
tuple[float, float]: AC energy drawn from the grid [Wh] and the
|
||||
battery plus AC-to-DC conversion losses [Wh].
|
||||
"""
|
||||
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 * scale * factor, hour
|
||||
)
|
||||
else:
|
||||
stored, battery_losses = self.battery.charge_energy(None, hour, charge_factor=factor)
|
||||
# DC energy entering the battery (before battery internal efficiency)
|
||||
dc_energy = stored + battery_losses
|
||||
# AC energy consumed from grid (accounts for AC->DC conversion loss). With a
|
||||
# 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 * scale)
|
||||
else:
|
||||
ac_energy = dc_energy / self.ac_to_dc_efficiency
|
||||
return ac_energy, battery_losses + (ac_energy - dc_energy)
|
||||
|
||||
def _delivered_ac_wh(
|
||||
self,
|
||||
battery_discharge_dc: float,
|
||||
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. ``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 * scale, requested_ac_wh
|
||||
)
|
||||
return battery_discharge_dc * dc_to_ac_efficiency
|
||||
|
||||
def _discharge_battery_to_ac(self, requested_ac_wh: float, hour: int) -> tuple[float, float]:
|
||||
"""Discharge battery energy and convert it to AC energy."""
|
||||
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 GeneticBattery:
|
||||
# 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, 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, scale
|
||||
)
|
||||
inverter_discharge_losses = battery_discharge_dc - battery_discharge_ac
|
||||
return battery_discharge_ac, discharge_losses + inverter_discharge_losses
|
||||
|
||||
# This runs for every slot of every candidate plan in which the battery
|
||||
# could serve load or export. For the Battery the release check and the
|
||||
# efficiency are computed in one go, without the nested calls. Without
|
||||
# battery profile data, Battery.discharge_energy() is inlined as well;
|
||||
# keep both in step.
|
||||
if battery.discharge_array[hour] == 0:
|
||||
# Not released in this slot: the battery delivers nothing.
|
||||
return 0.0, 0.0
|
||||
# With an efficiency curve, the efficiency is taken at the requested AC
|
||||
# energy of this conversion.
|
||||
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, scale)
|
||||
dc_request = requested_ac_wh / dc_to_ac_efficiency
|
||||
|
||||
if battery._curves is not None:
|
||||
# SoC / power dependent limits and efficiencies: one call.
|
||||
battery_discharge_dc, discharge_losses = battery.discharge_energy(dc_request, hour)
|
||||
else:
|
||||
soc_wh = battery.soc_wh
|
||||
min_soc_wh = battery.min_soc_wh
|
||||
discharged_raw_wh = battery._discharged_raw_wh_per_slot
|
||||
discharging_efficiency = battery.discharging_efficiency
|
||||
raw_available_wh = max(soc_wh - min_soc_wh, 0.0)
|
||||
if raw_available_wh == 0.0:
|
||||
# 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
|
||||
* (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
|
||||
battery_discharge_dc = min(dc_request, max_deliverable_wh)
|
||||
raw_used_wh = battery_discharge_dc / discharging_efficiency
|
||||
soc_wh -= raw_used_wh
|
||||
battery.soc_wh = max(soc_wh, min_soc_wh)
|
||||
discharged_raw_wh[hour] += raw_used_wh
|
||||
discharge_losses = raw_used_wh - battery_discharge_dc
|
||||
|
||||
# Same rule as _delivered_ac_wh(), without the call: a limited discharge
|
||||
# is converted with the efficiency at the AC energy actually delivered.
|
||||
if self.dc_to_ac_efficiency_curve is not None and battery_discharge_dc < dc_request * (
|
||||
1.0 - 1e-12
|
||||
):
|
||||
battery_discharge_ac = solve_ac_for_dc_energy(
|
||||
self.dc_to_ac_efficiency_curve,
|
||||
battery_discharge_dc,
|
||||
self.max_power_wh * scale,
|
||||
requested_ac_wh,
|
||||
)
|
||||
else:
|
||||
battery_discharge_ac = battery_discharge_dc * dc_to_ac_efficiency
|
||||
inverter_discharge_losses = battery_discharge_dc - battery_discharge_ac
|
||||
return battery_discharge_ac, discharge_losses + inverter_discharge_losses
|
||||
|
||||
def process_energy(
|
||||
self,
|
||||
generation: float,
|
||||
consumption: float,
|
||||
hour: int,
|
||||
allow_battery_grid_export: bool = False,
|
||||
battery_grid_export_factor: float = 1.0,
|
||||
) -> tuple[float, float, float, float]:
|
||||
"""Process one slot using probabilistic direct PV-to-load overlap.
|
||||
|
||||
``generation`` and ``consumption`` are interval energies. The load
|
||||
probability table is evaluated in watts and yields the expected direct
|
||||
PV-to-load power. The remaining load and PV surplus are then handled
|
||||
independently, because both can occur during different sub-intervals of
|
||||
the same hourly or 15-minute slot.
|
||||
|
||||
Args:
|
||||
generation: PV energy of the slot [Wh].
|
||||
consumption: Load energy of the slot [Wh].
|
||||
hour: Slot index.
|
||||
allow_battery_grid_export: Whether the battery may discharge into the
|
||||
grid in this slot (direct marketing).
|
||||
battery_grid_export_factor: Export level as a factor of the battery's
|
||||
rated discharge power [0.0 ... 1.0]. 1.0 exports as much as the
|
||||
battery and the inverter allow, which is the behaviour when no
|
||||
export rates are configured.
|
||||
"""
|
||||
# This method runs once per slot of every candidate plan. The bounds
|
||||
# below are written as conditional expressions instead of min()/max()
|
||||
# calls: "0.0 if x < 0.0 else x" is exactly max(x, 0.0) and
|
||||
# "b if b < a else a" is exactly min(a, b), NaN and signed zero included.
|
||||
losses = 0.0
|
||||
grid_export = 0.0
|
||||
generation = float(generation)
|
||||
if generation < 0.0:
|
||||
generation = 0.0
|
||||
consumption = float(consumption)
|
||||
if consumption < 0.0:
|
||||
consumption = 0.0
|
||||
battery = self.battery
|
||||
# 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 * scale
|
||||
expected_direct_power_w = (
|
||||
self.self_consumption_predictor.calculate_expected_direct_consumption(
|
||||
consumption / slot_duration_h,
|
||||
generation / slot_duration_h,
|
||||
)
|
||||
)
|
||||
direct_pv_energy = expected_direct_power_w * slot_duration_h
|
||||
else:
|
||||
direct_pv_energy = 0.0
|
||||
|
||||
# Direct PV is bounded by both input energies and by the AC energy the
|
||||
# inverter can move during this slot.
|
||||
if direct_pv_energy < 0.0:
|
||||
direct_pv_energy = 0.0
|
||||
if generation < direct_pv_energy:
|
||||
direct_pv_energy = generation
|
||||
if consumption < direct_pv_energy:
|
||||
direct_pv_energy = consumption
|
||||
if max_power_wh < direct_pv_energy:
|
||||
direct_pv_energy = max_power_wh
|
||||
remaining_load = consumption - direct_pv_energy
|
||||
if remaining_load < 0.0:
|
||||
remaining_load = 0.0
|
||||
pv_surplus = generation - direct_pv_energy
|
||||
if pv_surplus < 0.0:
|
||||
pv_surplus = 0.0
|
||||
remaining_inverter_ac_capacity = max_power_wh - direct_pv_energy
|
||||
if remaining_inverter_ac_capacity < 0.0:
|
||||
remaining_inverter_ac_capacity = 0.0
|
||||
|
||||
# Load gaps and PV surplus may both occur within the same coarse slot.
|
||||
# Cover the load gap first; this preserves the existing chronological
|
||||
# approximation and can create headroom for later PV charging.
|
||||
battery_discharge_ac = 0.0
|
||||
if remaining_load > 0.0 and battery and remaining_inverter_ac_capacity > 0.0:
|
||||
requested_ac_wh = (
|
||||
remaining_inverter_ac_capacity
|
||||
if remaining_inverter_ac_capacity < remaining_load
|
||||
else remaining_load
|
||||
)
|
||||
battery_discharge_ac, battery_discharge_losses = self._discharge_battery_to_ac(
|
||||
requested_ac_wh, hour
|
||||
)
|
||||
remaining_load = remaining_load - battery_discharge_ac
|
||||
if remaining_load < 0.0:
|
||||
remaining_load = 0.0
|
||||
remaining_inverter_ac_capacity = remaining_inverter_ac_capacity - battery_discharge_ac
|
||||
if remaining_inverter_ac_capacity < 0.0:
|
||||
remaining_inverter_ac_capacity = 0.0
|
||||
losses += battery_discharge_losses
|
||||
|
||||
grid_import = remaining_load
|
||||
|
||||
# Without PV surplus (night slots, or all PV consumed directly) there is
|
||||
# nothing to charge, export or curtail. (!= instead of >: a NaN forecast
|
||||
# keeps propagating into the result as before.)
|
||||
if pv_surplus != 0.0:
|
||||
# Charge from the probabilistic PV surplus on the DC path. Stored
|
||||
# energy plus charge losses equals the PV energy accepted by the
|
||||
# battery.
|
||||
remaining_surplus = pv_surplus
|
||||
if remaining_surplus > 0.0 and battery:
|
||||
charged_energy, charge_losses = battery.charge_energy(remaining_surplus, hour)
|
||||
remaining_surplus = remaining_surplus - charged_energy - charge_losses
|
||||
if remaining_surplus < 0.0:
|
||||
remaining_surplus = 0.0
|
||||
losses += charge_losses
|
||||
|
||||
pv_grid_export = (
|
||||
remaining_inverter_ac_capacity
|
||||
if remaining_inverter_ac_capacity < remaining_surplus
|
||||
else remaining_surplus
|
||||
)
|
||||
grid_export += pv_grid_export
|
||||
remaining_inverter_ac_capacity = remaining_inverter_ac_capacity - pv_grid_export
|
||||
if remaining_inverter_ac_capacity < 0.0:
|
||||
remaining_inverter_ac_capacity = 0.0
|
||||
# PV which can neither charge the battery nor pass through the
|
||||
# inverter is curtailed and reported as a loss.
|
||||
curtailed = remaining_surplus - pv_grid_export
|
||||
if curtailed < 0.0:
|
||||
curtailed = 0.0
|
||||
losses += curtailed
|
||||
|
||||
if allow_battery_grid_export and battery and remaining_inverter_ac_capacity > 0.0:
|
||||
export_factor = float(battery_grid_export_factor)
|
||||
if export_factor < 0.0:
|
||||
export_factor = 0.0
|
||||
if 1.0 < export_factor:
|
||||
export_factor = 1.0
|
||||
# Upper bounds of the export. With an efficiency curve, the
|
||||
# efficiency is estimated at the DC energy of each bound; the
|
||||
# conversion itself in _discharge_battery_to_ac() is exact and is
|
||||
# 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, 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(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
|
||||
if rated_export_ac < export_capacity:
|
||||
export_capacity = rated_export_ac
|
||||
battery_export_ac, battery_export_losses = self._discharge_battery_to_ac(
|
||||
export_capacity, hour
|
||||
)
|
||||
grid_export += battery_export_ac
|
||||
losses += battery_export_losses
|
||||
|
||||
self_consumption = direct_pv_energy + battery_discharge_ac
|
||||
return grid_export, grid_import, losses, self_consumption
|
||||
@@ -0,0 +1,97 @@
|
||||
"""Time windows of the GENETIC home appliance simulation.
|
||||
|
||||
GENETIC's own copy of the window logic it needs from ``config.configabc`` (ADR 0004: optimizers
|
||||
duplicate code instead of sharing it), on frozen dataclasses instead of settings models. The
|
||||
request's ``TimeWindow`` models derive them; the semantics are the same:
|
||||
|
||||
- ``start_time`` is a naive wall-clock time, interpreted in the timezone of the datetime it is
|
||||
compared with.
|
||||
- Date, weekday and month restrictions apply to the calendar date the window starts on.
|
||||
- The end is exclusive: ``end_time`` is the first occurrence of that clock time strictly after
|
||||
the start; the window ends at the later of ``end_time`` and ``start_time + duration``.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
from akkudoktoreos.utils.datetimeutil import Date, DateTime, Duration, Time
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class GeneticTimeWindow:
|
||||
"""A time window of the simulation, derived from a request's time window.
|
||||
|
||||
Attributes:
|
||||
start_time: Naive local start time.
|
||||
duration: Length of the window.
|
||||
end_time: Naive local end time; ``None`` uses the duration only.
|
||||
day_of_week: Weekday the window starts on, 0 (Monday) to 6 (Sunday); ``None`` any day.
|
||||
date: Calendar date the window starts on; ``None`` any date.
|
||||
month: Month the window starts in, 1 to 12; ``None`` any month.
|
||||
value: Value of the window; for cycle windows the 0-based cycle index, ``None`` belongs
|
||||
to no cycle.
|
||||
"""
|
||||
|
||||
start_time: Time
|
||||
duration: Duration
|
||||
end_time: Optional[Time] = None
|
||||
day_of_week: Optional[int] = None
|
||||
date: Optional[Date] = None
|
||||
month: Optional[int] = None
|
||||
value: Optional[float] = None
|
||||
|
||||
def start_end(self, reference_date: DateTime) -> tuple[DateTime, DateTime]:
|
||||
"""Return the start and exclusive end of the window opening on a date.
|
||||
|
||||
Args:
|
||||
reference_date: Datetime identifying the calendar date the window starts on. Its
|
||||
time of day is ignored.
|
||||
|
||||
Returns:
|
||||
The start datetime and the exclusive end datetime.
|
||||
"""
|
||||
start_day = reference_date.start_of("day")
|
||||
|
||||
# Use Pendulum's default (second occurrence) for ambiguous boundaries,
|
||||
# independently of the fold carried by the reference datetime.
|
||||
start = start_day.replace(
|
||||
hour=self.start_time.hour,
|
||||
minute=self.start_time.minute,
|
||||
second=self.start_time.second,
|
||||
microsecond=self.start_time.microsecond,
|
||||
fold=1,
|
||||
)
|
||||
|
||||
duration_end = start + self.duration
|
||||
|
||||
if self.end_time is None:
|
||||
return start, duration_end
|
||||
|
||||
start_clock = (
|
||||
self.start_time.hour,
|
||||
self.start_time.minute,
|
||||
self.start_time.second,
|
||||
self.start_time.microsecond,
|
||||
)
|
||||
end_clock = (
|
||||
self.end_time.hour,
|
||||
self.end_time.minute,
|
||||
self.end_time.second,
|
||||
self.end_time.microsecond,
|
||||
)
|
||||
|
||||
# Choose the date before setting the time: a nonexistent clock time on
|
||||
# the start day must not be normalized and carried into the following day.
|
||||
end_day = start_day.add(days=1) if end_clock <= start_clock else start_day
|
||||
explicit_end = end_day.replace(
|
||||
hour=self.end_time.hour,
|
||||
minute=self.end_time.minute,
|
||||
second=self.end_time.second,
|
||||
microsecond=self.end_time.microsecond,
|
||||
fold=1,
|
||||
)
|
||||
|
||||
# Same-timezone datetime ordering ignores fold during the repeated DST
|
||||
# hour. Pendulum subtraction measures elapsed time between the instants.
|
||||
end = explicit_end if (explicit_end - duration_end).total_seconds() > 0 else duration_end
|
||||
return start, end
|
||||
@@ -1,11 +0,0 @@
|
||||
"""Genetic optimization algorithm abstract and base classes."""
|
||||
|
||||
from pydantic import ConfigDict
|
||||
|
||||
from akkudoktoreos.core.pydantic import PydanticBaseModel
|
||||
|
||||
|
||||
class GeneticParametersBaseModel(PydanticBaseModel):
|
||||
"""Pydantic base model for parameters for the GENETIC algorithm."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
+177
-1054
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,854 @@
|
||||
"""REST API of GENETIC (ADR 0005, 0011): its router and public response models.
|
||||
|
||||
The router fetches nothing itself: the generic server fills the placeholder dependencies
|
||||
``last_run()`` and ``run()`` through ``app.dependency_overrides``. The response models are built
|
||||
from the result of a run (``solution_response()``).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import copy
|
||||
import dataclasses
|
||||
from typing import Any, Optional, Union
|
||||
|
||||
from fastapi import APIRouter, Body, Depends, Request, Response
|
||||
from pydantic import AliasChoices, ConfigDict, Field, computed_field, field_validator
|
||||
|
||||
from akkudoktoreos.core.pydantic import PydanticBaseModel
|
||||
from akkudoktoreos.optimization.genetic import geneticterminalvalue
|
||||
from akkudoktoreos.optimization.genetic.geneticparameters import GeneticParameters
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticOptimizationParameters,
|
||||
GeneticParametersBaseModel,
|
||||
GeneticRequest,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticresult import GeneticResult
|
||||
from akkudoktoreos.optimization.optimizer import (
|
||||
OptimizerApi,
|
||||
OptimizerProblem,
|
||||
OptimizerRun,
|
||||
RunTrigger,
|
||||
)
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime
|
||||
from akkudoktoreos.utils.utils import NumpyEncoder
|
||||
|
||||
# ----------------------------------------------------------------------------------------------
|
||||
# Response models
|
||||
# ----------------------------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TerminalValueCurve(PydanticBaseModel):
|
||||
"""Piecewise linear, concave value of battery energy left at the horizon.
|
||||
|
||||
``energy_wh`` and ``value_euro`` are the breakpoints of the cumulative
|
||||
value, ``marginal_euro_per_kwh`` the slope of each segment. Both arrays
|
||||
start at the origin; the curve is flat beyond its last breakpoint.
|
||||
"""
|
||||
|
||||
energy_wh: list[float] = Field(
|
||||
default_factory=list,
|
||||
json_schema_extra={
|
||||
"description": "Breakpoints of usable AC energy left in the battery [Wh]."
|
||||
},
|
||||
)
|
||||
value_euro: list[float] = Field(
|
||||
default_factory=list,
|
||||
json_schema_extra={"description": "Cumulative credit at each breakpoint [EUR]."},
|
||||
)
|
||||
operating_value_euro: list[float] = Field(
|
||||
default_factory=list,
|
||||
json_schema_extra={
|
||||
"description": "Tail operating component at each breakpoint [EUR]; empty for a proxy curve."
|
||||
},
|
||||
)
|
||||
continuation_value_euro: list[float] = Field(
|
||||
default_factory=list,
|
||||
json_schema_extra={
|
||||
"description": "Continuation component at each breakpoint [EUR]; empty for a proxy curve."
|
||||
},
|
||||
)
|
||||
marginal_euro_per_kwh: list[float] = Field(
|
||||
default_factory=list,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Marginal value of the segment that starts at each breakpoint "
|
||||
"[EUR/kWh]. May be negative or non-monotone in TAIL mode."
|
||||
)
|
||||
},
|
||||
)
|
||||
residual_energy_wh: float = Field(
|
||||
default=0.0,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Energy up to which the curve is backed by residual load - the "
|
||||
"knee. Everything beyond it is only worth an export."
|
||||
)
|
||||
},
|
||||
)
|
||||
window_slots: int = Field(
|
||||
default=0,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Number of trailing horizon slots the curve was derived from. "
|
||||
"Fewer slots than a full day mean a shorter proxy period."
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
class TailDiagnostics(PydanticBaseModel):
|
||||
"""Forecast summary used by the deterministic tail optimization."""
|
||||
|
||||
slots: int = 0
|
||||
slot_hours: float = 0.0
|
||||
soc_grid_points: int = 0
|
||||
min_import_price_euro_per_kwh: float = 0.0
|
||||
max_import_price_euro_per_kwh: float = 0.0
|
||||
min_feed_in_tariff_euro_per_kwh: float = 0.0
|
||||
max_feed_in_tariff_euro_per_kwh: float = 0.0
|
||||
negative_import_price_slots: int = 0
|
||||
positive_battery_export_slots: int = 0
|
||||
|
||||
|
||||
class TailPlanSlot(PydanticBaseModel):
|
||||
"""One diagnostic slot of the optimal tail path.
|
||||
|
||||
These values explain the lookahead used for fitness. They are diagnostics
|
||||
only and are never copied into the executable control arrays.
|
||||
"""
|
||||
|
||||
slot: int
|
||||
hour_from_start: float
|
||||
action: str
|
||||
alternative_action: str = ""
|
||||
decision_margin_euro: float = 0.0
|
||||
soc_start_percentage: float
|
||||
soc_end_percentage: float
|
||||
pv_wh: float
|
||||
load_wh: float
|
||||
grid_import_wh: float
|
||||
grid_export_wh: float
|
||||
battery_charge_wh: float
|
||||
battery_discharge_wh: float
|
||||
import_price_euro_per_kwh: float
|
||||
feed_in_tariff_euro_per_kwh: float
|
||||
slot_value_euro: float
|
||||
remaining_value_euro: float
|
||||
ac_charge_factor: float
|
||||
dc_charge_allowed: int
|
||||
discharge_allowed: int
|
||||
battery_grid_export_factor: float
|
||||
|
||||
|
||||
class TerminalValueResult(PydanticBaseModel):
|
||||
"""What the optimizer credited for the energy left in the battery."""
|
||||
|
||||
control_horizon_hours: float = 0
|
||||
requested_tail_hours: float = 0
|
||||
effective_tail_hours: float = 0
|
||||
tail_end_hour: float = 0
|
||||
continuation_mode: str = "FIXED"
|
||||
|
||||
mode: str = Field(
|
||||
json_schema_extra={
|
||||
"description": "Terminal value mode the run used: TAIL, AUTO or FIXED.",
|
||||
"examples": ["TAIL", "AUTO", "FIXED"],
|
||||
}
|
||||
)
|
||||
battery_energy_wh: float = Field(
|
||||
default=0.0,
|
||||
json_schema_extra={
|
||||
"description": "Usable AC energy left in the battery at the end of the horizon [Wh]."
|
||||
},
|
||||
)
|
||||
credited_euro: float = Field(
|
||||
default=0.0,
|
||||
json_schema_extra={"description": "Credit applied to the total balance [EUR]."},
|
||||
)
|
||||
tail_operating_euro: float = Field(
|
||||
default=0.0,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Optimal net cash flow within the effective tail for the selected "
|
||||
"control-end battery state [EUR]."
|
||||
)
|
||||
},
|
||||
)
|
||||
continuation_value_euro: float = Field(
|
||||
default=0.0,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Continuation credit remaining at the end of the optimal tail path [EUR]."
|
||||
)
|
||||
},
|
||||
)
|
||||
curve: Optional[TerminalValueCurve] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Combined tail value curve (tail operation plus continuation) read by fitness; "
|
||||
"None in FIXED mode."
|
||||
)
|
||||
},
|
||||
)
|
||||
continuation_curve: Optional[TerminalValueCurve] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": "Conservative AUTO proxy constructed at the effective tail end."
|
||||
},
|
||||
)
|
||||
tail_diagnostics: Optional[TailDiagnostics] = None
|
||||
tail_plan: list[TailPlanSlot] = Field(
|
||||
default_factory=list,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Diagnostic optimal battery path inside the tail. It explains the "
|
||||
"lookahead but is never an executable control plan."
|
||||
)
|
||||
},
|
||||
)
|
||||
reason: str = Field(
|
||||
default="",
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Why this mode applied. Empty in AUTO mode; in FIXED mode it "
|
||||
"says whether FIXED was configured or whether AUTO fell back "
|
||||
"because no curve could be derived."
|
||||
),
|
||||
"examples": ["", "terminal_value_mode is FIXED"],
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
class DeviceOptimizeResult(GeneticParametersBaseModel):
|
||||
device_id: str = Field(
|
||||
json_schema_extra={"description": "ID of device", "examples": ["device1"]}
|
||||
)
|
||||
hours: int = Field(
|
||||
gt=0,
|
||||
json_schema_extra={"description": "Number of hours in the simulation.", "examples": [24]},
|
||||
)
|
||||
|
||||
|
||||
class ElectricVehicleResult(DeviceOptimizeResult):
|
||||
"""Result class containing information related to the electric vehicle's charging and discharging behavior."""
|
||||
|
||||
device_id: str = Field(
|
||||
json_schema_extra={"description": "ID of electric vehicle", "examples": ["ev1"]}
|
||||
)
|
||||
charge_array: list[float] = Field(
|
||||
json_schema_extra={
|
||||
"description": "Hourly charging status (0 for no charging, 1 for charging)."
|
||||
}
|
||||
)
|
||||
discharge_array: list[int] = Field(
|
||||
json_schema_extra={
|
||||
"description": "Hourly discharging status (0 for no discharging, 1 for discharging)."
|
||||
}
|
||||
)
|
||||
discharging_efficiency: float = Field(
|
||||
json_schema_extra={"description": "The discharge efficiency as a float.."}
|
||||
)
|
||||
capacity_wh: int = Field(
|
||||
json_schema_extra={"description": "Capacity of the EV’s battery in watt-hours."}
|
||||
)
|
||||
charging_efficiency: float = Field(
|
||||
json_schema_extra={"description": "Charging efficiency as a float.."}
|
||||
)
|
||||
max_charge_power_w: int = Field(
|
||||
json_schema_extra={"description": "Maximum charging power in watts."}
|
||||
)
|
||||
max_discharge_power_w: Optional[float] = Field(
|
||||
default=None,
|
||||
json_schema_extra={"description": "Maximum discharging power in watts."},
|
||||
)
|
||||
soc_wh: float = Field(
|
||||
json_schema_extra={
|
||||
"description": "State of charge of the battery in watt-hours at the start of the simulation."
|
||||
}
|
||||
)
|
||||
initial_soc_percentage: int = Field(
|
||||
json_schema_extra={
|
||||
"description": "State of charge at the start of the simulation in percentage."
|
||||
}
|
||||
)
|
||||
|
||||
@field_validator("discharge_array", "charge_array", mode="before")
|
||||
def convert_numpy(cls, field: Any) -> Any:
|
||||
return NumpyEncoder.convert_numpy(field)[0]
|
||||
|
||||
|
||||
class GeneticSimulationResult(GeneticParametersBaseModel):
|
||||
"""This object contains the results of the simulation and provides insights into various parameters over the entire forecast period."""
|
||||
|
||||
model_config = ConfigDict(populate_by_name=True, extra="ignore")
|
||||
|
||||
load_wh_per_hour: list[float] = Field(
|
||||
validation_alias=AliasChoices("load_wh_per_hour", "Last_Wh_pro_Stunde"),
|
||||
json_schema_extra={"description": "The load in watt-hours per hour."},
|
||||
)
|
||||
ev_soc_per_hour: list[float] = Field(
|
||||
validation_alias=AliasChoices("ev_soc_per_hour", "EAuto_SoC_pro_Stunde"),
|
||||
json_schema_extra={"description": "The state of charge of the EV for each hour."},
|
||||
)
|
||||
revenue_per_hour: list[float] = Field(
|
||||
validation_alias=AliasChoices("revenue_per_hour", "Einnahmen_Euro_pro_Stunde"),
|
||||
json_schema_extra={
|
||||
"description": "The revenue from grid feed-in or other sources per hour."
|
||||
},
|
||||
)
|
||||
total_losses: float = Field(
|
||||
validation_alias=AliasChoices("total_losses", "Gesamt_Verluste"),
|
||||
json_schema_extra={"description": "The total losses in watt-hours over the entire period."},
|
||||
)
|
||||
total_balance: float = Field(
|
||||
validation_alias=AliasChoices("total_balance", "Gesamtbilanz_Euro"),
|
||||
json_schema_extra={"description": "The total balance of revenues minus costs."},
|
||||
)
|
||||
total_revenue: float = Field(
|
||||
validation_alias=AliasChoices("total_revenue", "Gesamteinnahmen_Euro"),
|
||||
json_schema_extra={"description": "The total revenues."},
|
||||
)
|
||||
total_costs: float = Field(
|
||||
validation_alias=AliasChoices("total_costs", "Gesamtkosten_Euro"),
|
||||
json_schema_extra={"description": "The total costs."},
|
||||
)
|
||||
home_appliance_wh_per_hour: list[Optional[float]] = Field(
|
||||
validation_alias=AliasChoices("home_appliance_wh_per_hour", "Home_appliance_wh_per_hour"),
|
||||
json_schema_extra={
|
||||
"description": "The energy consumption of a household appliance in watt-hours per hour."
|
||||
},
|
||||
)
|
||||
costs_per_hour: list[float] = Field(
|
||||
validation_alias=AliasChoices("costs_per_hour", "Kosten_Euro_pro_Stunde"),
|
||||
json_schema_extra={"description": "The costs per hour."},
|
||||
)
|
||||
grid_consumption_wh_per_hour: list[float] = Field(
|
||||
validation_alias=AliasChoices("grid_consumption_wh_per_hour", "Netzbezug_Wh_pro_Stunde"),
|
||||
json_schema_extra={"description": "The grid energy drawn in watt-hours per hour."},
|
||||
)
|
||||
grid_feed_in_wh_per_hour: list[float] = Field(
|
||||
validation_alias=AliasChoices("grid_feed_in_wh_per_hour", "Netzeinspeisung_Wh_pro_Stunde"),
|
||||
json_schema_extra={"description": "The energy fed into the grid in watt-hours per hour."},
|
||||
)
|
||||
losses_per_hour: list[float] = Field(
|
||||
validation_alias=AliasChoices("losses_per_hour", "Verluste_Pro_Stunde"),
|
||||
json_schema_extra={"description": "The losses in watt-hours per hour."},
|
||||
)
|
||||
battery_soc_per_hour: list[float] = Field(
|
||||
validation_alias=AliasChoices("battery_soc_per_hour", "akku_soc_pro_stunde"),
|
||||
json_schema_extra={
|
||||
"description": "The state of charge of the battery (not the EV) in percentage per hour."
|
||||
},
|
||||
)
|
||||
electricity_price: list[float] = Field(
|
||||
validation_alias=AliasChoices("electricity_price", "Electricity_price"),
|
||||
json_schema_extra={"description": "Used Electricity Price, including predictions"},
|
||||
)
|
||||
|
||||
# Computed fields for backward compatibility (deprecated German names)
|
||||
@computed_field(json_schema_extra={"deprecated": True})
|
||||
def Last_Wh_pro_Stunde(self) -> list[float]:
|
||||
"""Deprecated: Use load_wh_per_hour instead."""
|
||||
return self.load_wh_per_hour
|
||||
|
||||
@computed_field(json_schema_extra={"deprecated": True})
|
||||
def EAuto_SoC_pro_Stunde(self) -> list[float]:
|
||||
"""Deprecated: Use ev_soc_per_hour instead."""
|
||||
return self.ev_soc_per_hour
|
||||
|
||||
@computed_field(json_schema_extra={"deprecated": True})
|
||||
def Einnahmen_Euro_pro_Stunde(self) -> list[float]:
|
||||
"""Deprecated: Use revenue_per_hour instead."""
|
||||
return self.revenue_per_hour
|
||||
|
||||
@computed_field(json_schema_extra={"deprecated": True})
|
||||
def Gesamt_Verluste(self) -> float:
|
||||
"""Deprecated: Use total_losses instead."""
|
||||
return self.total_losses
|
||||
|
||||
@computed_field(json_schema_extra={"deprecated": True})
|
||||
def Gesamtbilanz_Euro(self) -> float:
|
||||
"""Deprecated: Use total_balance instead."""
|
||||
return self.total_balance
|
||||
|
||||
@computed_field(json_schema_extra={"deprecated": True})
|
||||
def Gesamteinnahmen_Euro(self) -> float:
|
||||
"""Deprecated: Use total_revenue instead."""
|
||||
return self.total_revenue
|
||||
|
||||
@computed_field(json_schema_extra={"deprecated": True})
|
||||
def Gesamtkosten_Euro(self) -> float:
|
||||
"""Deprecated: Use total_costs instead."""
|
||||
return self.total_costs
|
||||
|
||||
@computed_field(json_schema_extra={"deprecated": True})
|
||||
def Home_appliance_wh_per_hour(self) -> list[Optional[float]]:
|
||||
"""Deprecated: Use home_appliance_wh_per_hour instead."""
|
||||
return self.home_appliance_wh_per_hour
|
||||
|
||||
@computed_field(json_schema_extra={"deprecated": True})
|
||||
def Kosten_Euro_pro_Stunde(self) -> list[float]:
|
||||
"""Deprecated: Use costs_per_hour instead."""
|
||||
return self.costs_per_hour
|
||||
|
||||
@computed_field(json_schema_extra={"deprecated": True})
|
||||
def Netzbezug_Wh_pro_Stunde(self) -> list[float]:
|
||||
"""Deprecated: Use grid_consumption_wh_per_hour instead."""
|
||||
return self.grid_consumption_wh_per_hour
|
||||
|
||||
@computed_field(json_schema_extra={"deprecated": True})
|
||||
def Netzeinspeisung_Wh_pro_Stunde(self) -> list[float]:
|
||||
"""Deprecated: Use grid_feed_in_wh_per_hour instead."""
|
||||
return self.grid_feed_in_wh_per_hour
|
||||
|
||||
@computed_field(json_schema_extra={"deprecated": True})
|
||||
def Verluste_Pro_Stunde(self) -> list[float]:
|
||||
"""Deprecated: Use losses_per_hour instead."""
|
||||
return self.losses_per_hour
|
||||
|
||||
@computed_field(json_schema_extra={"deprecated": True})
|
||||
def akku_soc_pro_stunde(self) -> list[float]:
|
||||
"""Deprecated: Use battery_soc_per_hour instead."""
|
||||
return self.battery_soc_per_hour
|
||||
|
||||
@computed_field(json_schema_extra={"deprecated": True})
|
||||
def Electricity_price(self) -> list[float]:
|
||||
"""Deprecated: Use electricity_price instead."""
|
||||
return self.electricity_price
|
||||
|
||||
@field_validator(
|
||||
"load_wh_per_hour",
|
||||
"grid_feed_in_wh_per_hour",
|
||||
"battery_soc_per_hour",
|
||||
"grid_consumption_wh_per_hour",
|
||||
"costs_per_hour",
|
||||
"revenue_per_hour",
|
||||
"ev_soc_per_hour",
|
||||
"losses_per_hour",
|
||||
"home_appliance_wh_per_hour",
|
||||
"electricity_price",
|
||||
"feed_in_tariff",
|
||||
mode="before",
|
||||
)
|
||||
def convert_numpy(cls, field: Any) -> Any:
|
||||
return NumpyEncoder.convert_numpy(field)[0]
|
||||
|
||||
home_appliance_energy_wh: dict[str, list[float]] = Field(
|
||||
default_factory=dict,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Per-device appliance energy in watt-hours per optimization slot, "
|
||||
"keyed by device_id."
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
feed_in_tariff: list[float] = Field(
|
||||
validation_alias=AliasChoices("feed_in_tariff", "Feed_in_tariff"),
|
||||
default_factory=list,
|
||||
json_schema_extra={
|
||||
"description": "Used feed-in tariff in €/Wh per hour, including predictions"
|
||||
},
|
||||
)
|
||||
|
||||
home_appliance_running: dict[str, list[bool]] = Field(
|
||||
default_factory=dict, description="Active run occupancy, including zero-power phases."
|
||||
)
|
||||
|
||||
@field_validator("home_appliance_energy_wh", mode="before")
|
||||
def convert_numpy_appliance_energy(cls, field: Any) -> Any:
|
||||
if isinstance(field, dict):
|
||||
return {
|
||||
device_id: NumpyEncoder.convert_numpy(values)[0]
|
||||
for device_id, values in field.items()
|
||||
}
|
||||
return field
|
||||
|
||||
@computed_field(json_schema_extra={"deprecated": True})
|
||||
def Feed_in_tariff(self) -> Optional[list[float]]:
|
||||
"""Deprecated: use feed_in_tariff."""
|
||||
return self.feed_in_tariff
|
||||
|
||||
|
||||
class GeneticSolution(GeneticParametersBaseModel):
|
||||
"""**Note**: The first value of "load_wh_per_hour", "grid_feed_in_wh_per_hour", and "grid_consumption_wh_per_hour", will be set to null in the JSON output and represented as NaN or None in the corresponding classes' data returns. This approach is adopted to ensure that the current hour's processing remains unchanged."""
|
||||
|
||||
model_config = ConfigDict(populate_by_name=True, extra="ignore")
|
||||
|
||||
parameters: GeneticOptimizationParameters = Field(
|
||||
json_schema_extra={"description": "Optimization parameters used to generate solution."}
|
||||
)
|
||||
|
||||
ac_charge: list[float] = Field(
|
||||
json_schema_extra={
|
||||
"description": "Array with AC charging values as relative power (0.0-1.0), other values set to 0."
|
||||
}
|
||||
)
|
||||
|
||||
dc_charge: list[float] = Field(
|
||||
json_schema_extra={
|
||||
"description": "Array with DC charging values as relative power (0-1), other values set to 0."
|
||||
}
|
||||
)
|
||||
|
||||
discharge_allowed: list[int] = Field(
|
||||
json_schema_extra={
|
||||
"description": "Array with discharge values (1 for discharge, 0 otherwise)."
|
||||
}
|
||||
)
|
||||
|
||||
ev_charge_hours_float: Optional[list[float]] = Field(
|
||||
validation_alias=AliasChoices("ev_charge_hours_float", "eautocharge_hours_float"),
|
||||
json_schema_extra={
|
||||
"description": "Array with EV charging values as relative power (0.0-1.0), or `null` if no EV is optimized."
|
||||
},
|
||||
)
|
||||
|
||||
result: GeneticSimulationResult
|
||||
|
||||
ev_obj: Optional[ElectricVehicleResult] = Field(
|
||||
validation_alias=AliasChoices("ev_obj", "eauto_obj"),
|
||||
json_schema_extra={"description": "Electric vehicle state after optimization."},
|
||||
)
|
||||
|
||||
start_hour: int = Field(
|
||||
default=0,
|
||||
json_schema_extra={"description": "Start hour."},
|
||||
)
|
||||
|
||||
start_solution: Optional[list[float]] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": "An array of binary values (0 or 1) representing a possible starting solution for the simulation."
|
||||
},
|
||||
)
|
||||
|
||||
washingstart: Optional[int] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": "Can be `null` or contain an object representing the start of washing (if applicable)."
|
||||
},
|
||||
)
|
||||
|
||||
extra_data: Optional[dict[str, Union[list[int], list[float]]]] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": ("Dictionary of balance: TBD, losses: TBD, constraints: TBD.")
|
||||
},
|
||||
)
|
||||
|
||||
fitness_history: Optional[dict[str, Any]] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Dictionary of "
|
||||
"gen: Generation numbers (X-axis), "
|
||||
"avg: Average fitness for each generation (Y-axis), "
|
||||
"max: Maximum fitness for each generation (Y-axis), "
|
||||
"min: Minimum fitness for each generation (Y-axis)."
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
fixed_seed: Optional[int] = Field(
|
||||
default=None,
|
||||
json_schema_extra={"description": "Fixed seed."},
|
||||
)
|
||||
|
||||
@computed_field(json_schema_extra={"deprecated": True})
|
||||
def eautocharge_hours_float(self) -> Optional[list[float]]:
|
||||
"""Deprecated: Use ev_charge_hours_float instead."""
|
||||
return self.ev_charge_hours_float
|
||||
|
||||
@computed_field(json_schema_extra={"deprecated": True})
|
||||
def eauto_obj(self) -> Optional[ElectricVehicleResult]:
|
||||
"""Deprecated: Use ev_obj instead."""
|
||||
return self.ev_obj
|
||||
|
||||
@field_validator(
|
||||
"ac_charge",
|
||||
"dc_charge",
|
||||
"discharge_allowed",
|
||||
"battery_grid_export_allowed",
|
||||
"battery_grid_export_factor",
|
||||
mode="before",
|
||||
)
|
||||
def convert_numpy(cls, field: Any) -> Any:
|
||||
return NumpyEncoder.convert_numpy(field)[0]
|
||||
|
||||
controls_start_at_now: bool = Field(
|
||||
default=False, description="Control arrays start at the run timestamp instead of midnight."
|
||||
)
|
||||
|
||||
battery_grid_export_allowed: list[int] = Field(
|
||||
default_factory=list,
|
||||
json_schema_extra={
|
||||
"description": "Array with battery-to-grid export values (1 for export discharge, 0 otherwise)."
|
||||
},
|
||||
)
|
||||
|
||||
terminal_value: Optional[TerminalValueResult] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"The terminal value applied to the energy left in the battery at "
|
||||
"the end of the horizon, including the curve it was read from. "
|
||||
"None when no battery is part of the optimization."
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
battery_grid_export_factor: list[float] = Field(
|
||||
default_factory=list,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Array with the battery-to-grid export level per slot as factor "
|
||||
"of the rated discharge power (0.0 for no export). Empty when "
|
||||
"direct marketing is disabled; a solution without this array "
|
||||
"exports at full power wherever "
|
||||
"'battery_grid_export_allowed' is 1."
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
start_solution_datetime: Optional[DateTime] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Start of the slot that gene 0 of 'start_solution' controls. Send it "
|
||||
"back together with 'start_solution' so the next run can shift the "
|
||||
"warm start by the slots that have elapsed since."
|
||||
),
|
||||
"examples": [None, "2026-09-14T07:45:00+02:00"],
|
||||
},
|
||||
)
|
||||
|
||||
appliance_starts: dict[str, list[DateTime]] = Field(
|
||||
default_factory=dict,
|
||||
json_schema_extra={
|
||||
"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: dict[str, bool] = Field(
|
||||
default_factory=dict,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Per appliance device_id with a 'deadline_datetime': whether the "
|
||||
"scheduled run misses that deadline (or was not scheduled at "
|
||||
"all). Appliances without a deadline are not listed."
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
interval_seconds: int = Field(
|
||||
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]:
|
||||
"""Accept the usual date time representations, naive input is local time."""
|
||||
return GeneticOptimizationParameters.transform_start_solution_datetime(value)
|
||||
|
||||
|
||||
def _curve_response(
|
||||
curve: Optional[geneticterminalvalue.TerminalValueCurve],
|
||||
) -> Optional[dict[str, Any]]:
|
||||
"""The fields of a terminal value curve, without the replay context of a tail curve."""
|
||||
if curve is None:
|
||||
return None
|
||||
return {name: getattr(curve, name) for name in TerminalValueCurve.model_fields}
|
||||
|
||||
|
||||
def terminal_value_response(
|
||||
terminal_value: Optional[geneticterminalvalue.TerminalValueResult],
|
||||
) -> Optional[TerminalValueResult]:
|
||||
"""The public terminal value of a run.
|
||||
|
||||
Args:
|
||||
terminal_value: The terminal value of the result.
|
||||
|
||||
Returns:
|
||||
The terminal value as the REST API returns it.
|
||||
"""
|
||||
if terminal_value is None:
|
||||
return None
|
||||
return TerminalValueResult.model_validate(
|
||||
{
|
||||
**{
|
||||
field.name: getattr(terminal_value, field.name)
|
||||
for field in dataclasses.fields(terminal_value)
|
||||
},
|
||||
"curve": _curve_response(terminal_value.curve),
|
||||
"continuation_curve": _curve_response(terminal_value.continuation_curve),
|
||||
"tail_diagnostics": None
|
||||
if terminal_value.tail_diagnostics is None
|
||||
else dataclasses.asdict(terminal_value.tail_diagnostics),
|
||||
"tail_plan": [dataclasses.asdict(slot) for slot in terminal_value.tail_plan],
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def solution_response(result: GeneticResult) -> GeneticSolution:
|
||||
"""The public solution of a run.
|
||||
|
||||
Args:
|
||||
result: The result of the run; its request is echoed as ``parameters``.
|
||||
|
||||
Returns:
|
||||
The solution as the REST API returns it.
|
||||
"""
|
||||
return GeneticSolution.model_validate(
|
||||
{
|
||||
**{
|
||||
field.name: getattr(result, field.name)
|
||||
for field in dataclasses.fields(result)
|
||||
if field.name not in ("request", "result", "ev_obj", "terminal_value")
|
||||
},
|
||||
"parameters": result.request,
|
||||
"result": dataclasses.asdict(result.result),
|
||||
"ev_obj": None if result.ev_obj is None else dataclasses.asdict(result.ev_obj),
|
||||
"terminal_value": terminal_value_response(result.terminal_value),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------
|
||||
# Router
|
||||
# ----------------------------------------------------------------------------------------------
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def last_run() -> Optional[OptimizerRun[GeneticParameters, GeneticResult]]:
|
||||
"""Placeholder dependency: the latest GENETIC run, filled by the server.
|
||||
|
||||
Raises:
|
||||
NotImplementedError: The server did not fill the placeholder.
|
||||
"""
|
||||
raise NotImplementedError("Filled by the server through app.dependency_overrides.")
|
||||
|
||||
|
||||
def run() -> RunTrigger:
|
||||
"""Placeholder dependency: starts a GENETIC run, filled by the server.
|
||||
|
||||
Raises:
|
||||
NotImplementedError: The server did not fill the placeholder.
|
||||
"""
|
||||
raise NotImplementedError("Filled by the server through app.dependency_overrides.")
|
||||
|
||||
|
||||
def api() -> OptimizerApi:
|
||||
"""The REST API of GENETIC for the server.
|
||||
|
||||
Returns:
|
||||
The router and its placeholder dependencies.
|
||||
"""
|
||||
return OptimizerApi(router=router, last_run=last_run, run=run)
|
||||
|
||||
|
||||
@router.get("/v1/energy-management/optimization/solution/GENETIC", tags=["energy-management"])
|
||||
async def fastapi_energy_management_optimization_solution_genetic_get(
|
||||
latest: Optional[OptimizerRun[GeneticParameters, GeneticResult]] = Depends(last_run),
|
||||
) -> GeneticSolution:
|
||||
"""Get the latest GENETIC specific solution of the optimization."""
|
||||
if latest is None:
|
||||
raise OptimizerProblem(
|
||||
status=404,
|
||||
title="Algorithm specific optimization solution retrieval failed",
|
||||
detail=(
|
||||
"Can not get the 'GENETIC' optimization solution.\n"
|
||||
"Did you configure automatic 'GENETIC' optimization?\n"
|
||||
"Did you run the optimization/ energy management?"
|
||||
),
|
||||
)
|
||||
return solution_response(latest.result)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/v1/energy-management/optimization/solution/GENETIC/pdf",
|
||||
tags=["energy-management"],
|
||||
response_class=Response,
|
||||
responses={200: {"content": {"application/pdf": {}}}},
|
||||
)
|
||||
async def fastapi_energy_management_optimization_solution_genetic_pdf_get(
|
||||
latest: Optional[OptimizerRun[GeneticParameters, GeneticResult]] = Depends(last_run),
|
||||
) -> Response:
|
||||
"""Render the retained GENETIC result without rerunning optimization.
|
||||
|
||||
Rendering runs outside the event loop. Copy the result before offloading;
|
||||
its recorded timestamp, interval and inputs own the report's time grid.
|
||||
The legacy /visualization_results.pdf route continues to serve GENETIC0.
|
||||
"""
|
||||
if latest is None:
|
||||
raise OptimizerProblem(
|
||||
status=404,
|
||||
title="Optimization solution report retrieval failed",
|
||||
detail="Can not get the 'GENETIC' optimization solution.",
|
||||
)
|
||||
snapshot = copy.deepcopy(latest.result)
|
||||
# matplotlib is only needed for the PDF report; import it on first use.
|
||||
from akkudoktoreos.optimization.genetic import geneticvisualize
|
||||
|
||||
pdf = await asyncio.to_thread(
|
||||
geneticvisualize.genetic_prepare_visualize, parameters=latest.parameters, result=snapshot
|
||||
)
|
||||
return Response(
|
||||
content=pdf,
|
||||
media_type="application/pdf",
|
||||
headers={"Content-Disposition": 'inline; filename="optimization-genetic.pdf"'},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/v1/optimize", tags=["optimize"])
|
||||
async def fastapi_optimize_config(
|
||||
request: Request,
|
||||
parameters: GeneticRequest = Body(default_factory=GeneticRequest),
|
||||
trigger: RunTrigger = Depends(run),
|
||||
) -> GeneticSolution:
|
||||
"""Optimize GENETIC using configured devices and optional fresh runtime inputs.
|
||||
|
||||
Static settings belong in configuration; query overrides are rejected.
|
||||
Forecast arrays start at local
|
||||
midnight and contain Wh per configured GENETIC slot; prices are currency/Wh.
|
||||
An empty body uses configured providers. Explicit SoC values take precedence over
|
||||
fresh measured states of charge; missing usable measurements default to an assumed
|
||||
initial SoC of 0% without blocking a plan.
|
||||
The deprecated /optimize endpoint continues to run hourly GENETIC0.
|
||||
"""
|
||||
if request.query_params:
|
||||
raise OptimizerProblem(
|
||||
status=422,
|
||||
title="HTTP Error",
|
||||
detail="Configure optimization settings; query overrides are not supported.",
|
||||
)
|
||||
result = await trigger(request=parameters)
|
||||
if result is None:
|
||||
raise OptimizerProblem(
|
||||
status=503,
|
||||
title="GENETIC optimization failed",
|
||||
detail="No new solution was produced. Check configured devices and forecast coverage.",
|
||||
)
|
||||
if not isinstance(result, GeneticResult):
|
||||
raise OptimizerProblem(
|
||||
status=500,
|
||||
title="Unexpected optimization algorithm result",
|
||||
detail="GENETIC did not return its native solution type.",
|
||||
)
|
||||
return solution_response(result)
|
||||
@@ -0,0 +1,324 @@
|
||||
"""Appliance part of the GENETIC genome: allowed starts, layout and decoding.
|
||||
|
||||
Pure functions of the appliances and the run's slot grid. The algorithm builds and decodes its
|
||||
genome with them; the parameter preparation checks with the same rules that every appliance of a
|
||||
run can be scheduled.
|
||||
"""
|
||||
|
||||
import math
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass, field
|
||||
from functools import lru_cache
|
||||
from typing import Any, Optional
|
||||
|
||||
from akkudoktoreos.optimization.genetic.devices.genetichomeappliance import (
|
||||
GeneticHomeAppliance,
|
||||
GeneticScheduleMode,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ApplianceGeneSlot:
|
||||
"""One appliance start gene in the genome.
|
||||
|
||||
The gene value is an **index into ``allowed_start_slots``**, not an absolute
|
||||
slot. This guarantees every gene value maps to a genuinely valid start and
|
||||
keeps all allowed starts equally reachable by mutation/crossover.
|
||||
"""
|
||||
|
||||
gene_index: int
|
||||
appliance_index: int
|
||||
device_id: str
|
||||
run_index: int
|
||||
# Local calendar date of the run for DAILY appliances; None for ONCE.
|
||||
run_date: Optional[Any]
|
||||
allowed_start_slots: list[int]
|
||||
cycle_index: int = 0
|
||||
deadline_relaxed: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class ApplianceGeneLayout:
|
||||
"""Ordered descriptor of the appliance part of the genome.
|
||||
|
||||
Every genome-building step (create/split/merge/mutate/decode) consumes only
|
||||
this descriptor, so the appliance gene block can vary in length with the
|
||||
number of devices and DAILY run days without any hard-coded gene positions.
|
||||
"""
|
||||
|
||||
genes: list[ApplianceGeneSlot] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def n_genes(self) -> int:
|
||||
"""Number of appliance start genes."""
|
||||
return len(self.genes)
|
||||
|
||||
def signature(self) -> tuple:
|
||||
"""Stable identity of the layout for start-solution compatibility.
|
||||
|
||||
Two layouts with the same length can still describe different schedules;
|
||||
the signature captures device, run date and the allowed-start list so a
|
||||
cached start solution built for a different layout is not silently
|
||||
reused.
|
||||
"""
|
||||
return tuple(
|
||||
(gene.device_id, str(gene.run_date), gene.cycle_index, tuple(gene.allowed_start_slots))
|
||||
for gene in self.genes
|
||||
)
|
||||
|
||||
|
||||
def _run_date(appliance: GeneticHomeAppliance, slot0_datetime: Any, slot: int) -> Any:
|
||||
"""Local date of a run starting in ``slot``, the day a DAILY cycle counts for."""
|
||||
return slot0_datetime.add(seconds=slot * appliance.slot_interval_seconds).date()
|
||||
|
||||
|
||||
def build_appliance_layout(
|
||||
appliances: list[GeneticHomeAppliance],
|
||||
slot0_datetime: Any,
|
||||
*,
|
||||
start_slot: int,
|
||||
horizon_end_slot: int,
|
||||
control_end_slot: int,
|
||||
slot_duration_h: float,
|
||||
order_cache: dict[int, list[int]],
|
||||
) -> ApplianceGeneLayout:
|
||||
"""Keep each cycle's windows, completed cycles and local-day identity.
|
||||
|
||||
Args:
|
||||
appliances: The appliances of the run, with any run in progress pinned.
|
||||
slot0_datetime: Date-time of slot 0, the run start.
|
||||
start_slot: First slot an appliance may start in.
|
||||
horizon_end_slot: Exclusive end of the slots an appliance run must end in.
|
||||
control_end_slot: Exclusive control end of the run.
|
||||
slot_duration_h: Length of a slot in hours.
|
||||
order_cache: Feasible cycle order per appliance index; filled for the decoding.
|
||||
|
||||
Returns:
|
||||
The appliance genes of the genome.
|
||||
|
||||
Raises:
|
||||
ValueError: An appliance cannot be scheduled within its windows, deadline, minimum gaps
|
||||
and the control horizon.
|
||||
"""
|
||||
genes: list[ApplianceGeneSlot] = []
|
||||
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=earliest_slot,
|
||||
horizon_end_slot=horizon_end_slot,
|
||||
cycle_index=cycle,
|
||||
)
|
||||
relaxed_by_cycle[cycle] = appliance.deadline_relaxed
|
||||
if appliance.schedule_mode == GeneticScheduleMode.ONCE:
|
||||
groups = [
|
||||
(None, cycle, allowed_by_cycle[cycle])
|
||||
for cycle in cycles
|
||||
if cycle >= completed_cycles
|
||||
]
|
||||
else:
|
||||
by_date: dict[Any, dict[int, list[int]]] = {}
|
||||
for cycle, allowed in allowed_by_cycle.items():
|
||||
for slot in allowed:
|
||||
date = _run_date(appliance, slot0_datetime, slot)
|
||||
if date == first_date and cycle < completed_cycles:
|
||||
continue
|
||||
by_date.setdefault(date, {}).setdefault(cycle, []).append(slot)
|
||||
# Without any start the appliance cannot be scheduled if its windows and earliest
|
||||
# start are open for a cycle it still owes, but too short for the full run. A
|
||||
# horizon in which they are not open at all has nothing to plan.
|
||||
if not by_date and any(
|
||||
not (
|
||||
_run_date(appliance, slot0_datetime, slot) == first_date
|
||||
and cycle < completed_cycles
|
||||
)
|
||||
for cycle in cycles
|
||||
for slot in appliance.open_start_slots(
|
||||
slot0_datetime=slot0_datetime,
|
||||
earliest_slot=earliest_slot,
|
||||
horizon_end_slot=horizon_end_slot,
|
||||
cycle_index=cycle,
|
||||
)
|
||||
):
|
||||
raise ValueError(
|
||||
f"Home appliance '{appliance.device_id}' has no valid start within its windows, deadline and control horizon."
|
||||
)
|
||||
groups = [
|
||||
(date, cycle, allowed)
|
||||
for date, cycle_slots in sorted(by_date.items())
|
||||
for cycle, allowed in sorted(cycle_slots.items())
|
||||
]
|
||||
# A partially elapsed first day may have no feasible remaining run;
|
||||
# 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 >= completed_cycles
|
||||
}
|
||||
if set(cycle_slots) != expected:
|
||||
raise ValueError(
|
||||
f"Home appliance '{appliance.device_id}' has no complete cycle schedule on {date}."
|
||||
)
|
||||
for run_index, (date, cycle, allowed) in enumerate(groups):
|
||||
if not allowed:
|
||||
raise ValueError(
|
||||
f"Home appliance '{appliance.device_id}' cycle {cycle} has no valid start within its windows, deadline and control horizon."
|
||||
)
|
||||
genes.append(
|
||||
ApplianceGeneSlot(
|
||||
gene_index=len(genes),
|
||||
appliance_index=appliance_index,
|
||||
device_id=appliance.device_id,
|
||||
run_index=run_index,
|
||||
run_date=date,
|
||||
allowed_start_slots=allowed,
|
||||
cycle_index=cycle,
|
||||
deadline_relaxed=relaxed_by_cycle[cycle],
|
||||
)
|
||||
)
|
||||
layout = ApplianceGeneLayout(genes)
|
||||
# Detect impossible cross-cycle gaps before running a population search.
|
||||
decode_appliance_starts(
|
||||
layout,
|
||||
appliances,
|
||||
[0] * layout.n_genes,
|
||||
start_slot=start_slot,
|
||||
control_end_slot=control_end_slot,
|
||||
slot_duration_h=slot_duration_h,
|
||||
order_cache=order_cache,
|
||||
)
|
||||
return layout
|
||||
|
||||
|
||||
def decode_appliance_starts(
|
||||
layout: ApplianceGeneLayout,
|
||||
appliances: list[GeneticHomeAppliance],
|
||||
appliance_gene_values: list[int],
|
||||
*,
|
||||
start_slot: int,
|
||||
control_end_slot: int,
|
||||
slot_duration_h: float,
|
||||
order_cache: dict[int, list[int]],
|
||||
) -> dict[int, list[int]]:
|
||||
"""Repair requested starts jointly, preserving cycle windows and minimum gaps.
|
||||
|
||||
Backward latest-feasible bounds and a forward nearest-choice pass prevent
|
||||
an unlucky late first gene from making otherwise feasible cycles invalid.
|
||||
The canonical gene values are updated to describe the executed schedule.
|
||||
|
||||
Args:
|
||||
layout: The appliance genes of the genome.
|
||||
appliances: The appliances the genes refer to by index.
|
||||
appliance_gene_values: The appliance genes; updated to the executed schedule.
|
||||
start_slot: First slot an appliance may start in.
|
||||
control_end_slot: Exclusive control end of the run.
|
||||
slot_duration_h: Length of a slot in hours.
|
||||
order_cache: Feasible cycle order per appliance index, found once per run.
|
||||
|
||||
Returns:
|
||||
The start slots of each appliance, by appliance index.
|
||||
|
||||
Raises:
|
||||
ValueError: An appliance has no feasible schedule.
|
||||
"""
|
||||
starts_per_appliance: dict[int, list[int]] = defaultdict(list)
|
||||
grouped: dict[int, list[tuple[int, ApplianceGeneSlot]]] = defaultdict(list)
|
||||
for position, gene in enumerate(layout.genes):
|
||||
grouped[gene.appliance_index].append((position, gene))
|
||||
for appliance_index, entries in grouped.items():
|
||||
appliance = appliances[appliance_index]
|
||||
separation = appliance.run_slots + math.ceil(appliance.min_cycle_gap_h / slot_duration_h)
|
||||
by_position = dict(entries)
|
||||
|
||||
def requested_start(entry: tuple[int, ApplianceGeneSlot]) -> int:
|
||||
position, gene = entry
|
||||
index = min(
|
||||
max(int(appliance_gene_values[position]), 0), len(gene.allowed_start_slots) - 1
|
||||
)
|
||||
return gene.allowed_start_slots[0 if gene.deadline_relaxed else index]
|
||||
|
||||
def latest_bounds(order: list[tuple[int, ApplianceGeneSlot]]) -> Optional[list[int]]:
|
||||
bounds: list[int] = []
|
||||
limit = control_end_slot
|
||||
for _, gene in reversed(order):
|
||||
candidates = [slot for slot in gene.allowed_start_slots if slot <= limit]
|
||||
if not candidates:
|
||||
return None
|
||||
last = candidates[-1]
|
||||
bounds.append(last)
|
||||
limit = last - separation
|
||||
return list(reversed(bounds))
|
||||
|
||||
# Cycle numbers identify masks; they do not impose temporal order.
|
||||
# Keep every feasible order represented by a candidate genome.
|
||||
entries.sort(key=lambda entry: (requested_start(entry), entry[0]))
|
||||
latest = latest_bounds(entries)
|
||||
if latest is None:
|
||||
if appliance_index not in order_cache:
|
||||
|
||||
@lru_cache(maxsize=None)
|
||||
def feasible_order(
|
||||
remaining: tuple[int, ...], earliest: int
|
||||
) -> Optional[tuple[int, ...]]:
|
||||
if not remaining:
|
||||
return ()
|
||||
choices = []
|
||||
for position in remaining:
|
||||
allowed = [
|
||||
slot
|
||||
for slot in by_position[position].allowed_start_slots
|
||||
if slot >= earliest
|
||||
]
|
||||
if not allowed:
|
||||
return None
|
||||
choices.append((allowed[0], allowed[-1], position))
|
||||
# For a fixed order the earliest start dominates all later
|
||||
# starts for feasibility. Search permutations only once
|
||||
# per run, memoizing impossible remaining-cycle states.
|
||||
for first, _, position in sorted(choices):
|
||||
rest = feasible_order(
|
||||
tuple(index for index in remaining if index != position),
|
||||
first + separation,
|
||||
)
|
||||
if rest is not None:
|
||||
return (position, *rest)
|
||||
return None
|
||||
|
||||
order = feasible_order(tuple(sorted(by_position)), start_slot)
|
||||
if order is None:
|
||||
raise ValueError(
|
||||
f"Home appliance '{appliance.device_id}' cycles cannot fit their windows and minimum gaps."
|
||||
)
|
||||
order_cache[appliance_index] = list(order)
|
||||
entries = [
|
||||
(position, by_position[position]) for position in order_cache[appliance_index]
|
||||
]
|
||||
latest = latest_bounds(entries)
|
||||
if latest is None:
|
||||
raise ValueError(
|
||||
f"Home appliance '{appliance.device_id}' has no feasible cycle schedule."
|
||||
)
|
||||
earliest = start_slot
|
||||
for (position, gene), last in zip(entries, latest):
|
||||
allowed = gene.allowed_start_slots
|
||||
requested_index = min(max(int(appliance_gene_values[position]), 0), len(allowed) - 1)
|
||||
requested = allowed[requested_index]
|
||||
candidates = [slot for slot in allowed if earliest <= slot <= last]
|
||||
if not candidates:
|
||||
raise ValueError(f"Home appliance '{gene.device_id}' has no feasible cycle start.")
|
||||
chosen = (
|
||||
candidates[0]
|
||||
if gene.deadline_relaxed
|
||||
else min(candidates, key=lambda slot: (abs(slot - requested), slot))
|
||||
)
|
||||
starts_per_appliance[appliance_index].append(chosen)
|
||||
appliance_gene_values[position] = allowed.index(chosen)
|
||||
earliest = chosen + separation
|
||||
return starts_per_appliance
|
||||
@@ -0,0 +1,710 @@
|
||||
"""Solution conversion of GENETIC (ADR 0003, 0006).
|
||||
|
||||
Turns the result of a run into the optimization solution and the energy management plan, from
|
||||
the optimization parameters (run start, time zone) and the result (genes, simulation result and
|
||||
the forecast and device parameters it echoes) only.
|
||||
"""
|
||||
|
||||
from typing import Optional, cast
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from loguru import logger
|
||||
|
||||
from akkudoktoreos.core.emplan import (
|
||||
DDBCInstruction,
|
||||
EnergyManagementPlan,
|
||||
FRBCInstruction,
|
||||
)
|
||||
from akkudoktoreos.core.pydantic import PydanticDateTimeDataFrame
|
||||
from akkudoktoreos.devices.devicesabc import (
|
||||
ApplianceOperationMode,
|
||||
BatteryOperationMode,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticparameters import GeneticParameters
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticInverterRequest,
|
||||
GeneticOptimizationParameters,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticresult import GeneticResult
|
||||
from akkudoktoreos.optimization.optimization import OptimizationSolution
|
||||
from akkudoktoreos.utils.datetimeutil import to_datetime
|
||||
|
||||
|
||||
async def convert(
|
||||
parameters: GeneticParameters, result: GeneticResult
|
||||
) -> tuple[OptimizationSolution, EnergyManagementPlan]:
|
||||
"""Convert the result of a run into the optimization solution and the plan.
|
||||
|
||||
Args:
|
||||
parameters: The optimization parameters of the run.
|
||||
result: The result of the run.
|
||||
|
||||
Returns:
|
||||
The optimization solution and the energy management plan.
|
||||
"""
|
||||
return await optimization_solution(parameters, result), energy_management_plan(
|
||||
parameters, result
|
||||
)
|
||||
|
||||
|
||||
def _battery_device_id(result: GeneticResult) -> str:
|
||||
"""Device ID of the run's battery."""
|
||||
parameters = result.request
|
||||
if parameters is not None and parameters.pv_battery is not None:
|
||||
return parameters.pv_battery.device_id
|
||||
return "battery1"
|
||||
|
||||
|
||||
def _ev_device_id(result: GeneticResult) -> str:
|
||||
"""Device ID of the run's electric vehicle."""
|
||||
parameters = result.request
|
||||
if parameters is not None and parameters.ev is not None:
|
||||
return parameters.ev.device_id
|
||||
return "ev1"
|
||||
|
||||
|
||||
def _battery_operation_from_solution(
|
||||
ac_charge: float,
|
||||
dc_charge: float,
|
||||
discharge_allowed: bool,
|
||||
battery_grid_export_allowed: bool = False,
|
||||
battery_grid_export_factor: float = 1.0,
|
||||
) -> tuple[BatteryOperationMode, float]:
|
||||
"""Maps low-level solution to a representative operation mode and factor.
|
||||
|
||||
Args:
|
||||
ac_charge (float): Allowed AC-side charging power (relative units).
|
||||
dc_charge (float): Allowed DC-side charging power (relative units).
|
||||
discharge_allowed (bool): Whether discharging to local load is permitted.
|
||||
battery_grid_export_allowed (bool): Whether discharge into the grid is permitted.
|
||||
battery_grid_export_factor (float): Export level as factor of the rated
|
||||
discharge power ]0.0 ... 1.0]. Becomes the operation factor of
|
||||
GRID_SUPPORT_EXPORT.
|
||||
|
||||
Returns:
|
||||
tuple[BatteryOperationMode, float]: A tuple containing
|
||||
- `BatteryOperationMode`: the representative high-level operation mode.
|
||||
- `float`: the operation factor corresponding to the active signal.
|
||||
|
||||
Notes:
|
||||
- Explicit grid export is separate from local-load discharge.
|
||||
- The mapping prioritizes export > AC charge > DC charge > discharge.
|
||||
- Multiple strategies can produce the same low-level signals; this function
|
||||
returns a representative mode based on a defined priority order.
|
||||
"""
|
||||
# (0,0,0) → Nothing allowed
|
||||
if (
|
||||
ac_charge <= 0.0
|
||||
and dc_charge <= 0.0
|
||||
and not discharge_allowed
|
||||
and not battery_grid_export_allowed
|
||||
):
|
||||
return BatteryOperationMode.IDLE, 1.0
|
||||
|
||||
if battery_grid_export_allowed:
|
||||
if ac_charge > 0.0 or dc_charge > 0.0:
|
||||
raise ValueError(
|
||||
"Illegal state: battery_grid_export_allowed cannot be combined with charging"
|
||||
)
|
||||
return BatteryOperationMode.GRID_SUPPORT_EXPORT, min(
|
||||
max(float(battery_grid_export_factor), 0.0), 1.0
|
||||
)
|
||||
|
||||
# (0,0,1) -> Discharge for local load only: serve local demand, no grid
|
||||
# charging and no export.
|
||||
if ac_charge <= 0.0 and dc_charge <= 0.0 and discharge_allowed:
|
||||
return BatteryOperationMode.SELF_CONSUMPTION, 1.0
|
||||
|
||||
# (ac>0,0,0) → AC charge only
|
||||
if ac_charge > 0.0 and dc_charge <= 0.0 and not discharge_allowed:
|
||||
return BatteryOperationMode.GRID_SUPPORT_IMPORT, ac_charge
|
||||
|
||||
# (0,dc>0,0) → DC charge only
|
||||
if ac_charge <= 0.0 and dc_charge > 0.0 and not discharge_allowed:
|
||||
return BatteryOperationMode.NON_EXPORT, dc_charge
|
||||
|
||||
# (ac>0,dc>0,0) → Both charge paths, no discharge
|
||||
if ac_charge > 0.0 and dc_charge > 0.0 and not discharge_allowed:
|
||||
return BatteryOperationMode.FORCED_CHARGE, ac_charge
|
||||
|
||||
# (ac>0,0,1) → AC charge + discharge - does not make sense
|
||||
if ac_charge > 0.0 and dc_charge <= 0.0 and discharge_allowed:
|
||||
raise ValueError(
|
||||
f"Illegal state: ac_charge: {ac_charge} and discharge_allowed: {discharge_allowed}"
|
||||
)
|
||||
|
||||
# (0,dc>0,1) → DC charge + discharge
|
||||
if ac_charge <= 0.0 and dc_charge > 0.0 and discharge_allowed:
|
||||
return BatteryOperationMode.SELF_CONSUMPTION, dc_charge
|
||||
|
||||
# (ac>0,dc>0,1) → Fully flexible - does not make sense
|
||||
if ac_charge > 0.0 and dc_charge > 0.0 and discharge_allowed:
|
||||
raise ValueError(
|
||||
f"Illegal state: ac_charge: {ac_charge} and discharge_allowed: {discharge_allowed}"
|
||||
)
|
||||
|
||||
# Fallback → safe idle
|
||||
return BatteryOperationMode.IDLE, 1.0
|
||||
|
||||
|
||||
def _inverter_parameters_list(
|
||||
parameters: Optional[GeneticOptimizationParameters],
|
||||
) -> list[GeneticInverterRequest]:
|
||||
"""Return the inverter parameters the solution was computed with, as a list.
|
||||
|
||||
Args:
|
||||
parameters: The forecast and device parameters the result echoes.
|
||||
|
||||
Returns:
|
||||
The inverter, or no inverter.
|
||||
"""
|
||||
if parameters is not None and parameters.inverter is not None:
|
||||
return [parameters.inverter]
|
||||
return []
|
||||
|
||||
|
||||
def _soc_clamped_operation_factors(
|
||||
result: GeneticResult,
|
||||
ac_charge: float,
|
||||
dc_charge: float,
|
||||
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.
|
||||
|
||||
The raw gene values represent the optimizer's *intent* and are stored
|
||||
verbatim in the ``genetic_*`` solution columns. This method derives
|
||||
the *effective* values that can physically be executed given the
|
||||
battery's state of charge, used for the ``battery1_*_op_*`` columns
|
||||
and for ``energy_management_plan`` instructions.
|
||||
|
||||
Clamping rules:
|
||||
- AC charge factor: scaled down proportionally when the battery
|
||||
headroom (max_soc − current_soc) is smaller than what the
|
||||
commanded factor would store in one optimization slot. Set to 0 when full.
|
||||
- DC charge factor (PV): zeroed when battery is at or above max SOC
|
||||
(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 = result.request
|
||||
bat_list = []
|
||||
if parameters is not None and parameters.pv_battery is not None:
|
||||
bat_list = [parameters.pv_battery]
|
||||
if not bat_list:
|
||||
return ac_charge, dc_charge, discharge_allowed, battery_grid_export_allowed
|
||||
|
||||
bat = bat_list[0]
|
||||
min_soc = float(bat.min_soc_percentage)
|
||||
max_soc = float(bat.max_soc_percentage)
|
||||
capacity_wh = float(bat.capacity_wh)
|
||||
ch_eff = float(bat.charging_efficiency)
|
||||
headroom_wh = max(0.0, (max_soc - soc_pct) / 100.0 * capacity_wh)
|
||||
|
||||
# --- AC charge: scale to available headroom ---
|
||||
effective_ac = ac_charge
|
||||
if effective_ac > 0.0:
|
||||
if headroom_wh <= 0.0:
|
||||
effective_ac = 0.0
|
||||
else:
|
||||
inv_list = _inverter_parameters_list(parameters)
|
||||
ac_to_dc_eff = float(inv_list[0].ac_to_dc_efficiency) if inv_list else 1.0
|
||||
max_ac_cp_w = (
|
||||
float(inv_list[0].max_ac_charge_power_w)
|
||||
if inv_list and inv_list[0].max_ac_charge_power_w is not None
|
||||
else float(cast(float, bat.max_charge_power_w))
|
||||
)
|
||||
# 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(result.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
|
||||
)
|
||||
if max_dc_per_slot_wh > headroom_wh:
|
||||
effective_ac = effective_ac * (headroom_wh / max_dc_per_slot_wh)
|
||||
|
||||
# --- DC charge (PV): zero when battery is full ---
|
||||
effective_dc = dc_charge
|
||||
if effective_dc > 0.0 and headroom_wh <= 0.0:
|
||||
effective_dc = 0.0
|
||||
|
||||
# --- Discharge: block at min SOC ---
|
||||
effective_dis = discharge_allowed and (soc_pct > min_soc)
|
||||
effective_grid_export = battery_grid_export_allowed and (soc_pct > min_soc)
|
||||
|
||||
return effective_ac, effective_dc, effective_dis, effective_grid_export
|
||||
|
||||
|
||||
async def optimization_solution(
|
||||
parameters: GeneticParameters, result: GeneticResult
|
||||
) -> OptimizationSolution:
|
||||
"""Provide the result of a run as a general optimization solution.
|
||||
|
||||
The battery modes are controlled by the grid control triggers:
|
||||
|
||||
- ac_charge: charge from grid
|
||||
- discharge_allowed: discharge to local load
|
||||
- battery_grid_export_allowed: discharge to grid
|
||||
|
||||
The following battery modes are supported:
|
||||
|
||||
- SELF_CONSUMPTION: discharge_allowed == 1 and ac_charge == 0 (with or without dc_charge)
|
||||
- GRID_SUPPORT_EXPORT: battery_grid_export_allowed == 1
|
||||
- GRID_SUPPORT_IMPORT: ac_charge > 0 and discharge_allowed == 0 or 1
|
||||
|
||||
Args:
|
||||
parameters: The optimization parameters of the run (run start, time zone).
|
||||
result: The result of the run.
|
||||
|
||||
Returns:
|
||||
The optimization solution.
|
||||
"""
|
||||
start_datetime = result.start_solution_datetime or parameters.settings.start_datetime
|
||||
# New controls use the run-relative control horizon; old payloads retain a midnight prefix.
|
||||
# entries indexed by slot (slot 0 == 00:00 local). Index this serializer
|
||||
# by slot too. At the default interval of 3600 s slots_per_hour == 1 and
|
||||
# this is the established hourly behaviour.
|
||||
interval_s = result.interval_seconds
|
||||
start_local = start_datetime.in_timezone(cast(str, parameters.settings.timezone))
|
||||
start_day_slot = (
|
||||
0
|
||||
if result.controls_start_at_now
|
||||
else int((start_local - start_local.start_of("day")).total_seconds() // interval_s)
|
||||
)
|
||||
# power [W] -> energy per slot [Wh]: multiply by the slot duration in hours.
|
||||
|
||||
# --- Create index based on list length and interval ---
|
||||
# Ensure we only use the minimum of results and commands if differing
|
||||
periods = min(len(result.result.costs_per_hour), len(result.ac_charge) - start_day_slot)
|
||||
time_index = pd.date_range(
|
||||
start=start_datetime,
|
||||
periods=periods,
|
||||
freq=f"{interval_s}s",
|
||||
)
|
||||
n_points = len(time_index)
|
||||
end_datetime = start_datetime.add(seconds=interval_s * n_points)
|
||||
|
||||
# Fill solution into dataframe with correct column names
|
||||
# - load_energy_wh: Load of all energy consumers in wh"
|
||||
# - grid_energy_wh: Grid energy feed in (negative) or consumption (positive) in wh"
|
||||
# - costs_amt: Costs in money amount"
|
||||
# - revenue_amt: Revenue in money amount"
|
||||
# - losses_energy_wh: Energy losses in wh"
|
||||
# - <device-id>_<operation>_op_mode: Operation mode of the device (1.0 when active)."
|
||||
# - <device-id>_<operation>_op_factor: Operation mode factor of the device."
|
||||
# - <device-id>_soc_factor: State of charge of a battery/ electric vehicle device as factor of total capacity."
|
||||
# - <device-id>_energy_wh: Energy consumption (positive) of a device in wh."
|
||||
|
||||
solution = pd.DataFrame(
|
||||
{
|
||||
"date_time": time_index,
|
||||
# result starts at start_day_slot
|
||||
"load_energy_wh": result.result.load_wh_per_hour[:n_points],
|
||||
"grid_feedin_energy_wh": result.result.grid_feed_in_wh_per_hour[:n_points],
|
||||
"grid_consumption_energy_wh": result.result.grid_consumption_wh_per_hour[:n_points],
|
||||
"costs_amt": result.result.costs_per_hour[:n_points],
|
||||
"revenue_amt": result.result.revenue_per_hour[:n_points],
|
||||
"losses_energy_wh": result.result.losses_per_hour[:n_points],
|
||||
},
|
||||
index=time_index,
|
||||
)
|
||||
|
||||
if result.request.pv_battery is not None:
|
||||
# Add battery data
|
||||
battery_device_id = _battery_device_id(result)
|
||||
solution[f"{battery_device_id}_soc_factor"] = [
|
||||
v / 100
|
||||
for v in result.result.battery_soc_per_hour[
|
||||
:n_points
|
||||
] # result starts at start_day_slot
|
||||
]
|
||||
operation: dict[str, list[float]] = {
|
||||
"genetic_ac_charge_factor": [],
|
||||
"genetic_dc_charge_factor": [],
|
||||
"genetic_discharge_allowed_factor": [],
|
||||
"genetic_battery_grid_export_allowed_factor": [],
|
||||
}
|
||||
# ac_charge, dc_charge, discharge_allowed start at hour 0 of start day
|
||||
for hour_idx, rate in enumerate(result.ac_charge):
|
||||
if hour_idx < start_day_slot:
|
||||
continue
|
||||
if hour_idx >= start_day_slot + n_points:
|
||||
break
|
||||
ac_charge_hour = result.ac_charge[hour_idx]
|
||||
dc_charge_hour = result.dc_charge[hour_idx]
|
||||
discharge_allowed_hour = bool(result.discharge_allowed[hour_idx])
|
||||
battery_grid_export_allowed_hour = (
|
||||
bool(result.battery_grid_export_allowed[hour_idx])
|
||||
if hour_idx < len(result.battery_grid_export_allowed)
|
||||
else False
|
||||
)
|
||||
# Solutions written before graded export carry no factor array; they
|
||||
# exported at full power wherever the signal was set.
|
||||
battery_grid_export_factor_hour = (
|
||||
float(result.battery_grid_export_factor[hour_idx])
|
||||
if hour_idx < len(result.battery_grid_export_factor)
|
||||
else (1.0 if battery_grid_export_allowed_hour else 0.0)
|
||||
)
|
||||
|
||||
# Raw genetic gene values — optimizer intent, stored verbatim
|
||||
operation["genetic_ac_charge_factor"].append(ac_charge_hour)
|
||||
operation["genetic_dc_charge_factor"].append(dc_charge_hour)
|
||||
operation["genetic_discharge_allowed_factor"].append(float(discharge_allowed_hour))
|
||||
operation["genetic_battery_grid_export_allowed_factor"].append(
|
||||
battery_grid_export_factor_hour
|
||||
)
|
||||
|
||||
# SOC-clamped effective values — what can physically be executed at
|
||||
# this hour given the expected battery state of charge.
|
||||
result_idx = hour_idx - start_day_slot
|
||||
soc_h_pct = (
|
||||
result.result.battery_soc_per_hour[result_idx]
|
||||
if result_idx < len(result.result.battery_soc_per_hour)
|
||||
else 0.0
|
||||
)
|
||||
eff_ac, eff_dc, eff_dis, eff_grid_export = _soc_clamped_operation_factors(
|
||||
result,
|
||||
ac_charge_hour,
|
||||
dc_charge_hour,
|
||||
discharge_allowed_hour,
|
||||
soc_h_pct,
|
||||
battery_grid_export_allowed_hour,
|
||||
result.first_slot_fraction if result_idx == 0 else 1.0,
|
||||
)
|
||||
operation_mode, operation_mode_factor = _battery_operation_from_solution(
|
||||
eff_ac, eff_dc, eff_dis, eff_grid_export, battery_grid_export_factor_hour
|
||||
)
|
||||
for mode in BatteryOperationMode:
|
||||
mode_key = f"{battery_device_id}_{mode.lower()}_op_mode"
|
||||
factor_key = f"{battery_device_id}_{mode.lower()}_op_factor"
|
||||
if mode_key not in operation.keys():
|
||||
operation[mode_key] = []
|
||||
operation[factor_key] = []
|
||||
if mode == operation_mode:
|
||||
operation[mode_key].append(1.0)
|
||||
operation[factor_key].append(operation_mode_factor)
|
||||
else:
|
||||
operation[mode_key].append(0.0)
|
||||
operation[factor_key].append(0.0)
|
||||
for key in operation.keys():
|
||||
if len(operation[key]) != n_points:
|
||||
error_msg = f"instruction {key} has invalid length {len(operation[key])} - expected {n_points}"
|
||||
logger.error(error_msg)
|
||||
raise ValueError(error_msg)
|
||||
solution[key] = operation[key]
|
||||
|
||||
# Add EV battery solution
|
||||
# eautocharge_hours_float start at hour 0 of start day
|
||||
# result.EAuto_SoC_pro_Stunde start at start_datetime.hour
|
||||
if result.ev_obj:
|
||||
ev_device_id = _ev_device_id(result)
|
||||
if result.ev_charge_hours_float is None:
|
||||
# Electric vehicle is full enough. No load times.
|
||||
solution[f"{ev_device_id}_soc_factor"] = [
|
||||
result.ev_obj.initial_soc_percentage / 100.0
|
||||
] * n_points
|
||||
solution["genetic_ev_charge_factor"] = [0.0] * n_points
|
||||
# operation modes
|
||||
operation_mode = BatteryOperationMode.IDLE
|
||||
for mode in BatteryOperationMode:
|
||||
mode_key = f"{ev_device_id}_{mode.lower()}_op_mode"
|
||||
factor_key = f"{ev_device_id}_{mode.lower()}_op_factor"
|
||||
if mode == operation_mode:
|
||||
solution[mode_key] = [1.0] * n_points
|
||||
solution[factor_key] = [1.0] * n_points
|
||||
else:
|
||||
solution[mode_key] = [0.0] * n_points
|
||||
solution[factor_key] = [0.0] * n_points
|
||||
else:
|
||||
solution[f"{ev_device_id}_soc_factor"] = [
|
||||
v / 100 for v in result.result.ev_soc_per_hour[:n_points]
|
||||
]
|
||||
operation = {
|
||||
"genetic_ev_charge_factor": [],
|
||||
}
|
||||
for hour_idx, rate in enumerate(result.ev_charge_hours_float):
|
||||
if hour_idx < start_day_slot:
|
||||
continue
|
||||
if hour_idx >= start_day_slot + n_points:
|
||||
break
|
||||
operation["genetic_ev_charge_factor"].append(rate)
|
||||
operation_mode, operation_mode_factor = _battery_operation_from_solution(
|
||||
rate, 0.0, False
|
||||
)
|
||||
for mode in BatteryOperationMode:
|
||||
mode_key = f"{ev_device_id}_{mode.lower()}_op_mode"
|
||||
factor_key = f"{ev_device_id}_{mode.lower()}_op_factor"
|
||||
if mode_key not in operation.keys():
|
||||
operation[mode_key] = []
|
||||
operation[factor_key] = []
|
||||
if mode == operation_mode:
|
||||
operation[mode_key].append(1.0)
|
||||
operation[factor_key].append(operation_mode_factor)
|
||||
else:
|
||||
operation[mode_key].append(0.0)
|
||||
operation[factor_key].append(0.0)
|
||||
for key in operation.keys():
|
||||
if len(operation[key]) != n_points:
|
||||
error_msg = f"instruction {key} has invalid length {len(operation[key])} - expected {n_points}"
|
||||
logger.error(error_msg)
|
||||
raise ValueError(error_msg)
|
||||
solution[key] = operation[key]
|
||||
|
||||
# Add home appliance data, one block of columns per device. Per-device
|
||||
# energy arrays start at start_day_slot, like the other result arrays.
|
||||
for device_id, energy_wh in result.result.home_appliance_energy_wh.items():
|
||||
solution[f"{device_id}_energy_wh"] = energy_wh[:n_points]
|
||||
operation = {
|
||||
f"{device_id}_run_op_mode": [],
|
||||
f"{device_id}_run_op_factor": [],
|
||||
f"{device_id}_off_op_mode": [],
|
||||
f"{device_id}_off_op_factor": [],
|
||||
}
|
||||
running_slots = result.result.home_appliance_running.get(device_id, [])
|
||||
for hour_idx, energy in enumerate(solution[f"{device_id}_energy_wh"]):
|
||||
running = (
|
||||
running_slots[hour_idx]
|
||||
if hour_idx < len(running_slots)
|
||||
else bool(energy and energy > 0.0)
|
||||
)
|
||||
if running:
|
||||
operation[f"{device_id}_run_op_mode"].append(1.0)
|
||||
operation[f"{device_id}_run_op_factor"].append(1.0)
|
||||
operation[f"{device_id}_off_op_mode"].append(0.0)
|
||||
operation[f"{device_id}_off_op_factor"].append(0.0)
|
||||
else:
|
||||
operation[f"{device_id}_run_op_mode"].append(0.0)
|
||||
operation[f"{device_id}_run_op_factor"].append(0.0)
|
||||
operation[f"{device_id}_off_op_mode"].append(1.0)
|
||||
operation[f"{device_id}_off_op_factor"].append(1.0)
|
||||
for key in operation.keys():
|
||||
if len(operation[key]) != n_points:
|
||||
error_msg = f"instruction {key} has invalid length {len(operation[key])} - expected {n_points}"
|
||||
logger.error(error_msg)
|
||||
raise ValueError(error_msg)
|
||||
solution[key] = operation[key]
|
||||
|
||||
# Fill prediction into dataframe with correct column names
|
||||
# - pvforecast_ac_energy_wh_energy_wh: PV energy prediction (positive) in wh
|
||||
# - elec_price_amt_kwh: Electricity price prediction in money per kwh
|
||||
# - weather_temp_air_celcius: Temperature in °C"
|
||||
# - loadforecast_energy_wh: Load energy prediction in wh
|
||||
# - loadakkudoktor_std_energy_wh: Load energy standard deviation prediction in wh
|
||||
# - loadakkudoktor_mean_energy_wh: Load mean energy prediction in wh
|
||||
prediction = pd.DataFrame(
|
||||
{
|
||||
"date_time": time_index,
|
||||
},
|
||||
index=time_index,
|
||||
)
|
||||
if result.controls_start_at_now:
|
||||
snapshot = result.request.ems
|
||||
prediction["pvforecast_ac_energy_wh"] = snapshot.pv_forecast_wh[:n_points]
|
||||
prediction["loadforecast_energy_wh"] = snapshot.total_load[:n_points]
|
||||
prediction["elec_price_amt_kwh"] = (
|
||||
np.asarray(snapshot.electricity_price_per_wh[:n_points]) * 1000
|
||||
)
|
||||
tariffs = snapshot.feed_in_tariff_per_wh
|
||||
prediction["feed_in_tariff_amt_kwh"] = (
|
||||
np.asarray(tariffs[:n_points]) * 1000 if isinstance(tariffs, list) else tariffs * 1000
|
||||
)
|
||||
if result.controls_start_at_now and result.request.temperature_forecast is not None:
|
||||
prediction["weather_air_temp_celcius"] = result.request.temperature_forecast[:n_points]
|
||||
|
||||
optimization_solution = OptimizationSolution(
|
||||
id=f"optimization-genetic@{to_datetime(as_string=True)}",
|
||||
generated_at=to_datetime(),
|
||||
comment="Optimization solution derived from GeneticSolution.",
|
||||
valid_from=start_datetime,
|
||||
valid_until=end_datetime,
|
||||
total_losses_energy_wh=result.result.total_losses,
|
||||
total_revenues_amt=result.result.total_revenue,
|
||||
total_costs_amt=result.result.total_costs,
|
||||
fitness_score={
|
||||
result.result.total_costs,
|
||||
},
|
||||
prediction=PydanticDateTimeDataFrame.from_dataframe(prediction),
|
||||
solution=PydanticDateTimeDataFrame.from_dataframe(solution),
|
||||
)
|
||||
|
||||
return optimization_solution
|
||||
|
||||
|
||||
def energy_management_plan(
|
||||
parameters: GeneticParameters, result: GeneticResult
|
||||
) -> EnergyManagementPlan:
|
||||
"""Provide the result of a run as an energy management plan.
|
||||
|
||||
Args:
|
||||
parameters: The optimization parameters of the run (run start, time zone).
|
||||
result: The result of the run.
|
||||
|
||||
Returns:
|
||||
The energy management plan.
|
||||
"""
|
||||
start_datetime = result.start_solution_datetime or parameters.settings.start_datetime
|
||||
# Index by slot, not hour (mirrors optimization_solution). At the default
|
||||
# interval of 3600 s this reduces to the start hour-of-day.
|
||||
interval_s = result.interval_seconds
|
||||
start_local = start_datetime.in_timezone(cast(str, parameters.settings.timezone))
|
||||
start_day_slot = (
|
||||
0
|
||||
if result.controls_start_at_now
|
||||
else int((start_local - start_local.start_of("day")).total_seconds() // interval_s)
|
||||
)
|
||||
plan = EnergyManagementPlan(
|
||||
id=f"plan-genetic@{to_datetime(as_string=True)}",
|
||||
generated_at=to_datetime(),
|
||||
instructions=[],
|
||||
comment="Energy management plan derived from GeneticSolution.",
|
||||
)
|
||||
|
||||
if result.request.pv_battery is not None:
|
||||
# Add battery instructions (fill rate based control)
|
||||
last_operation_mode: Optional[str] = None
|
||||
last_operation_mode_factor: Optional[float] = None
|
||||
resource_id = _battery_device_id(result)
|
||||
# ac_charge, dc_charge, discharge_allowed start at hour 0 of start day
|
||||
logger.debug("BAT: {} - {}", resource_id, result.ac_charge[start_day_slot:])
|
||||
for hour_idx, rate in enumerate(result.ac_charge):
|
||||
if hour_idx < start_day_slot:
|
||||
continue
|
||||
# Derive SOC-clamped effective factors so that FRBCInstruction
|
||||
# operation_mode_factor reflects what can physically be executed,
|
||||
# while the raw genetic gene values are preserved in the solution
|
||||
# dataframe (genetic_*_factor columns).
|
||||
result_idx = hour_idx - start_day_slot
|
||||
soc_h_pct = (
|
||||
result.result.battery_soc_per_hour[result_idx]
|
||||
if result_idx < len(result.result.battery_soc_per_hour)
|
||||
else 0.0
|
||||
)
|
||||
battery_grid_export_allowed_hour = (
|
||||
bool(result.battery_grid_export_allowed[hour_idx])
|
||||
if hour_idx < len(result.battery_grid_export_allowed)
|
||||
else False
|
||||
)
|
||||
eff_ac, eff_dc, eff_dis, eff_grid_export = _soc_clamped_operation_factors(
|
||||
result,
|
||||
result.ac_charge[hour_idx],
|
||||
result.dc_charge[hour_idx],
|
||||
bool(result.discharge_allowed[hour_idx]),
|
||||
soc_h_pct,
|
||||
battery_grid_export_allowed_hour,
|
||||
result.first_slot_fraction if result_idx == 0 else 1.0,
|
||||
)
|
||||
operation_mode, operation_mode_factor = _battery_operation_from_solution(
|
||||
eff_ac,
|
||||
eff_dc,
|
||||
eff_dis,
|
||||
eff_grid_export,
|
||||
result.battery_grid_export_factor[hour_idx]
|
||||
if hour_idx < len(result.battery_grid_export_factor)
|
||||
else 1.0,
|
||||
)
|
||||
if (
|
||||
operation_mode == last_operation_mode
|
||||
and operation_mode_factor == last_operation_mode_factor
|
||||
):
|
||||
# Skip, we already added the instruction
|
||||
continue
|
||||
last_operation_mode = operation_mode
|
||||
last_operation_mode_factor = operation_mode_factor
|
||||
execution_time = start_datetime.add(seconds=interval_s * (hour_idx - start_day_slot))
|
||||
plan.add_instruction(
|
||||
FRBCInstruction(
|
||||
resource_id=resource_id,
|
||||
execution_time=execution_time,
|
||||
actuator_id=resource_id,
|
||||
operation_mode_id=operation_mode,
|
||||
operation_mode_factor=operation_mode_factor,
|
||||
)
|
||||
)
|
||||
|
||||
# Add EV battery instructions (fill rate based control)
|
||||
# eautocharge_hours_float start at hour 0 of start day
|
||||
if result.ev_obj:
|
||||
resource_id = _ev_device_id(result)
|
||||
if result.ev_charge_hours_float is None:
|
||||
# Electric vehicle is full enough. No load times.
|
||||
logger.debug("EV: {} - SoC >= min, no optimization", resource_id)
|
||||
plan.add_instruction(
|
||||
FRBCInstruction(
|
||||
resource_id=resource_id,
|
||||
execution_time=start_datetime,
|
||||
actuator_id=resource_id,
|
||||
operation_mode_id=BatteryOperationMode.IDLE,
|
||||
operation_mode_factor=1.0,
|
||||
)
|
||||
)
|
||||
else:
|
||||
last_operation_mode = None
|
||||
last_operation_mode_factor = None
|
||||
logger.debug("EV: {} - {}", resource_id, result.ev_charge_hours_float[start_day_slot:])
|
||||
for hour_idx, rate in enumerate(result.ev_charge_hours_float):
|
||||
if hour_idx < start_day_slot:
|
||||
continue
|
||||
operation_mode, operation_mode_factor = _battery_operation_from_solution(
|
||||
rate, 0.0, False
|
||||
)
|
||||
if (
|
||||
operation_mode == last_operation_mode
|
||||
and operation_mode_factor == last_operation_mode_factor
|
||||
):
|
||||
# Skip, we already added the instruction
|
||||
continue
|
||||
last_operation_mode = operation_mode
|
||||
last_operation_mode_factor = operation_mode_factor
|
||||
execution_time = start_datetime.add(
|
||||
seconds=interval_s * (hour_idx - start_day_slot)
|
||||
)
|
||||
plan.add_instruction(
|
||||
FRBCInstruction(
|
||||
resource_id=resource_id,
|
||||
execution_time=execution_time,
|
||||
actuator_id=resource_id,
|
||||
operation_mode_id=operation_mode,
|
||||
operation_mode_factor=operation_mode_factor,
|
||||
)
|
||||
)
|
||||
|
||||
# Add home appliance instructions (demand driven based control), one
|
||||
# stream of instructions per device. A new instruction is only emitted on
|
||||
# a transition between OFF (energy == 0) and RUN (energy > 0); a mere
|
||||
# power change within a running profile does not add an instruction.
|
||||
for resource_id, energy_wh in result.result.home_appliance_energy_wh.items():
|
||||
last_state: Optional[bool] = None
|
||||
for hours, energy in enumerate(energy_wh):
|
||||
# hours starts at start_datetime with 0
|
||||
if energy is None:
|
||||
raise ValueError(
|
||||
f"Unexpected value {energy} in home_appliance_energy_wh[{resource_id}]"
|
||||
)
|
||||
running_slots = result.result.home_appliance_running.get(resource_id, [])
|
||||
running = running_slots[hours] if hours < len(running_slots) else energy > 0.0
|
||||
if last_state is None or running != last_state:
|
||||
appliance_mode = (
|
||||
ApplianceOperationMode.RUN if running else ApplianceOperationMode.OFF
|
||||
)
|
||||
execution_time = start_datetime.add(seconds=interval_s * hours)
|
||||
plan.add_instruction(
|
||||
DDBCInstruction(
|
||||
resource_id=resource_id,
|
||||
execution_time=execution_time,
|
||||
actuator_id=resource_id,
|
||||
operation_mode_id=appliance_mode,
|
||||
operation_mode_factor=1.0,
|
||||
)
|
||||
)
|
||||
last_state = running
|
||||
|
||||
if not plan.instructions:
|
||||
plan.valid_from = start_datetime
|
||||
return plan
|
||||
@@ -1,19 +0,0 @@
|
||||
"""Genetic optimization algorithm device interfaces/ parameters."""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from akkudoktoreos.optimization.genetic.geneticabc import GeneticParametersBaseModel
|
||||
|
||||
|
||||
class DeviceParameters(GeneticParametersBaseModel):
|
||||
device_id: str = Field(json_schema_extra={"description": "ID of device", "examples": "device1"})
|
||||
hours: Optional[int] = Field(
|
||||
default=None,
|
||||
gt=0,
|
||||
json_schema_extra={
|
||||
"description": "Number of prediction hours. Defaults to global config prediction hours.",
|
||||
"examples": [None],
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,208 @@
|
||||
"""Load-dependent conversion efficiency of the GENETIC simulation devices.
|
||||
|
||||
GENETIC's own copy of the efficiency curve helpers (ADR 0004: optimizers duplicate code instead
|
||||
of sharing it), so its simulation does not import the shared device configuration.
|
||||
"""
|
||||
|
||||
import math
|
||||
from collections.abc import Sequence
|
||||
from typing import Optional
|
||||
|
||||
|
||||
def validate_efficiency_curve(
|
||||
curve: Optional[list[tuple[float, float]]],
|
||||
) -> Optional[list[tuple[float, float]]]:
|
||||
"""Validate a load-dependent conversion efficiency curve.
|
||||
|
||||
A curve is a list of ``(load_fraction, efficiency)`` points. The load
|
||||
fraction is the converted power relative to the rated power of the device
|
||||
(0.0 = idle, 1.0 = rated power), the efficiency is the conversion
|
||||
efficiency at that load.
|
||||
|
||||
Rules:
|
||||
- At least two points.
|
||||
- Load fractions are finite, within [0, 1] and strictly increasing
|
||||
(sorted, no duplicates).
|
||||
- Efficiencies are finite and within (0, 1].
|
||||
|
||||
Args:
|
||||
curve: The curve points, or None for no curve.
|
||||
|
||||
Returns:
|
||||
The unchanged curve, or None.
|
||||
|
||||
Raises:
|
||||
ValueError: If the curve violates one of the rules.
|
||||
"""
|
||||
if curve is None:
|
||||
return None
|
||||
if len(curve) < 2:
|
||||
raise ValueError("An efficiency curve needs at least two points.")
|
||||
previous_fraction: Optional[float] = None
|
||||
for fraction, efficiency in curve:
|
||||
if not math.isfinite(fraction) or not 0.0 <= fraction <= 1.0:
|
||||
raise ValueError(f"Efficiency curve load fraction {fraction} is outside of [0, 1].")
|
||||
if not math.isfinite(efficiency) or not 0.0 < efficiency <= 1.0:
|
||||
raise ValueError(f"Efficiency curve efficiency {efficiency} is outside of (0, 1].")
|
||||
if previous_fraction is not None and fraction <= previous_fraction:
|
||||
raise ValueError(
|
||||
"Efficiency curve load fractions must be strictly increasing "
|
||||
f"(sorted, no duplicates); got {fraction} after {previous_fraction}."
|
||||
)
|
||||
previous_fraction = fraction
|
||||
return curve
|
||||
|
||||
|
||||
def interpolate_efficiency_curve(
|
||||
curve: Sequence[tuple[float, float]], load_fraction: float
|
||||
) -> float:
|
||||
"""Return the efficiency of a curve at a load fraction.
|
||||
|
||||
Interpolates linearly between the curve points. Load fractions below the
|
||||
first or above the last point are clamped to the efficiency of that point.
|
||||
|
||||
Args:
|
||||
curve: Points as validated by ``validate_efficiency_curve``.
|
||||
load_fraction: Converted power relative to the rated power.
|
||||
|
||||
Returns:
|
||||
The efficiency at ``load_fraction``.
|
||||
"""
|
||||
first_fraction, first_efficiency = curve[0]
|
||||
if load_fraction <= first_fraction:
|
||||
return first_efficiency
|
||||
for fraction, efficiency in curve[1:]:
|
||||
if load_fraction <= fraction:
|
||||
return first_efficiency + (load_fraction - first_fraction) / (
|
||||
fraction - first_fraction
|
||||
) * (efficiency - first_efficiency)
|
||||
first_fraction, first_efficiency = fraction, efficiency
|
||||
return first_efficiency
|
||||
|
||||
|
||||
def solve_ac_for_dc_energy(
|
||||
curve: Sequence[tuple[float, float]],
|
||||
dc_wh: float,
|
||||
rated_wh: float,
|
||||
upper_ac_wh: float,
|
||||
) -> float:
|
||||
"""Return the AC energy a DC energy yields through a load-dependent conversion.
|
||||
|
||||
The efficiency of a curve depends on the AC load actually delivered, so for a
|
||||
given DC energy the delivered AC energy ``a`` is the solution of
|
||||
``a = dc_wh * efficiency(a / rated_wh)``. The curve is piecewise linear and
|
||||
clamped at both ends, so the equation is solved exactly on each piece.
|
||||
|
||||
Args:
|
||||
curve: Points as validated by ``validate_efficiency_curve``.
|
||||
dc_wh: DC energy available to the conversion in one slot.
|
||||
rated_wh: AC energy at rated power in one slot (load fraction 1.0).
|
||||
upper_ac_wh: Upper bound of the result, e.g. the requested AC energy.
|
||||
|
||||
Returns:
|
||||
The largest consistent AC energy that does not exceed ``upper_ac_wh``.
|
||||
"""
|
||||
if dc_wh <= 0.0 or rated_wh <= 0.0 or upper_ac_wh <= 0.0:
|
||||
return 0.0
|
||||
tolerance = 1e-9
|
||||
best = -1.0
|
||||
|
||||
def consider(ac_wh: float, low: float, high: float) -> None:
|
||||
nonlocal best
|
||||
fraction = ac_wh / rated_wh
|
||||
if (
|
||||
low - tolerance <= fraction <= high + tolerance
|
||||
and 0.0 < ac_wh <= upper_ac_wh * (1.0 + tolerance)
|
||||
and ac_wh > best
|
||||
):
|
||||
best = ac_wh
|
||||
|
||||
first_fraction, first_efficiency = curve[0]
|
||||
last_fraction, last_efficiency = curve[-1]
|
||||
# Clamped ends: constant efficiency below the first and above the last point.
|
||||
consider(dc_wh * first_efficiency, float("-inf"), first_fraction)
|
||||
consider(dc_wh * last_efficiency, last_fraction, float("inf"))
|
||||
for (x0, e0), (x1, e1) in zip(curve, curve[1:]):
|
||||
slope = (e1 - e0) / (x1 - x0)
|
||||
# a = dc * (e0 + slope * (a / rated - x0)) => a * (1 - dc*slope/rated) = dc * (e0 - slope*x0)
|
||||
denominator = 1.0 - dc_wh * slope / rated_wh
|
||||
if abs(denominator) < 1e-12:
|
||||
continue
|
||||
consider(dc_wh * (e0 - slope * x0) / denominator, x0, x1)
|
||||
if best >= 0.0:
|
||||
return min(best, upper_ac_wh)
|
||||
# No piece holds a solution within the bound (only possible numerically at a
|
||||
# kink): converge on it from the bound.
|
||||
ac_wh = min(upper_ac_wh, dc_wh)
|
||||
for _ in range(50):
|
||||
next_ac_wh = min(dc_wh * interpolate_efficiency_curve(curve, ac_wh / rated_wh), upper_ac_wh)
|
||||
if abs(next_ac_wh - ac_wh) <= tolerance:
|
||||
break
|
||||
ac_wh = next_ac_wh
|
||||
return ac_wh
|
||||
|
||||
|
||||
def solve_ac_for_charge_dc_energy(
|
||||
curve: Sequence[tuple[float, float]],
|
||||
dc_wh: float,
|
||||
rated_wh: float,
|
||||
) -> float:
|
||||
"""Return the AC energy an AC→DC conversion draws to deliver a DC energy.
|
||||
|
||||
The efficiency of a curve depends on the AC load drawn, so the AC energy
|
||||
``a`` that delivers ``dc_wh`` is the solution of
|
||||
``a * efficiency(a / rated_wh) = dc_wh``. The curve is piecewise linear and
|
||||
clamped at both ends; on each piece the equation is quadratic and solved
|
||||
exactly.
|
||||
|
||||
Args:
|
||||
curve: Points as validated by ``validate_efficiency_curve``.
|
||||
dc_wh: DC energy delivered by the conversion in one slot.
|
||||
rated_wh: AC energy at rated power in one slot (load fraction 1.0).
|
||||
|
||||
Returns:
|
||||
The smallest consistent AC energy, 0.0 for no DC energy.
|
||||
"""
|
||||
if dc_wh <= 0.0:
|
||||
return 0.0
|
||||
if rated_wh <= 0.0:
|
||||
return dc_wh / curve[-1][1]
|
||||
tolerance = 1e-9
|
||||
best = float("inf")
|
||||
|
||||
def consider(ac_wh: float, low: float, high: float) -> None:
|
||||
nonlocal best
|
||||
fraction = ac_wh / rated_wh
|
||||
if low - tolerance <= fraction <= high + tolerance and 0.0 < ac_wh < best:
|
||||
best = ac_wh
|
||||
|
||||
first_fraction, first_efficiency = curve[0]
|
||||
last_fraction, last_efficiency = curve[-1]
|
||||
# Clamped ends: constant efficiency below the first and above the last point.
|
||||
consider(dc_wh / first_efficiency, float("-inf"), first_fraction)
|
||||
consider(dc_wh / last_efficiency, last_fraction, float("inf"))
|
||||
for (x0, e0), (x1, e1) in zip(curve, curve[1:]):
|
||||
slope = (e1 - e0) / (x1 - x0)
|
||||
# a * (c + k * a) = dc with c = e0 - slope * x0 and k = slope / rated.
|
||||
c = e0 - slope * x0
|
||||
k = slope / rated_wh
|
||||
if abs(k) < 1e-15:
|
||||
if c > 0.0:
|
||||
consider(dc_wh / c, x0, x1)
|
||||
continue
|
||||
discriminant = c * c + 4.0 * k * dc_wh
|
||||
if discriminant < 0.0:
|
||||
continue
|
||||
root = math.sqrt(discriminant)
|
||||
consider((-c + root) / (2.0 * k), x0, x1)
|
||||
consider((-c - root) / (2.0 * k), x0, x1)
|
||||
if best < float("inf"):
|
||||
return best
|
||||
# Only possible numerically at a kink: converge on it.
|
||||
ac_wh = dc_wh / interpolate_efficiency_curve(curve, 1.0)
|
||||
for _ in range(50):
|
||||
next_ac_wh = dc_wh / interpolate_efficiency_curve(curve, ac_wh / rated_wh)
|
||||
if abs(next_ac_wh - ac_wh) <= tolerance:
|
||||
break
|
||||
ac_wh = next_ac_wh
|
||||
return ac_wh
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Forecasts and prices of the GENETIC simulation."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Union
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class GeneticEnergyManagementParameters:
|
||||
"""Forecasts and prices per slot of a run, derived from the request.
|
||||
|
||||
Attributes:
|
||||
pv_forecast_wh: PV energy per slot [Wh].
|
||||
electricity_price_per_wh: Electricity price per slot [currency/Wh].
|
||||
feed_in_tariff_per_wh: Feed-in tariff per slot, or one value for all slots
|
||||
[currency/Wh].
|
||||
price_per_wh_battery: Value of energy left in the battery [currency/Wh].
|
||||
total_load: Load energy per slot [Wh].
|
||||
"""
|
||||
|
||||
pv_forecast_wh: tuple[float, ...]
|
||||
electricity_price_per_wh: tuple[float, ...]
|
||||
feed_in_tariff_per_wh: Union[tuple[float, ...], float]
|
||||
price_per_wh_battery: float
|
||||
total_load: tuple[float, ...]
|
||||
@@ -0,0 +1,166 @@
|
||||
"""Expected direct PV-to-load power of the GENETIC inverter simulation.
|
||||
|
||||
GENETIC's own copy of the self-consumption probability table evaluation (ADR 0004). The backend
|
||||
comes from the run settings (``optimization.self_consumption_interpolator``, read by the
|
||||
parameter preparation), never from the configuration directly (ADR 0003).
|
||||
"""
|
||||
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
from akkudoktoreos.utils.gridinterpolator import (
|
||||
GridInterpolatorBackend,
|
||||
SwitchableGridInterpolator,
|
||||
load_grid_interpolator,
|
||||
)
|
||||
|
||||
# The table shipped with EOS: minute-load probabilities per one-hour mean load.
|
||||
_TABLE_FILE = (
|
||||
Path(__file__).parent.parent.parent.resolve() / "data" / "regular_grid_interpolator.pkl"
|
||||
)
|
||||
|
||||
|
||||
def fixed_order_dot(a: np.ndarray, b: np.ndarray) -> float:
|
||||
"""Return the dot product of two vectors, summed from the first element to the last.
|
||||
|
||||
``np.dot`` calls BLAS, whose kernel is chosen per CPU at run time, so the last bit of the
|
||||
result depends on the machine. The optimizer compares fitness values exactly; here every
|
||||
product is rounded and added in index order, with Python floats: the same result on every
|
||||
CPU.
|
||||
|
||||
Args:
|
||||
a: First vector.
|
||||
b: Second vector, same length as ``a``.
|
||||
|
||||
Returns:
|
||||
``sum(a[i] * b[i])`` in index order.
|
||||
"""
|
||||
total = 0.0
|
||||
for x, y in zip(a.tolist(), b.tolist(), strict=True):
|
||||
total += x * y
|
||||
return total
|
||||
|
||||
|
||||
class GeneticLoadInterpolator:
|
||||
"""Expected direct consumption from the self-consumption probability table."""
|
||||
|
||||
LOAD_DISTRIBUTION_CACHE_SIZE = 4096
|
||||
DIRECT_CONSUMPTION_CACHE_SIZE = 8192
|
||||
|
||||
def __init__(self, backend: GridInterpolatorBackend) -> None:
|
||||
"""Load the table.
|
||||
|
||||
Args:
|
||||
backend: How the table is evaluated.
|
||||
"""
|
||||
self.interpolator = SwitchableGridInterpolator(
|
||||
load_grid_interpolator(_TABLE_FILE), lambda: backend
|
||||
)
|
||||
self.load_power_min_w = float(self.interpolator.grid[0][0])
|
||||
self.load_power_max_w = float(self.interpolator.grid[0][-1])
|
||||
self.minute_load_levels_w = np.asarray(self.interpolator.grid[1], dtype=float)
|
||||
# The table is static and the backend fixed, so a cached value never goes stale; the
|
||||
# caches are only bounded in size.
|
||||
self._load_distributions: dict[float, tuple[np.ndarray, np.ndarray]] = {}
|
||||
self._direct_consumption: dict[tuple[float, float], float] = {}
|
||||
|
||||
def _load_distribution(self, mean_load_power_w: float) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""Return the conditional minute-load distribution for a mean load.
|
||||
|
||||
Negative masses from the linear interpolation between mean-load rows are removed and
|
||||
the result is normalized. Callers must not modify the returned arrays.
|
||||
"""
|
||||
bounded_mean_load_w = min(
|
||||
max(float(mean_load_power_w), self.load_power_min_w), self.load_power_max_w
|
||||
)
|
||||
cached = self._load_distributions.get(bounded_mean_load_w)
|
||||
if cached is not None:
|
||||
return cached
|
||||
points = np.column_stack(
|
||||
(
|
||||
np.full(self.minute_load_levels_w.shape, bounded_mean_load_w),
|
||||
self.minute_load_levels_w,
|
||||
)
|
||||
)
|
||||
probabilities = np.maximum(np.asarray(self.interpolator(points), dtype=float), 0.0)
|
||||
probability_sum = float(probabilities.sum())
|
||||
if probability_sum <= 0.0:
|
||||
distribution = (self.minute_load_levels_w, probabilities)
|
||||
else:
|
||||
distribution = (self.minute_load_levels_w, probabilities / probability_sum)
|
||||
if bounded_mean_load_w == bounded_mean_load_w: # not NaN: NaN never matches a key
|
||||
if len(self._load_distributions) >= self.LOAD_DISTRIBUTION_CACHE_SIZE:
|
||||
self._load_distributions.clear()
|
||||
self._load_distributions[bounded_mean_load_w] = distribution
|
||||
return distribution
|
||||
|
||||
def calculate_expected_direct_consumption(
|
||||
self, mean_load_power_w: float, pv_power_w: float
|
||||
) -> float:
|
||||
"""Calculate expected direct PV-to-load power in watts.
|
||||
|
||||
For conditional minute-load probabilities ``p_i`` and load-bin powers ``L_i``, the
|
||||
expected direct consumption is ``sum(p_i * min(L_i, pv_power_w))``. The load-bin powers
|
||||
are rescaled to preserve the supplied forecast mean exactly.
|
||||
|
||||
Args:
|
||||
mean_load_power_w: Mean load power of the forecast interval [W].
|
||||
pv_power_w: Mean PV power of the forecast interval [W].
|
||||
|
||||
Returns:
|
||||
Expected direct PV-to-load power [W].
|
||||
"""
|
||||
cache = self._direct_consumption
|
||||
key = (mean_load_power_w, pv_power_w)
|
||||
cached = cache.get(key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
result = self._expected_direct_consumption(mean_load_power_w, pv_power_w)
|
||||
if len(cache) >= self.DIRECT_CONSUMPTION_CACHE_SIZE:
|
||||
cache.clear()
|
||||
cache[key] = result
|
||||
return result
|
||||
|
||||
def _expected_direct_consumption(self, mean_load_power_w: float, pv_power_w: float) -> float:
|
||||
"""Calculate the expected direct PV-to-load power in watts, uncached."""
|
||||
mean_load_power_w = max(float(mean_load_power_w), 0.0)
|
||||
pv_power_w = max(float(pv_power_w), 0.0)
|
||||
if mean_load_power_w == 0.0 or pv_power_w == 0.0:
|
||||
return 0.0
|
||||
|
||||
load_levels_w, probabilities = self._load_distribution(mean_load_power_w)
|
||||
modeled_mean_load_w = fixed_order_dot(probabilities, load_levels_w)
|
||||
if modeled_mean_load_w <= 0.0:
|
||||
return 0.0
|
||||
|
||||
normalized_load_levels_w = load_levels_w * (mean_load_power_w / modeled_mean_load_w)
|
||||
expected_direct_power_w = fixed_order_dot(
|
||||
probabilities, np.minimum(normalized_load_levels_w, pv_power_w)
|
||||
)
|
||||
return min(max(expected_direct_power_w, 0.0), min(mean_load_power_w, pv_power_w))
|
||||
|
||||
|
||||
# One interpolator per backend, created on first use.
|
||||
_interpolators: dict[GridInterpolatorBackend, GeneticLoadInterpolator] = {}
|
||||
_interpolators_lock = threading.Lock()
|
||||
|
||||
|
||||
def get_genetic_load_interpolator(backend: GridInterpolatorBackend) -> GeneticLoadInterpolator:
|
||||
"""Return the shared interpolator for ``backend``.
|
||||
|
||||
Args:
|
||||
backend: How the table is evaluated.
|
||||
|
||||
Returns:
|
||||
The interpolator, loaded on first use.
|
||||
"""
|
||||
interpolator = _interpolators.get(backend)
|
||||
if interpolator is None:
|
||||
with _interpolators_lock:
|
||||
interpolator = _interpolators.get(backend)
|
||||
if interpolator is None:
|
||||
interpolator = GeneticLoadInterpolator(backend)
|
||||
_interpolators[backend] = interpolator
|
||||
return interpolator
|
||||
@@ -0,0 +1,77 @@
|
||||
"""GENETIC behind the optimizer interface (ADR 0006)."""
|
||||
|
||||
from collections.abc import Mapping
|
||||
from typing import Any, Optional
|
||||
|
||||
from akkudoktoreos.core.emplan import EnergyManagementPlan
|
||||
from akkudoktoreos.optimization.genetic import geneticconvert, geneticprepare
|
||||
from akkudoktoreos.optimization.genetic.geneticparameters import GeneticParameters
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import GeneticRequest
|
||||
from akkudoktoreos.optimization.genetic.geneticresult import GeneticResult
|
||||
from akkudoktoreos.optimization.optimization import OptimizationSolution
|
||||
from akkudoktoreos.optimization.optimizer import OptimizerApi, RunClock
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime
|
||||
|
||||
|
||||
class GeneticOptimizer:
|
||||
"""The GENETIC optimizer."""
|
||||
|
||||
name = "GENETIC"
|
||||
|
||||
def run_clock(self) -> RunClock:
|
||||
"""See ``Optimizer.run_clock()``."""
|
||||
return geneticprepare.run_clock()
|
||||
|
||||
async def prepare(
|
||||
self,
|
||||
start_datetime: DateTime,
|
||||
observation_datetime: DateTime,
|
||||
warm_start: Optional[GeneticResult],
|
||||
overrides: Optional[Mapping[str, Any]] = None,
|
||||
) -> GeneticParameters:
|
||||
"""See ``Optimizer.prepare()``."""
|
||||
return await geneticprepare.prepare(
|
||||
start_datetime, observation_datetime, warm_start, overrides
|
||||
)
|
||||
|
||||
async def prepare_from_request(
|
||||
self,
|
||||
request: GeneticRequest,
|
||||
start_datetime: DateTime,
|
||||
observation_datetime: DateTime,
|
||||
warm_start: Optional[GeneticResult],
|
||||
overrides: Optional[Mapping[str, Any]] = None,
|
||||
) -> GeneticParameters:
|
||||
"""See ``Optimizer.prepare_from_request()``."""
|
||||
return await geneticprepare.prepare_from_request(
|
||||
request, start_datetime, observation_datetime, warm_start, overrides
|
||||
)
|
||||
|
||||
def run(self, parameters: GeneticParameters) -> GeneticResult:
|
||||
"""See ``Optimizer.run()``."""
|
||||
# Imported on first use: the simulation is only needed for a run.
|
||||
from akkudoktoreos.optimization.genetic.geneticalgorithm import (
|
||||
GeneticOptimization,
|
||||
)
|
||||
|
||||
optimization = GeneticOptimization(parameters.settings)
|
||||
return optimization.optimize_ems(
|
||||
start_hour=parameters.start_hour,
|
||||
parameters=parameters.request,
|
||||
ngen=parameters.settings.generations,
|
||||
individuals=parameters.settings.individuals,
|
||||
start_solution_datetime=parameters.start_solution_datetime,
|
||||
)
|
||||
|
||||
def api(self) -> OptimizerApi:
|
||||
"""See ``Optimizer.api()``."""
|
||||
# Imported on first use: the router is only needed by the server.
|
||||
from akkudoktoreos.optimization.genetic import geneticapi
|
||||
|
||||
return geneticapi.api()
|
||||
|
||||
async def convert(
|
||||
self, parameters: GeneticParameters, result: GeneticResult
|
||||
) -> tuple[OptimizationSolution, EnergyManagementPlan]:
|
||||
"""See ``Optimizer.convert()``."""
|
||||
return await geneticconvert.convert(parameters, result)
|
||||
@@ -0,0 +1,217 @@
|
||||
"""Optimization parameters of GENETIC: the complete input of one run (ADR 0003, 0006, 0009).
|
||||
|
||||
A run reads nothing but these parameters: the run settings and the forecast and device
|
||||
parameters. They are prepared once before the run by ``geneticprepare``.
|
||||
|
||||
The simulation reads the forecast and device dataclasses, which the request
|
||||
(``GeneticOptimizationParameters``) derives. The request itself is kept for the conversion, the
|
||||
visualization and the public responses.
|
||||
"""
|
||||
|
||||
import math
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Optional, Union
|
||||
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticOptimizationParameters,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticsettings import TerminalValueMode
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime
|
||||
from akkudoktoreos.utils.gridinterpolator import GridInterpolatorBackend
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class GeneticRunSettings:
|
||||
"""Algorithm settings and run clock of one run, resolved from configuration and overrides.
|
||||
|
||||
Attributes:
|
||||
interval_sec: Length of one optimization slot in seconds (900 or 3600).
|
||||
horizon_hours: Control horizon in hours.
|
||||
tail_horizon_hours: Requested forecast tail beyond the control horizon in hours.
|
||||
prediction_hours: Forecast budget in hours.
|
||||
individuals: Population size; ``None`` uses the algorithm's default.
|
||||
generations: Number of generations; ``None`` uses the algorithm's default.
|
||||
seed: Random seed; ``None`` gives a random seed.
|
||||
penalties: Penalty parameters by name (e.g. ``ev_soc_miss``).
|
||||
workers: Number of evaluation processes; ``None`` chooses automatically.
|
||||
pin_workers: Pin the evaluation processes to fixed CPU cores.
|
||||
fitness_cache_max_entries: Size limit of the fitness cache; ``None`` is unbounded.
|
||||
terminal_value_mode: How energy left at the end of the horizon is valued.
|
||||
terminal_value_window_hours: Price window of the terminal value.
|
||||
direct_marketing_enabled: Optimize DC charging and battery export for direct marketing.
|
||||
battery_charge_rates: Charge rates of the first configured battery, used when the
|
||||
request has none.
|
||||
battery_grid_export_rates: Grid export rates of the first configured battery, used when
|
||||
the request has none.
|
||||
ev_charge_rates: Charge rates of the first configured electric vehicle, used when the
|
||||
request has none.
|
||||
start_datetime: Start of the run's first slot.
|
||||
observation_datetime: Unrounded moment of the run that measurements refer to.
|
||||
timezone: Site time zone of the appliance start times; ``None`` is the local time zone.
|
||||
self_consumption_interpolator: How the inverter's self-consumption table is evaluated.
|
||||
verbose: Log the progress of the run.
|
||||
"""
|
||||
|
||||
interval_sec: int
|
||||
horizon_hours: int
|
||||
tail_horizon_hours: int
|
||||
prediction_hours: int
|
||||
individuals: Optional[int]
|
||||
generations: Optional[int]
|
||||
seed: Optional[int]
|
||||
penalties: Mapping[str, Union[float, int, str]]
|
||||
workers: Optional[int]
|
||||
pin_workers: bool
|
||||
fitness_cache_max_entries: Optional[int]
|
||||
terminal_value_mode: TerminalValueMode
|
||||
terminal_value_window_hours: int
|
||||
direct_marketing_enabled: bool
|
||||
battery_charge_rates: Optional[tuple[float, ...]]
|
||||
battery_grid_export_rates: Optional[tuple[float, ...]]
|
||||
ev_charge_rates: Optional[tuple[float, ...]]
|
||||
start_datetime: DateTime
|
||||
observation_datetime: DateTime
|
||||
timezone: Optional[str]
|
||||
self_consumption_interpolator: GridInterpolatorBackend
|
||||
verbose: bool
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class GeneticParameters:
|
||||
"""Everything a GENETIC run needs.
|
||||
|
||||
Attributes:
|
||||
request: Forecast and device parameters of the run, including the warm start.
|
||||
start_hour: Hour of the day the run starts at.
|
||||
settings: Algorithm settings and run clock of the run.
|
||||
start_solution_datetime: Start of slot 0 of the start solution of ``request``. It is the
|
||||
request's own one, or that of the previous run when the request echoes the previous
|
||||
run's genome without it; the request stays as the client sent it.
|
||||
"""
|
||||
|
||||
request: GeneticOptimizationParameters
|
||||
start_hour: int
|
||||
settings: GeneticRunSettings
|
||||
start_solution_datetime: Optional[DateTime] = None
|
||||
|
||||
|
||||
def parameters_to_dict(parameters: GeneticParameters) -> dict[str, Any]:
|
||||
"""Serialize the parameters into plain JSON values, e.g. for a replay file.
|
||||
|
||||
NaN in the forecast series (a gap the preparation keeps) becomes ``None``; the series
|
||||
carry no other ``None``.
|
||||
|
||||
Args:
|
||||
parameters: The parameters to serialize.
|
||||
|
||||
Returns:
|
||||
A dictionary that ``parameters_from_dict()`` turns back into equal parameters.
|
||||
"""
|
||||
settings = parameters.settings
|
||||
request = parameters.request.model_dump(mode="json")
|
||||
for key, values in request["ems"].items():
|
||||
if isinstance(values, list):
|
||||
request["ems"][key] = [None if math.isnan(value) else value for value in values]
|
||||
return {
|
||||
"request": request,
|
||||
"start_hour": parameters.start_hour,
|
||||
"settings": {
|
||||
"interval_sec": settings.interval_sec,
|
||||
"horizon_hours": settings.horizon_hours,
|
||||
"tail_horizon_hours": settings.tail_horizon_hours,
|
||||
"prediction_hours": settings.prediction_hours,
|
||||
"individuals": settings.individuals,
|
||||
"generations": settings.generations,
|
||||
"seed": settings.seed,
|
||||
"penalties": dict(settings.penalties),
|
||||
"workers": settings.workers,
|
||||
"pin_workers": settings.pin_workers,
|
||||
"fitness_cache_max_entries": settings.fitness_cache_max_entries,
|
||||
"terminal_value_mode": settings.terminal_value_mode.value,
|
||||
"terminal_value_window_hours": settings.terminal_value_window_hours,
|
||||
"direct_marketing_enabled": settings.direct_marketing_enabled,
|
||||
"battery_charge_rates": _list_or_none(settings.battery_charge_rates),
|
||||
"battery_grid_export_rates": _list_or_none(settings.battery_grid_export_rates),
|
||||
"ev_charge_rates": _list_or_none(settings.ev_charge_rates),
|
||||
"start_datetime": _datetime_to_dict(settings.start_datetime),
|
||||
"observation_datetime": _datetime_to_dict(settings.observation_datetime),
|
||||
"timezone": settings.timezone,
|
||||
"self_consumption_interpolator": settings.self_consumption_interpolator.value,
|
||||
"verbose": settings.verbose,
|
||||
},
|
||||
"start_solution_datetime": (
|
||||
None
|
||||
if parameters.start_solution_datetime is None
|
||||
else _datetime_to_dict(parameters.start_solution_datetime)
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def parameters_from_dict(data: Mapping[str, Any]) -> GeneticParameters:
|
||||
"""Deserialize parameters written by ``parameters_to_dict()``.
|
||||
|
||||
Args:
|
||||
data: The serialized parameters.
|
||||
|
||||
Returns:
|
||||
The parameters.
|
||||
"""
|
||||
settings = data["settings"]
|
||||
request = dict(data["request"])
|
||||
request["ems"] = dict(request["ems"])
|
||||
for key, values in request["ems"].items():
|
||||
if isinstance(values, list):
|
||||
request["ems"][key] = [math.nan if value is None else value for value in values]
|
||||
return GeneticParameters(
|
||||
request=GeneticOptimizationParameters.model_validate(request),
|
||||
start_hour=data["start_hour"],
|
||||
settings=GeneticRunSettings(
|
||||
interval_sec=settings["interval_sec"],
|
||||
horizon_hours=settings["horizon_hours"],
|
||||
tail_horizon_hours=settings["tail_horizon_hours"],
|
||||
prediction_hours=settings["prediction_hours"],
|
||||
individuals=settings["individuals"],
|
||||
generations=settings["generations"],
|
||||
seed=settings["seed"],
|
||||
penalties=dict(settings["penalties"]),
|
||||
workers=settings["workers"],
|
||||
pin_workers=settings["pin_workers"],
|
||||
fitness_cache_max_entries=settings["fitness_cache_max_entries"],
|
||||
terminal_value_mode=TerminalValueMode(settings["terminal_value_mode"]),
|
||||
terminal_value_window_hours=settings["terminal_value_window_hours"],
|
||||
direct_marketing_enabled=settings["direct_marketing_enabled"],
|
||||
battery_charge_rates=_tuple_or_none(settings["battery_charge_rates"]),
|
||||
battery_grid_export_rates=_tuple_or_none(settings["battery_grid_export_rates"]),
|
||||
ev_charge_rates=_tuple_or_none(settings["ev_charge_rates"]),
|
||||
start_datetime=_datetime_from_dict(settings["start_datetime"]),
|
||||
observation_datetime=_datetime_from_dict(settings["observation_datetime"]),
|
||||
timezone=settings["timezone"],
|
||||
self_consumption_interpolator=GridInterpolatorBackend(
|
||||
settings["self_consumption_interpolator"]
|
||||
),
|
||||
verbose=settings["verbose"],
|
||||
),
|
||||
start_solution_datetime=(
|
||||
None
|
||||
if data["start_solution_datetime"] is None
|
||||
else _datetime_from_dict(data["start_solution_datetime"])
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _datetime_to_dict(value: DateTime) -> dict[str, Optional[str]]:
|
||||
# The offset alone would lose daylight saving time; keep the named zone as well.
|
||||
return {"datetime": value.isoformat(), "timezone": value.timezone_name}
|
||||
|
||||
|
||||
def _datetime_from_dict(data: Mapping[str, Optional[str]]) -> DateTime:
|
||||
return to_datetime(data["datetime"], in_timezone=data["timezone"])
|
||||
|
||||
|
||||
def _list_or_none(values: Optional[tuple[float, ...]]) -> Optional[list[float]]:
|
||||
return None if values is None else list(values)
|
||||
|
||||
|
||||
def _tuple_or_none(values: Optional[list[float]]) -> Optional[tuple[float, ...]]:
|
||||
return None if values is None else tuple(values)
|
||||
@@ -1,303 +0,0 @@
|
||||
"""GENETIC algorithm paramters.
|
||||
|
||||
This module defines the Pydantic-based configuration and input parameter models
|
||||
used in the energy optimization routines, including photovoltaic forecasts,
|
||||
electricity pricing, and system component parameters.
|
||||
|
||||
It also provides a method to assemble these parameters from predictions,
|
||||
forecasts, and fallback defaults, preparing them for optimization runs.
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional, Union
|
||||
|
||||
from loguru import logger
|
||||
from pydantic import (
|
||||
AliasChoices,
|
||||
ConfigDict,
|
||||
Field,
|
||||
computed_field,
|
||||
field_validator,
|
||||
model_validator,
|
||||
)
|
||||
from typing_extensions import Self
|
||||
|
||||
from akkudoktoreos.core.coreabc import (
|
||||
ConfigMixin,
|
||||
MeasurementMixin,
|
||||
PredictionMixin,
|
||||
)
|
||||
from akkudoktoreos.devices.genetic.battery import (
|
||||
ElectricVehicleParameters,
|
||||
SolarPanelBatteryParameters,
|
||||
)
|
||||
from akkudoktoreos.devices.genetic.homeappliance import HomeApplianceParameters
|
||||
from akkudoktoreos.devices.genetic.inverter import InverterParameters
|
||||
from akkudoktoreos.optimization.genetic.geneticabc import GeneticParametersBaseModel
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime
|
||||
|
||||
# Do not import directly from akkudoktoreos.core.coreabc
|
||||
# EnergyManagementSystemMixin - Creates circular dependency with ems.py
|
||||
# StartMixin - Creates circular dependency with ems.py
|
||||
|
||||
|
||||
class GeneticEnergyManagementParameters(GeneticParametersBaseModel):
|
||||
"""Encapsulates energy-related forecasts and costs used in GENETIC optimization."""
|
||||
|
||||
model_config = ConfigDict(populate_by_name=True, extra="ignore")
|
||||
|
||||
pv_forecast_wh: list[float] = Field(
|
||||
validation_alias=AliasChoices("pv_forecast_wh", "pv_prognose_wh"),
|
||||
json_schema_extra={
|
||||
"description": "An array of floats representing the forecasted photovoltaic energy in watt-hours per slot for different time intervals."
|
||||
},
|
||||
)
|
||||
electricity_price_per_wh: list[float] = Field(
|
||||
validation_alias=AliasChoices("electricity_price_per_wh", "strompreis_euro_pro_wh"),
|
||||
json_schema_extra={
|
||||
"description": "An array of floats representing the electricity price per watt-hour for different time intervals."
|
||||
},
|
||||
)
|
||||
feed_in_tariff_per_wh: Union[list[float], float] = Field(
|
||||
validation_alias=AliasChoices("feed_in_tariff_per_wh", "einspeiseverguetung_euro_pro_wh"),
|
||||
json_schema_extra={
|
||||
"description": "A float or array of floats representing the feed-in compensation per watt-hour."
|
||||
},
|
||||
)
|
||||
price_per_wh_battery: float = Field(
|
||||
validation_alias=AliasChoices("price_per_wh_battery", "preis_euro_pro_wh_akku"),
|
||||
json_schema_extra={
|
||||
"description": "A float representing the cost of battery energy per watt-hour."
|
||||
},
|
||||
)
|
||||
total_load: list[float] = Field(
|
||||
validation_alias=AliasChoices("total_load", "gesamtlast"),
|
||||
json_schema_extra={
|
||||
"description": "An array of floats representing the total load (consumption) in watt-hours per slot for different time intervals."
|
||||
},
|
||||
)
|
||||
|
||||
# Computed fields for backward compatibility (deprecated German names)
|
||||
@computed_field(json_schema_extra={"deprecated": True})
|
||||
def pv_prognose_wh(self) -> list[float]:
|
||||
"""Deprecated: Use pv_forecast_wh instead."""
|
||||
return self.pv_forecast_wh
|
||||
|
||||
@computed_field(json_schema_extra={"deprecated": True})
|
||||
def strompreis_euro_pro_wh(self) -> list[float]:
|
||||
"""Deprecated: Use electricity_price_per_wh instead."""
|
||||
return self.electricity_price_per_wh
|
||||
|
||||
@computed_field(json_schema_extra={"deprecated": True})
|
||||
def einspeiseverguetung_euro_pro_wh(self) -> Union[list[float], float]:
|
||||
"""Deprecated: Use feed_in_tariff_per_wh instead."""
|
||||
return self.feed_in_tariff_per_wh
|
||||
|
||||
@computed_field(json_schema_extra={"deprecated": True})
|
||||
def preis_euro_pro_wh_akku(self) -> float:
|
||||
"""Deprecated: Use price_per_wh_battery instead."""
|
||||
return self.price_per_wh_battery
|
||||
|
||||
@computed_field(json_schema_extra={"deprecated": True})
|
||||
def gesamtlast(self) -> list[float]:
|
||||
"""Deprecated: Use total_load instead."""
|
||||
return self.total_load
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_forecast_arrays(self) -> Self:
|
||||
"""Require forecasts; the optimizer validates control coverage and clips the tail."""
|
||||
arrays = [self.pv_forecast_wh, self.electricity_price_per_wh, self.total_load]
|
||||
if isinstance(self.feed_in_tariff_per_wh, list):
|
||||
arrays.append(self.feed_in_tariff_per_wh)
|
||||
if any(not values for values in arrays):
|
||||
raise ValueError("Forecast arrays must not be empty.")
|
||||
return self
|
||||
|
||||
|
||||
class GeneticOptimizationParameters(
|
||||
ConfigMixin,
|
||||
MeasurementMixin,
|
||||
PredictionMixin,
|
||||
# EnergyManagementSystemMixin, # Creates circular dependency with ems.py
|
||||
# StartMixin, # Creates circular dependency with ems.py
|
||||
GeneticParametersBaseModel,
|
||||
):
|
||||
"""Main parameter class for running the genetic energy optimization.
|
||||
|
||||
Collects all model and configuration parameters necessary to run the
|
||||
optimization process, such as forecasts, pricing, battery and appliance models.
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(populate_by_name=True, extra="ignore")
|
||||
|
||||
ems: GeneticEnergyManagementParameters
|
||||
pv_battery: Optional[SolarPanelBatteryParameters] = Field(
|
||||
validation_alias=AliasChoices("pv_battery", "pv_akku"),
|
||||
json_schema_extra={"description": "PV battery parameters."},
|
||||
)
|
||||
inverter: Optional[InverterParameters]
|
||||
ev: Optional[ElectricVehicleParameters] = Field(
|
||||
validation_alias=AliasChoices("ev", "eauto"),
|
||||
json_schema_extra={"description": "Electric vehicle parameters."},
|
||||
)
|
||||
dishwasher: Optional[HomeApplianceParameters] = None
|
||||
temperature_forecast: Optional[list[Optional[float]]] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": "An array of floats representing the temperature forecast in degrees Celsius for different time intervals."
|
||||
},
|
||||
)
|
||||
start_solution: Optional[list[float]] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": "Can be `null` or contain a previous solution (if available)."
|
||||
},
|
||||
)
|
||||
|
||||
forecast_interval_seconds: Optional[int] = Field(
|
||||
default=None,
|
||||
description="Input interval: 3600 for hourly, or optimization interval for native slots.",
|
||||
)
|
||||
|
||||
home_appliances: Optional[list[HomeApplianceParameters]] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": "List of flexible consumers (home appliances) to schedule."
|
||||
},
|
||||
)
|
||||
|
||||
start_solution_datetime: Optional[DateTime] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Start of the slot that gene 0 of 'start_solution' controls, as "
|
||||
"returned with the previous solution. The warm start is shifted by "
|
||||
"the slots that have elapsed until this run. Without it, a "
|
||||
"'start_solution' identical to the last solution of this server "
|
||||
"uses that solution's start; any other one is used unshifted."
|
||||
),
|
||||
"examples": [None, "2026-09-14T07:45:00+02:00"],
|
||||
},
|
||||
)
|
||||
|
||||
@field_validator("forecast_interval_seconds")
|
||||
@classmethod
|
||||
def validate_forecast_interval(cls, value: Optional[int]) -> Optional[int]:
|
||||
if value not in (None, 900, 3600):
|
||||
raise ValueError("forecast_interval_seconds must be 900 or 3600")
|
||||
return value
|
||||
|
||||
@field_validator("start_solution_datetime", mode="before")
|
||||
@classmethod
|
||||
def transform_start_solution_datetime(cls, value: Any) -> Optional[DateTime]:
|
||||
"""Accept the usual date time representations, naive input is local time."""
|
||||
if value is None:
|
||||
return None
|
||||
# A stored run must retain its timezone/fold even when the server host
|
||||
# uses another local timezone. ISO offsets survive JSON round trips.
|
||||
aware = value
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
aware = datetime.fromisoformat(value)
|
||||
except ValueError:
|
||||
pass
|
||||
if isinstance(aware, datetime) and aware.tzinfo is not None:
|
||||
return DateTime.instance(aware)
|
||||
return to_datetime(value)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_home_appliances(self) -> Self:
|
||||
"""Reject conflicting home appliance definitions.
|
||||
|
||||
The deprecated ``dishwasher`` field and the new ``home_appliances`` list
|
||||
must not be set at the same time; nothing is silently overwritten.
|
||||
Device ids within ``home_appliances`` must be unique.
|
||||
"""
|
||||
# Read the deprecated field via __dict__ to avoid emitting a deprecation
|
||||
# warning on every internal validation.
|
||||
dishwasher = self.__dict__.get("dishwasher")
|
||||
if dishwasher is not None and self.home_appliances is not None:
|
||||
raise ValueError(
|
||||
"Provide either 'home_appliances' or the deprecated 'dishwasher', not both."
|
||||
)
|
||||
appliances = self.home_appliances or []
|
||||
device_ids = [appliance.device_id for appliance in appliances]
|
||||
if len(device_ids) != len(set(device_ids)):
|
||||
raise ValueError("home_appliances device_id values must be unique.")
|
||||
return self
|
||||
|
||||
def resolved_home_appliances(self) -> list[HomeApplianceParameters]:
|
||||
"""Return the effective home appliance list.
|
||||
|
||||
Maps the deprecated single ``dishwasher`` onto a one-element list so the
|
||||
optimizer only ever deals with the list form.
|
||||
"""
|
||||
if self.home_appliances is not None:
|
||||
return list(self.home_appliances)
|
||||
dishwasher = self.__dict__.get("dishwasher")
|
||||
if dishwasher is not None:
|
||||
return [dishwasher]
|
||||
return []
|
||||
|
||||
# Computed fields for backward compatibility (deprecated German names)
|
||||
@computed_field(json_schema_extra={"deprecated": True})
|
||||
def pv_akku(self) -> Optional[SolarPanelBatteryParameters]:
|
||||
"""Deprecated: Use pv_battery instead."""
|
||||
return self.pv_battery
|
||||
|
||||
@computed_field(json_schema_extra={"deprecated": True})
|
||||
def eauto(self) -> Optional[ElectricVehicleParameters]:
|
||||
"""Deprecated: Use ev instead."""
|
||||
return self.ev
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_list_length(self) -> Self:
|
||||
"""Ensure that temperature forecast list matches the PV forecast length.
|
||||
|
||||
Raises:
|
||||
ValueError: If list lengths mismatch.
|
||||
"""
|
||||
arr_length = len(self.ems.pv_forecast_wh)
|
||||
if self.temperature_forecast is not None and arr_length != len(self.temperature_forecast):
|
||||
raise ValueError("Input lists have different lengths")
|
||||
return self
|
||||
|
||||
@field_validator("start_solution")
|
||||
def validate_start_solution(
|
||||
cls, start_solution: Optional[list[float]]
|
||||
) -> Optional[list[float]]:
|
||||
"""Validate that the starting solution has at least two elements.
|
||||
|
||||
Args:
|
||||
start_solution (list[float]): Optional list of solution values.
|
||||
|
||||
Returns:
|
||||
list[float]: Validated list.
|
||||
|
||||
Raises:
|
||||
ValueError: If the solution is too short.
|
||||
"""
|
||||
if start_solution is not None and len(start_solution) < 2:
|
||||
raise ValueError("Requires at least two values.")
|
||||
return start_solution
|
||||
|
||||
@classmethod
|
||||
async def prepare(cls) -> "Optional[GeneticOptimizationParameters]":
|
||||
"""Resolve configured devices and fresh forecasts for automatic optimization.
|
||||
|
||||
Missing inputs cancel the run without changing providers or inventing devices.
|
||||
The same resolver serves the configuration-owned HTTP request.
|
||||
"""
|
||||
from akkudoktoreos.optimization.genetic.configrequest import (
|
||||
ConfigOptimizationRequest,
|
||||
)
|
||||
|
||||
try:
|
||||
return await ConfigOptimizationRequest().resolve()
|
||||
except Exception as exc:
|
||||
logger.error(
|
||||
"Cannot prepare GENETIC parameters; canceling optimization with provider {}: {}",
|
||||
cls.config.feedintariff.provider,
|
||||
exc,
|
||||
)
|
||||
return None
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,245 @@
|
||||
"""Optimization result of GENETIC: the output of one run (ADR 0006, 0009, 0010).
|
||||
|
||||
Plain frozen dataclasses. Their values are normalised as the public response models validate them
|
||||
(``geneticapi``): NumPy arrays become lists, NaN in NumPy arrays becomes ``None`` and values get the
|
||||
field's number type, so that the conversion, the visualization and a response built from a result
|
||||
see the same values as before the result became a dataclass (ADR 0008).
|
||||
"""
|
||||
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Optional, Union
|
||||
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticOptimizationParameters,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticterminalvalue import TerminalValueResult
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime
|
||||
from akkudoktoreos.utils.utils import NumpyEncoder
|
||||
|
||||
# Keys of the simulation output (German and current) and the field names of the result.
|
||||
SIMULATION_KEYS: Mapping[str, str] = {
|
||||
"Last_Wh_pro_Stunde": "load_wh_per_hour",
|
||||
"EAuto_SoC_pro_Stunde": "ev_soc_per_hour",
|
||||
"Einnahmen_Euro_pro_Stunde": "revenue_per_hour",
|
||||
"Gesamt_Verluste": "total_losses",
|
||||
"Gesamtbilanz_Euro": "total_balance",
|
||||
"Gesamteinnahmen_Euro": "total_revenue",
|
||||
"Gesamtkosten_Euro": "total_costs",
|
||||
"Home_appliance_wh_per_hour": "home_appliance_wh_per_hour",
|
||||
"Kosten_Euro_pro_Stunde": "costs_per_hour",
|
||||
"Netzbezug_Wh_pro_Stunde": "grid_consumption_wh_per_hour",
|
||||
"Netzeinspeisung_Wh_pro_Stunde": "grid_feed_in_wh_per_hour",
|
||||
"Verluste_Pro_Stunde": "losses_per_hour",
|
||||
"akku_soc_pro_stunde": "battery_soc_per_hour",
|
||||
"Electricity_price": "electricity_price",
|
||||
"Feed_in_tariff": "feed_in_tariff",
|
||||
"home_appliance_energy_wh": "home_appliance_energy_wh",
|
||||
"home_appliance_running": "home_appliance_running",
|
||||
}
|
||||
|
||||
|
||||
def _values(values: Any) -> list[Any]:
|
||||
"""NumPy arrays as lists (NaN as ``None``), as ``NumpyEncoder.convert_numpy`` does."""
|
||||
return list(NumpyEncoder.convert_numpy(values)[0])
|
||||
|
||||
|
||||
def _float(value: Any) -> float:
|
||||
if isinstance(value, bool) or value is None:
|
||||
raise ValueError(f"Not a number: {value!r}")
|
||||
return float(value)
|
||||
|
||||
|
||||
def _int(value: Any) -> int:
|
||||
number = float(value)
|
||||
if isinstance(value, bool) or not number.is_integer():
|
||||
raise ValueError(f"Not an integer: {value!r}")
|
||||
return int(number)
|
||||
|
||||
|
||||
def float_list(values: Any) -> list[float]:
|
||||
"""A list of floats, coerced as a ``list[float]`` model field does."""
|
||||
return [_float(value) for value in _values(values)]
|
||||
|
||||
|
||||
def optional_float_list(values: Any) -> list[Optional[float]]:
|
||||
"""A list of floats or ``None``, coerced as a ``list[Optional[float]]`` field does."""
|
||||
return [None if value is None else _float(value) for value in _values(values)]
|
||||
|
||||
|
||||
def int_list(values: Any) -> list[int]:
|
||||
"""A list of integers, coerced as a ``list[int]`` model field does."""
|
||||
return [_int(value) for value in _values(values)]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class GeneticSimulationOutput:
|
||||
"""Values of the simulated best solution, per slot from the run start, and totals.
|
||||
|
||||
Attributes:
|
||||
home_appliance_energy_wh: Energy of each home appliance per slot [Wh], by device id.
|
||||
feed_in_tariff: Feed-in tariff per slot.
|
||||
home_appliance_running: Active run occupancy of each home appliance per slot, including
|
||||
zero-power phases, by device id.
|
||||
"""
|
||||
|
||||
load_wh_per_hour: list[float]
|
||||
ev_soc_per_hour: list[float]
|
||||
revenue_per_hour: list[float]
|
||||
total_losses: float
|
||||
total_balance: float
|
||||
total_revenue: float
|
||||
total_costs: float
|
||||
home_appliance_wh_per_hour: list[Optional[float]]
|
||||
costs_per_hour: list[float]
|
||||
grid_consumption_wh_per_hour: list[float]
|
||||
grid_feed_in_wh_per_hour: list[float]
|
||||
losses_per_hour: list[float]
|
||||
battery_soc_per_hour: list[float]
|
||||
electricity_price: list[float]
|
||||
home_appliance_energy_wh: dict[str, list[float]] = field(default_factory=dict)
|
||||
feed_in_tariff: list[float] = field(default_factory=list)
|
||||
home_appliance_running: dict[str, list[bool]] = field(default_factory=dict)
|
||||
|
||||
@classmethod
|
||||
def from_simulation(cls, output: Mapping[str, Any]) -> "GeneticSimulationOutput":
|
||||
"""Build the output from the simulation's dictionary (German keys).
|
||||
|
||||
Args:
|
||||
output: The dictionary ``GeneticSimulation.simulate()`` returns, with the home
|
||||
appliance energy and occupancy added.
|
||||
|
||||
Returns:
|
||||
The normalised simulation output.
|
||||
"""
|
||||
values = {
|
||||
SIMULATION_KEYS[key]: value for key, value in output.items() if key in SIMULATION_KEYS
|
||||
}
|
||||
totals = ("total_losses", "total_balance", "total_revenue", "total_costs")
|
||||
fields: dict[str, Any] = {}
|
||||
for key, value in values.items():
|
||||
if key in totals:
|
||||
fields[key] = _float(value)
|
||||
elif key == "home_appliance_wh_per_hour":
|
||||
fields[key] = optional_float_list(value)
|
||||
elif key == "home_appliance_energy_wh":
|
||||
fields[key] = {device_id: float_list(energy) for device_id, energy in value.items()}
|
||||
elif key == "home_appliance_running":
|
||||
fields[key] = {device_id: list(running) for device_id, running in value.items()}
|
||||
else:
|
||||
fields[key] = float_list(value)
|
||||
return cls(**fields)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class GeneticElectricVehicleState:
|
||||
"""The electric vehicle at the end of the simulated best solution.
|
||||
|
||||
Attributes:
|
||||
device_id: ID of the electric vehicle.
|
||||
hours: Number of slots of the simulation.
|
||||
charge_array: Charging factor per slot.
|
||||
discharge_array: 1 where discharging is allowed, per slot.
|
||||
discharging_efficiency: Discharging efficiency (0 to 1).
|
||||
capacity_wh: Battery capacity [Wh].
|
||||
charging_efficiency: Charging efficiency (0 to 1).
|
||||
max_charge_power_w: Maximum charging power [W].
|
||||
max_discharge_power_w: Maximum discharging power [W], if limited.
|
||||
soc_wh: State of charge at the end of the simulation [Wh].
|
||||
initial_soc_percentage: State of charge at the start [%].
|
||||
"""
|
||||
|
||||
device_id: str
|
||||
hours: int
|
||||
charge_array: list[float]
|
||||
discharge_array: list[int]
|
||||
discharging_efficiency: float
|
||||
capacity_wh: int
|
||||
charging_efficiency: float
|
||||
max_charge_power_w: int
|
||||
max_discharge_power_w: Optional[float]
|
||||
soc_wh: float
|
||||
initial_soc_percentage: int
|
||||
|
||||
@classmethod
|
||||
def from_battery(cls, state: Mapping[str, Any]) -> "GeneticElectricVehicleState":
|
||||
"""Build the state from ``GeneticBattery.to_dict()``.
|
||||
|
||||
Args:
|
||||
state: The battery's dictionary.
|
||||
|
||||
Returns:
|
||||
The normalised electric vehicle state.
|
||||
"""
|
||||
max_discharge_power_w = state.get("max_discharge_power_w")
|
||||
return cls(
|
||||
device_id=str(state["device_id"]),
|
||||
hours=_int(state["hours"]),
|
||||
charge_array=float_list(state["charge_array"]),
|
||||
discharge_array=int_list(state["discharge_array"]),
|
||||
discharging_efficiency=_float(state["discharging_efficiency"]),
|
||||
capacity_wh=_int(state["capacity_wh"]),
|
||||
charging_efficiency=_float(state["charging_efficiency"]),
|
||||
max_charge_power_w=_int(state["max_charge_power_w"]),
|
||||
max_discharge_power_w=(
|
||||
None if max_discharge_power_w is None else _float(max_discharge_power_w)
|
||||
),
|
||||
soc_wh=_float(state["soc_wh"]),
|
||||
initial_soc_percentage=_int(state["initial_soc_percentage"]),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class GeneticResult:
|
||||
"""Output of one GENETIC run.
|
||||
|
||||
The control arrays and per-slot values start at the run start (``controls_start_at_now``).
|
||||
|
||||
Attributes:
|
||||
request: The request the run optimized, after its adaptation to the configuration and
|
||||
the slot grid; the response echoes it as ``parameters``.
|
||||
ac_charge: AC charging factor per slot.
|
||||
dc_charge: DC charging factor per slot.
|
||||
discharge_allowed: 1 where discharging is allowed, per slot.
|
||||
ev_charge_hours_float: EV charging factor per slot, or ``None`` without an EV.
|
||||
result: Simulated values of the best solution.
|
||||
ev_obj: The electric vehicle at the end of the simulation, if any.
|
||||
start_hour: Hour of the day the run started at.
|
||||
start_solution: Best individual, the warm start of the next run.
|
||||
washingstart: Deprecated start hour of a single hourly home appliance, if any.
|
||||
extra_data: Extra data of the run.
|
||||
fitness_history: Fitness per generation.
|
||||
fixed_seed: Seed of the run.
|
||||
controls_start_at_now: The control arrays start at the run timestamp, not midnight.
|
||||
battery_grid_export_allowed: 1 where battery export to the grid is allowed, per slot.
|
||||
terminal_value: What the run credited for the energy left in the battery.
|
||||
battery_grid_export_factor: Battery grid export factor per slot.
|
||||
start_solution_datetime: Start of slot 0 of ``start_solution``.
|
||||
appliance_starts: Planned run starts of each home appliance, by device id.
|
||||
appliance_deadline_missed: Whether a home appliance misses its deadline, by device id.
|
||||
interval_seconds: Duration of one slot [s].
|
||||
first_slot_fraction: Fraction of the first slot that is still ahead at the run start.
|
||||
"""
|
||||
|
||||
request: GeneticOptimizationParameters
|
||||
ac_charge: list[float]
|
||||
dc_charge: list[float]
|
||||
discharge_allowed: list[int]
|
||||
ev_charge_hours_float: Optional[list[float]]
|
||||
result: GeneticSimulationOutput
|
||||
ev_obj: Optional[GeneticElectricVehicleState]
|
||||
start_hour: int = 0
|
||||
start_solution: Optional[list[float]] = None
|
||||
washingstart: Optional[int] = None
|
||||
extra_data: Optional[dict[str, Union[list[int], list[float]]]] = None
|
||||
fitness_history: Optional[dict[str, Any]] = None
|
||||
fixed_seed: Optional[int] = None
|
||||
controls_start_at_now: bool = False
|
||||
battery_grid_export_allowed: list[int] = field(default_factory=list)
|
||||
terminal_value: Optional[TerminalValueResult] = None
|
||||
battery_grid_export_factor: list[float] = field(default_factory=list)
|
||||
start_solution_datetime: Optional[DateTime] = None
|
||||
appliance_starts: dict[str, list[DateTime]] = field(default_factory=dict)
|
||||
appliance_deadline_missed: dict[str, bool] = field(default_factory=dict)
|
||||
interval_seconds: int = 3600
|
||||
first_slot_fraction: float = 1.0
|
||||
@@ -61,7 +61,7 @@ class TerminalValueMode(StrEnum):
|
||||
FIXED = "FIXED"
|
||||
|
||||
|
||||
class GeneticCommonSettings(SettingsBaseModel):
|
||||
class GeneticSettings(SettingsBaseModel):
|
||||
"""GENETIC Optimization Algorithm Configuration."""
|
||||
|
||||
interval_sec: Literal[900, 3600] = Field(
|
||||
|
||||
@@ -0,0 +1,556 @@
|
||||
"""Simulation of GENETIC: the energy flows of one genome over the slots of a run."""
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
import numpy as np
|
||||
from loguru import logger
|
||||
|
||||
from akkudoktoreos.optimization.genetic.devices.geneticbattery import GeneticBattery
|
||||
from akkudoktoreos.optimization.genetic.devices.genetichomeappliance import (
|
||||
GeneticHomeAppliance,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.devices.geneticinverter import GeneticInverter
|
||||
from akkudoktoreos.optimization.genetic.geneticenergymanagement import (
|
||||
GeneticEnergyManagementParameters,
|
||||
)
|
||||
|
||||
|
||||
def _slot_values(values: Any) -> Any:
|
||||
"""Return per-slot values as plain Python numbers for the simulation loop.
|
||||
|
||||
Reading single elements of a NumPy array yields NumPy scalars, whose
|
||||
arithmetic is several times slower than that of Python numbers. The values
|
||||
are the same IEEE doubles (or integers), so the results do not change.
|
||||
Other element types are left as they are.
|
||||
"""
|
||||
if isinstance(values, np.ndarray) and (values.dtype == np.float64 or values.dtype.kind in "iu"):
|
||||
return values.tolist()
|
||||
return values
|
||||
|
||||
|
||||
class GeneticSimulation:
|
||||
"""Device simulation for GENETIC optimization algorithm.
|
||||
|
||||
``prepare()`` sets the forecasts, prices and devices of a run; ``simulate()`` evaluates one
|
||||
candidate plan.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
"""Create an empty simulation; ``prepare()`` fills it."""
|
||||
# Starting slot of the latest simulate() call.
|
||||
self.start_hour: int = 0
|
||||
self.optimization_hours: Optional[int] = 24
|
||||
self.prediction_hours: Optional[int] = 48
|
||||
# Per-slot forecasts and prices [Wh, currency/Wh].
|
||||
self.load_energy_array: Optional[np.ndarray] = None
|
||||
self.pv_prediction_wh: Optional[np.ndarray] = None
|
||||
self.elect_price_hourly: Optional[np.ndarray] = None
|
||||
self.elect_revenue_per_hour_arr: Optional[np.ndarray] = None
|
||||
# Use direct marketing behavior for feed-in/export decisions.
|
||||
self.direct_marketing_enabled: bool = False
|
||||
self.battery: Optional[GeneticBattery] = None
|
||||
self.ev: Optional[GeneticBattery] = None
|
||||
# Flexible consumers scheduled by the optimizer.
|
||||
self.home_appliances: list[GeneticHomeAppliance] = []
|
||||
self.inverter: Optional[GeneticInverter] = None
|
||||
# Per-slot actions of the candidate plan.
|
||||
self.ac_charge_hours: Optional[np.ndarray] = None
|
||||
self.dc_charge_hours: Optional[np.ndarray] = None
|
||||
self.bat_discharge_hours: Optional[np.ndarray] = None
|
||||
# Per-slot permission for battery discharge into the grid.
|
||||
self.bat_grid_export_hours: Optional[np.ndarray] = None
|
||||
self.ev_charge_hours: Optional[np.ndarray] = None
|
||||
self.ev_discharge_hours: Optional[np.ndarray] = None
|
||||
|
||||
@property
|
||||
def home_appliance(self) -> Optional[GeneticHomeAppliance]:
|
||||
"""Deprecated singular device accessor."""
|
||||
return self.home_appliances[0] if self.home_appliances else None
|
||||
|
||||
@home_appliance.setter
|
||||
def home_appliance(self, appliance: Optional[GeneticHomeAppliance]) -> None:
|
||||
self.home_appliances = [appliance] if appliance is not None else []
|
||||
|
||||
def prepare(
|
||||
self,
|
||||
parameters: GeneticEnergyManagementParameters,
|
||||
optimization_hours: int,
|
||||
prediction_hours: int,
|
||||
ev: Optional[GeneticBattery] = None,
|
||||
home_appliance: Optional[GeneticHomeAppliance] = None,
|
||||
inverter: Optional[GeneticInverter] = None,
|
||||
direct_marketing_enabled: bool = False,
|
||||
home_appliances: Optional[list[GeneticHomeAppliance]] = None,
|
||||
) -> None:
|
||||
"""Prepare simulation runs.
|
||||
|
||||
Populate internal arrays and device references used during simulation.
|
||||
"""
|
||||
self.optimization_hours = optimization_hours
|
||||
self.prediction_hours = prediction_hours
|
||||
self.direct_marketing_enabled = direct_marketing_enabled
|
||||
|
||||
# Load arrays from provided EMS parameters
|
||||
self.load_energy_array = np.array(parameters.total_load, float)
|
||||
self.pv_prediction_wh = np.array(parameters.pv_forecast_wh, float)
|
||||
self.elect_price_hourly = np.array(parameters.electricity_price_per_wh, float)
|
||||
self.elect_revenue_per_hour_arr = (
|
||||
np.array(parameters.feed_in_tariff_per_wh, float)
|
||||
if isinstance(parameters.feed_in_tariff_per_wh, (list, tuple))
|
||||
else np.full(len(self.load_energy_array), parameters.feed_in_tariff_per_wh, float)
|
||||
)
|
||||
|
||||
# Associate devices
|
||||
if inverter:
|
||||
self.battery = inverter.battery
|
||||
else:
|
||||
self.battery = None
|
||||
self.ev = ev
|
||||
if home_appliance is not None and home_appliances is not None:
|
||||
raise ValueError("Use home_appliance or home_appliances, not both.")
|
||||
self.home_appliances = home_appliances or (
|
||||
[home_appliance] if home_appliance is not None else []
|
||||
)
|
||||
self.inverter = inverter
|
||||
|
||||
# Initialize per-hour action arrays for the prediction horizon
|
||||
self.ac_charge_hours = np.full(self.prediction_hours, 0.0)
|
||||
self.dc_charge_hours = np.full(self.prediction_hours, 0.0)
|
||||
self.bat_discharge_hours = np.full(self.prediction_hours, 0.0)
|
||||
self.bat_grid_export_hours = np.full(self.prediction_hours, 0.0)
|
||||
self.ev_charge_hours = np.full(self.prediction_hours, 0.0)
|
||||
self.ev_discharge_hours = np.full(self.prediction_hours, 0.0)
|
||||
|
||||
def reset(self) -> None:
|
||||
if self.ev:
|
||||
self.ev.reset()
|
||||
if self.battery:
|
||||
self.battery.reset()
|
||||
|
||||
def simulate(self, start_hour: int) -> dict[str, Any]:
|
||||
"""Simulate energy usage and costs for the given start hour.
|
||||
|
||||
akku_soc_pro_stunde begin of the hour, initial hour state!
|
||||
last_wh_pro_stunde integral of last hour (end state)
|
||||
"""
|
||||
# Remember start hour
|
||||
self.start_hour = start_hour
|
||||
|
||||
# Provide fast (3x..5x) local read access (vs. self.xxx) for repetitive read access
|
||||
load_energy_array_fast = self.load_energy_array
|
||||
ev_charge_hours_fast = self.ev_charge_hours
|
||||
ev_discharge_hours_fast = self.ev_discharge_hours
|
||||
ac_charge_hours_fast = self.ac_charge_hours
|
||||
dc_charge_hours_fast = self.dc_charge_hours
|
||||
bat_discharge_hours_fast = self.bat_discharge_hours
|
||||
bat_grid_export_hours_fast = self.bat_grid_export_hours
|
||||
elect_price_hourly_fast = self.elect_price_hourly
|
||||
elect_revenue_per_hour_arr_fast = self.elect_revenue_per_hour_arr
|
||||
pv_prediction_wh_fast = self.pv_prediction_wh
|
||||
battery_fast = self.battery
|
||||
ev_fast = self.ev
|
||||
home_appliances_fast = self.home_appliances
|
||||
inverter_fast = self.inverter
|
||||
direct_marketing_enabled_fast = self.direct_marketing_enabled
|
||||
|
||||
# Check for simulation integrity (in a way that mypy understands)
|
||||
if (
|
||||
load_energy_array_fast is None
|
||||
or pv_prediction_wh_fast is None
|
||||
or elect_price_hourly_fast is None
|
||||
or ev_charge_hours_fast is None
|
||||
or ac_charge_hours_fast is None
|
||||
or dc_charge_hours_fast is None
|
||||
or elect_revenue_per_hour_arr_fast is None
|
||||
or bat_discharge_hours_fast is None
|
||||
or bat_grid_export_hours_fast is None
|
||||
or ev_discharge_hours_fast is None
|
||||
):
|
||||
missing = []
|
||||
if load_energy_array_fast is None:
|
||||
missing.append("Load Energy Array")
|
||||
if pv_prediction_wh_fast is None:
|
||||
missing.append("PV Prediction Wh")
|
||||
if elect_price_hourly_fast is None:
|
||||
missing.append("Electricity Price Hourly")
|
||||
if ev_charge_hours_fast is None:
|
||||
missing.append("EV Charge Hours")
|
||||
if ac_charge_hours_fast is None:
|
||||
missing.append("AC Charge Hours")
|
||||
if dc_charge_hours_fast is None:
|
||||
missing.append("DC Charge Hours")
|
||||
if elect_revenue_per_hour_arr_fast is None:
|
||||
missing.append("Electricity Revenue Per Hour")
|
||||
if bat_discharge_hours_fast is None:
|
||||
missing.append("Battery Discharge Hours")
|
||||
if bat_grid_export_hours_fast is None:
|
||||
missing.append("Battery Grid Export Hours")
|
||||
if ev_discharge_hours_fast is None:
|
||||
missing.append("EV Discharge Hours")
|
||||
msg = ", ".join(missing)
|
||||
logger.error("Mandatory data missing - %s", msg)
|
||||
raise ValueError(f"Mandatory data missing: {msg}")
|
||||
|
||||
if not (
|
||||
len(load_energy_array_fast)
|
||||
== len(pv_prediction_wh_fast)
|
||||
== len(elect_price_hourly_fast)
|
||||
):
|
||||
error_msg = f"Array sizes do not match: Load Curve = {len(load_energy_array_fast)}, PV Forecast = {len(pv_prediction_wh_fast)}, Electricity Price = {len(elect_price_hourly_fast)}"
|
||||
logger.error(error_msg)
|
||||
raise ValueError(error_msg)
|
||||
|
||||
end_hour = min(
|
||||
len(load_energy_array_fast), self.prediction_hours or len(load_energy_array_fast)
|
||||
)
|
||||
total_hours = end_hour - start_hour
|
||||
if total_hours < 0:
|
||||
raise ValueError("negative dimensions are not allowed")
|
||||
|
||||
# Per-slot results are collected in plain lists (element writes into
|
||||
# NumPy arrays are slow) and turned into arrays after the loop.
|
||||
nan = float("nan")
|
||||
loads_energy_per_hour: Any = [nan] * total_hours
|
||||
feedin_energy_per_hour: Any = [nan] * total_hours
|
||||
consumption_energy_per_hour: Any = [nan] * total_hours
|
||||
costs_per_hour: Any = [nan] * total_hours
|
||||
revenue_per_hour: Any = [nan] * total_hours
|
||||
losses_wh_per_hour: Any = [nan] * total_hours
|
||||
electricity_price_per_hour: Any = [nan] * total_hours
|
||||
feed_in_tariff_per_hour: Any = [nan] * total_hours
|
||||
soc_per_hour: Any
|
||||
soc_ev_per_hour: Any
|
||||
home_appliance_wh_per_hour: Any
|
||||
|
||||
# Set initial state
|
||||
if battery_fast:
|
||||
soc_per_hour = [nan] * total_hours
|
||||
|
||||
soc_per_hour[0] = battery_fast.current_soc_percentage()
|
||||
|
||||
# Determine AC charging availability from inverter parameters
|
||||
if inverter_fast:
|
||||
ac_to_dc_eff_fast = inverter_fast.ac_to_dc_efficiency
|
||||
dc_to_ac_eff_fast = inverter_fast.dc_to_ac_efficiency
|
||||
max_ac_charge_w_fast = inverter_fast.max_ac_charge_power_w
|
||||
else:
|
||||
ac_to_dc_eff_fast = 1.0
|
||||
dc_to_ac_eff_fast = 1.0
|
||||
max_ac_charge_w_fast = None
|
||||
|
||||
ac_charging_possible = ac_to_dc_eff_fast > 0 and (
|
||||
max_ac_charge_w_fast is None or max_ac_charge_w_fast > 0
|
||||
)
|
||||
|
||||
# If AC charging is disabled via inverter, zero out AC charge hours.
|
||||
# In place, not by rebinding: the reported plan is read back from
|
||||
# this very array, so a rebind would leave AC charge values in the
|
||||
# solution that the simulation never executed - and a controller
|
||||
# acting on them would grid-charge the battery unplanned.
|
||||
if not ac_charging_possible:
|
||||
ac_charge_hours_fast[:] = 0.0
|
||||
|
||||
# Fill the charge array of the battery
|
||||
dc_charge_hours_fast[0:start_hour] = 0
|
||||
dc_charge_hours_fast[end_hour:] = 0
|
||||
ac_charge_hours_fast[0:start_hour] = 0
|
||||
ac_charge_hours_fast[end_hour:] = 0
|
||||
battery_fast.charge_array = np.where(
|
||||
ac_charge_hours_fast != 0, ac_charge_hours_fast, dc_charge_hours_fast
|
||||
)
|
||||
# Fill the discharge array of the battery
|
||||
bat_discharge_hours_fast[0:start_hour] = 0
|
||||
bat_discharge_hours_fast[end_hour:] = 0
|
||||
bat_grid_export_hours_fast[0:start_hour] = 0
|
||||
bat_grid_export_hours_fast[end_hour:] = 0
|
||||
battery_fast.discharge_array = np.where(
|
||||
(bat_discharge_hours_fast > 0)
|
||||
| (
|
||||
direct_marketing_enabled_fast
|
||||
& (bat_grid_export_hours_fast > 0)
|
||||
& (elect_revenue_per_hour_arr_fast[: len(bat_grid_export_hours_fast)] > 0.0)
|
||||
),
|
||||
1,
|
||||
0,
|
||||
)
|
||||
else:
|
||||
# Default return if no battery is available
|
||||
soc_per_hour = np.full((total_hours), 0)
|
||||
ac_to_dc_eff_fast = 1.0
|
||||
dc_to_ac_eff_fast = 1.0
|
||||
max_ac_charge_w_fast = None
|
||||
ac_charging_possible = False
|
||||
|
||||
if ev_fast:
|
||||
soc_ev_per_hour = [nan] * total_hours
|
||||
|
||||
soc_ev_per_hour[0] = ev_fast.current_soc_percentage()
|
||||
# Fill the charge array of the ev
|
||||
ev_charge_hours_fast[0:start_hour] = 0
|
||||
ev_charge_hours_fast[end_hour:] = 0
|
||||
ev_fast.charge_array = ev_charge_hours_fast
|
||||
# Fill the discharge array of the ev
|
||||
ev_discharge_hours_fast[0:start_hour] = 0
|
||||
ev_discharge_hours_fast[end_hour:] = 0
|
||||
ev_fast.discharge_array = ev_discharge_hours_fast
|
||||
else:
|
||||
# Default return if no electric vehicle is available
|
||||
soc_ev_per_hour = np.full((total_hours), 0)
|
||||
|
||||
if home_appliances_fast:
|
||||
home_appliance_enabled = True
|
||||
# The aggregate appliance load (sum over all devices). Each
|
||||
# appliance already carries its own resampled load curve, built
|
||||
# from the decoded start(s) before this call.
|
||||
home_appliance_wh_per_hour = [nan] * total_hours
|
||||
appliance_loads_fast = [
|
||||
appliance.get_load_for_hour for appliance in home_appliances_fast
|
||||
]
|
||||
else:
|
||||
home_appliance_enabled = False
|
||||
# Default return if no home appliance is available
|
||||
home_appliance_wh_per_hour = np.full((total_hours), 0)
|
||||
appliance_loads_fast = []
|
||||
|
||||
# The per-slot inputs as plain numbers. They are final here: the loop
|
||||
# itself changes only the charge arrays of the devices, and those after
|
||||
# the slot value was read.
|
||||
load_energy_array_fast = _slot_values(load_energy_array_fast)
|
||||
pv_prediction_wh_fast = _slot_values(pv_prediction_wh_fast)
|
||||
elect_price_hourly_fast = _slot_values(elect_price_hourly_fast)
|
||||
elect_revenue_per_hour_arr_fast = _slot_values(elect_revenue_per_hour_arr_fast)
|
||||
bat_grid_export_hours_fast = _slot_values(bat_grid_export_hours_fast)
|
||||
ac_charge_hours_fast = _slot_values(ac_charge_hours_fast)
|
||||
ev_charge_hours_fast = _slot_values(ev_charge_hours_fast)
|
||||
if battery_fast:
|
||||
battery_lcos_per_wh_factor = battery_fast.levelized_cost_of_storage_kwh
|
||||
|
||||
# Aggregate appliance load per slot, summed once per candidate in the
|
||||
# order the loop used to add the appliances (0.0 + first + second ...).
|
||||
# Anything unusual (another appliance class, a curve that does not
|
||||
# cover the simulated slots) keeps the per-slot lookups and their
|
||||
# range check.
|
||||
appliance_load_fast: Optional[list[float]] = None
|
||||
if home_appliance_enabled and start_hour >= 0:
|
||||
appliance_load_fast = [0.0] * end_hour
|
||||
for appliance in home_appliances_fast:
|
||||
curve = getattr(appliance, "load_curve", None)
|
||||
if (
|
||||
type(appliance).get_load_for_hour is not GeneticHomeAppliance.get_load_for_hour
|
||||
or not isinstance(curve, np.ndarray)
|
||||
or curve.dtype != np.float64
|
||||
or curve.ndim != 1
|
||||
or len(curve) < end_hour
|
||||
or appliance.prediction_hours < end_hour
|
||||
):
|
||||
appliance_load_fast = None
|
||||
break
|
||||
appliance_load_fast = [
|
||||
total + load for total, load in zip(appliance_load_fast, curve.tolist())
|
||||
]
|
||||
|
||||
# State of charge in percent, read directly where the device uses the
|
||||
# plain Battery formula (two method calls per slot otherwise).
|
||||
battery_soc_direct = bool(
|
||||
battery_fast
|
||||
and type(battery_fast).current_soc_percentage is GeneticBattery.current_soc_percentage
|
||||
)
|
||||
ev_soc_direct = bool(
|
||||
ev_fast
|
||||
and type(ev_fast).current_soc_percentage is GeneticBattery.current_soc_percentage
|
||||
)
|
||||
battery_lcos_direct = False
|
||||
if battery_fast is not None and type(battery_fast) is GeneticBattery:
|
||||
battery_lcos_direct = True
|
||||
if battery_fast._curves is None:
|
||||
battery_discharged_raw_fast = battery_fast._discharged_raw_wh_per_slot
|
||||
battery_discharging_efficiency_fast = battery_fast.discharging_efficiency
|
||||
else:
|
||||
# With power dependent efficiencies the delivered energy is kept
|
||||
# per slot (see Battery.discharged_energy_wh()).
|
||||
battery_discharged_raw_fast = battery_fast._curves.discharged_dc_wh_per_slot
|
||||
battery_discharging_efficiency_fast = 1.0
|
||||
|
||||
for hour in range(start_hour, end_hour):
|
||||
hour_idx = hour - start_hour
|
||||
|
||||
# Accumulate loads and PV generation
|
||||
consumption = load_energy_array_fast[hour]
|
||||
slot_losses = 0.0
|
||||
|
||||
# Home appliances (sum the per-slot load of all flexible consumers)
|
||||
if home_appliance_enabled:
|
||||
if appliance_load_fast is not None:
|
||||
ha_load = appliance_load_fast[hour]
|
||||
else:
|
||||
ha_load = 0.0
|
||||
for appliance_load in appliance_loads_fast:
|
||||
ha_load += appliance_load(hour)
|
||||
consumption += ha_load
|
||||
home_appliance_wh_per_hour[hour_idx] = ha_load
|
||||
|
||||
# E-Auto handling
|
||||
if ev_fast:
|
||||
# save begin state
|
||||
if ev_soc_direct:
|
||||
soc_ev_per_hour[hour_idx] = (ev_fast.soc_wh / ev_fast.capacity_wh) * 100
|
||||
else:
|
||||
soc_ev_per_hour[hour_idx] = ev_fast.current_soc_percentage()
|
||||
ev_charge_factor = ev_charge_hours_fast[hour]
|
||||
if ev_charge_factor > 0:
|
||||
stored_energy_ev, verluste_eauto = ev_fast.charge_energy(
|
||||
wh=None, hour=hour, charge_factor=ev_charge_factor
|
||||
)
|
||||
# The inverter/grid must supply the EV charger's raw input,
|
||||
# not only the energy stored after charging losses.
|
||||
consumption += stored_energy_ev + verluste_eauto
|
||||
slot_losses += verluste_eauto
|
||||
|
||||
# Save battery SOC before inverter processing = true begin-of-interval state.
|
||||
# Must be recorded here (before DC charge/discharge) so the displayed SOC at
|
||||
# timestamp T reflects what the battery actually had at the START of interval T,
|
||||
# not the post-DC result. Consistent with the EV SOC convention above.
|
||||
if battery_fast:
|
||||
if battery_soc_direct:
|
||||
soc_per_hour[hour_idx] = (battery_fast.soc_wh / battery_fast.capacity_wh) * 100
|
||||
else:
|
||||
soc_per_hour[hour_idx] = battery_fast.current_soc_percentage()
|
||||
|
||||
# Process inverter logic
|
||||
energy_feedin_grid_actual = energy_consumption_grid_actual = losses = eigenverbrauch = (
|
||||
0.0
|
||||
)
|
||||
|
||||
# AC charge factor of this slot, capped by max_ac_charge_power_w
|
||||
ac_charge_factor = 0.0
|
||||
if battery_fast and ac_charging_possible:
|
||||
ac_charge_factor = ac_charge_hours_fast[hour]
|
||||
# No AC charging in this slot (the usual case): nothing to cap.
|
||||
if inverter_fast and ac_charge_factor != 0:
|
||||
ac_charge_factor = inverter_fast.ac_charge_factor(ac_charge_factor)
|
||||
|
||||
if inverter_fast:
|
||||
# Some inverters cap the total charge power with the AC setpoint;
|
||||
# that cap has to be in place before PV charges the battery.
|
||||
if ac_charge_factor > 0.0:
|
||||
inverter_fast.begin_ac_charge_slot(hour, ac_charge_factor)
|
||||
energy_produced = pv_prediction_wh_fast[hour]
|
||||
hourly_feed_in_tariff = elect_revenue_per_hour_arr_fast[hour]
|
||||
# bat_grid_export_hours carries the export level per slot:
|
||||
# 0.0 = no export, otherwise the factor of the rated discharge
|
||||
# power the optimizer selected.
|
||||
battery_grid_export_factor = float(bat_grid_export_hours_fast[hour])
|
||||
battery_grid_export_allowed = (
|
||||
direct_marketing_enabled_fast
|
||||
and hourly_feed_in_tariff > 0.0
|
||||
and battery_grid_export_factor > 0.0
|
||||
)
|
||||
(
|
||||
energy_feedin_grid_actual,
|
||||
energy_consumption_grid_actual,
|
||||
losses,
|
||||
eigenverbrauch,
|
||||
) = inverter_fast.process_energy(
|
||||
energy_produced,
|
||||
consumption,
|
||||
hour,
|
||||
battery_grid_export_allowed,
|
||||
battery_grid_export_factor,
|
||||
)
|
||||
else:
|
||||
hourly_feed_in_tariff = elect_revenue_per_hour_arr_fast[hour]
|
||||
# Without an inverter the grid supplies the whole load; PV is not converted.
|
||||
energy_consumption_grid_actual = consumption
|
||||
|
||||
# AC PV Battery Charge
|
||||
if ac_charge_factor > 0.0 and battery_fast:
|
||||
if inverter_fast:
|
||||
ac_energy, ac_charge_losses = inverter_fast.charge_battery_from_grid(
|
||||
hour, ac_charge_factor
|
||||
)
|
||||
else:
|
||||
# Without an inverter the grid charges the battery losslessly
|
||||
# (AC-to-DC efficiency 1.0).
|
||||
stored, ac_charge_losses = battery_fast.charge_energy(
|
||||
None, hour, charge_factor=ac_charge_factor
|
||||
)
|
||||
ac_energy = stored + ac_charge_losses
|
||||
consumption += ac_energy
|
||||
energy_consumption_grid_actual += ac_energy
|
||||
slot_losses += ac_charge_losses
|
||||
|
||||
# Update hourly arrays
|
||||
if (
|
||||
direct_marketing_enabled_fast
|
||||
and hourly_feed_in_tariff < 0.0
|
||||
and energy_feedin_grid_actual > 0.0
|
||||
):
|
||||
slot_losses += energy_feedin_grid_actual
|
||||
energy_feedin_grid_actual = 0.0
|
||||
|
||||
feedin_energy_per_hour[hour_idx] = energy_feedin_grid_actual
|
||||
consumption_energy_per_hour[hour_idx] = energy_consumption_grid_actual
|
||||
losses_wh_per_hour[hour_idx] = slot_losses + losses
|
||||
loads_energy_per_hour[hour_idx] = consumption
|
||||
hourly_electricity_price = elect_price_hourly_fast[hour]
|
||||
electricity_price_per_hour[hour_idx] = hourly_electricity_price
|
||||
feed_in_tariff_per_hour[hour_idx] = hourly_feed_in_tariff
|
||||
|
||||
# Financial calculations
|
||||
grid_cost = energy_consumption_grid_actual * hourly_electricity_price
|
||||
# LCOS is charged exactly once on battery-delivered DC energy. It is
|
||||
# not charged on input energy, internal discharge losses, or the
|
||||
# downstream DC-to-AC inverter loss.
|
||||
battery_lcos_cost = 0.0
|
||||
if battery_lcos_direct:
|
||||
# Battery.discharged_energy_wh(), without the call per slot.
|
||||
battery_lcos_cost = (
|
||||
battery_discharged_raw_fast[hour]
|
||||
* battery_discharging_efficiency_fast
|
||||
* battery_lcos_per_wh_factor
|
||||
/ 1000.0
|
||||
)
|
||||
elif battery_fast:
|
||||
battery_lcos_cost = (
|
||||
battery_fast.discharged_energy_wh(hour) * battery_lcos_per_wh_factor / 1000.0
|
||||
)
|
||||
costs_per_hour[hour_idx] = grid_cost + battery_lcos_cost
|
||||
revenue_per_hour[hour_idx] = energy_feedin_grid_actual * hourly_feed_in_tariff
|
||||
|
||||
loads_energy_per_hour = np.array(loads_energy_per_hour, dtype=float)
|
||||
feedin_energy_per_hour = np.array(feedin_energy_per_hour, dtype=float)
|
||||
consumption_energy_per_hour = np.array(consumption_energy_per_hour, dtype=float)
|
||||
costs_per_hour = np.array(costs_per_hour, dtype=float)
|
||||
revenue_per_hour = np.array(revenue_per_hour, dtype=float)
|
||||
losses_wh_per_hour = np.array(losses_wh_per_hour, dtype=float)
|
||||
electricity_price_per_hour = np.array(electricity_price_per_hour, dtype=float)
|
||||
feed_in_tariff_per_hour = np.array(feed_in_tariff_per_hour, dtype=float)
|
||||
if battery_fast:
|
||||
soc_per_hour = np.array(soc_per_hour, dtype=float)
|
||||
if ev_fast:
|
||||
soc_ev_per_hour = np.array(soc_ev_per_hour, dtype=float)
|
||||
if home_appliance_enabled:
|
||||
home_appliance_wh_per_hour = np.array(home_appliance_wh_per_hour, dtype=float)
|
||||
|
||||
total_cost = np.nansum(costs_per_hour)
|
||||
total_losses = np.nansum(losses_wh_per_hour)
|
||||
total_revenue = np.nansum(revenue_per_hour)
|
||||
|
||||
# Prepare output dictionary
|
||||
return {
|
||||
"Last_Wh_pro_Stunde": loads_energy_per_hour,
|
||||
"Netzeinspeisung_Wh_pro_Stunde": feedin_energy_per_hour,
|
||||
"Netzbezug_Wh_pro_Stunde": consumption_energy_per_hour,
|
||||
"Kosten_Euro_pro_Stunde": costs_per_hour,
|
||||
"akku_soc_pro_stunde": soc_per_hour,
|
||||
"Einnahmen_Euro_pro_Stunde": revenue_per_hour,
|
||||
"Gesamtbilanz_Euro": total_cost - total_revenue, # Fitness score ("FitnessMin")
|
||||
"EAuto_SoC_pro_Stunde": soc_ev_per_hour,
|
||||
"Gesamteinnahmen_Euro": total_revenue,
|
||||
"Gesamtkosten_Euro": total_cost,
|
||||
"Verluste_Pro_Stunde": losses_wh_per_hour,
|
||||
"Gesamt_Verluste": total_losses,
|
||||
"Home_appliance_wh_per_hour": home_appliance_wh_per_hour,
|
||||
"Electricity_price": electricity_price_per_hour,
|
||||
"Feed_in_tariff": feed_in_tariff_per_hour,
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
+45
-28
@@ -5,12 +5,15 @@ Tail actions never enter the executable control arrays. The selected path may
|
||||
be returned separately as diagnostics so users can inspect the lookahead.
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
from pydantic import PrivateAttr
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from akkudoktoreos.devices.genetic.battery import Battery
|
||||
from akkudoktoreos.devices.genetic.inverter import Inverter
|
||||
from akkudoktoreos.optimization.genetic.terminalvalue import (
|
||||
import numpy as np
|
||||
|
||||
from akkudoktoreos.optimization.genetic.devices.geneticbattery import GeneticBattery
|
||||
from akkudoktoreos.optimization.genetic.devices.geneticinverter import GeneticInverter
|
||||
from akkudoktoreos.optimization.genetic.geneticterminalvalue import (
|
||||
TailPlanSlot,
|
||||
TerminalValueCurve,
|
||||
)
|
||||
@@ -35,8 +38,8 @@ def _action_name(action: TailAction) -> str:
|
||||
|
||||
def _simulate_action(
|
||||
*,
|
||||
bat: Battery,
|
||||
inv: Inverter,
|
||||
bat: GeneticBattery,
|
||||
inv: GeneticInverter,
|
||||
energy_wh: float,
|
||||
action: TailAction,
|
||||
price: float,
|
||||
@@ -93,14 +96,19 @@ def _simulate_action(
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class TailValueCurve(TerminalValueCurve):
|
||||
"""Value of usable AC battery energy, including the value of empty capacity.
|
||||
|
||||
Neither values nor marginal values are constrained to be monotone. The empty
|
||||
state can earn money by charging at negative prices and selling later.
|
||||
|
||||
Attributes:
|
||||
trace_context: What ``diagnostic_plan()`` needs to replay the optimal tail path; not
|
||||
part of the curve's value.
|
||||
"""
|
||||
|
||||
_trace_context: dict = PrivateAttr(default_factory=dict)
|
||||
trace_context: Mapping[str, Any] = field(default_factory=dict, repr=False, compare=False)
|
||||
|
||||
def value(self, energy_wh: float) -> float:
|
||||
return (
|
||||
@@ -117,18 +125,19 @@ class TailValueCurve(TerminalValueCurve):
|
||||
|
||||
def diagnostic_plan(self, energy_wh: float, control_horizon_hours: float) -> list[TailPlanSlot]:
|
||||
"""Replay the optimal tail path for one control-end battery state."""
|
||||
context = self._trace_context
|
||||
context = self.trace_context
|
||||
if not context:
|
||||
return []
|
||||
bat = Battery(
|
||||
bat = GeneticBattery(
|
||||
context["battery_parameters"],
|
||||
prediction_hours=1,
|
||||
slot_duration_h=context["slot_duration_h"],
|
||||
)
|
||||
inv = Inverter(
|
||||
inv = GeneticInverter(
|
||||
context["inverter_parameters"],
|
||||
battery=bat,
|
||||
slot_duration_h=context["slot_duration_h"],
|
||||
self_consumption_backend=context["self_consumption_backend"],
|
||||
)
|
||||
conversion = bat.discharging_efficiency * inv.reference_dc_to_ac_efficiency
|
||||
state_wh = bat.min_soc_wh + (energy_wh / conversion if conversion > 0 else 0.0)
|
||||
@@ -205,8 +214,8 @@ class TailValueCurve(TerminalValueCurve):
|
||||
|
||||
def build_tail_value_curve(
|
||||
*,
|
||||
battery: Battery,
|
||||
inverter: Inverter,
|
||||
battery: GeneticBattery,
|
||||
inverter: GeneticInverter,
|
||||
prices_euro_per_wh: np.ndarray,
|
||||
load_wh: np.ndarray,
|
||||
pv_wh: np.ndarray,
|
||||
@@ -229,9 +238,16 @@ def build_tail_value_curve(
|
||||
]
|
||||
if len({len(a) for a in arrays}) != 1 or any(not np.isfinite(a).all() for a in arrays):
|
||||
raise ValueError("Tail forecasts must have equal lengths and contain only finite values")
|
||||
bat = Battery(battery.parameters, prediction_hours=1, slot_duration_h=battery.slot_duration_h)
|
||||
bat = GeneticBattery(
|
||||
battery.parameters, prediction_hours=1, slot_duration_h=battery.slot_duration_h
|
||||
)
|
||||
bat.charge_array = np.zeros(1, dtype=float)
|
||||
inv = Inverter(inverter.parameters, battery=bat, slot_duration_h=battery.slot_duration_h)
|
||||
inv = GeneticInverter(
|
||||
inverter.parameters,
|
||||
battery=bat,
|
||||
slot_duration_h=battery.slot_duration_h,
|
||||
self_consumption_backend=inverter.self_consumption_backend,
|
||||
)
|
||||
states = np.linspace(bat.min_soc_wh, bat.max_soc_wh, grid_points)
|
||||
usable = (
|
||||
(states - bat.min_soc_wh) * bat.discharging_efficiency * inv.reference_dc_to_ac_efficiency
|
||||
@@ -289,18 +305,19 @@ def build_tail_value_curve(
|
||||
continuation_value_euro=continuation_values.tolist(),
|
||||
marginal_euro_per_kwh=(np.diff(values) / np.maximum(np.diff(usable), 1e-9) * 1000).tolist(),
|
||||
window_slots=len(arrays[0]),
|
||||
trace_context={
|
||||
"battery_parameters": battery.parameters,
|
||||
"inverter_parameters": inverter.parameters,
|
||||
"self_consumption_backend": inverter.self_consumption_backend,
|
||||
"slot_duration_h": battery.slot_duration_h,
|
||||
"states": states,
|
||||
"future_values": future_values,
|
||||
"actions": actions,
|
||||
"prices": arrays[0],
|
||||
"load": arrays[1],
|
||||
"pv": arrays[2],
|
||||
"tariffs": arrays[3],
|
||||
"direct_marketing": direct_marketing,
|
||||
},
|
||||
)
|
||||
result._trace_context = {
|
||||
"battery_parameters": battery.parameters,
|
||||
"inverter_parameters": inverter.parameters,
|
||||
"slot_duration_h": battery.slot_duration_h,
|
||||
"states": states,
|
||||
"future_values": future_values,
|
||||
"actions": actions,
|
||||
"prices": arrays[0],
|
||||
"load": arrays[1],
|
||||
"pv": arrays[2],
|
||||
"tariffs": arrays[3],
|
||||
"direct_marketing": direct_marketing,
|
||||
}
|
||||
return result
|
||||
+57
-126
@@ -23,72 +23,43 @@ aid, not a prediction - which is also why the marginal values are deliberately
|
||||
conservative wherever a choice exists.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Optional
|
||||
|
||||
import numpy as np
|
||||
from loguru import logger
|
||||
from pydantic import Field
|
||||
|
||||
from akkudoktoreos.core.pydantic import PydanticBaseModel
|
||||
|
||||
|
||||
class TerminalValueCurve(PydanticBaseModel):
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class TerminalValueCurve:
|
||||
"""Piecewise linear, concave value of battery energy left at the horizon.
|
||||
|
||||
``energy_wh`` and ``value_euro`` are the breakpoints of the cumulative
|
||||
value, ``marginal_euro_per_kwh`` the slope of each segment. Both arrays
|
||||
start at the origin; the curve is flat beyond its last breakpoint.
|
||||
|
||||
Attributes:
|
||||
energy_wh: Breakpoints of usable AC energy left in the battery [Wh].
|
||||
value_euro: Cumulative credit at each breakpoint [EUR].
|
||||
operating_value_euro: Tail operating component at each breakpoint [EUR]; empty for a
|
||||
proxy curve.
|
||||
continuation_value_euro: Continuation component at each breakpoint [EUR]; empty for a
|
||||
proxy curve.
|
||||
marginal_euro_per_kwh: Marginal value of the segment that starts at each breakpoint
|
||||
[EUR/kWh]. May be negative or non-monotone in TAIL mode.
|
||||
residual_energy_wh: Energy up to which the curve is backed by residual load - the knee.
|
||||
Everything beyond it is only worth an export.
|
||||
window_slots: Number of trailing horizon slots the curve was derived from. Fewer slots
|
||||
than a full day mean a shorter proxy period.
|
||||
"""
|
||||
|
||||
energy_wh: list[float] = Field(
|
||||
default_factory=list,
|
||||
json_schema_extra={
|
||||
"description": "Breakpoints of usable AC energy left in the battery [Wh]."
|
||||
},
|
||||
)
|
||||
value_euro: list[float] = Field(
|
||||
default_factory=list,
|
||||
json_schema_extra={"description": "Cumulative credit at each breakpoint [EUR]."},
|
||||
)
|
||||
operating_value_euro: list[float] = Field(
|
||||
default_factory=list,
|
||||
json_schema_extra={
|
||||
"description": "Tail operating component at each breakpoint [EUR]; empty for a proxy curve."
|
||||
},
|
||||
)
|
||||
continuation_value_euro: list[float] = Field(
|
||||
default_factory=list,
|
||||
json_schema_extra={
|
||||
"description": "Continuation component at each breakpoint [EUR]; empty for a proxy curve."
|
||||
},
|
||||
)
|
||||
marginal_euro_per_kwh: list[float] = Field(
|
||||
default_factory=list,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Marginal value of the segment that starts at each breakpoint "
|
||||
"[EUR/kWh]. May be negative or non-monotone in TAIL mode."
|
||||
)
|
||||
},
|
||||
)
|
||||
residual_energy_wh: float = Field(
|
||||
default=0.0,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Energy up to which the curve is backed by residual load - the "
|
||||
"knee. Everything beyond it is only worth an export."
|
||||
)
|
||||
},
|
||||
)
|
||||
window_slots: int = Field(
|
||||
default=0,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Number of trailing horizon slots the curve was derived from. "
|
||||
"Fewer slots than a full day mean a shorter proxy period."
|
||||
)
|
||||
},
|
||||
)
|
||||
energy_wh: list[float] = field(default_factory=list)
|
||||
value_euro: list[float] = field(default_factory=list)
|
||||
operating_value_euro: list[float] = field(default_factory=list)
|
||||
continuation_value_euro: list[float] = field(default_factory=list)
|
||||
marginal_euro_per_kwh: list[float] = field(default_factory=list)
|
||||
residual_energy_wh: float = 0.0
|
||||
window_slots: int = 0
|
||||
|
||||
def value(self, energy_wh: float) -> float:
|
||||
"""Return the credit for ``energy_wh`` of usable AC energy [EUR].
|
||||
@@ -104,7 +75,8 @@ class TerminalValueCurve(PydanticBaseModel):
|
||||
return float(np.interp(energy_wh, self.energy_wh, self.value_euro))
|
||||
|
||||
|
||||
class TailDiagnostics(PydanticBaseModel):
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class TailDiagnostics:
|
||||
"""Forecast summary used by the deterministic tail optimization."""
|
||||
|
||||
slots: int = 0
|
||||
@@ -118,7 +90,8 @@ class TailDiagnostics(PydanticBaseModel):
|
||||
positive_battery_export_slots: int = 0
|
||||
|
||||
|
||||
class TailPlanSlot(PydanticBaseModel):
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class TailPlanSlot:
|
||||
"""One diagnostic slot of the optimal tail path.
|
||||
|
||||
These values explain the lookahead used for fitness. They are diagnostics
|
||||
@@ -148,84 +121,42 @@ class TailPlanSlot(PydanticBaseModel):
|
||||
battery_grid_export_factor: float
|
||||
|
||||
|
||||
class TerminalValueResult(PydanticBaseModel):
|
||||
"""What the optimizer credited for the energy left in the battery."""
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class TerminalValueResult:
|
||||
"""What the optimizer credited for the energy left in the battery.
|
||||
|
||||
Attributes:
|
||||
mode: Terminal value mode the run used: TAIL, AUTO or FIXED.
|
||||
battery_energy_wh: Usable AC energy left in the battery at the end of the horizon [Wh].
|
||||
credited_euro: Credit applied to the total balance [EUR].
|
||||
tail_operating_euro: Optimal net cash flow within the effective tail for the selected
|
||||
control-end battery state [EUR].
|
||||
continuation_value_euro: Continuation credit remaining at the end of the optimal tail
|
||||
path [EUR].
|
||||
curve: Combined tail value curve (tail operation plus continuation) read by fitness;
|
||||
None in FIXED mode.
|
||||
continuation_curve: Conservative AUTO proxy constructed at the effective tail end.
|
||||
tail_plan: Diagnostic optimal battery path inside the tail. It explains the lookahead
|
||||
but is never an executable control plan.
|
||||
reason: Why this mode applied. Empty in AUTO mode; in FIXED mode it says whether FIXED
|
||||
was configured or whether AUTO fell back because no curve could be derived.
|
||||
"""
|
||||
|
||||
control_horizon_hours: float = 0
|
||||
requested_tail_hours: float = 0
|
||||
effective_tail_hours: float = 0
|
||||
tail_end_hour: float = 0
|
||||
continuation_mode: str = "FIXED"
|
||||
|
||||
mode: str = Field(
|
||||
json_schema_extra={
|
||||
"description": "Terminal value mode the run used: TAIL, AUTO or FIXED.",
|
||||
"examples": ["TAIL", "AUTO", "FIXED"],
|
||||
}
|
||||
)
|
||||
battery_energy_wh: float = Field(
|
||||
default=0.0,
|
||||
json_schema_extra={
|
||||
"description": "Usable AC energy left in the battery at the end of the horizon [Wh]."
|
||||
},
|
||||
)
|
||||
credited_euro: float = Field(
|
||||
default=0.0,
|
||||
json_schema_extra={"description": "Credit applied to the total balance [EUR]."},
|
||||
)
|
||||
tail_operating_euro: float = Field(
|
||||
default=0.0,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Optimal net cash flow within the effective tail for the selected "
|
||||
"control-end battery state [EUR]."
|
||||
)
|
||||
},
|
||||
)
|
||||
continuation_value_euro: float = Field(
|
||||
default=0.0,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Continuation credit remaining at the end of the optimal tail path [EUR]."
|
||||
)
|
||||
},
|
||||
)
|
||||
curve: Optional[TerminalValueCurve] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Combined tail value curve (tail operation plus continuation) read by fitness; "
|
||||
"None in FIXED mode."
|
||||
)
|
||||
},
|
||||
)
|
||||
continuation_curve: Optional[TerminalValueCurve] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": "Conservative AUTO proxy constructed at the effective tail end."
|
||||
},
|
||||
)
|
||||
mode: str
|
||||
battery_energy_wh: float = 0.0
|
||||
credited_euro: float = 0.0
|
||||
tail_operating_euro: float = 0.0
|
||||
continuation_value_euro: float = 0.0
|
||||
curve: Optional[TerminalValueCurve] = None
|
||||
continuation_curve: Optional[TerminalValueCurve] = None
|
||||
tail_diagnostics: Optional[TailDiagnostics] = None
|
||||
tail_plan: list[TailPlanSlot] = Field(
|
||||
default_factory=list,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Diagnostic optimal battery path inside the tail. It explains the "
|
||||
"lookahead but is never an executable control plan."
|
||||
)
|
||||
},
|
||||
)
|
||||
reason: str = Field(
|
||||
default="",
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Why this mode applied. Empty in AUTO mode; in FIXED mode it "
|
||||
"says whether FIXED was configured or whether AUTO fell back "
|
||||
"because no curve could be derived."
|
||||
),
|
||||
"examples": ["", "terminal_value_mode is FIXED"],
|
||||
},
|
||||
)
|
||||
tail_plan: list[TailPlanSlot] = field(default_factory=list)
|
||||
reason: str = ""
|
||||
|
||||
|
||||
def build_terminal_value_curve(
|
||||
@@ -1,3 +1,4 @@
|
||||
import dataclasses
|
||||
import json
|
||||
import textwrap
|
||||
from collections.abc import Sequence
|
||||
@@ -11,8 +12,8 @@ import numpy as np
|
||||
import pendulum
|
||||
from matplotlib.backends.backend_pdf import PdfPages
|
||||
|
||||
from akkudoktoreos.core.coreabc import ConfigMixin, get_ems
|
||||
from akkudoktoreos.optimization.genetic.geneticsolution import GeneticSolution
|
||||
from akkudoktoreos.optimization.genetic.geneticparameters import GeneticParameters
|
||||
from akkudoktoreos.optimization.genetic.geneticresult import GeneticResult
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime
|
||||
|
||||
matplotlib.use(
|
||||
@@ -23,15 +24,26 @@ matplotlib.use(
|
||||
debug_visualize: bool = False
|
||||
|
||||
|
||||
class GeneticVisualizationReport(ConfigMixin):
|
||||
class GeneticVisualizationReport:
|
||||
"""PDF report of a GENETIC run: groups of charts, rendered page by page."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
version: str = "0.0.1",
|
||||
interval_seconds: int = 3600,
|
||||
timezone: Optional[str] = None,
|
||||
) -> None:
|
||||
"""Create an empty report.
|
||||
|
||||
Args:
|
||||
version: Version shown in the report.
|
||||
interval_seconds: Length of one slot of the charts.
|
||||
timezone: Time zone of the charts' hours; ``None`` is the local time zone.
|
||||
"""
|
||||
if interval_seconds <= 0:
|
||||
raise ValueError("Report interval must be positive")
|
||||
self.interval_seconds = interval_seconds
|
||||
self.timezone = timezone
|
||||
# Initialize the report with empty groups
|
||||
self.groups: list[list[Callable[[], None]]] = [] # Store groups of charts
|
||||
self.current_group: list[
|
||||
@@ -43,9 +55,7 @@ class GeneticVisualizationReport(ConfigMixin):
|
||||
self.pdf_pages: PdfPages | None = None
|
||||
|
||||
self.version = version # overwrite version as test for constant output of pdf for test
|
||||
self.current_time = to_datetime(
|
||||
as_string="YYYY-MM-DD HH:mm:ss", in_timezone=self.config.general.timezone
|
||||
)
|
||||
self.current_time = to_datetime(as_string="YYYY-MM-DD HH:mm:ss", in_timezone=self.timezone)
|
||||
|
||||
def add_chart_to_group(self, chart_func: Callable[[], None], title: str | None) -> None:
|
||||
"""Add a chart function to the current group and save it as a PNG and SVG."""
|
||||
@@ -184,7 +194,7 @@ class GeneticVisualizationReport(ConfigMixin):
|
||||
plt.grid(True)
|
||||
|
||||
# Add vertical line for the current date if within the axis range
|
||||
current_time = pendulum.now(self.config.general.timezone)
|
||||
current_time = to_datetime(in_timezone=self.timezone)
|
||||
if timestamps[0].subtract(hours=2) <= current_time <= timestamps[-1]:
|
||||
plt.axvline(mdates.date2num(current_time), color="r", linestyle="--", label="Now")
|
||||
plt.text(
|
||||
@@ -457,13 +467,26 @@ class GeneticVisualizationReport(ConfigMixin):
|
||||
|
||||
|
||||
def genetic_prepare_visualize(
|
||||
solution: GeneticSolution,
|
||||
parameters: GeneticParameters,
|
||||
result: GeneticResult,
|
||||
) -> bytes:
|
||||
"""Render the PDF report of a run.
|
||||
|
||||
Args:
|
||||
parameters: The optimization parameters of the run (run start, time zone).
|
||||
result: The result of the run.
|
||||
|
||||
Returns:
|
||||
The PDF document.
|
||||
"""
|
||||
global debug_visualize
|
||||
|
||||
report = GeneticVisualizationReport(interval_seconds=solution.interval_seconds)
|
||||
# New solutions own their timeline. The fallback supports historical hourly solutions.
|
||||
start_datetime = solution.start_solution_datetime or get_ems().start_datetime
|
||||
solution = result
|
||||
report = GeneticVisualizationReport(
|
||||
interval_seconds=solution.interval_seconds, timezone=parameters.settings.timezone
|
||||
)
|
||||
# New solutions own their timeline; the run start is the fallback.
|
||||
start_datetime = solution.start_solution_datetime or parameters.settings.start_datetime
|
||||
start_offset = 0 if solution.controls_start_at_now else solution.start_hour
|
||||
control_slots = len(solution.result.load_wh_per_hour)
|
||||
end_offset = start_offset + control_slots
|
||||
@@ -472,7 +495,7 @@ def genetic_prepare_visualize(
|
||||
report.create_line_chart_date(
|
||||
start_datetime,
|
||||
[
|
||||
solution.parameters.ems.total_load[start_offset:end_offset],
|
||||
solution.request.ems.total_load[start_offset:end_offset],
|
||||
],
|
||||
title="Load Profile",
|
||||
# xlabel="Hours", # not enough space
|
||||
@@ -482,7 +505,7 @@ def genetic_prepare_visualize(
|
||||
report.create_line_chart_date(
|
||||
start_datetime,
|
||||
[
|
||||
solution.parameters.ems.pv_forecast_wh[start_offset:end_offset],
|
||||
solution.request.ems.pv_forecast_wh[start_offset:end_offset],
|
||||
],
|
||||
title="PV Forecast",
|
||||
# xlabel="Hours", # not enough space
|
||||
@@ -492,20 +515,20 @@ def genetic_prepare_visualize(
|
||||
report.create_line_chart_date(
|
||||
start_datetime,
|
||||
[
|
||||
np.asarray(solution.parameters.ems.feed_in_tariff_per_wh[start_offset:end_offset])
|
||||
if isinstance(solution.parameters.ems.feed_in_tariff_per_wh, list)
|
||||
else np.full(control_slots, solution.parameters.ems.feed_in_tariff_per_wh)
|
||||
np.asarray(solution.request.ems.feed_in_tariff_per_wh[start_offset:end_offset])
|
||||
if isinstance(solution.request.ems.feed_in_tariff_per_wh, list)
|
||||
else np.full(control_slots, solution.request.ems.feed_in_tariff_per_wh)
|
||||
],
|
||||
title="Remuneration",
|
||||
# xlabel="Hours", # not enough space
|
||||
ylabel="amount/Wh",
|
||||
x2label=None, # not enough space
|
||||
)
|
||||
if solution.parameters.temperature_forecast:
|
||||
if solution.request.temperature_forecast:
|
||||
report.create_line_chart_date(
|
||||
start_datetime,
|
||||
[
|
||||
solution.parameters.temperature_forecast[start_offset:end_offset],
|
||||
solution.request.temperature_forecast[start_offset:end_offset],
|
||||
],
|
||||
title="Temperature Forecast",
|
||||
# xlabel="Hours", # not enough space
|
||||
@@ -554,7 +577,7 @@ def genetic_prepare_visualize(
|
||||
)
|
||||
report.create_line_chart_date(
|
||||
start_date=start_datetime, # start_date
|
||||
y_list=[solution.parameters.ems.electricity_price_per_wh[start_offset:end_offset]],
|
||||
y_list=[solution.request.ems.electricity_price_per_wh[start_offset:end_offset]],
|
||||
# title="Electricity Price", # not enough space
|
||||
# xlabel="Date", # not enough space
|
||||
ylabel="Electricity Price (amount/Wh)",
|
||||
@@ -706,7 +729,7 @@ def genetic_prepare_visualize(
|
||||
|
||||
|
||||
def _add_solution_diagnostics(
|
||||
report: GeneticVisualizationReport, solution: GeneticSolution, start: DateTime
|
||||
report: GeneticVisualizationReport, solution: GeneticResult, start: DateTime
|
||||
) -> None:
|
||||
"""Render the retained run diagnostics; tail actions are never executable controls."""
|
||||
report.add_text_page(
|
||||
@@ -761,7 +784,9 @@ def _add_solution_diagnostics(
|
||||
report.finalize_group()
|
||||
if terminal.tail_diagnostics is not None:
|
||||
report.add_json_page(
|
||||
terminal.tail_diagnostics.model_dump(), title="Tail Forecast Summary", fontsize=10
|
||||
dataclasses.asdict(terminal.tail_diagnostics),
|
||||
title="Tail Forecast Summary",
|
||||
fontsize=10,
|
||||
)
|
||||
report.finalize_group()
|
||||
curve = terminal.curve
|
||||
|
||||
@@ -14,7 +14,7 @@ from akkudoktoreos.optimization.genetic0.genetic0request import (
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic0.genetic0result import Genetic0Result
|
||||
from akkudoktoreos.optimization.optimization import OptimizationSolution
|
||||
from akkudoktoreos.optimization.optimizer import OptimizerApi
|
||||
from akkudoktoreos.optimization.optimizer import OptimizerApi, RunClock
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime
|
||||
|
||||
|
||||
@@ -23,6 +23,10 @@ class Genetic0Optimizer:
|
||||
|
||||
name = "GENETIC0"
|
||||
|
||||
def run_clock(self) -> RunClock:
|
||||
"""See ``Optimizer.run_clock()``: hourly slots in the server's local time."""
|
||||
return RunClock(slot_seconds=3600)
|
||||
|
||||
async def prepare(
|
||||
self,
|
||||
start_datetime: DateTime,
|
||||
|
||||
@@ -828,7 +828,7 @@ def inverter_request(
|
||||
The inverter parameters of the request.
|
||||
|
||||
Raises:
|
||||
InverterResolutionError: See ``InverterCommonSettings.to_genetic_param``.
|
||||
InverterResolutionError: See ``InverterCommonSettings.resolve_operating_parameters``.
|
||||
"""
|
||||
p = operating_parameters or settings.resolve_operating_parameters()
|
||||
return Genetic0InverterRequest(
|
||||
|
||||
@@ -9,11 +9,11 @@ from akkudoktoreos.core.pydantic import (
|
||||
PydanticBaseModel,
|
||||
PydanticDateTimeDataFrame,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic0 import Genetic0Settings
|
||||
from akkudoktoreos.optimization.genetic.geneticsettings import (
|
||||
GeneticCommonSettings,
|
||||
from akkudoktoreos.optimization.genetic import (
|
||||
GeneticSettings,
|
||||
normalize_genetic_settings,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic0 import Genetic0Settings
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime
|
||||
from akkudoktoreos.utils.gridinterpolator import GridInterpolatorBackend
|
||||
|
||||
@@ -51,8 +51,8 @@ class OptimizationCommonSettings(SettingsBaseModel):
|
||||
},
|
||||
)
|
||||
|
||||
genetic: GeneticCommonSettings = Field(
|
||||
default_factory=GeneticCommonSettings,
|
||||
genetic: GeneticSettings = Field(
|
||||
default_factory=GeneticSettings,
|
||||
json_schema_extra={
|
||||
"description": "GENETIC optimization algorithm configuration.",
|
||||
"examples": [{"individuals": 400, "seed": None, "penalties": {"ev_soc_miss": 10}}],
|
||||
|
||||
@@ -20,6 +20,21 @@ RequestT_contra = TypeVar("RequestT_contra", contravariant=True)
|
||||
ResultT = TypeVar("ResultT")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class RunClock:
|
||||
"""The clock an optimizer's runs follow (ADR 0006).
|
||||
|
||||
Attributes:
|
||||
slot_seconds: Length of the optimizer's slots; the run start is rounded down to a slot
|
||||
boundary. 900 or 3600.
|
||||
timezone: Time zone a run without an explicit start starts in, e.g. the site's time zone
|
||||
for slots that follow the local day; ``None`` uses the server's local time.
|
||||
"""
|
||||
|
||||
slot_seconds: int
|
||||
timezone: Optional[str] = None
|
||||
|
||||
|
||||
class Optimizer(Protocol[ParametersT, RequestT_contra, ResultT]):
|
||||
"""An optimizer, driven by the energy management.
|
||||
|
||||
@@ -29,6 +44,17 @@ class Optimizer(Protocol[ParametersT, RequestT_contra, ResultT]):
|
||||
|
||||
name: str
|
||||
|
||||
def run_clock(self) -> RunClock:
|
||||
"""The slot length and time zone the energy management starts the next run in.
|
||||
|
||||
Read from the optimizer's settings by its parameter preparation, before the run start is
|
||||
fixed; never fails.
|
||||
|
||||
Returns:
|
||||
The clock of the next run.
|
||||
"""
|
||||
...
|
||||
|
||||
async def prepare(
|
||||
self,
|
||||
start_datetime: DateTime,
|
||||
|
||||
@@ -11,14 +11,21 @@ from typing import Any, Optional
|
||||
from akkudoktoreos.optimization.optimizer import Optimizer
|
||||
|
||||
|
||||
def _genetic() -> Optimizer[Any, Any, Any]:
|
||||
from akkudoktoreos.optimization.genetic import GeneticOptimizer
|
||||
|
||||
return GeneticOptimizer()
|
||||
|
||||
|
||||
def _genetic0() -> Optimizer[Any, Any, Any]:
|
||||
from akkudoktoreos.optimization.genetic0 import Genetic0Optimizer
|
||||
|
||||
return Genetic0Optimizer()
|
||||
|
||||
|
||||
# Optimizer name -> factory. GENETIC joins when it is migrated.
|
||||
# Optimizer name -> factory.
|
||||
_FACTORIES: dict[str, Callable[[], Optimizer[Any, Any, Any]]] = {
|
||||
"GENETIC": _genetic,
|
||||
"GENETIC0": _genetic0,
|
||||
}
|
||||
|
||||
@@ -48,6 +55,6 @@ def optimizer_names() -> list[str]:
|
||||
"""Names of all registered optimizers.
|
||||
|
||||
Returns:
|
||||
The names, e.g. ``["GENETIC0"]``.
|
||||
The names, e.g. ``["GENETIC", "GENETIC0"]``.
|
||||
"""
|
||||
return list(_FACTORIES)
|
||||
|
||||
Reference in New Issue
Block a user