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:
Bobby Noelte
2026-11-27 13:55:41 +01:00
co-authored by Claude Opus 5.5
parent b108335ee4
commit b3d5334d3e
156 changed files with 146594 additions and 7766 deletions
+3 -2
View File
@@ -391,8 +391,9 @@ class SettingsEOSDefaults(SettingsEOS):
prediction = self.prediction.hours
if prediction is None or prediction < control:
logger.warning(
"Prediction horizon {} h is shorter than the {} h control horizon. Optimization "
"runs will fail until prediction.hours covers the control horizon.",
"Prediction horizon {} h is shorter than the {} h control horizon. GENETIC "
"plans the control horizon with fallback forecasts until prediction.hours covers "
"it.",
prediction,
control,
)
+1 -3
View File
@@ -504,9 +504,7 @@ def migrate_config_data(config_data: Dict[str, Any]) -> "SettingsEOSDefaults":
# Normalize this provider before the generic field-by-field transfer. Validate
# coupled bounds together so a transient intermediate default cannot lose them.
config_data = dict(config_data)
from akkudoktoreos.optimization.genetic.geneticsettings import (
normalize_genetic_settings,
)
from akkudoktoreos.optimization.genetic import normalize_genetic_settings
if "optimization" in config_data:
config_data["optimization"] = normalize_genetic_settings(config_data["optimization"])
+27 -142
View File
@@ -6,7 +6,7 @@ from asyncio import Lock, get_running_loop
from collections.abc import Mapping
from concurrent.futures import ThreadPoolExecutor
from enum import StrEnum
from typing import Any, ClassVar, Optional, cast
from typing import Any, ClassVar, Optional
from loguru import logger
from pydantic import computed_field
@@ -21,17 +21,11 @@ from akkudoktoreos.core.coreabc import (
from akkudoktoreos.core.emplan import EnergyManagementPlan
from akkudoktoreos.core.emsettings import EnergyManagementMode
from akkudoktoreos.core.pydantic import PydanticBaseModel
from akkudoktoreos.optimization.genetic.configrequest import ConfigOptimizationRequest
from akkudoktoreos.optimization.genetic.genetic import GeneticOptimization
from akkudoktoreos.optimization.genetic.geneticparams import (
GeneticOptimizationParameters,
)
from akkudoktoreos.optimization.genetic.geneticsolution import GeneticSolution
from akkudoktoreos.optimization.optimization import (
OptimizationAlgorithm,
OptimizationSolution,
)
from akkudoktoreos.optimization.optimizer import OptimizerRun
from akkudoktoreos.optimization.optimizer import OptimizerRun, RunClock
from akkudoktoreos.optimization.optimizerregistry import get_optimizer
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime
@@ -121,10 +115,6 @@ class EnergyManagement(
# opimization solution of the latest energy management run
_optimization_solution: ClassVar[Optional[OptimizationSolution]] = None
# Solution of the genetic algorithm of latest energy management run with optimization
# For classic API
_genetic_solution: ClassVar[Optional[GeneticSolution]] = None
# Parameters and result of the latest run per optimizer of the registry, by optimizer name.
# The result is the warm start of the optimizer's next run.
_optimizer_runs: ClassVar[dict[str, OptimizerRun[Any, Any]]] = {}
@@ -165,7 +155,8 @@ class EnergyManagement(
Args:
start_datetime (Optional[DateTime]): The datetime to set as the start.
If None, the current datetime is used.
interval_seconds: Explicit slot duration; otherwise use the configured algorithm.
interval_seconds: Explicit slot duration; otherwise the slot of the configured
optimizer's run clock.
Returns:
DateTime: The adjusted start datetime.
@@ -174,11 +165,7 @@ class EnergyManagement(
start_datetime = to_datetime()
cls._observation_datetime = start_datetime
if interval_seconds is None:
interval_seconds = (
cls.config.optimization.genetic.interval_sec
if cls.config.optimization.algorithm == OptimizationAlgorithm.GENETIC
else 3600
)
interval_seconds = cls._run_clock(cls.config.optimization.algorithm).slot_seconds
if interval_seconds not in (900, 3600):
raise ValueError("Optimization slots must be 900 or 3600 seconds.")
midnight = start_datetime.start_of("day").int_timestamp
@@ -189,6 +176,12 @@ class EnergyManagement(
)
return cls._start_datetime
@staticmethod
def _run_clock(algorithm: str) -> RunClock:
"""The run clock of the optimizer ``algorithm``; hourly local slots if unknown."""
optimizer = get_optimizer(algorithm)
return RunClock(slot_seconds=3600) if optimizer is None else optimizer.run_clock()
@classmethod
def stage(cls) -> EnergyManagementStage:
"""Get the the stage of the energy management.
@@ -216,15 +209,6 @@ class EnergyManagement(
"""
return cls._optimization_solution
@classmethod
def genetic_solution(cls) -> Optional[GeneticSolution]:
"""Get the latest solution of the genetic algorithm.
Returns:
Optional[GeneticSolution]: The latest solution of the genetic algorithm.
"""
return cls._genetic_solution
@classmethod
def optimizer_run(cls, name: str) -> Optional[OptimizerRun[Any, Any]]:
"""Get the parameters and result of the latest successful run of an optimizer.
@@ -255,12 +239,6 @@ class EnergyManagement(
start_datetime: Optional[DateTime] = None,
mode: Optional[EnergyManagementMode] = None,
algorithm: Optional[OptimizationAlgorithm] = None,
genetic_parameters: Optional[
GeneticOptimizationParameters | ConfigOptimizationRequest
] = None,
genetic_generations: Optional[int] = None,
genetic_individuals: Optional[int] = None,
genetic_seed: Optional[int] = None,
request: Optional[Any] = None,
overrides: Optional[Mapping[str, Any]] = None,
force_enable: Optional[bool] = False,
@@ -286,20 +264,12 @@ class EnergyManagement(
- "GENETIC0": Optimization uses the `GENETIC0` optimization algorithm.
Defaults to the algorithm defined in the current configuration.
genetic_parameters (GeneticOptimizationParameters, optional): The
parameter set for the `GENETIC` algorithm. If not provided, it will
be constructed based on the current configuration and predictions.
genetic_generations (int, optional): The number of generations for the
`GENETIC` algorithm. Defaults to the algorithm's internal default (400)
if not specified.
genetic_individuals (int, optional): Population size override for this run.
genetic_seed (int, optional): The seed for the `GENETIC` algorithm. Defaults
to the algorithm's internal random seed if not specified.
request (optional): An optimization request for an optimizer of the registry
(e.g. `GENETIC0`), completed by its `prepare_from_request()`. If not provided,
the optimizer prepares its parameters from configuration and predictions.
overrides (Mapping, optional): Run-time overrides of the settings of an optimizer
of the registry, e.g. ``{"generations": 10, "seed": 42}``.
request (optional): An optimization request for the optimizer (e.g. a
`GeneticRequest` for `GENETIC`), completed by its
`prepare_from_request()`. If not provided, the optimizer prepares its
parameters from configuration and predictions.
overrides (Mapping, optional): Run-time overrides of the optimizer's settings,
e.g. ``{"generations": 10, "seed": 42}``.
force_enable (bool, optional): If True, bypasses any disabled state
to force the update process. This is mostly applicable to
prediction providers.
@@ -330,18 +300,12 @@ class EnergyManagement(
# None leads to current time as start datetime
if algorithm is None:
algorithm = self.config.optimization.algorithm
if start_datetime is None and algorithm == OptimizationAlgorithm.GENETIC:
# Consumer windows and midnight-based forecasts use the site clock,
run_clock = EnergyManagement._run_clock(algorithm)
if start_datetime is None and run_clock.timezone is not None:
# E.g. consumer windows and midnight-based forecasts use the site clock,
# which can differ from the server's local timezone.
start_datetime = to_datetime(in_timezone=self.config.general.timezone)
self.set_start_datetime(
start_datetime,
interval_seconds=(
self.config.optimization.genetic.interval_sec
if algorithm == OptimizationAlgorithm.GENETIC
else 3600
),
)
start_datetime = to_datetime(in_timezone=run_clock.timezone)
self.set_start_datetime(start_datetime, interval_seconds=run_clock.slot_seconds)
# Throw away any memory cached results of the last energy management run.
CacheEnergyManagementStore().clear()
@@ -386,82 +350,10 @@ class EnergyManagement(
algorithm = self.config.optimization.algorithm
run_solution: Any
optimizer = (
None if algorithm == OptimizationAlgorithm.GENETIC else get_optimizer(algorithm)
)
# --- GENETIC algorithm ---
if algorithm == OptimizationAlgorithm.GENETIC:
# Prepare optimization parameters
# This also creates default configurations for missing values and updates the predictions
logger.info(f"{algorithm}: Starting optimzation parameter preparation.")
try:
if isinstance(genetic_parameters, ConfigOptimizationRequest):
genetic_parameters = await genetic_parameters.resolve()
elif genetic_parameters is None:
genetic_parameters = await GeneticOptimizationParameters.prepare()
if genetic_parameters is None:
logger.error("GENETIC: Parameter preparation failed; canceling run.")
EnergyManagement._stage = EnergyManagementStage.IDLE
return None
except Exception:
logger.exception("GENETIC: Parameter preparation failed.")
EnergyManagement._stage = EnergyManagementStage.IDLE
return None
# Take values from config if not given
if genetic_generations is None:
genetic_generations = self.config.optimization.genetic.generations
if genetic_seed is None:
genetic_seed = self.config.optimization.genetic.seed
if EnergyManagement._start_datetime is None: # Make mypy happy - already set by us
raise RuntimeError(f"{algorithm}: Start datetime not set.")
# --- Optimization (CPU-bound → MUST offload) ---
try:
genetic_optimization = GeneticOptimization(
verbose=bool(self.config.server.verbose),
fixed_seed=genetic_seed,
)
loop = get_running_loop()
start_hour = EnergyManagement._start_datetime.hour
genetic_solution = await loop.run_in_executor(
None,
lambda: genetic_optimization.optimize_ems(
start_hour=start_hour,
parameters=cast(
GeneticOptimizationParameters, genetic_parameters
), # cast for mypy
ngen=genetic_generations,
individuals=genetic_individuals,
),
)
# Build all representations before publishing any of them.
optimization_solution = await genetic_solution.optimization_solution()
plan = genetic_solution.energy_management_plan()
except Exception:
logger.exception(f"{algorithm}: Energy management optimization failed.")
EnergyManagement._stage = EnergyManagementStage.IDLE
return None
# Publish a consistent set without yielding to another coroutine.
EnergyManagement._genetic_solution = genetic_solution
EnergyManagement._optimization_solution = optimization_solution
EnergyManagement._plan = plan
run_solution = genetic_solution
logger.debug(
"{}: Energy management genetic solution:\n{}",
algorithm,
EnergyManagement._genetic_solution,
)
optimizer = get_optimizer(algorithm)
# --- Optimizers of the registry ---
elif optimizer is not None:
if optimizer is not None:
# Prepare optimization parameters
logger.info(f"{algorithm}: Starting optimzation parameter preparation.")
if EnergyManagement._start_datetime is None: # Make mypy happy - already set by us
@@ -471,6 +363,8 @@ class EnergyManagement(
previous = EnergyManagement._optimizer_runs.get(optimizer.name)
warm_start = None if previous is None else previous.result
try:
# The preparation never fails: invalid inputs get fallbacks (ADR 0006). An
# exception here is a bug, handled like one in the run or the conversion.
if request is None:
parameters = await optimizer.prepare(
start, observation, warm_start, overrides
@@ -479,17 +373,8 @@ class EnergyManagement(
parameters = await optimizer.prepare_from_request(
request, start, observation, warm_start, overrides
)
except Exception:
# Until every optimizer's preparation never fails (ADR 0006).
logger.exception(
f"{algorithm}: Energy management run canceled. "
"Could not prepare optimisation parameters."
)
EnergyManagement._stage = EnergyManagementStage.IDLE
return None
# --- Optimization (CPU-bound → MUST offload) ---
try:
# --- Optimization (CPU-bound → MUST offload) ---
loop = get_running_loop()
result = await loop.run_in_executor(None, optimizer.run, parameters)
+3 -3
View File
@@ -370,9 +370,9 @@ class ConsumerDeadlinePolicy(StrEnum):
automation.
- STRICT:
Keep the deadline. A ONCE consumer without a feasible start makes the
optimization fail; a DAILY consumer is simply not scheduled on days
without a feasible start.
Keep the deadline. A ONCE consumer without a feasible start is left out
of the optimization run (error logged); a DAILY consumer is simply not
scheduled on days without a feasible start.
"""
BEST_EFFORT = "BEST_EFFORT"
@@ -120,10 +120,6 @@ from akkudoktoreos.measurement.batterycapacity import (
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime
if TYPE_CHECKING:
from akkudoktoreos.devices.genetic.battery import (
ElectricVehicleParameters,
SolarPanelBatteryParameters,
)
from akkudoktoreos.devices.profile.batteryprofileruntime import BatteryProfile
@@ -396,7 +392,7 @@ class BatteriesCommonSettings(DevicesBaseSettings):
except ValueError as exc:
raise BatteryResolutionError(f"Battery '{self.device_id}': {exc}") from exc
def _genetic_snapshot(
def snapshot_with_profile(
self, operating_parameters: Optional[BatteryOperatingParameters], use_profile_tables: bool
) -> tuple[BatteryOperatingParameters, Optional["BatteryProfile"]]:
"""Return the snapshot to convert and the profile, loading the profile once.
@@ -407,6 +403,14 @@ class BatteriesCommonSettings(DevicesBaseSettings):
profile that was changed or deleted meanwhile, and the power tables
belong to the same profile version as the snapshot.
Args:
operating_parameters: Resolved snapshot; None resolves at the reference operating
point.
use_profile_tables: Whether the conversion adds the profile's tables.
Returns:
The snapshot and the profile (None without tables).
Raises:
BatteryResolutionError: See ``resolve_operating_parameters``; only
if no snapshot is given.
@@ -425,15 +429,23 @@ class BatteriesCommonSettings(DevicesBaseSettings):
profile,
)
def _genetic_power_parameters(
def power_and_efficiency_fields(
self, p: BatteryOperatingParameters, profile: Optional["BatteryProfile"]
) -> dict[str, Any]:
"""Return the power and efficiency fields of the GENETIC battery parameters.
"""Return the power and efficiency fields of an optimizer's battery parameters.
With power curves from the profile, the rated powers are the highest
powers over SoC; the per-SoC tables limit them in the simulation.
Without (no profile, or the profile allows no charging at this
temperature), the powers resolved at the operating point apply.
Args:
p: The resolved operating parameters.
profile: The battery profile, or None.
Returns:
``max_charge_power_w``, ``max_discharge_power_w`` and, with power curves, the
power limit tables and efficiency curves.
"""
curves = None
if profile is not None:
@@ -1009,78 +1021,6 @@ class BatteriesCommonSettings(DevicesBaseSettings):
"""Measured SoC from which the battery counts as fully charged [%]."""
return self._reference_resolution()[1].detect_percentage
def to_genetic_pv_bat_param(
self,
operating_parameters: Optional[BatteryOperatingParameters] = None,
use_profile_tables: bool = True,
) -> "SolarPanelBatteryParameters":
"""Return SolarPanelBatteryParameters for the GENETIC optimizer.
Args:
operating_parameters: Resolved snapshot to convert, e.g. from
``resolve_current_operating_parameters``. None resolves at the
reference operating point.
use_profile_tables: Whether to add the SoC dependent power limits
and efficiency curves of the profile. False for a snapshot
resolved without profile (see
``resolve_operating_parameters_or_defaults``); requires
``operating_parameters``.
Raises:
BatteryResolutionError: See ``resolve_operating_parameters``.
"""
from akkudoktoreos.devices.genetic.battery import SolarPanelBatteryParameters
p, profile = self._genetic_snapshot(operating_parameters, use_profile_tables)
return SolarPanelBatteryParameters(
device_id=self.device_id,
capacity_wh=p.capacity_wh,
charging_efficiency=p.charging_efficiency,
discharging_efficiency=p.discharging_efficiency,
min_soc_percentage=p.min_soc_percentage,
max_soc_percentage=p.max_soc_percentage,
charge_rates=self.charge_rates,
grid_export_rates=self.grid_export_rates,
**self._genetic_power_parameters(p, profile),
levelized_cost_of_storage_kwh=self.levelized_cost_of_storage_amt_kwh,
)
def to_genetic_ev_bat_param(
self,
operating_parameters: Optional[BatteryOperatingParameters] = None,
use_profile_tables: bool = True,
) -> "ElectricVehicleParameters":
"""Return ElectricVehicleParameters for the GENETIC optimizer.
Args:
operating_parameters: Resolved snapshot to convert, e.g. from
``resolve_current_operating_parameters``. None resolves at the
reference operating point.
use_profile_tables: Whether to add the SoC dependent power limits
and efficiency curves of the profile. False for a snapshot
resolved without profile (see
``resolve_operating_parameters_or_defaults``); requires
``operating_parameters``.
Raises:
BatteryResolutionError: See ``resolve_operating_parameters``.
"""
from akkudoktoreos.devices.genetic.battery import ElectricVehicleParameters
p, profile = self._genetic_snapshot(operating_parameters, use_profile_tables)
return ElectricVehicleParameters(
device_id=self.device_id,
capacity_wh=p.capacity_wh,
charging_efficiency=p.charging_efficiency,
discharging_efficiency=p.discharging_efficiency,
charge_rates=self.charge_rates,
min_soc_percentage=p.min_soc_percentage,
max_soc_percentage=p.max_soc_percentage,
min_soc_deadline_datetime=self.min_soc_deadline_datetime,
min_soc_max_duration_h=self.min_soc_max_duration_h,
**self._genetic_power_parameters(p, profile),
)
@field_validator("charge_rates", mode="before")
def validate_and_sort_charge_rates(cls, v: Any) -> NDArray[Shape["*"], float]:
# None means fallback to default values
@@ -3,7 +3,7 @@
Note: Used for the GENETIC and GENETIC0 algorithm.
"""
from typing import TYPE_CHECKING, Any, Optional, Self
from typing import Any, Optional, Self
from pydantic import Field, computed_field, field_validator, model_validator
@@ -20,9 +20,6 @@ from akkudoktoreos.devices.devicesabc import (
from akkudoktoreos.devices.settings.devicebasesettings import DevicesBaseSettings
from akkudoktoreos.utils.datetimeutil import DateTime, compare_datetimes, to_datetime
if TYPE_CHECKING:
from akkudoktoreos.devices.genetic.homeappliance import HomeApplianceParameters
class HomeApplianceCommonSettings(DevicesBaseSettings):
"""Controllable home appliance device settings.
@@ -309,7 +306,8 @@ class HomeApplianceCommonSettings(DevicesBaseSettings):
"description": (
"What to do when 'deadline_datetime' cannot be met: BEST_EFFORT "
"runs as early as possible instead (warning logged), STRICT keeps "
"the deadline (a ONCE consumer then fails the optimization)."
"the deadline (an appliance that cannot meet it is left out of the "
"run, error logged)."
),
"examples": ["BEST_EFFORT", "STRICT"],
},
@@ -368,30 +366,6 @@ class HomeApplianceCommonSettings(DevicesBaseSettings):
return self.cycle_time_windows.num_cycles()
return self.num_cycles
# ------------------------------------------------------------------
# GENETIC domain conversion
# ------------------------------------------------------------------
def to_genetic_param(self) -> "HomeApplianceParameters":
"""Return HomeApplianceParameters for the GENETIC optimizer."""
from akkudoktoreos.devices.genetic.homeappliance import HomeApplianceParameters
return HomeApplianceParameters(
device_id=self.device_id,
consumption_wh=self.consumption_wh,
duration_h=self.duration_h,
num_cycles=self.effective_num_cycles,
min_cycle_gap_h=self.min_cycle_gap_h,
time_windows=self.cycle_time_windows,
shared_time_windows=self.time_windows,
load_profile_power_w=self.load_profile_power_w,
load_profile_interval_seconds=self.load_profile_interval_seconds,
schedule_mode=self.schedule_mode,
earliest_start_datetime=self.earliest_start_datetime,
deadline_datetime=self.deadline_datetime,
deadline_policy=self.deadline_policy,
)
@computed_field # type: ignore[prop-decorator]
@property
def measurement_keys(self) -> Optional[list[str]]:
@@ -43,7 +43,6 @@ from akkudoktoreos.devices.settings.inverterresolution import (
from akkudoktoreos.utils.datetimeutil import DateTime
if TYPE_CHECKING:
from akkudoktoreos.devices.genetic.inverter import InverterParameters
from akkudoktoreos.devices.profile.inverterprofile import InverterProfile
@@ -674,42 +673,6 @@ class InverterCommonSettings(DevicesBaseSettings):
p = self._effective_parameters()
return p.ac_to_dc_efficiency if p is not None else None
# ------------------------------------------------------------------
# GENETIC domain conversion
# ------------------------------------------------------------------
def to_genetic_param(
self, operating_parameters: Optional[InverterOperatingParameters] = None
) -> "InverterParameters":
"""Return InverterParameters for the GENETIC optimizer.
Args:
operating_parameters: Resolved snapshot to convert, e.g. from
``resolve_current_operating_parameters``. None resolves at the
reference operating point.
Raises:
InverterResolutionError: If the snapshot is resolved here and the
inverter cannot be resolved.
"""
from akkudoktoreos.devices.genetic.inverter import InverterParameters
p = operating_parameters or self.resolve_operating_parameters()
return InverterParameters(
device_id=self.device_id,
max_power_wh=p.max_power_w,
battery_id=self.battery_id,
ac_to_dc_efficiency=p.ac_to_dc_efficiency,
dc_to_ac_efficiency=p.dc_to_ac_efficiency,
dc_to_ac_efficiency_curve=list(p.dc_to_ac_efficiency_curve),
ac_to_dc_efficiency_curve=list(p.ac_to_dc_efficiency_curve),
dc_to_ac_efficiency_reference_load_fraction=(
self.dc_to_ac_efficiency_reference_load_fraction
),
max_ac_charge_power_w=p.max_ac_charge_power_w,
ac_charge_limits_total_charge=p.ac_charge_limits_total_charge,
)
@computed_field # type: ignore[prop-decorator]
@property
def measurement_key_temperature_degc(self) -> str:
@@ -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,
)
@@ -1,22 +1,65 @@
import math
"""Battery and electric vehicle of the GENETIC simulation."""
from dataclasses import dataclass
from typing import Any, Iterator, Optional
import numpy as np
from pydantic import Field, field_validator, model_validator
from akkudoktoreos.devices.devicesabc import validate_efficiency_curve
from akkudoktoreos.devices.settings.batteryresolution import (
BATTERY_SOC_TABLE_POINTS as SOC_TABLE_POINTS,
)
from akkudoktoreos.devices.settings.batterysettings import BATTERY_DEFAULT_CHARGE_RATES
from akkudoktoreos.optimization.genetic.geneticdevices import DeviceParameters
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime
# 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
def _dense_efficiency_table(curve: Optional[list[tuple[float, float]]]) -> Optional[list[float]]:
@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
@@ -25,282 +68,6 @@ def _dense_efficiency_table(curve: Optional[list[tuple[float, float]]]) -> Optio
return [float(value) for value in np.interp(grid, fractions, efficiencies)]
def max_charging_power_field(description: Optional[str] = None) -> float:
if description is None:
description = "Maximum charging power in watts."
# 0: the battery may not charge, e.g. the profile inhibits it at a low temperature.
return Field(default=5000, ge=0, json_schema_extra={"description": description})
def initial_soc_percentage_field(description: str) -> int:
return Field(
default=0, ge=0, le=100, json_schema_extra={"description": description, "examples": [42]}
)
def discharging_efficiency_field(default_value: float) -> float:
return Field(
default=default_value,
gt=0,
le=1,
json_schema_extra={
"description": "A float representing the discharge efficiency of the battery."
},
)
class BaseBatteryParameters(DeviceParameters):
"""Battery Device Simulation Configuration."""
device_id: str = Field(
json_schema_extra={"description": "ID of battery", "examples": ["battery1"]}
)
capacity_wh: int = Field(
gt=0,
json_schema_extra={
"description": "An integer representing the capacity of the battery in watt-hours.",
"examples": [8000],
},
)
charging_efficiency: float = Field(
default=0.88,
gt=0,
le=1,
json_schema_extra={
"description": "A float representing the charging efficiency of the battery."
},
)
discharging_efficiency: float = discharging_efficiency_field(0.88)
max_charge_power_w: Optional[float] = max_charging_power_field()
max_discharge_power_w: Optional[float] = Field(
default=None,
ge=0,
json_schema_extra={
"description": (
"Maximum discharging power in watts. 0 means discharging is inhibited. "
"None uses max_charge_power_w."
),
"examples": [None, 4000],
},
)
initial_soc_percentage: int = initial_soc_percentage_field(
"An integer representing the state of charge of the battery at the **start** of the current hour (not the current state)."
)
min_soc_percentage: int = Field(
default=0,
ge=0,
le=100,
json_schema_extra={
"description": "An integer representing the minimum state of charge (SOC) of the battery in percentage.",
"examples": [10],
},
)
max_soc_percentage: int = Field(
default=100,
ge=0,
le=100,
json_schema_extra={
"description": "An integer representing the maximum state of charge (SOC) of the battery in percentage."
},
)
charge_rates: Optional[list[float]] = Field(
default=None,
json_schema_extra={
"description": "Charge rates as factor of maximum charging power [0.00 ... 1.00]. None denotes all charge rates are available.",
"examples": [[0.0, 0.25, 0.5, 0.75, 1.0], None],
},
)
grid_export_rates: Optional[list[float]] = Field(
default=None,
json_schema_extra={
"description": (
"Battery-to-grid export rates as factor of maximum discharge "
"power ]0.00 ... 1.00]. These levels are available to algorithms "
"that explicitly enable battery-to-grid export. None leaves the "
"choice of export levels to the caller."
),
"examples": [[0.25, 0.5, 0.75, 1.0], [1.0], None],
},
)
charge_power_limit_w_by_soc: Optional[list[float]] = Field(
default=None,
json_schema_extra={
"description": (
"Maximum charging power [W] per state of charge, e.g. from a battery "
f"profile. {SOC_TABLE_POINTS} values, index i is the limit at SoC i %. "
"Further limits max_charge_power_w. None means no SoC dependent limit."
),
"examples": [None],
},
)
discharge_power_limit_w_by_soc: Optional[list[float]] = Field(
default=None,
json_schema_extra={
"description": (
"Maximum discharging power [W] per state of charge, e.g. from a battery "
f"profile. {SOC_TABLE_POINTS} values, index i is the limit at SoC i %. "
"Further limits max_discharge_power_w. None means no SoC dependent limit."
),
"examples": [None],
},
)
charging_efficiency_curve: Optional[list[tuple[float, float]]] = Field(
default=None,
json_schema_extra={
"description": (
"Power dependent charging efficiency as a list of (power_fraction, "
"efficiency) points. The power fraction is the charging power relative "
"to max_charge_power_w [0.0 ... 1.0]; points must be strictly increasing "
"in power fraction, efficiencies in (0, 1]. Values are interpolated "
"linearly and clamped to the first/last point. When set, the curve "
"replaces charging_efficiency in the simulation. None means constant "
"charging_efficiency."
),
"examples": [None, [[0.0, 0.975], [0.5, 0.96], [1.0, 0.94]]],
},
)
discharging_efficiency_curve: Optional[list[tuple[float, float]]] = Field(
default=None,
json_schema_extra={
"description": (
"Power dependent discharging efficiency as a list of (power_fraction, "
"efficiency) points. The power fraction is the discharging power "
"relative to max_discharge_power_w [0.0 ... 1.0]; same rules as "
"charging_efficiency_curve. When set, the curve replaces "
"discharging_efficiency in the simulation. None means constant "
"discharging_efficiency."
),
"examples": [None, [[0.0, 0.975], [1.0, 0.96]]],
},
)
@field_validator("charge_power_limit_w_by_soc", "discharge_power_limit_w_by_soc")
@classmethod
def _validate_power_limit_by_soc(cls, value: Optional[list[float]]) -> Optional[list[float]]:
if value is None:
return None
if len(value) != SOC_TABLE_POINTS:
raise ValueError(
f"A power limit table needs {SOC_TABLE_POINTS} values (SoC 0 % ... 100 %), "
f"got {len(value)}."
)
for power_w in value:
if not math.isfinite(power_w) or power_w < 0:
raise ValueError(f"Power limits must be finite and >= 0 W, got {power_w}.")
return value
@field_validator("charging_efficiency_curve", "discharging_efficiency_curve")
@classmethod
def _validate_efficiency_curve(
cls, value: Optional[list[tuple[float, float]]]
) -> Optional[list[tuple[float, float]]]:
return validate_efficiency_curve(value)
class SolarPanelBatteryParameters(BaseBatteryParameters):
"""PV battery device simulation configuration."""
levelized_cost_of_storage_kwh: float = Field(
default=0.0,
ge=0.0,
json_schema_extra={
"description": (
"Levelized cost of storage applied once to each kWh delivered "
"by the battery [EUR/kWh]."
),
"examples": [0.12],
},
)
max_charge_power_w: Optional[float] = max_charging_power_field()
full_charge_soc_percentage: Optional[int] = Field(
default=None,
ge=1,
le=100,
json_schema_extra={
"description": (
"State of charge a due full charge has to reach at least once "
"before 'full_charge_deadline_datetime' [%]. Must not exceed "
"'max_soc_percentage'. None means no full charge is due."
),
"examples": [None, 100],
},
)
full_charge_deadline_datetime: Optional[DateTime] = Field(
default=None,
json_schema_extra={
"description": (
"Moment by which 'full_charge_soc_percentage' has to be reached. "
"A date time without timezone is read as local time. None means "
"end of the optimization horizon."
),
"examples": [None, "2026-11-20T07:00:00+01:00"],
},
)
@field_validator("full_charge_deadline_datetime", mode="before")
@classmethod
def transform_full_charge_deadline(cls, value: Any) -> Optional[DateTime]:
"""Accept the usual date time representations, naive input is local time."""
if value is None:
return None
return to_datetime(value)
@model_validator(mode="after")
def validate_full_charge_target(self) -> "SolarPanelBatteryParameters":
"""A full charge target above the maximum SoC could never be reached."""
if (
self.full_charge_soc_percentage is not None
and self.full_charge_soc_percentage > self.max_soc_percentage
):
raise ValueError("full_charge_soc_percentage must be <= max_soc_percentage")
return self
class ElectricVehicleParameters(BaseBatteryParameters):
"""Battery Electric Vehicle Device Simulation Configuration."""
device_id: str = Field(
json_schema_extra={"description": "ID of electric vehicle", "examples": ["ev1"]}
)
discharging_efficiency: float = discharging_efficiency_field(1.0)
initial_soc_percentage: int = initial_soc_percentage_field(
"An integer representing the current state of charge (SOC) of the battery in percentage."
)
min_soc_deadline_datetime: Optional[DateTime] = Field(
default=None,
json_schema_extra={
"description": (
"Absolute moment by which 'min_soc_percentage' has to be "
"reached (departure time). A date time without timezone is read "
"as local time. None means end of the optimization horizon."
),
"examples": [None, "2026-07-16T07:00:00+02:00"],
},
)
min_soc_max_duration_h: Optional[float] = Field(
default=None,
gt=0,
allow_inf_nan=False,
json_schema_extra={
"description": (
"Maximum time from the start of the optimization until "
"'min_soc_percentage' has to be reached [h]. Combined with "
"'min_soc_deadline_datetime' the earlier of the two applies."
),
"examples": [None, 6.0],
},
)
@field_validator("min_soc_deadline_datetime", mode="before")
@classmethod
def transform_deadline_to_datetime(cls, value: Any) -> Optional[DateTime]:
"""Accept the usual date time representations, naive input is local time."""
if value is None:
return None
return to_datetime(value)
class _PowerCurves:
"""Battery profile data of a simulated battery, prepared for fast access.
@@ -340,7 +107,7 @@ class _PowerCurves:
def __init__(
self,
parameters: "BaseBatteryParameters",
parameters: GeneticBatteryParameters,
capacity_wh: float,
max_charge_power_w: float,
max_discharge_power_w: float,
@@ -387,7 +154,7 @@ def _table_entry(table: list[float], index: int) -> float:
return table[index]
class Battery:
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.
@@ -403,7 +170,7 @@ class Battery:
def __init__(
self,
parameters: BaseBatteryParameters,
parameters: GeneticBatteryParameters,
prediction_hours: int,
slot_duration_h: float = 1.0,
first_slot_fraction: float = 1.0,
@@ -439,26 +206,17 @@ class Battery:
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
if isinstance(self.parameters, SolarPanelBatteryParameters)
else 0.0
)
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(BATTERY_DEFAULT_CHARGE_RATES, dtype=float)
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
# Only assign for storage battery
self.min_soc_percentage = (
self.parameters.min_soc_percentage
if isinstance(self.parameters, SolarPanelBatteryParameters)
else 0
)
self.min_soc_percentage = self.parameters.min_soc_percentage
self.max_soc_percentage = self.parameters.max_soc_percentage
# Initialize state of charge
@@ -886,7 +644,7 @@ class Battery:
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 isinstance(self.parameters, ElectricVehicleParameters):
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.
@@ -3,7 +3,7 @@ from typing import List, Sequence
from loguru import logger
class Heatpump:
class GeneticHeatpump:
MAX_HEAT_OUTPUT = 5000
"""Maximum heating power in watts"""
@@ -135,7 +135,7 @@ if __name__ == "__main__":
initial_indoor_temperature = 15 # Initial indoor temperature
insulation_efficiency = 0.8 # Insulation efficiency
desired_indoor_temperature = 20 # Desired indoor temperature
hp = Heatpump(max_heating_power, 24) # Initialize heat pump with prediction hours
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))
@@ -2,63 +2,93 @@
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. Given a set of
requested start times, `HomeAppliance` repairs them into a
feasible, chronologically ordered schedule and produces the resulting
per-slot energy curve.
(cycles), within one or more allowed time windows.
Time windows are always expressed as a `CycleTimeWindowSequence`
(see ``akkudoktoreos.config.configabc``): each contained 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.
When no windows are configured, every cycle defaults to a single
window spanning the full prediction horizon (i.e. unconstrained).
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.
Cycle start times are repaired according to the following rules:
1. Round and clip the requested start to the simulation horizon.
2. Snap each cycle's start to the nearest start allowed by that
cycle's own time window.
3. Sort all cycle starts chronologically, keeping each start paired
with the cycle (and therefore the allowed-start mask) it belongs
to.
4. Walk the sorted starts and push any cycle that starts too soon
after its predecessor to the next start allowed by its own
window, enforcing the appliance duration plus the configured
minimum idle gap.
5. Generate the combined hourly load curve from the final starts.
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 typing import Any, Optional, Self
from dataclasses import dataclass
from enum import StrEnum
from typing import Any, Optional
import numpy as np
from loguru import logger
from pydantic import Field, field_validator, model_validator
from akkudoktoreos.config.configabc import (
CycleTimeWindowSequence,
TimeWindow,
TimeWindowSequence,
ValueTimeWindow,
from akkudoktoreos.optimization.genetic.devices.genetictimewindow import (
GeneticTimeWindow,
)
from akkudoktoreos.devices.devicesabc import (
ConsumerDeadlinePolicy,
ConsumerScheduleMode,
validate_home_appliance_load_definition,
)
from akkudoktoreos.optimization.genetic.geneticdevices import DeviceParameters
from akkudoktoreos.utils.datetimeutil import (
DateTime,
Duration,
compare_datetimes,
to_datetime,
to_duration,
to_time,
)
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,
@@ -115,207 +145,12 @@ def resample_power_to_slot_energy(
return out
class HomeApplianceParameters(DeviceParameters):
"""Configuration for a simulated home appliance device."""
device_id: str = Field(
json_schema_extra={
"description": "ID of home appliance",
"examples": ["dishwasher"],
}
)
consumption_wh: Optional[int] = Field(
default=None,
gt=0,
json_schema_extra={
"description": (
"An integer representing the energy consumption "
"of a household device in watt-hours."
),
"examples": [2000],
},
)
duration_h: Optional[int] = Field(
default=None,
gt=0,
json_schema_extra={
"description": (
"An integer representing the usage duration of a household device in hours."
),
"examples": [3],
},
)
num_cycles: int = Field(
default=1,
gt=0,
json_schema_extra={
"description": "Number of cycles the appliance must run.",
"examples": [2],
},
)
completed_cycles: int = Field(
default=0, ge=0, description="Cycles already completed on the first planning day."
)
run_started_datetime: Optional[DateTime] = Field(
default=None,
json_schema_extra={
"description": (
"Start of the run in progress, None when the appliance is not "
"running. The run is kept until the device reports it as finished: "
"its remaining load is fixed from now on, independent of windows, "
"deadline and gene, and it is not counted in 'completed_cycles' yet."
),
"examples": [None, "2026-11-14T00:47:45+01:00"],
},
)
min_cycle_gap_h: int = Field(
default=0,
ge=0,
json_schema_extra={
"description": (
"Minimum idle time between the end of one cycle and the start of the next cycle."
),
"examples": [1],
},
)
time_windows: Optional[CycleTimeWindowSequence] = Field(
default=None,
json_schema_extra={
"description": (
"Allowed per-cycle time windows. Each window's `value` "
"encodes the 0-based cycle index it applies to; multiple "
"windows may share a cycle index. When omitted, every "
"cycle is unconstrained across the full prediction "
"horizon."
),
"examples": [
[
{
"start_time": "10:00",
"duration": "3 hours",
"value": 0,
},
],
],
},
)
shared_time_windows: Optional[TimeWindowSequence] = Field(
default=None,
description="Allowed recurring windows shared by every cycle; intersected with per-cycle windows.",
)
load_profile_power_w: Optional[list[float]] = Field(
default=None,
json_schema_extra={
"description": (
"Explicit load profile describing a single complete run as a "
"sequence of non-negative power values in watts. Each value "
"covers 'load_profile_interval_seconds'. Mutually exclusive with "
"consumption_wh/duration_h."
),
"examples": [[200.0, 2000.0, 1800.0, 100.0]],
},
)
load_profile_interval_seconds: Optional[int] = Field(
default=None,
gt=0,
json_schema_extra={
"description": (
"Duration of one 'load_profile_power_w' step in seconds. Defaults "
"to the configured optimization interval when a profile is given."
),
"examples": [900, 3600],
},
)
schedule_mode: ConsumerScheduleMode = Field(
default=ConsumerScheduleMode.ONCE,
json_schema_extra={
"description": (
"Scheduling mode: ONCE (a single run within the horizon) or DAILY "
"(one run per local calendar day with a feasible full run)."
),
"examples": ["ONCE", "DAILY"],
},
)
earliest_start_datetime: Optional[DateTime] = Field(
default=None,
json_schema_extra={
"description": (
"Absolute earliest moment the run may start. Starts before it are "
"dropped, in addition to 'time_windows' and the horizon. A date "
"time without timezone is read as local time. This bound is never "
"relaxed."
),
"examples": [None, "2026-07-15T20:00:00+02:00"],
},
)
deadline_datetime: Optional[DateTime] = Field(
default=None,
json_schema_extra={
"description": (
"Absolute deadline: the complete run must have *finished* at or "
"before this moment (e.g. end of the day, or 03:00 tonight). A "
"date time without timezone is read as local time. See "
"'deadline_policy' for what happens when no start can meet it."
),
"examples": [None, "2026-07-16T03:00:00+02:00"],
},
)
deadline_policy: ConsumerDeadlinePolicy = Field(
default=ConsumerDeadlinePolicy.BEST_EFFORT,
json_schema_extra={
"description": (
"What to do when 'deadline_datetime' cannot be met: BEST_EFFORT "
"runs as early as possible instead (warning logged), STRICT keeps "
"the deadline (a ONCE consumer then fails the optimization)."
),
"examples": ["BEST_EFFORT", "STRICT"],
},
)
@field_validator(
"earliest_start_datetime", "deadline_datetime", "run_started_datetime", mode="before"
)
@classmethod
def transform_to_datetime(cls, value: Any) -> Optional[DateTime]:
"""Accept the usual date time representations, naive input is local time."""
if value is None:
return None
return to_datetime(value)
@model_validator(mode="after")
def validate_load_definition(self) -> Self:
"""Ensure a complete load definition and valid completed-cycle count."""
if self.completed_cycles > self.num_cycles:
raise ValueError("completed_cycles must not exceed num_cycles.")
validate_home_appliance_load_definition(
load_profile_power_w=self.load_profile_power_w,
load_profile_interval_seconds=self.load_profile_interval_seconds,
consumption_wh=self.consumption_wh,
duration_h=self.duration_h,
)
return self
@model_validator(mode="after")
def validate_schedule_bounds(self) -> Self:
"""Reject an empty scheduling interval."""
if self.earliest_start_datetime is not None and self.deadline_datetime is not None:
if compare_datetimes(self.deadline_datetime, self.earliest_start_datetime).le:
raise ValueError(
f"deadline_datetime {self.deadline_datetime} must be after "
f"earliest_start_datetime {self.earliest_start_datetime}."
)
return self
class HomeAppliance:
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 the start-time
repair algorithm.
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
@@ -324,12 +159,12 @@ class HomeAppliance:
def __init__(
self,
parameters: HomeApplianceParameters,
parameters: GeneticHomeApplianceParameters,
optimization_hours: int,
prediction_hours: int,
slot_duration_h: float = 1.0,
) -> None:
"""Initializes the appliance and builds its allowed-start masks.
"""Initializes the appliance.
Args:
parameters: The appliance's configuration.
@@ -351,6 +186,8 @@ class HomeAppliance:
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
@@ -376,26 +213,6 @@ class HomeAppliance:
# Start times for remaining cycles, in chronological order.
self.start_hours: list[int] = []
# Absolute cycle index corresponding to each remaining cycle.
#
# Example:
# num_cycles = 4
# completed_cycles = 2
#
# remaining_cycle_indices = [2, 3]
self.remaining_cycle_indices: list[int] = []
# start_allowed[k][hour]
#
# k is the index into remaining_cycle_indices (NOT into the
# chronologically-sorted self.start_hours).
self.start_allowed: list[np.ndarray] = []
self.start_earliest: list[int] = []
self.start_latest: list[int] = []
self._setup()
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:
@@ -520,7 +337,7 @@ class HomeAppliance:
"""
pinned = 0
if self.run_in_progress and (
self.schedule_mode == ConsumerScheduleMode.ONCE or self.pinned_run_date == first_date
self.schedule_mode == GeneticScheduleMode.ONCE or self.pinned_run_date == first_date
):
pinned = 1
return min(self.num_cycles, self.completed_cycles + pinned)
@@ -596,7 +413,7 @@ class HomeAppliance:
if (
allowed
or self.deadline_datetime is None
or self.deadline_policy == ConsumerDeadlinePolicy.STRICT
or self.deadline_policy == GeneticDeadlinePolicy.STRICT
):
return allowed
@@ -624,6 +441,39 @@ class HomeAppliance:
)
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,
*,
@@ -632,6 +482,7 @@ class HomeAppliance:
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.
@@ -641,11 +492,13 @@ class HomeAppliance:
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).
"""
run_slots = self.run_slots
if run_slots is None:
run_slots = self.run_slots
if run_slots <= 0:
return []
@@ -671,9 +524,7 @@ class HomeAppliance:
raise ValueError("Cycle index is outside the configured cycle range.")
cycle_windows = [
window
for window in (
self.parameters.time_windows.windows if self.parameters.time_windows else []
)
for window in self.cycle_windows
if window.value is not None and int(window.value) == cycle_index
]
@@ -683,7 +534,7 @@ class HomeAppliance:
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.windows, start_dt, run_duration)
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)
@@ -693,7 +544,11 @@ class HomeAppliance:
@staticmethod
def _windows_allow_run(
windows: Sequence[TimeWindow], start: DateTime, duration: Duration, *, merge: bool = False
windows: Sequence[GeneticTimeWindow],
start: DateTime,
duration: Duration,
*,
merge: bool = False,
) -> bool:
"""Check full coverage including windows anchored on previous local dates.
@@ -717,7 +572,7 @@ class HomeAppliance:
continue
if window.month is not None and anchor.month != window.month:
continue
opening, closing = window._window_start_end(anchor)
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:
@@ -792,32 +647,6 @@ class HomeAppliance:
# Setup
# ------------------------------------------------------------------
def _setup(self) -> None:
"""Sets up appliance parameters and default time windows.
When no ``time_windows`` are configured, builds a single
placeholder window spanning the full prediction horizon with
``value`` left unset. ``CycleTimeWindowSequence.cycles_to_matrix``
ignores windows whose ``value`` is ``None``, so this window never
matches any cycle; every remaining cycle then falls through to
the "no window for this cycle" branch in
``_build_cycle_start_allowed``, which treats it as unconstrained.
The net effect is the same as having no windows at all, without
assigning cycles an explicit (and misleadingly meaningful)
``value``.
"""
if self.parameters.time_windows is None:
self.parameters.time_windows = CycleTimeWindowSequence(
windows=[
ValueTimeWindow(
start_time=to_time("00:00"),
duration=to_duration(f"{self.prediction_hours} hours"),
),
]
)
self._build_start_allowed()
@property
def num_remaining_cycles(self) -> int:
"""int: Number of cycles which still have to be scheduled."""
@@ -826,9 +655,7 @@ class HomeAppliance:
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,
and rebuilds the allowed-start masks for the cycles that
remain.
Clears any previously scheduled start times and load curve.
Args:
completed_cycles: Number of cycles completed so far.
@@ -841,353 +668,6 @@ class HomeAppliance:
self.start_hours = []
self.reset_load_curve()
self._build_start_allowed()
# ------------------------------------------------------------------
# Time-window handling
# ------------------------------------------------------------------
def _build_start_allowed(self) -> None:
"""Builds allowed start positions for all remaining cycles."""
if self.parameters.time_windows is None:
raise ValueError("Expected time windows in parameters, got {self.parameters}.")
self.start_allowed = []
self.start_earliest = []
self.start_latest = []
self.remaining_cycle_indices = list(
range(
self.completed_cycles,
self.num_cycles,
)
)
if not self.remaining_cycle_indices:
return
start_datetime = to_datetime().set(
hour=0,
minute=0,
second=0,
microsecond=0,
)
end_datetime = start_datetime.add(
seconds=self.prediction_hours * self.slot_interval_seconds,
)
interval = to_duration(self.slot_interval_seconds)
self._build_cycle_start_allowed(
self.parameters.time_windows,
start_datetime,
end_datetime,
interval,
)
def _build_cycle_start_allowed(
self,
time_windows: CycleTimeWindowSequence,
start_datetime: DateTime,
end_datetime: DateTime,
interval: Duration,
) -> None:
"""Builds allowed starts from per-cycle windows.
Args:
time_windows: Windows associated with individual cycles.
start_datetime: Start of the simulation horizon.
end_datetime: End of the simulation horizon.
interval: Step size used to sample the cycle windows.
"""
cycle_indices, matrix = time_windows.cycles_to_matrix(
start_datetime=start_datetime,
end_datetime=end_datetime,
interval=interval,
)
cycle_to_row = {cycle: row for row, cycle in enumerate(cycle_indices)}
max_start = max(
0,
self.prediction_hours - self.run_slots,
)
# The matrix tells us which individual *steps* are inside
# the cycle window. We still have to check that the complete
# appliance duration fits inside the window.
for cycle in self.remaining_cycle_indices:
row_index = cycle_to_row.get(cycle)
if row_index is None:
# No window for this cycle -> unconstrained.
allowed = np.zeros(
self.prediction_hours,
dtype=bool,
)
allowed[: max_start + 1] = True
else:
allowed = self._build_duration_feasibility(
matrix[row_index],
)
self.start_allowed.append(allowed)
allowed_indices = np.flatnonzero(allowed)
if len(allowed_indices):
self.start_earliest.append(int(allowed_indices[0]))
self.start_latest.append(int(allowed_indices[-1]))
else:
self.start_earliest.append(0)
self.start_latest.append(max_start)
def _build_duration_feasibility(
self,
window_steps: np.ndarray,
) -> np.ndarray:
"""Returns starts where the complete appliance fits in a window.
A start ``s`` is feasible when every step in
``window_steps[s : s + duration_h]`` lies inside the cycle's
window (i.e. sums to ``duration_h``).
Args:
window_steps: Per-hour membership of the cycle's window
(1.0 inside the window, 0.0 outside), one value per
hour of the prediction horizon.
Returns:
Boolean mask, one entry per hour of the prediction
horizon, ``True`` where a cycle of length ``duration_h``
can start without leaving the window.
"""
horizon = len(window_steps)
max_start = max(
0,
horizon - self.run_slots,
)
allowed = np.zeros(
horizon,
dtype=bool,
)
if self.run_slots > horizon:
return allowed
# Rolling sum of `duration_h` consecutive steps, aligned so
# that window_sums[s] == sum(window_steps[s : s + duration_h]).
cumulative = np.concatenate(([0.0], np.cumsum(window_steps)))
window_sums = cumulative[self.run_slots :] - cumulative[: -self.run_slots]
allowed[: max_start + 1] = window_sums[: max_start + 1] == float(self.run_slots)
return allowed
# ------------------------------------------------------------------
# Scheduling / repair
# ------------------------------------------------------------------
def set_starting_times(
self,
start_hours: list[int],
) -> list[int]:
"""Sets and repairs the start times of all remaining cycles.
See the module docstring for the repair algorithm.
Args:
start_hours: Requested start hour for each remaining
cycle, in the same order as ``remaining_cycle_indices``
(i.e. matching ``self.start_allowed``).
Returns:
The repaired, chronologically ordered start hours.
Raises:
ValueError: If ``start_hours`` does not have exactly
``num_remaining_cycles`` entries.
"""
if len(start_hours) != self.num_remaining_cycles:
raise ValueError(
f"Expected {self.num_remaining_cycles} start times, got {len(start_hours)}."
)
if self.num_remaining_cycles == 0:
self.start_hours = []
self._build_load_curve()
return []
max_start = max(
0,
self.prediction_hours - self.run_slots,
)
# 1. Round and clip.
starts = [
max(
0,
min(
int(round(start)),
max_start,
),
)
for start in start_hours
]
# 2. Snap each cycle to its nearest allowed start, keeping the
# start paired with the cycle (start_allowed index) it
# belongs to.
repaired = [
(
self._repair_start(
start,
cycle_index,
max_start,
),
cycle_index,
)
for cycle_index, start in enumerate(starts)
]
# 3. Sort by start time, keeping each cycle's own index
# attached so its allowed-start mask is still used
# correctly in step 4.
repaired.sort(key=lambda pair: pair[0])
# 4. Enforce duration + minimum idle gap. Each cycle is
# pushed forward, if needed, to the next start allowed by
# its *own* window.
min_next_start = self.run_slots + math.ceil(self.min_cycle_gap_h / self.slot_duration_h)
final_starts = [repaired[0][0]]
for index in range(1, len(repaired)):
_, cycle_index = repaired[index]
earliest = final_starts[index - 1] + min_next_start
candidate = self._first_allowed_start_at_or_after(
cycle_index=cycle_index,
earliest=earliest,
)
if candidate is None:
# No valid start remains for this cycle.
final_starts.append(max_start)
else:
final_starts.append(candidate)
# 5. Reconstruct load curve from the final schedule.
self.start_hours = final_starts
self._build_load_curve()
return list(self.start_hours)
def _repair_start(
self,
start: int,
cycle_index: int,
max_start: int,
) -> int:
"""Snaps a start to the nearest allowed start.
Args:
start: Requested (already rounded and clipped) start
hour.
cycle_index: Index into ``self.start_allowed`` for the
cycle being repaired.
max_start: Latest hour at which any cycle may start
without exceeding the prediction horizon, used as a
fallback when the cycle has no allowed start at all.
Returns:
The nearest hour allowed for this cycle, or ``max_start``
if the cycle has no allowed start.
"""
allowed = self.start_allowed[cycle_index]
if not np.any(allowed):
# Same fallback as the vectorized implementation.
return max_start
if allowed[start]:
return start
allowed_indices = np.flatnonzero(allowed)
distances = np.abs(allowed_indices - start)
return int(allowed_indices[np.argmin(distances)])
def _first_allowed_start_at_or_after(
self,
cycle_index: int,
earliest: int,
) -> int | None:
"""Returns the first allowed start at or after ``earliest``.
Args:
cycle_index: Index into ``self.start_allowed`` for the
cycle being scheduled.
earliest: Earliest acceptable start hour.
Returns:
The first allowed hour ``>= earliest``, or ``None`` if no
such hour exists.
"""
allowed = self.start_allowed[cycle_index]
allowed_indices = np.flatnonzero(allowed)
if len(allowed_indices) == 0:
return None
position = np.searchsorted(
allowed_indices,
max(0, earliest),
side="left",
)
if position >= len(allowed_indices):
return None
return int(allowed_indices[position])
# ------------------------------------------------------------------
# Backwards-compatible single-cycle interface
# ------------------------------------------------------------------
def set_starting_time(
self,
start_hour: int,
global_start_hour: int = 0,
) -> int:
"""Sets the start time of the first remaining cycle.
Args:
start_hour: Requested start hour for the first remaining
cycle.
global_start_hour: Retained for API compatibility with
the old, single-cycle implementation. Unused.
Returns:
The repaired start hour of the first remaining cycle, or
``start_hour`` unchanged if there are no remaining
cycles.
"""
if self.num_remaining_cycles == 0:
self.reset_load_curve()
return start_hour
if self.start_hours:
starts = list(self.start_hours)
else:
starts = [self.start_earliest[index] for index in range(self.num_remaining_cycles)]
starts[0] = start_hour
repaired = self.set_starting_times(starts)
return repaired[0]
# ------------------------------------------------------------------
# Load curve
@@ -1,151 +1,72 @@
"""Inverter of the GENETIC simulation."""
from bisect import bisect_left
from dataclasses import dataclass
from typing import Optional
from loguru import logger
from pydantic import Field, field_validator
from akkudoktoreos.devices.devicesabc import (
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,
validate_efficiency_curve,
)
from akkudoktoreos.devices.genetic.battery import Battery
from akkudoktoreos.optimization.genetic.geneticdevices import DeviceParameters
from akkudoktoreos.prediction.interpolator import get_eos_load_interpolator
from akkudoktoreos.optimization.genetic.geneticloadinterpolator import (
get_genetic_load_interpolator,
)
from akkudoktoreos.utils.gridinterpolator import GridInterpolatorBackend
class InverterParameters(DeviceParameters):
"""Inverter Device Simulation Configuration."""
@dataclass(frozen=True, slots=True)
class GeneticInverterParameters:
"""An inverter of the simulation, derived from its request.
device_id: str = Field(
json_schema_extra={"description": "ID of inverter", "examples": ["inverter1"]}
)
max_power_wh: float = Field(gt=0, json_schema_extra={"examples": [10000]})
battery_id: Optional[str] = Field(
default=None,
json_schema_extra={"description": "ID of battery", "examples": [None, "battery1"]},
)
ac_to_dc_efficiency: float = Field(
default=1.0,
ge=0,
le=1,
json_schema_extra={
"description": (
"Efficiency of AC to DC conversion (for AC/grid charging of battery). "
"Set to 0 to disable AC charging via inverter. "
"Default 1.0 for backward compatibility (no additional inverter loss)."
),
"examples": [0.95, 1.0, 0.0],
},
)
dc_to_ac_efficiency: float = Field(
default=1.0,
gt=0,
le=1,
json_schema_extra={
"description": (
"Efficiency of DC to AC conversion (for battery discharging to AC load/grid). "
"Default 1.0 for backward compatibility (no additional inverter loss)."
),
"examples": [0.95, 1.0],
},
)
dc_to_ac_efficiency_curve: Optional[list[tuple[float, float]]] = Field(
default=None,
json_schema_extra={
"description": (
"Load-dependent efficiency of DC to AC conversion as a list of "
"(load_fraction, efficiency) points. The load fraction is the AC power "
"of the conversion relative to max_power_wh [0.0 ... 1.0]; points must be "
"strictly increasing in load fraction, efficiencies in (0, 1]. Values are "
"interpolated linearly and clamped to the first/last point. When set, the "
"curve replaces dc_to_ac_efficiency. "
"Default None (constant dc_to_ac_efficiency)."
),
"examples": [None, [[0.02, 0.8], [0.07, 0.93], [0.3, 0.96], [1.0, 0.95]]],
},
)
dc_to_ac_efficiency_reference_load_fraction: float = Field(
default=0.06,
ge=0,
le=1,
json_schema_extra={
"description": (
"Load fraction at which dc_to_ac_efficiency_curve is evaluated where "
"stored battery energy is valued without a specific conversion "
"(e.g. remaining battery energy at the end of the horizon, AC charge "
"break-even). Should represent the typical load the battery serves, "
"e.g. the night-time base load. Only used with dc_to_ac_efficiency_curve. "
"Default 0.06."
),
"examples": [0.06, 0.1],
},
)
ac_to_dc_efficiency_curve: Optional[list[tuple[float, float]]] = Field(
default=None,
json_schema_extra={
"description": (
"Load-dependent efficiency of AC to DC conversion (AC/grid charging of the "
"battery) as a list of (load_fraction, efficiency) points. The load "
"fraction is the AC power drawn relative to max_power_wh [0.0 ... 1.0]; "
"same rules as dc_to_ac_efficiency_curve. When set, the curve replaces "
"ac_to_dc_efficiency for the energy drawn from the grid; "
"ac_to_dc_efficiency still converts the AC charge power limit and should "
"be the efficiency at that limit. Default None (constant "
"ac_to_dc_efficiency)."
),
"examples": [None, [[0.05, 0.86], [0.3, 0.96], [1.0, 0.96]]],
},
)
max_ac_charge_power_w: Optional[float] = Field(
default=None,
ge=0,
json_schema_extra={
"description": (
"Maximum AC charging power in watts. "
"None means no additional limit (battery's own max_charge_power_w applies). "
"Set to 0 to disable AC charging."
),
"examples": [None, 0, 5000],
},
)
ac_charge_limits_total_charge: bool = Field(
default=False,
json_schema_extra={
"description": (
"True if the AC charge setpoint caps the battery's total charge power, "
"PV included. PV surplus above it is exported, not stored. False keeps "
"the default model: PV surplus charges first and the grid adds "
"ac_charge x max_charge_power_w on top."
),
"examples": [False, True],
},
)
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.
"""
@field_validator("dc_to_ac_efficiency_curve", "ac_to_dc_efficiency_curve")
@classmethod
def _validate_efficiency_curves(
cls, value: Optional[list[tuple[float, float]]]
) -> Optional[list[tuple[float, float]]]:
return validate_efficiency_curve(value)
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 Inverter:
class GeneticInverter:
"""Inverter of the simulation: converts PV, battery and grid energy within its power."""
def __init__(
self,
parameters: InverterParameters,
battery: Optional[Battery] = None,
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: InverterParameters = parameters
self.battery: Optional[Battery] = battery
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()
@@ -162,7 +83,9 @@ class Inverter:
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_eos_load_interpolator()
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
@@ -196,7 +119,7 @@ class Inverter:
"""
if self.dc_to_ac_efficiency_curve is None:
return self.dc_to_ac_efficiency
curve: list[tuple[float, float]] = self.dc_to_ac_efficiency_curve
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
@@ -320,7 +243,7 @@ class Inverter:
if not battery or requested_ac_wh <= 0.0:
return 0.0, 0.0
scale = self.first_slot_fraction if hour == 0 else 1.0
if type(battery) is not Battery:
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
@@ -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")
@@ -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
@@ -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
@@ -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)
+22 -107
View File
@@ -10,7 +10,7 @@ import sys
import traceback
from contextlib import asynccontextmanager
from enum import Enum
from typing import Annotated, Any, AsyncGenerator, Dict, List, Optional, Union
from typing import Annotated, Any, AsyncGenerator, Dict, List, NoReturn, Optional, Union
from urllib.parse import urljoin, urlsplit
import psutil
@@ -57,8 +57,6 @@ from akkudoktoreos.core.types import (
)
from akkudoktoreos.core.version import __version__
from akkudoktoreos.devices.devices import ResourceKey
from akkudoktoreos.optimization.genetic.configrequest import ConfigOptimizationRequest
from akkudoktoreos.optimization.genetic.geneticsolution import GeneticSolution
from akkudoktoreos.optimization.optimization import (
OptimizationAlgorithm,
OptimizationSolution,
@@ -1869,74 +1867,31 @@ def fastapi_energy_management_optimization_solution_get() -> OptimizationSolutio
return solution
@app.get("/v1/energy-management/optimization/solution/{algorithm}", tags=["energy-management"])
async def fastapi_energy_management_optimization_solution_algorithm_get(
algorithm: OptimizationAlgorithm,
) -> GeneticSolution:
"""Get the latest algorithm specific solution of the optimization.
@app.get(
"/v1/energy-management/optimization/solution/{algorithm}",
tags=["energy-management"],
include_in_schema=False,
response_model=None,
)
def fastapi_energy_management_optimization_solution_unknown_get(algorithm: str) -> NoReturn:
"""Answer a solution request for an algorithm without its own solution endpoint.
Optimizers of the registry serve their own solution path (e.g. ``.../solution/GENETIC0``).
The registered optimizers serve their solutions from their own routers, which take
precedence; any other algorithm name is unknown.
Args:
algorithm: Optimization algorithm
algorithm: Name of the requested optimization algorithm.
Raises:
EOSProblem: Always, with status 404.
"""
solution: Optional[GeneticSolution] = None
if algorithm not in get_config().optimization.algorithms:
raise EOSProblem(
status=404,
title="Algorithm specific optimization solution retrieval failed",
detail=f"Optimization algorithm '{algorithm}' unknown.",
)
if algorithm == OptimizationAlgorithm.GENETIC:
solution = get_ems().genetic_solution()
if solution is None:
raise EOSProblem(
status=404,
title="Algorithm specific optimization solution retrieval failed",
detail=(
f"Can not get the '{algorithm}' optimization solution.\n"
f"Did you configure automatic '{algorithm}' optimization?\n"
"Did you run the optimization/ energy management?"
),
)
return solution
@app.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() -> 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.
"""
retained = get_ems().genetic_solution()
if retained is None:
raise EOSProblem(
status=404,
title="Optimization solution report retrieval failed",
detail="Can not get the 'GENETIC' optimization solution.",
)
snapshot = retained.model_copy(deep=True)
# matplotlib is only needed for the PDF report; import it on first use.
from akkudoktoreos.optimization.genetic.geneticvisualize import (
genetic_prepare_visualize,
)
pdf = await asyncio.to_thread(genetic_prepare_visualize, solution=snapshot)
return Response(
content=pdf,
media_type="application/pdf",
headers={"Content-Disposition": 'inline; filename="optimization-genetic.pdf"'},
raise EOSProblem(
status=404,
title="Unknown optimization algorithm",
detail=(
f"Optimization algorithm '{algorithm}' unknown; "
f"known algorithms: {', '.join(optimizer_names())}."
),
)
@@ -2247,46 +2202,6 @@ async def fastapi_pvforecast() -> ForecastResponse:
return ForecastResponse(temperature=temp_air_list, pvpower=ac_power_list)
@app.post("/v1/optimize", tags=["optimize"])
async def fastapi_optimize_config(
request: Request,
parameters: ConfigOptimizationRequest = Body(default_factory=ConfigOptimizationRequest),
) -> 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 HTTPException(
status_code=422,
detail="Configure optimization settings; query overrides are not supported.",
)
solution = await get_ems().run(
mode=EnergyManagementMode.OPTIMIZATION,
algorithm=OptimizationAlgorithm.GENETIC,
genetic_parameters=parameters,
)
if solution is None:
raise EOSProblem(
status=503,
title="GENETIC optimization failed",
detail="No new solution was produced. Check configured devices and forecast coverage.",
)
if not isinstance(solution, GeneticSolution):
raise EOSProblem(
status=500,
title="Unexpected optimization algorithm result",
detail="GENETIC did not return its native solution type.",
)
return solution
@app.get("/site-map", include_in_schema=False)
def site_map() -> RedirectResponse:
return RedirectResponse(url="/docs")