mirror of
https://github.com/Akkudoktor-EOS/EOS.git
synced 2026-12-02 18:36:28 +01:00
refactor(genetic0): refactor GENETIC0 to consolidated optimizer architecture
Pin the conversion, plan and visualization of golden runs. Drive GENETIC0 through the optimizer registry. Move GENETIC0 into one directory with role-named modules. Prepare every run input once, run from the parameters. Fall back on bad inputs instead of cancelling the run. Simulate from frozen device dataclasses, not settings. Convert and visualize from the parameters and result only. Serve GENETIC0 from its own router, return a frozen result. Additional changes - Fix the run start of the golden runs and add a run across the DST switch. - Configure a home appliance so the conversion covers it. - Pass the warm start to the legacy preparation instead of reading the EMS. - Replace EnergyManagement.genetic0_solution() by optimizer_result(name). - Cover the warm start of the parameter preparation. - Rename Genetic0OptimizationParameters to Genetic0Request, Genetic0CommonSettings to Genetic0Settings. - Say in ADR 0007 and the skill that a move relabels baseline entries one to one. - Record the renamed OpenAPI schemas in CHANGELOG.md and the upgrade guide. - Add the observation time to the optimizer interface. - Cache the load interpolator by its backend instead of in the EMS run cache. - Add replay files that reproduce each golden result from its parameters. - Stop writing demo providers, demo devices and defaults into the configuration. - Count a NaN state of charge as invalid. - Remove the unused electricity fee check. - Record the fallbacks in CHANGELOG.md instead of the former demo providers. - Leave out a battery that is not linked to the inverter. - Count infinite forecast values as missing. - Extend a prediction.hours that leaves fewer than two hours after the start hour. - Do not charge from the grid without any known price. - Without an inverter, buy the whole load from the grid instead of planning it at no cost. - Keep the zone of the run start in the replay files. - Correct the DVhub documentation that said a missing tariff cancels the run. - Rename the request models to <Name><Thing>Request. - Move the settings' to_genetic0_*() converters into the preparation. - Remove the solution's unreachable configuration fallbacks. - Record the renamed OpenAPI schemas in CHANGELOG.md and the upgrade guide. - Add EnergyManagement.optimizer_run() and render the PDF from the run's own start. - Read the presentation series from the earlier of the run's start hours. - Render the PDF report for runs of any length, not only 48 hours. - Add the generic OptimizerProblem, rendered like EOSProblem. - Move Genetic0ParametersBaseModel into genetic0request.py. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Assisted-by: Claude Code (claude-opus-5-5)
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
9adf7b8be2
commit
40d0fab9d2
@@ -3,9 +3,10 @@ import threading
|
||||
import traceback
|
||||
import urllib.request
|
||||
from asyncio import Lock, get_running_loop
|
||||
from collections.abc import Mapping
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from enum import StrEnum
|
||||
from typing import ClassVar, Optional, cast
|
||||
from typing import Any, ClassVar, Optional, cast
|
||||
|
||||
from loguru import logger
|
||||
from pydantic import computed_field
|
||||
@@ -20,10 +21,6 @@ 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.genetic0.genetic0params import (
|
||||
Genetic0OptimizationParameters,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic0.genetic0solution import Genetic0Solution
|
||||
from akkudoktoreos.optimization.genetic.configrequest import ConfigOptimizationRequest
|
||||
from akkudoktoreos.optimization.genetic.genetic import GeneticOptimization
|
||||
from akkudoktoreos.optimization.genetic.geneticparams import (
|
||||
@@ -34,6 +31,8 @@ from akkudoktoreos.optimization.optimization import (
|
||||
OptimizationAlgorithm,
|
||||
OptimizationSolution,
|
||||
)
|
||||
from akkudoktoreos.optimization.optimizer import OptimizerRun
|
||||
from akkudoktoreos.optimization.optimizerregistry import get_optimizer
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime
|
||||
|
||||
# The executor to execute the CPU heavy energy management run
|
||||
@@ -126,9 +125,9 @@ class EnergyManagement(
|
||||
# For classic API
|
||||
_genetic_solution: ClassVar[Optional[GeneticSolution]] = None
|
||||
|
||||
# Solution of the genetic0 algorithm of latest energy management run with optimization
|
||||
# For classic API
|
||||
_genetic0_solution: ClassVar[Optional[Genetic0Solution]] = 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]]] = {}
|
||||
|
||||
# energy management lock (for energy management run)
|
||||
_run_lock: ClassVar[Lock] = Lock()
|
||||
@@ -227,13 +226,29 @@ class EnergyManagement(
|
||||
return cls._genetic_solution
|
||||
|
||||
@classmethod
|
||||
def genetic0_solution(cls) -> Optional[Genetic0Solution]:
|
||||
"""Get the latest solution of the genetic0 algorithm.
|
||||
def optimizer_run(cls, name: str) -> Optional[OptimizerRun[Any, Any]]:
|
||||
"""Get the parameters and result of the latest successful run of an optimizer.
|
||||
|
||||
Args:
|
||||
name: The optimizer's name, e.g. ``"GENETIC0"``.
|
||||
|
||||
Returns:
|
||||
Optional[Genetic0Solution]: The latest solution of the genetic algorithm.
|
||||
The optimizer's latest run, or None if it has not run yet.
|
||||
"""
|
||||
return cls._genetic0_solution
|
||||
return cls._optimizer_runs.get(name)
|
||||
|
||||
@classmethod
|
||||
def optimizer_result(cls, name: str) -> Optional[Any]:
|
||||
"""Get the result of the latest successful run of an optimizer of the registry.
|
||||
|
||||
Args:
|
||||
name: The optimizer's name, e.g. ``"GENETIC0"``.
|
||||
|
||||
Returns:
|
||||
The optimizer's native optimization result, or None if it has not run yet.
|
||||
"""
|
||||
run = cls._optimizer_runs.get(name)
|
||||
return None if run is None else run.result
|
||||
|
||||
async def run(
|
||||
self,
|
||||
@@ -246,12 +261,11 @@ class EnergyManagement(
|
||||
genetic_generations: Optional[int] = None,
|
||||
genetic_individuals: Optional[int] = None,
|
||||
genetic_seed: Optional[int] = None,
|
||||
genetic0_parameters: Optional[Genetic0OptimizationParameters] = None,
|
||||
genetic0_generations: Optional[int] = None,
|
||||
genetic0_seed: Optional[int] = None,
|
||||
request: Optional[Any] = None,
|
||||
overrides: Optional[Mapping[str, Any]] = None,
|
||||
force_enable: Optional[bool] = False,
|
||||
force_update: Optional[bool] = False,
|
||||
) -> Optional[GeneticSolution | Genetic0Solution]:
|
||||
) -> Optional[Any]:
|
||||
"""Run the energy management.
|
||||
|
||||
This method initializes the energy management run by setting its
|
||||
@@ -281,14 +295,11 @@ class EnergyManagement(
|
||||
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.
|
||||
genetic0_parameters (Genetic0OptimizationParameters, optional): The
|
||||
parameter set for the `GENETIC0` algorithm. If not provided, it will
|
||||
be constructed based on the current configuration and predictions.
|
||||
genetic0_generations (int, optional): The number of generations for the
|
||||
`GENETIC0` algorithm. Defaults to the algorithm's internal default (400)
|
||||
if not specified.
|
||||
genetic0_seed (int, optional): The seed for the `GENETIC0` 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}``.
|
||||
force_enable (bool, optional): If True, bypasses any disabled state
|
||||
to force the update process. This is mostly applicable to
|
||||
prediction providers.
|
||||
@@ -374,7 +385,10 @@ class EnergyManagement(
|
||||
if algorithm is None:
|
||||
algorithm = self.config.optimization.algorithm
|
||||
|
||||
run_solution: GeneticSolution | Genetic0Solution
|
||||
run_solution: Any
|
||||
optimizer = (
|
||||
None if algorithm == OptimizationAlgorithm.GENETIC else get_optimizer(algorithm)
|
||||
)
|
||||
|
||||
# --- GENETIC algorithm ---
|
||||
if algorithm == OptimizationAlgorithm.GENETIC:
|
||||
@@ -446,59 +460,41 @@ class EnergyManagement(
|
||||
EnergyManagement._genetic_solution,
|
||||
)
|
||||
|
||||
# --- GENETIC0 algorithm ---
|
||||
elif algorithm == OptimizationAlgorithm.GENETIC0:
|
||||
# --- Optimizers of the registry ---
|
||||
elif optimizer is not None:
|
||||
# Prepare optimization parameters
|
||||
# This also creates default configurations for missing values and updates the predictions
|
||||
logger.info(f"{algorithm}: Starting optimzation parameter preparation.")
|
||||
if genetic0_parameters is None:
|
||||
genetic0_parameters = await Genetic0OptimizationParameters.prepare()
|
||||
if genetic0_parameters is None:
|
||||
logger.error(
|
||||
f"{algorithm}: Energy management run canceled. "
|
||||
"Could not prepare optimisation parameters."
|
||||
)
|
||||
EnergyManagement._stage = EnergyManagementStage.IDLE
|
||||
return None
|
||||
|
||||
# Take values from config if not given
|
||||
if genetic0_generations is None:
|
||||
genetic0_generations = self.config.optimization.genetic0.generations
|
||||
if genetic0_seed is None:
|
||||
genetic0_seed = self.config.optimization.genetic0.seed
|
||||
|
||||
if EnergyManagement._start_datetime is None: # Make mypy happy - already set by us
|
||||
raise RuntimeError(f"{algorithm}: Start datetime not set.")
|
||||
start = EnergyManagement._start_datetime
|
||||
observation = EnergyManagement._observation_datetime or start
|
||||
previous = EnergyManagement._optimizer_runs.get(optimizer.name)
|
||||
warm_start = None if previous is None else previous.result
|
||||
try:
|
||||
if request is None:
|
||||
parameters = await optimizer.prepare(
|
||||
start, observation, warm_start, overrides
|
||||
)
|
||||
else:
|
||||
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:
|
||||
# Imported on first use: a server that runs GENETIC never needs
|
||||
# the GENETIC0 optimizer and its simulation.
|
||||
from akkudoktoreos.optimization.genetic0.genetic0 import (
|
||||
Genetic0Optimization,
|
||||
)
|
||||
|
||||
genetic0_optimization = Genetic0Optimization(
|
||||
verbose=bool(self.config.server.verbose),
|
||||
fixed_seed=genetic0_seed,
|
||||
)
|
||||
|
||||
loop = get_running_loop()
|
||||
start_hour = EnergyManagement._start_datetime.hour
|
||||
genetic0_solution = await loop.run_in_executor(
|
||||
None,
|
||||
lambda: genetic0_optimization.optimize_ems(
|
||||
start_hour=start_hour,
|
||||
parameters=cast(
|
||||
Genetic0OptimizationParameters, genetic0_parameters
|
||||
), # cast for mypy
|
||||
ngen=genetic0_generations,
|
||||
),
|
||||
)
|
||||
result = await loop.run_in_executor(None, optimizer.run, parameters)
|
||||
|
||||
# Build all representations before publishing any of them.
|
||||
optimization_solution = await genetic0_solution.optimization_solution()
|
||||
plan = genetic0_solution.energy_management_plan()
|
||||
optimization_solution, plan = await optimizer.convert(parameters, result)
|
||||
|
||||
except Exception:
|
||||
logger.exception(f"{algorithm}: Energy management optimization failed.")
|
||||
@@ -506,16 +502,14 @@ class EnergyManagement(
|
||||
return None
|
||||
|
||||
# Publish a consistent set without yielding to another coroutine.
|
||||
EnergyManagement._genetic0_solution = genetic0_solution
|
||||
EnergyManagement._optimizer_runs[optimizer.name] = OptimizerRun(
|
||||
parameters=parameters, result=result
|
||||
)
|
||||
EnergyManagement._optimization_solution = optimization_solution
|
||||
EnergyManagement._plan = plan
|
||||
run_solution = genetic0_solution
|
||||
run_solution = result
|
||||
|
||||
logger.debug(
|
||||
"{}: Energy management genetic solution:\n{}",
|
||||
algorithm,
|
||||
EnergyManagement._genetic0_solution,
|
||||
)
|
||||
logger.debug("{}: Energy management optimizer result:\n{}", algorithm, result)
|
||||
|
||||
else:
|
||||
logger.error(f"Unknown optimization algorithm: '{algorithm}'. Skipping.")
|
||||
|
||||
@@ -1,136 +0,0 @@
|
||||
from typing import Optional
|
||||
|
||||
import numpy as np
|
||||
from pydantic import Field
|
||||
|
||||
from akkudoktoreos.config.configabc import TimeWindow, TimeWindowSequence
|
||||
from akkudoktoreos.optimization.genetic0.genetic0devices import Genetic0DeviceParameters
|
||||
from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration, to_time
|
||||
|
||||
|
||||
class Genetic0HomeApplianceParameters(Genetic0DeviceParameters):
|
||||
"""Home Appliance Device Simulation Configuration."""
|
||||
|
||||
device_id: str = Field(
|
||||
json_schema_extra={"description": "ID of home appliance", "examples": ["dishwasher"]}
|
||||
)
|
||||
consumption_wh: int = Field(
|
||||
gt=0,
|
||||
json_schema_extra={
|
||||
"description": "An integer representing the energy consumption of a household device in watt-hours.",
|
||||
"examples": [2000],
|
||||
},
|
||||
)
|
||||
duration_h: int = Field(
|
||||
gt=0,
|
||||
json_schema_extra={
|
||||
"description": "An integer representing the usage duration of a household device in hours.",
|
||||
"examples": [3],
|
||||
},
|
||||
)
|
||||
time_windows: Optional[TimeWindowSequence] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": "List of allowed time windows. Defaults to optimization general time window.",
|
||||
"examples": [
|
||||
[
|
||||
{"start_time": "10:00", "duration": "3 hours"},
|
||||
],
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
class Genetic0HomeAppliance:
|
||||
def __init__(
|
||||
self,
|
||||
parameters: Genetic0HomeApplianceParameters,
|
||||
optimization_hours: int,
|
||||
prediction_hours: int,
|
||||
):
|
||||
self.parameters: Genetic0HomeApplianceParameters = parameters
|
||||
self.prediction_hours = prediction_hours
|
||||
self._setup()
|
||||
|
||||
def _setup(self) -> None:
|
||||
"""Sets up the home appliance parameters based provided parameters."""
|
||||
self.load_curve = np.zeros(self.prediction_hours) # Initialize the load curve with zeros
|
||||
self.duration_h = self.parameters.duration_h
|
||||
self.consumption_wh = self.parameters.consumption_wh
|
||||
# setup possible start times
|
||||
if self.parameters.time_windows is None:
|
||||
self.parameters.time_windows = TimeWindowSequence(
|
||||
windows=[
|
||||
TimeWindow(
|
||||
start_time=to_time("00:00"),
|
||||
duration=to_duration(f"{self.prediction_hours} hours"),
|
||||
),
|
||||
]
|
||||
)
|
||||
start_datetime = to_datetime().set(hour=0, minute=0, second=0)
|
||||
duration = to_duration(f"{self.duration_h} hours")
|
||||
self.start_allowed: list[bool] = []
|
||||
for hour in range(0, self.prediction_hours):
|
||||
self.start_allowed.append(
|
||||
self.parameters.time_windows.contains(
|
||||
start_datetime.add(hours=hour), duration=duration
|
||||
)
|
||||
)
|
||||
start_earliest = self.parameters.time_windows.earliest_start_time(duration, start_datetime)
|
||||
if start_earliest:
|
||||
self.start_earliest = start_earliest.hour
|
||||
else:
|
||||
self.start_earliest = 0
|
||||
start_latest = self.parameters.time_windows.latest_start_time(duration, start_datetime)
|
||||
if start_latest:
|
||||
self.start_latest = start_latest.hour
|
||||
else:
|
||||
self.start_latest = 23
|
||||
|
||||
def set_starting_time(self, start_hour: int, global_start_hour: int = 0) -> int:
|
||||
"""Sets the start time of the device and generates the corresponding load curve.
|
||||
|
||||
:param start_hour: The hour at which the device should start.
|
||||
"""
|
||||
if not self.start_allowed[start_hour]:
|
||||
# It is not allowed (by the time windows) to start the application at this time
|
||||
if global_start_hour <= self.start_latest:
|
||||
# There is a time window left to start the appliance. Use it
|
||||
start_hour = self.start_latest
|
||||
else:
|
||||
# There is no time window left to run the application
|
||||
# Set the start into tomorrow
|
||||
start_hour = self.start_earliest + 24
|
||||
|
||||
self.reset_load_curve()
|
||||
|
||||
# Calculate power per hour based on total consumption and duration
|
||||
power_per_hour = self.consumption_wh / self.duration_h # Convert to watt-hours
|
||||
|
||||
# Set the power for the duration of use in the load curve array
|
||||
if start_hour < len(self.load_curve):
|
||||
end_hour = min(start_hour + self.duration_h, self.prediction_hours)
|
||||
self.load_curve[start_hour:end_hour] = power_per_hour
|
||||
|
||||
return start_hour
|
||||
|
||||
def reset_load_curve(self) -> None:
|
||||
"""Resets the load curve."""
|
||||
self.load_curve = np.zeros(self.prediction_hours)
|
||||
|
||||
def get_load_curve(self) -> np.ndarray:
|
||||
"""Returns the current load curve."""
|
||||
return self.load_curve
|
||||
|
||||
def get_load_for_hour(self, hour: int) -> float:
|
||||
"""Returns the load for a specific hour.
|
||||
|
||||
:param hour: The hour for which the load is queried.
|
||||
:return: The load in watts for the specified hour.
|
||||
"""
|
||||
if hour < 0 or hour >= self.prediction_hours:
|
||||
raise ValueError(
|
||||
f"The specified hour {hour} is outside the available time frame {self.prediction_hours}."
|
||||
)
|
||||
|
||||
return self.load_curve[hour]
|
||||
@@ -120,10 +120,6 @@ from akkudoktoreos.measurement.batterycapacity import (
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from akkudoktoreos.devices.genetic0.genetic0battery import (
|
||||
Genetic0ElectricVehicleParameters,
|
||||
Genetic0SolarPanelBatteryParameters,
|
||||
)
|
||||
from akkudoktoreos.devices.genetic.battery import (
|
||||
ElectricVehicleParameters,
|
||||
SolarPanelBatteryParameters,
|
||||
@@ -1085,77 +1081,6 @@ class BatteriesCommonSettings(DevicesBaseSettings):
|
||||
**self._genetic_power_parameters(p, profile),
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# GENETIC0 domain conversion
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def to_genetic0_pv_bat_param(
|
||||
self, operating_parameters: Optional[BatteryOperatingParameters] = None
|
||||
) -> "Genetic0SolarPanelBatteryParameters":
|
||||
"""Return Genetic0SolarPanelBatteryParameters for the GENETIC0 optimizer.
|
||||
|
||||
Args:
|
||||
operating_parameters: Resolved snapshot to convert, e.g. from
|
||||
``resolve_current_operating_parameters``. None resolves at the
|
||||
reference operating point.
|
||||
|
||||
Raises:
|
||||
BatteryResolutionError: See ``resolve_operating_parameters``.
|
||||
"""
|
||||
from akkudoktoreos.devices.genetic0.genetic0battery import (
|
||||
Genetic0SolarPanelBatteryParameters,
|
||||
)
|
||||
|
||||
p = (
|
||||
operating_parameters
|
||||
if operating_parameters is not None
|
||||
else self.resolve_operating_parameters()
|
||||
)
|
||||
return Genetic0SolarPanelBatteryParameters(
|
||||
device_id=self.device_id,
|
||||
capacity_wh=p.capacity_wh,
|
||||
charging_efficiency=p.charging_efficiency,
|
||||
discharging_efficiency=p.discharging_efficiency,
|
||||
max_charge_power_w=p.max_charge_power_w,
|
||||
max_discharge_power_w=p.max_discharge_power_w,
|
||||
min_soc_percentage=p.min_soc_percentage,
|
||||
max_soc_percentage=p.max_soc_percentage,
|
||||
)
|
||||
|
||||
def to_genetic0_ev_bat_param(
|
||||
self, operating_parameters: Optional[BatteryOperatingParameters] = None
|
||||
) -> "Genetic0ElectricVehicleParameters":
|
||||
"""Return Genetic0ElectricVehicleParameters for the GENETIC0 optimizer.
|
||||
|
||||
Args:
|
||||
operating_parameters: Resolved snapshot to convert, e.g. from
|
||||
``resolve_current_operating_parameters``. None resolves at the
|
||||
reference operating point.
|
||||
|
||||
Raises:
|
||||
BatteryResolutionError: See ``resolve_operating_parameters``.
|
||||
"""
|
||||
from akkudoktoreos.devices.genetic0.genetic0battery import (
|
||||
Genetic0ElectricVehicleParameters,
|
||||
)
|
||||
|
||||
p = (
|
||||
operating_parameters
|
||||
if operating_parameters is not None
|
||||
else self.resolve_operating_parameters()
|
||||
)
|
||||
return Genetic0ElectricVehicleParameters(
|
||||
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,
|
||||
max_charge_power_w=p.max_charge_power_w,
|
||||
max_discharge_power_w=p.max_discharge_power_w,
|
||||
min_soc_percentage=p.min_soc_percentage,
|
||||
max_soc_percentage=p.max_soc_percentage,
|
||||
)
|
||||
|
||||
@field_validator("charge_rates", mode="before")
|
||||
def validate_and_sort_charge_rates(cls, v: Any) -> NDArray[Shape["*"], float]:
|
||||
# None means fallback to default values
|
||||
|
||||
@@ -21,9 +21,6 @@ from akkudoktoreos.devices.settings.devicebasesettings import DevicesBaseSetting
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime, compare_datetimes, to_datetime
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from akkudoktoreos.devices.genetic0.genetic0homeappliance import (
|
||||
Genetic0HomeApplianceParameters,
|
||||
)
|
||||
from akkudoktoreos.devices.genetic.homeappliance import HomeApplianceParameters
|
||||
|
||||
|
||||
@@ -395,27 +392,6 @@ class HomeApplianceCommonSettings(DevicesBaseSettings):
|
||||
deadline_policy=self.deadline_policy,
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# GENETIC0 domain conversion
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def to_genetic0_param(self) -> "Genetic0HomeApplianceParameters":
|
||||
"""Return Genetic0HomeApplianceParameters for the GENETIC0 optimizer."""
|
||||
from akkudoktoreos.devices.genetic0.genetic0homeappliance import (
|
||||
Genetic0HomeApplianceParameters,
|
||||
)
|
||||
|
||||
if self.load_profile_power_w is not None:
|
||||
raise ValueError("Explicit appliance load profiles require the GENETIC optimizer.")
|
||||
if self.consumption_wh is None or self.duration_h is None:
|
||||
raise ValueError("GENETIC0 requires a flat appliance load definition.")
|
||||
return Genetic0HomeApplianceParameters(
|
||||
device_id=self.device_id,
|
||||
consumption_wh=self.consumption_wh,
|
||||
duration_h=self.duration_h,
|
||||
time_windows=self.cycle_time_windows,
|
||||
)
|
||||
|
||||
@computed_field # type: ignore[prop-decorator]
|
||||
@property
|
||||
def measurement_keys(self) -> Optional[list[str]]:
|
||||
|
||||
@@ -43,9 +43,6 @@ from akkudoktoreos.devices.settings.inverterresolution import (
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from akkudoktoreos.devices.genetic0.genetic0inverter import (
|
||||
Genetic0InverterParameters,
|
||||
)
|
||||
from akkudoktoreos.devices.genetic.inverter import InverterParameters
|
||||
from akkudoktoreos.devices.profile.inverterprofile import InverterProfile
|
||||
|
||||
@@ -713,35 +710,6 @@ class InverterCommonSettings(DevicesBaseSettings):
|
||||
ac_charge_limits_total_charge=p.ac_charge_limits_total_charge,
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# GENETIC0 domain conversion
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def to_genetic0_param(
|
||||
self, operating_parameters: Optional[InverterOperatingParameters] = None
|
||||
) -> "Genetic0InverterParameters":
|
||||
"""Return Genetic0InverterParameters for the GENETIC0 optimizer.
|
||||
|
||||
GENETIC0 uses constant efficiencies: the DC→AC efficiency at the
|
||||
reference load fraction and the AC→DC efficiency at the AC charge limit.
|
||||
|
||||
Raises:
|
||||
InverterResolutionError: See ``to_genetic_param``.
|
||||
"""
|
||||
from akkudoktoreos.devices.genetic0.genetic0inverter import (
|
||||
Genetic0InverterParameters,
|
||||
)
|
||||
|
||||
p = operating_parameters or self.resolve_operating_parameters()
|
||||
return Genetic0InverterParameters(
|
||||
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,
|
||||
max_ac_charge_power_w=p.max_ac_charge_power_w,
|
||||
)
|
||||
|
||||
@computed_field # type: ignore[prop-decorator]
|
||||
@property
|
||||
def measurement_key_temperature_degc(self) -> str:
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
"""GENETIC0 optimizer: the only module code outside the optimizer imports (ADR 0005).
|
||||
|
||||
``Genetic0Optimizer`` and ``Genetic0Settings`` 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.genetic0.genetic0optimizer import Genetic0Optimizer
|
||||
from akkudoktoreos.optimization.genetic0.genetic0settings import Genetic0Settings
|
||||
|
||||
__all__ = ["Genetic0Optimizer", "Genetic0Settings"]
|
||||
|
||||
|
||||
def __getattr__(name: str) -> Any:
|
||||
if name == "Genetic0Optimizer":
|
||||
from akkudoktoreos.optimization.genetic0.genetic0optimizer import (
|
||||
Genetic0Optimizer,
|
||||
)
|
||||
|
||||
return Genetic0Optimizer
|
||||
if name == "Genetic0Settings":
|
||||
from akkudoktoreos.optimization.genetic0.genetic0settings import (
|
||||
Genetic0Settings,
|
||||
)
|
||||
|
||||
return Genetic0Settings
|
||||
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
||||
+56
-108
@@ -1,121 +1,71 @@
|
||||
"""GENETIC0 battery simulation device (stationary battery or electric vehicle)."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Iterator, Optional
|
||||
|
||||
import numpy as np
|
||||
from pydantic import Field
|
||||
|
||||
from akkudoktoreos.devices.settings.batterysettings import BATTERY_DEFAULT_CHARGE_RATES
|
||||
from akkudoktoreos.optimization.genetic0.genetic0devices import Genetic0DeviceParameters
|
||||
# Charge rates of a battery that has none; copied from the battery settings, optimizers share no
|
||||
# code with the configuration (ADR 0004).
|
||||
BATTERY_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,
|
||||
)
|
||||
|
||||
|
||||
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})
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Genetic0BatteryParameters:
|
||||
"""Parameters of a simulated battery.
|
||||
|
||||
Attributes:
|
||||
device_id: ID of the battery.
|
||||
capacity_wh: Capacity in watt-hours.
|
||||
charging_efficiency: Charging efficiency (0, 1].
|
||||
discharging_efficiency: Discharging efficiency (0, 1].
|
||||
max_charge_power_w: Maximum charging power in watts; ``None`` uses the capacity.
|
||||
max_discharge_power_w: Maximum discharging power in watts; ``None`` uses the charging
|
||||
power.
|
||||
initial_soc_percentage: State of charge at the start of the run in percent.
|
||||
min_soc_percentage: Minimum state of charge in percent.
|
||||
max_soc_percentage: Maximum state of charge in percent.
|
||||
charge_rates: Available charge rates as factors of the charging power; ``None`` or empty
|
||||
gives the default rates.
|
||||
stationary: A stationary (PV) battery keeps its minimum state of charge; an electric
|
||||
vehicle may be discharged to 0.
|
||||
"""
|
||||
|
||||
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 Genetic0BaseBatteryParameters(Genetic0DeviceParameters):
|
||||
"""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: the battery may not discharge. "
|
||||
"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],
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
class Genetic0SolarPanelBatteryParameters(Genetic0BaseBatteryParameters):
|
||||
"""PV battery device simulation configuration."""
|
||||
|
||||
max_charge_power_w: Optional[float] = max_charging_power_field()
|
||||
|
||||
|
||||
class Genetic0ElectricVehicleParameters(Genetic0BaseBatteryParameters):
|
||||
"""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."
|
||||
)
|
||||
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, ...]]
|
||||
stationary: bool
|
||||
|
||||
|
||||
class Genetic0Battery:
|
||||
"""Represents a battery device with methods to simulate energy charging and discharging."""
|
||||
|
||||
def __init__(self, parameters: Genetic0BaseBatteryParameters, prediction_hours: int):
|
||||
def __init__(self, parameters: Genetic0BatteryParameters, prediction_hours: int) -> None:
|
||||
"""Set up the battery.
|
||||
|
||||
Args:
|
||||
parameters: Battery parameters.
|
||||
prediction_hours: Length of the simulated arrays.
|
||||
"""
|
||||
self.parameters = parameters
|
||||
self.prediction_hours = prediction_hours
|
||||
self._setup()
|
||||
@@ -137,9 +87,7 @@ class Genetic0Battery:
|
||||
|
||||
# Only assign for storage battery
|
||||
self.min_soc_percentage = (
|
||||
self.parameters.min_soc_percentage
|
||||
if isinstance(self.parameters, Genetic0SolarPanelBatteryParameters)
|
||||
else 0
|
||||
self.parameters.min_soc_percentage if self.parameters.stationary else 0
|
||||
)
|
||||
self.max_soc_percentage = self.parameters.max_soc_percentage
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
"""GENETIC0 home appliance simulation device."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Genetic0HomeApplianceParameters:
|
||||
"""Parameters of a simulated home appliance.
|
||||
|
||||
Attributes:
|
||||
device_id: ID of the appliance.
|
||||
consumption_wh: Energy of one run in watt-hours.
|
||||
duration_h: Duration of one run in hours.
|
||||
start_allowed: Per hour of the arrays, whether a run may start then.
|
||||
start_earliest: Earliest hour of the day a run may start.
|
||||
start_latest: Latest hour of the day a run may start.
|
||||
"""
|
||||
|
||||
device_id: str
|
||||
consumption_wh: int
|
||||
duration_h: int
|
||||
start_allowed: tuple[bool, ...]
|
||||
start_earliest: int
|
||||
start_latest: int
|
||||
|
||||
|
||||
class Genetic0HomeAppliance:
|
||||
def __init__(
|
||||
self,
|
||||
parameters: Genetic0HomeApplianceParameters,
|
||||
optimization_hours: int,
|
||||
prediction_hours: int,
|
||||
) -> None:
|
||||
"""Set up the home appliance.
|
||||
|
||||
Args:
|
||||
parameters: Home appliance parameters.
|
||||
optimization_hours: Optimization horizon in hours (unused).
|
||||
prediction_hours: Length of the simulated arrays.
|
||||
"""
|
||||
self.parameters: Genetic0HomeApplianceParameters = parameters
|
||||
self.prediction_hours = prediction_hours
|
||||
self._setup()
|
||||
|
||||
def _setup(self) -> None:
|
||||
"""Sets up the home appliance parameters based provided parameters."""
|
||||
self.load_curve = np.zeros(self.prediction_hours) # Initialize the load curve with zeros
|
||||
self.duration_h = self.parameters.duration_h
|
||||
self.consumption_wh = self.parameters.consumption_wh
|
||||
# Possible start times, evaluated from the time windows by the parameter preparation.
|
||||
self.start_allowed: list[bool] = list(self.parameters.start_allowed)
|
||||
self.start_earliest = self.parameters.start_earliest
|
||||
self.start_latest = self.parameters.start_latest
|
||||
|
||||
def set_starting_time(self, start_hour: int, global_start_hour: int = 0) -> int:
|
||||
"""Sets the start time of the device and generates the corresponding load curve.
|
||||
|
||||
:param start_hour: The hour at which the device should start.
|
||||
"""
|
||||
if not self.start_allowed[start_hour]:
|
||||
# It is not allowed (by the time windows) to start the application at this time
|
||||
if global_start_hour <= self.start_latest:
|
||||
# There is a time window left to start the appliance. Use it
|
||||
start_hour = self.start_latest
|
||||
else:
|
||||
# There is no time window left to run the application
|
||||
# Set the start into tomorrow
|
||||
start_hour = self.start_earliest + 24
|
||||
|
||||
self.reset_load_curve()
|
||||
|
||||
# Calculate power per hour based on total consumption and duration
|
||||
power_per_hour = self.consumption_wh / self.duration_h # Convert to watt-hours
|
||||
|
||||
# Set the power for the duration of use in the load curve array
|
||||
if start_hour < len(self.load_curve):
|
||||
end_hour = min(start_hour + self.duration_h, self.prediction_hours)
|
||||
self.load_curve[start_hour:end_hour] = power_per_hour
|
||||
|
||||
return start_hour
|
||||
|
||||
def reset_load_curve(self) -> None:
|
||||
"""Resets the load curve."""
|
||||
self.load_curve = np.zeros(self.prediction_hours)
|
||||
|
||||
def get_load_curve(self) -> np.ndarray:
|
||||
"""Returns the current load curve."""
|
||||
return self.load_curve
|
||||
|
||||
def get_load_for_hour(self, hour: int) -> float:
|
||||
"""Returns the load for a specific hour.
|
||||
|
||||
:param hour: The hour for which the load is queried.
|
||||
:return: The load in watts for the specified hour.
|
||||
"""
|
||||
if hour < 0 or hour >= self.prediction_hours:
|
||||
raise ValueError(
|
||||
f"The specified hour {hour} is outside the available time frame {self.prediction_hours}."
|
||||
)
|
||||
|
||||
return self.load_curve[hour]
|
||||
+40
-52
@@ -1,63 +1,36 @@
|
||||
"""GENETIC0 inverter simulation device."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
from loguru import logger
|
||||
from pydantic import Field
|
||||
|
||||
from akkudoktoreos.devices.genetic0.genetic0battery import Genetic0Battery
|
||||
from akkudoktoreos.optimization.genetic0.genetic0devices import Genetic0DeviceParameters
|
||||
from akkudoktoreos.optimization.genetic0.devices.genetic0battery import Genetic0Battery
|
||||
from akkudoktoreos.optimization.genetic0.genetic0loadinterpolator import (
|
||||
get_genetic0_load_interpolator,
|
||||
)
|
||||
from akkudoktoreos.utils.gridinterpolator import GridInterpolatorBackend
|
||||
|
||||
|
||||
class Genetic0InverterParameters(Genetic0DeviceParameters):
|
||||
"""Inverter Device Simulation Configuration."""
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Genetic0InverterParameters:
|
||||
"""Parameters of a simulated inverter.
|
||||
|
||||
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],
|
||||
},
|
||||
)
|
||||
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],
|
||||
},
|
||||
)
|
||||
Attributes:
|
||||
device_id: ID of the inverter.
|
||||
max_power_wh: Maximum power the inverter can handle per hour.
|
||||
battery_id: ID of the battery behind the inverter, if any.
|
||||
ac_to_dc_efficiency: Efficiency of AC charging.
|
||||
dc_to_ac_efficiency: Efficiency of DC to AC conversion.
|
||||
max_ac_charge_power_w: Maximum AC charging power in watts; ``None`` uses the battery's.
|
||||
"""
|
||||
|
||||
device_id: str
|
||||
max_power_wh: float
|
||||
battery_id: Optional[str]
|
||||
ac_to_dc_efficiency: float
|
||||
dc_to_ac_efficiency: float
|
||||
max_ac_charge_power_w: Optional[float]
|
||||
|
||||
|
||||
class Genetic0Inverter:
|
||||
@@ -65,9 +38,22 @@ class Genetic0Inverter:
|
||||
self,
|
||||
parameters: Genetic0InverterParameters,
|
||||
battery: Optional[Genetic0Battery] = None,
|
||||
):
|
||||
self_consumption_interpolator: GridInterpolatorBackend = GridInterpolatorBackend.SCIPY,
|
||||
) -> None:
|
||||
"""Set up the inverter simulation.
|
||||
|
||||
Args:
|
||||
parameters: Inverter parameters.
|
||||
battery: Battery behind the inverter, if any.
|
||||
self_consumption_interpolator: How the self-consumption table is evaluated; the run
|
||||
settings pass the configured backend.
|
||||
|
||||
Raises:
|
||||
ValueError: The battery is not the one the inverter parameters name.
|
||||
"""
|
||||
self.parameters: Genetic0InverterParameters = parameters
|
||||
self.battery: Optional[Genetic0Battery] = battery
|
||||
self.self_consumption_interpolator = self_consumption_interpolator
|
||||
self._setup()
|
||||
|
||||
def _setup(self) -> None:
|
||||
@@ -75,7 +61,9 @@ class Genetic0Inverter:
|
||||
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_genetic0_load_interpolator()
|
||||
self.self_consumption_predictor = get_genetic0_load_interpolator(
|
||||
self.self_consumption_interpolator
|
||||
)
|
||||
self.max_power_wh = (
|
||||
self.parameters.max_power_wh
|
||||
) # Maximum power that the inverter can handle
|
||||
@@ -1,11 +0,0 @@
|
||||
"""Genetic0 optimization algorithm abstract and base classes."""
|
||||
|
||||
from pydantic import ConfigDict
|
||||
|
||||
from akkudoktoreos.core.pydantic import PydanticBaseModel
|
||||
|
||||
|
||||
class Genetic0ParametersBaseModel(PydanticBaseModel):
|
||||
"""Pydantic base model for parameters for the GENETIC algorithm."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
+107
-511
@@ -1,453 +1,56 @@
|
||||
"""Genetic0 algorithm."""
|
||||
"""GENETIC0 algorithm: the genetic search over the simulation."""
|
||||
|
||||
import random
|
||||
import time
|
||||
from typing import Any, Optional
|
||||
from typing import Any, Optional, cast
|
||||
|
||||
import numpy as np
|
||||
from deap import algorithms, base, creator, tools
|
||||
from loguru import logger
|
||||
from numpydantic import NDArray, Shape
|
||||
from pydantic import ConfigDict, Field
|
||||
|
||||
from akkudoktoreos.core.pydantic import PydanticBaseModel
|
||||
from akkudoktoreos.devices.genetic0.genetic0battery import Genetic0Battery
|
||||
from akkudoktoreos.devices.genetic0.genetic0homeappliance import Genetic0HomeAppliance
|
||||
from akkudoktoreos.devices.genetic0.genetic0inverter import Genetic0Inverter
|
||||
from akkudoktoreos.optimization.genetic0.genetic0params import (
|
||||
Genetic0EnergyManagementParameters,
|
||||
Genetic0OptimizationParameters,
|
||||
from akkudoktoreos.optimization.genetic0.devices.genetic0battery import Genetic0Battery
|
||||
from akkudoktoreos.optimization.genetic0.devices.genetic0homeappliance import (
|
||||
Genetic0HomeAppliance,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic0.genetic0solution import (
|
||||
Genetic0SimulationResult,
|
||||
Genetic0Solution,
|
||||
from akkudoktoreos.optimization.genetic0.devices.genetic0inverter import (
|
||||
Genetic0Inverter,
|
||||
)
|
||||
from akkudoktoreos.optimization.optimizationabc import OptimizationBase
|
||||
from akkudoktoreos.optimization.genetic0.genetic0parameters import (
|
||||
Genetic0Parameters,
|
||||
Genetic0RunSettings,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic0.genetic0result import (
|
||||
Genetic0ElectricVehicleState,
|
||||
Genetic0Result,
|
||||
Genetic0SimulationOutput,
|
||||
float_list,
|
||||
int_list,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic0.genetic0simulation import Genetic0Simulation
|
||||
|
||||
|
||||
class Genetic0Simulation(PydanticBaseModel):
|
||||
"""Device simulation for GENETIC optimization algorithm."""
|
||||
class Genetic0Optimization:
|
||||
"""GENETIC algorithm to solve energy optimization.
|
||||
|
||||
# Disable validation on assignment to speed up simulation runs.
|
||||
model_config = ConfigDict(
|
||||
validate_assignment=False,
|
||||
)
|
||||
Reads nothing but its run settings and the parameters passed to ``optimize_ems()``.
|
||||
"""
|
||||
|
||||
start_hour: int = Field(
|
||||
default=0,
|
||||
ge=0,
|
||||
le=23,
|
||||
json_schema_extra={"description": "Starting hour on day for optimizations."},
|
||||
)
|
||||
def __init__(self, settings: Genetic0RunSettings):
|
||||
"""Initialize the optimization problem with the settings of the run.
|
||||
|
||||
optimization_hours: Optional[int] = Field(
|
||||
default=24,
|
||||
ge=0,
|
||||
json_schema_extra={"description": "Number of hours into the future for optimizations."},
|
||||
)
|
||||
|
||||
prediction_hours: Optional[int] = Field(
|
||||
default=48,
|
||||
ge=0,
|
||||
json_schema_extra={"description": "Number of hours into the future for predictions"},
|
||||
)
|
||||
|
||||
load_energy_array: Optional[NDArray[Shape["*"], float]] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": "An array of floats representing the total load (consumption) in watts for different time intervals."
|
||||
},
|
||||
)
|
||||
pv_prediction_wh: Optional[NDArray[Shape["*"], float]] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": "An array of floats representing the forecasted photovoltaic output in watts for different time intervals."
|
||||
},
|
||||
)
|
||||
elect_price_hourly: Optional[NDArray[Shape["*"], float]] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": "An array of floats representing the electricity price per watt-hour for different time intervals."
|
||||
},
|
||||
)
|
||||
elect_revenue_per_hour_arr: Optional[NDArray[Shape["*"], float]] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": "An array of floats representing the feed-in compensation per watt-hour."
|
||||
},
|
||||
)
|
||||
|
||||
battery: Optional[Genetic0Battery] = Field(
|
||||
default=None, json_schema_extra={"description": "TBD."}
|
||||
)
|
||||
ev: Optional[Genetic0Battery] = Field(default=None, json_schema_extra={"description": "TBD."})
|
||||
home_appliance: Optional[Genetic0HomeAppliance] = Field(
|
||||
default=None, json_schema_extra={"description": "TBD."}
|
||||
)
|
||||
inverter: Optional[Genetic0Inverter] = Field(
|
||||
default=None, json_schema_extra={"description": "TBD."}
|
||||
)
|
||||
|
||||
ac_charge_hours: Optional[NDArray[Shape["*"], float]] = Field(
|
||||
default=None, json_schema_extra={"description": "TBD"}
|
||||
)
|
||||
dc_charge_hours: Optional[NDArray[Shape["*"], float]] = Field(
|
||||
default=None, json_schema_extra={"description": "TBD"}
|
||||
)
|
||||
bat_discharge_hours: Optional[NDArray[Shape["*"], float]] = Field(
|
||||
default=None, json_schema_extra={"description": "TBD"}
|
||||
)
|
||||
ev_charge_hours: Optional[NDArray[Shape["*"], float]] = Field(
|
||||
default=None, json_schema_extra={"description": "TBD"}
|
||||
)
|
||||
ev_discharge_hours: Optional[NDArray[Shape["*"], float]] = Field(
|
||||
default=None, json_schema_extra={"description": "TBD"}
|
||||
)
|
||||
home_appliance_start_hour: Optional[int] = Field(
|
||||
default=None,
|
||||
json_schema_extra={"description": "Home appliance start hour - None denotes no start."},
|
||||
)
|
||||
|
||||
def prepare(
|
||||
self,
|
||||
parameters: Genetic0EnergyManagementParameters,
|
||||
optimization_hours: int,
|
||||
prediction_hours: int,
|
||||
ev: Optional[Genetic0Battery] = None,
|
||||
home_appliance: Optional[Genetic0HomeAppliance] = None,
|
||||
inverter: Optional[Genetic0Inverter] = None,
|
||||
) -> None:
|
||||
"""Prepare simulation runs.
|
||||
|
||||
Populate internal arrays and device references used during simulation.
|
||||
Args:
|
||||
settings: Algorithm settings of the run.
|
||||
"""
|
||||
self.optimization_hours = optimization_hours
|
||||
self.prediction_hours = prediction_hours
|
||||
|
||||
# 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.asarray(parameters.feed_in_tariff_per_wh, dtype=float)
|
||||
if isinstance(parameters.feed_in_tariff_per_wh, list)
|
||||
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
|
||||
self.home_appliance = home_appliance
|
||||
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.ev_charge_hours = np.full(self.prediction_hours, 0.0)
|
||||
self.ev_discharge_hours = np.full(self.prediction_hours, 0.0)
|
||||
self.home_appliance_start_hour = None
|
||||
|
||||
def reset(self) -> None:
|
||||
if self.ev:
|
||||
self.ev.reset()
|
||||
if self.battery:
|
||||
self.battery.reset()
|
||||
self.home_appliance_start_hour = None
|
||||
|
||||
def simulate(self, start_hour: int) -> dict[str, Any]:
|
||||
"""Simulate energy usage and costs for the given start hour.
|
||||
|
||||
battery_soc_per_hour begin of the hour, initial hour state!
|
||||
load_wh_per_hour 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
|
||||
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_appliance_fast = self.home_appliance
|
||||
inverter_fast = self.inverter
|
||||
|
||||
# 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 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("Genetic0Battery Discharge 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 = len(load_energy_array_fast)
|
||||
total_hours = end_hour - start_hour
|
||||
|
||||
# Pre-allocate arrays for the results, optimized for speed
|
||||
loads_energy_per_hour = np.full((total_hours), np.nan)
|
||||
feedin_energy_per_hour = np.full((total_hours), np.nan)
|
||||
consumption_energy_per_hour = np.full((total_hours), np.nan)
|
||||
costs_per_hour = np.full((total_hours), np.nan)
|
||||
revenue_per_hour = np.full((total_hours), np.nan)
|
||||
losses_wh_per_hour = np.full((total_hours), np.nan)
|
||||
electricity_price_per_hour = np.full((total_hours), np.nan)
|
||||
|
||||
# Set initial state
|
||||
if battery_fast:
|
||||
# Pre-allocate arrays for the results, optimized for speed
|
||||
soc_per_hour = np.full((total_hours), np.nan)
|
||||
|
||||
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
|
||||
if not ac_charging_possible:
|
||||
ac_charge_hours_fast = np.zeros_like(ac_charge_hours_fast)
|
||||
|
||||
# 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
|
||||
battery_fast.discharge_array = bat_discharge_hours_fast
|
||||
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:
|
||||
# Pre-allocate arrays for the results, optimized for speed
|
||||
soc_ev_per_hour = np.full((total_hours), np.nan)
|
||||
|
||||
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_appliance_fast and self.home_appliance_start_hour is not None:
|
||||
home_appliance_enabled = True
|
||||
# Pre-allocate arrays for the results, optimized for speed
|
||||
home_appliance_wh_per_hour = np.full((total_hours), np.nan)
|
||||
|
||||
self.home_appliance_start_hour = home_appliance_fast.set_starting_time(
|
||||
self.home_appliance_start_hour, start_hour
|
||||
)
|
||||
else:
|
||||
home_appliance_enabled = False
|
||||
# Default return if no home appliance is available
|
||||
home_appliance_wh_per_hour = np.full((total_hours), 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]
|
||||
losses_wh_per_hour[hour_idx] = 0.0
|
||||
|
||||
# Home appliances
|
||||
if home_appliance_enabled:
|
||||
ha_load = home_appliance_fast.get_load_for_hour(hour) # type: ignore[union-attr]
|
||||
consumption += ha_load
|
||||
home_appliance_wh_per_hour[hour_idx] = ha_load
|
||||
|
||||
# E-Auto handling
|
||||
if ev_fast:
|
||||
soc_ev_per_hour[hour_idx] = ev_fast.current_soc_percentage() # save begin state
|
||||
if ev_charge_hours_fast[hour] > 0:
|
||||
loaded_energy_ev, ev_charge_losses = ev_fast.charge_energy(
|
||||
wh=None, hour=hour, charge_factor=ev_charge_hours_fast[hour]
|
||||
)
|
||||
consumption += loaded_energy_ev
|
||||
losses_wh_per_hour[hour_idx] += ev_charge_losses
|
||||
|
||||
# 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:
|
||||
soc_per_hour[hour_idx] = battery_fast.current_soc_percentage()
|
||||
|
||||
# Process inverter logic
|
||||
energy_feedin_grid_actual = energy_consumption_grid_actual = losses = (
|
||||
self_consumption
|
||||
) = 0.0
|
||||
|
||||
if inverter_fast:
|
||||
energy_produced = pv_prediction_wh_fast[hour]
|
||||
(
|
||||
energy_feedin_grid_actual,
|
||||
energy_consumption_grid_actual,
|
||||
losses,
|
||||
self_consumption,
|
||||
) = inverter_fast.process_energy(energy_produced, consumption, hour)
|
||||
|
||||
# AC PV Battery Charge
|
||||
if battery_fast:
|
||||
hour_ac_charge = ac_charge_hours_fast[hour]
|
||||
if hour_ac_charge > 0.0 and ac_charging_possible:
|
||||
# Cap charge factor by max_ac_charge_power_w if set
|
||||
effective_charge_factor = hour_ac_charge
|
||||
if max_ac_charge_w_fast is not None and battery_fast.max_charge_power_w > 0:
|
||||
# DC power = max_charge_power_w * factor
|
||||
# AC power = DC power / ac_to_dc_eff
|
||||
# AC power must be <= max_ac_charge_power_w
|
||||
max_dc_factor = (
|
||||
max_ac_charge_w_fast * ac_to_dc_eff_fast
|
||||
) / battery_fast.max_charge_power_w
|
||||
effective_charge_factor = min(effective_charge_factor, max_dc_factor)
|
||||
|
||||
if effective_charge_factor > 0:
|
||||
battery_charged_energy_actual, battery_losses_actual = (
|
||||
battery_fast.charge_energy(
|
||||
None, hour, charge_factor=effective_charge_factor
|
||||
)
|
||||
)
|
||||
|
||||
# DC energy entering the battery (before battery internal efficiency)
|
||||
dc_energy = battery_charged_energy_actual + battery_losses_actual
|
||||
# AC energy consumed from grid (accounts for AC→DC conversion loss)
|
||||
ac_energy = dc_energy / ac_to_dc_eff_fast
|
||||
# Genetic0Inverter AC→DC conversion losses
|
||||
inverter_charge_losses = ac_energy - dc_energy
|
||||
|
||||
consumption += ac_energy
|
||||
energy_consumption_grid_actual += ac_energy
|
||||
losses_wh_per_hour[hour_idx] += (
|
||||
battery_losses_actual + inverter_charge_losses
|
||||
)
|
||||
|
||||
# Update hourly arrays
|
||||
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] += 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
|
||||
|
||||
# Financial calculations
|
||||
costs_per_hour[hour_idx] = energy_consumption_grid_actual * hourly_electricity_price
|
||||
revenue_per_hour[hour_idx] = (
|
||||
energy_feedin_grid_actual * elect_revenue_per_hour_arr_fast[hour]
|
||||
)
|
||||
|
||||
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,
|
||||
}
|
||||
|
||||
|
||||
class Genetic0Optimization(OptimizationBase):
|
||||
"""GENETIC algorithm to solve energy optimization."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
verbose: bool = False,
|
||||
fixed_seed: Optional[int] = None,
|
||||
):
|
||||
"""Initialize the optimization problem with the required parameters."""
|
||||
self.settings = settings
|
||||
self.start_hour = 0
|
||||
self.opti_param: dict[str, Any] = {}
|
||||
self.fixed_ev_hours = (
|
||||
self.config.prediction.hours - self.config.optimization.genetic0.horizon_hours
|
||||
)
|
||||
self.fixed_ev_hours = settings.prediction_hours - settings.horizon_hours
|
||||
self.ev_possible_charge_values: list[float] = [1.0]
|
||||
# Separate charge-level list for battery AC charging (independent of EV rates).
|
||||
# Populated from parameters.pv_battery.charge_rates in optimize_ems.
|
||||
self.bat_possible_charge_values: list[float] = [1.0]
|
||||
self.verbose = verbose
|
||||
self.fix_seed = fixed_seed
|
||||
self.verbose = settings.verbose
|
||||
self.fix_seed = settings.seed
|
||||
self.optimize_ev = True
|
||||
self.optimize_dc_charge = False
|
||||
self.fitness_history: dict[str, Any] = {}
|
||||
@@ -517,23 +120,23 @@ class Genetic0Optimization(OptimizationBase):
|
||||
total_states = 3 * len_bat
|
||||
|
||||
# 1. Mutating the charge_discharge part
|
||||
charge_discharge_part = individual[: self.config.prediction.hours]
|
||||
charge_discharge_part = individual[: self.settings.prediction_hours]
|
||||
(charge_discharge_mutated,) = self.toolbox.mutate_charge_discharge(charge_discharge_part)
|
||||
|
||||
# Instead of a fixed clamping to 0..8 or 0..6 dynamically:
|
||||
charge_discharge_mutated = np.clip(charge_discharge_mutated, 0, total_states - 1)
|
||||
individual[: self.config.prediction.hours] = charge_discharge_mutated
|
||||
individual[: self.settings.prediction_hours] = charge_discharge_mutated
|
||||
|
||||
# 2. Mutating the EV charge part, if active
|
||||
if self.optimize_ev:
|
||||
ev_charge_part = individual[
|
||||
self.config.prediction.hours : self.config.prediction.hours * 2
|
||||
self.settings.prediction_hours : self.settings.prediction_hours * 2
|
||||
]
|
||||
(ev_charge_part_mutated,) = self.toolbox.mutate_ev_charge_index(ev_charge_part)
|
||||
ev_charge_part_mutated[self.config.prediction.hours - self.fixed_ev_hours :] = [
|
||||
ev_charge_part_mutated[self.settings.prediction_hours - self.fixed_ev_hours :] = [
|
||||
0
|
||||
] * self.fixed_ev_hours
|
||||
individual[self.config.prediction.hours : self.config.prediction.hours * 2] = (
|
||||
individual[self.settings.prediction_hours : self.settings.prediction_hours * 2] = (
|
||||
ev_charge_part_mutated
|
||||
)
|
||||
|
||||
@@ -549,13 +152,13 @@ class Genetic0Optimization(OptimizationBase):
|
||||
def create_individual(self) -> list[int]:
|
||||
# Start with discharge states for the individual
|
||||
individual_components = [
|
||||
self.toolbox.attr_discharge_state() for _ in range(self.config.prediction.hours)
|
||||
self.toolbox.attr_discharge_state() for _ in range(self.settings.prediction_hours)
|
||||
]
|
||||
|
||||
# Add EV charge index values if optimize_ev is True
|
||||
if self.optimize_ev:
|
||||
individual_components += [
|
||||
self.toolbox.attr_ev_charge_index() for _ in range(self.config.prediction.hours)
|
||||
self.toolbox.attr_ev_charge_index() for _ in range(self.settings.prediction_hours)
|
||||
]
|
||||
|
||||
# Add the start time of the household appliance if it's being optimized
|
||||
@@ -588,7 +191,7 @@ class Genetic0Optimization(OptimizationBase):
|
||||
individual.extend(ev_charge_hours_index.tolist())
|
||||
elif self.optimize_ev:
|
||||
# If optimize_ev is active but no EV data is available, append zeros
|
||||
individual.extend([0] * self.config.prediction.hours)
|
||||
individual.extend([0] * self.settings.prediction_hours)
|
||||
|
||||
# Add dishwasher start time if applicable
|
||||
if self.opti_param.get("home_appliance", 0) > 0 and washingstart_int is not None:
|
||||
@@ -610,13 +213,13 @@ class Genetic0Optimization(OptimizationBase):
|
||||
3. Dishwasher start time (integer if applicable).
|
||||
"""
|
||||
# Discharge hours as a NumPy array of ints
|
||||
discharge_hours_bin = np.array(individual[: self.config.prediction.hours], dtype=int)
|
||||
discharge_hours_bin = np.array(individual[: self.settings.prediction_hours], dtype=int)
|
||||
|
||||
# EV charge hours as a NumPy array of ints (if optimize_ev is True)
|
||||
ev_charge_hours_index = (
|
||||
# append ev charging states to individual
|
||||
np.array(
|
||||
individual[self.config.prediction.hours : self.config.prediction.hours * 2],
|
||||
individual[self.settings.prediction_hours : self.settings.prediction_hours * 2],
|
||||
dtype=int,
|
||||
)
|
||||
if self.optimize_ev
|
||||
@@ -722,7 +325,7 @@ class Genetic0Optimization(OptimizationBase):
|
||||
if self.optimize_dc_charge:
|
||||
self.simulation.dc_charge_hours = dc_charge_hours
|
||||
else:
|
||||
self.simulation.dc_charge_hours = np.full(self.config.prediction.hours, 1)
|
||||
self.simulation.dc_charge_hours = np.full(self.settings.prediction_hours, 1)
|
||||
self.simulation.ac_charge_hours = ac_charge_hours
|
||||
|
||||
if ev_charge_hours_index is not None:
|
||||
@@ -734,15 +337,15 @@ class Genetic0Optimization(OptimizationBase):
|
||||
self.simulation.ev_charge_hours = ev_charge_hours_float
|
||||
else:
|
||||
# discharge is set to 0 by default
|
||||
self.simulation.ev_charge_hours = np.full(self.config.prediction.hours, 0)
|
||||
self.simulation.ev_charge_hours = np.full(self.settings.prediction_hours, 0)
|
||||
|
||||
# Do the simulation and return result.
|
||||
return self.simulation.simulate(self.ems.start_datetime.hour)
|
||||
return self.simulation.simulate(self.start_hour)
|
||||
|
||||
def evaluate(
|
||||
self,
|
||||
individual: list[int],
|
||||
parameters: Genetic0OptimizationParameters,
|
||||
parameters: Genetic0Parameters,
|
||||
start_hour: int,
|
||||
worst_case: bool,
|
||||
) -> tuple[float]:
|
||||
@@ -755,9 +358,9 @@ class Genetic0Optimization(OptimizationBase):
|
||||
Args:
|
||||
individual (list[int]):
|
||||
The genome representing one candidate solution.
|
||||
parameters (Genetic0EnergyManagementParameters):
|
||||
Optimization parameters that influence simulation behavior,
|
||||
constraints, and scoring logic.
|
||||
parameters (Genetic0Parameters):
|
||||
Optimization parameters of the run: forecasts, devices and settings that
|
||||
influence simulation behavior, constraints, and scoring logic.
|
||||
start_hour (int):
|
||||
The simulation start hour (0–23 or domain-specific).
|
||||
Used to initialize time-based scheduling or constraints.
|
||||
@@ -926,9 +529,7 @@ class Genetic0Optimization(OptimizationBase):
|
||||
|
||||
# Configurable penalty multiplier (default 1 = economic loss in currency units)
|
||||
try:
|
||||
ac_penalty_factor = float(
|
||||
self.config.optimization.genetic0.penalties["ac_charge_break_even"]
|
||||
)
|
||||
ac_penalty_factor = float(self.settings.penalties["ac_charge_break_even"])
|
||||
except Exception:
|
||||
ac_penalty_factor = 1.0
|
||||
|
||||
@@ -975,7 +576,7 @@ class Genetic0Optimization(OptimizationBase):
|
||||
|
||||
if self.optimize_ev and parameters.ev and self.simulation.ev:
|
||||
try:
|
||||
penalty = self.config.optimization.genetic0.penalties["ev_soc_miss"]
|
||||
penalty = self.settings.penalties["ev_soc_miss"]
|
||||
except Exception:
|
||||
# Use default
|
||||
penalty = 10
|
||||
@@ -987,7 +588,9 @@ class Genetic0Optimization(OptimizationBase):
|
||||
ev_soc_percentage < parameters.ev.min_soc_percentage
|
||||
or ev_soc_percentage > parameters.ev.max_soc_percentage
|
||||
):
|
||||
total_balance += abs(parameters.ev.min_soc_percentage - ev_soc_percentage) * penalty
|
||||
total_balance += abs(parameters.ev.min_soc_percentage - ev_soc_percentage) * cast(
|
||||
float, penalty
|
||||
)
|
||||
|
||||
return (total_balance,)
|
||||
|
||||
@@ -1002,7 +605,7 @@ class Genetic0Optimization(OptimizationBase):
|
||||
"""
|
||||
# Set the number of inviduals in a generation
|
||||
try:
|
||||
individuals = self.config.optimization.genetic0.individuals
|
||||
individuals = self.settings.individuals
|
||||
if individuals is None:
|
||||
raise
|
||||
except Exception:
|
||||
@@ -1057,28 +660,23 @@ class Genetic0Optimization(OptimizationBase):
|
||||
|
||||
def optimize_ems(
|
||||
self,
|
||||
parameters: Genetic0OptimizationParameters,
|
||||
start_hour: Optional[int] = None,
|
||||
parameters: Genetic0Parameters,
|
||||
worst_case: bool = False,
|
||||
ngen: Optional[int] = None,
|
||||
) -> Genetic0Solution:
|
||||
"""Perform EMS (Energy Management System) optimization and visualize results."""
|
||||
if start_hour is None:
|
||||
start_hour = self.ems.start_datetime.hour
|
||||
# Start hour has to be in sync with energy management
|
||||
if start_hour != self.ems.start_datetime.hour:
|
||||
raise ValueError(
|
||||
f"Start hour not synced. EMS {self.ems.start_datetime.hour} vs. GENETIC0 {start_hour}."
|
||||
)
|
||||
) -> Genetic0Result:
|
||||
"""Perform EMS (Energy Management System) optimization.
|
||||
|
||||
Args:
|
||||
parameters: The optimization parameters of the run.
|
||||
worst_case: Evaluate the worst case.
|
||||
|
||||
Returns:
|
||||
The solution of the run.
|
||||
"""
|
||||
start_hour = parameters.start_hour
|
||||
self.start_hour = start_hour
|
||||
|
||||
# Set the number of generations
|
||||
generations = ngen
|
||||
if generations is None:
|
||||
try:
|
||||
generations = self.config.optimization.genetic0.generations
|
||||
except Exception:
|
||||
generations = 400
|
||||
logger.error("Generations not configured. Using {}.", generations)
|
||||
generations = self.settings.generations
|
||||
|
||||
self.simulation.reset()
|
||||
|
||||
@@ -1087,31 +685,25 @@ class Genetic0Optimization(OptimizationBase):
|
||||
if parameters.pv_battery:
|
||||
battery = Genetic0Battery(
|
||||
parameters.pv_battery,
|
||||
prediction_hours=self.config.prediction.hours,
|
||||
prediction_hours=self.settings.prediction_hours,
|
||||
)
|
||||
battery.set_charge_per_hour(np.full(self.config.prediction.hours, 0))
|
||||
battery.set_charge_per_hour(np.full(self.settings.prediction_hours, 0))
|
||||
|
||||
ev: Optional[Genetic0Battery] = None
|
||||
if parameters.ev:
|
||||
ev = Genetic0Battery(
|
||||
parameters.ev,
|
||||
prediction_hours=self.config.prediction.hours,
|
||||
prediction_hours=self.settings.prediction_hours,
|
||||
)
|
||||
ev.set_charge_per_hour(np.full(self.config.prediction.hours, 1))
|
||||
ev.set_charge_per_hour(np.full(self.settings.prediction_hours, 1))
|
||||
self.optimize_ev = (
|
||||
parameters.ev.min_soc_percentage - parameters.ev.initial_soc_percentage >= 0
|
||||
)
|
||||
# electrical vehicle charge rates
|
||||
if parameters.ev.charge_rates is not None:
|
||||
self.ev_possible_charge_values = parameters.ev.charge_rates
|
||||
elif (
|
||||
self.config.devices.electric_vehicles
|
||||
and len(self.config.devices.electric_vehicles) > 0
|
||||
and list(self.config.devices.electric_vehicles.values())[0].charge_rates is not None
|
||||
):
|
||||
self.ev_possible_charge_values = list(
|
||||
self.config.devices.electric_vehicles.values()
|
||||
)[0].charge_rates
|
||||
self.ev_possible_charge_values = list(parameters.ev.charge_rates)
|
||||
elif self.settings.ev_charge_rates is not None:
|
||||
self.ev_possible_charge_values = list(self.settings.ev_charge_rates)
|
||||
else:
|
||||
warning_msg = "No charge rates provided for electric vehicle - using default."
|
||||
logger.warning(warning_msg)
|
||||
@@ -1138,13 +730,9 @@ class Genetic0Optimization(OptimizationBase):
|
||||
self.bat_possible_charge_values = [
|
||||
r for r in parameters.pv_battery.charge_rates if r > 0.0
|
||||
] or [1.0]
|
||||
elif (
|
||||
self.config.devices.batteries
|
||||
and len(self.config.devices.batteries) > 0
|
||||
and list(self.config.devices.batteries.values())[0].charge_rates
|
||||
):
|
||||
elif self.settings.battery_charge_rates:
|
||||
self.bat_possible_charge_values = [
|
||||
r for r in list(self.config.devices.batteries.values())[0].charge_rates if r > 0.0
|
||||
r for r in self.settings.battery_charge_rates if r > 0.0
|
||||
] or [1.0]
|
||||
else:
|
||||
self.bat_possible_charge_values = [1.0]
|
||||
@@ -1154,8 +742,8 @@ class Genetic0Optimization(OptimizationBase):
|
||||
dishwasher = (
|
||||
Genetic0HomeAppliance(
|
||||
parameters=parameters.dishwasher,
|
||||
optimization_hours=self.config.optimization.genetic0.horizon_hours,
|
||||
prediction_hours=self.config.prediction.hours,
|
||||
optimization_hours=self.settings.horizon_hours,
|
||||
prediction_hours=self.settings.prediction_hours,
|
||||
)
|
||||
if parameters.dishwasher is not None
|
||||
else None
|
||||
@@ -1167,13 +755,14 @@ class Genetic0Optimization(OptimizationBase):
|
||||
inverter = Genetic0Inverter(
|
||||
parameters.inverter,
|
||||
battery=battery,
|
||||
self_consumption_interpolator=self.settings.self_consumption_interpolator,
|
||||
)
|
||||
|
||||
# Prepare device simulation
|
||||
self.simulation.prepare(
|
||||
parameters=parameters.ems,
|
||||
optimization_hours=self.config.optimization.genetic0.horizon_hours,
|
||||
prediction_hours=self.config.prediction.hours,
|
||||
optimization_hours=self.settings.horizon_hours,
|
||||
prediction_hours=self.settings.prediction_hours,
|
||||
inverter=inverter, # battery is part of inverter
|
||||
ev=ev,
|
||||
home_appliance=dishwasher,
|
||||
@@ -1187,7 +776,11 @@ class Genetic0Optimization(OptimizationBase):
|
||||
)
|
||||
|
||||
start_time = time.time()
|
||||
start_solution, extra_data = self.optimize(parameters.start_solution, ngen=generations)
|
||||
# None (not configured) is passed on as before.
|
||||
start_solution, extra_data = self.optimize(
|
||||
None if parameters.start_solution is None else list(parameters.start_solution),
|
||||
ngen=generations, # type: ignore[arg-type]
|
||||
)
|
||||
elapsed_time = time.time() - start_time
|
||||
logger.debug(f"Time evaluate inner: {elapsed_time:.4f} sec.")
|
||||
|
||||
@@ -1225,20 +818,23 @@ class Genetic0Optimization(OptimizationBase):
|
||||
else []
|
||||
)
|
||||
|
||||
return Genetic0Solution(
|
||||
**{
|
||||
"parameters": parameters,
|
||||
"ac_charge": ac_charge_hours,
|
||||
"dc_charge": dc_charge_hours,
|
||||
"discharge_allowed": discharge,
|
||||
"ev_charge_hours_float": ev_charge_hours_float,
|
||||
"result": Genetic0SimulationResult(**simulation_result),
|
||||
"ev_obj": self.simulation.ev,
|
||||
"start_hour": start_hour,
|
||||
"start_solution": start_solution,
|
||||
"washingstart": washingstart_int,
|
||||
"extra_data": extra_data,
|
||||
"fitness_history": self.fitness_history,
|
||||
"fixed_seed": self.fix_seed,
|
||||
}
|
||||
return Genetic0Result(
|
||||
ac_charge=float_list(ac_charge_hours),
|
||||
dc_charge=float_list(dc_charge_hours),
|
||||
discharge_allowed=int_list(discharge),
|
||||
ev_charge_hours_float=(
|
||||
None if ev_charge_hours_float is None else float_list(ev_charge_hours_float)
|
||||
),
|
||||
result=Genetic0SimulationOutput.from_simulation(simulation_result),
|
||||
ev_obj=(
|
||||
None
|
||||
if self.simulation.ev is None
|
||||
else Genetic0ElectricVehicleState.from_battery(self.simulation.ev.to_dict())
|
||||
),
|
||||
start_hour=start_hour,
|
||||
start_solution=None if start_solution is None else float_list(start_solution),
|
||||
washingstart=None if washingstart_int is None else int(washingstart_int),
|
||||
extra_data=extra_data,
|
||||
fitness_history=self.fitness_history,
|
||||
fixed_seed=self.fix_seed,
|
||||
)
|
||||
@@ -0,0 +1,592 @@
|
||||
"""REST API of GENETIC0 (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 optimization parameters and the result of a run.
|
||||
"""
|
||||
|
||||
import dataclasses
|
||||
from typing import Annotated, Any, Optional, Union
|
||||
|
||||
from fastapi import APIRouter, Depends, Query, Response
|
||||
from pydantic import AliasChoices, ConfigDict, Field, computed_field, field_validator
|
||||
|
||||
from akkudoktoreos.optimization.genetic0.genetic0parameters import Genetic0Parameters
|
||||
from akkudoktoreos.optimization.genetic0.genetic0request import (
|
||||
Genetic0ParametersBaseModel,
|
||||
Genetic0Request,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic0.genetic0result import (
|
||||
Genetic0ElectricVehicleState,
|
||||
Genetic0Result,
|
||||
)
|
||||
from akkudoktoreos.optimization.optimizer import (
|
||||
OptimizerApi,
|
||||
OptimizerProblem,
|
||||
OptimizerRun,
|
||||
RunTrigger,
|
||||
)
|
||||
from akkudoktoreos.utils.datetimeutil import to_datetime
|
||||
from akkudoktoreos.utils.utils import NumpyEncoder
|
||||
|
||||
|
||||
class DeviceOptimizeResult(Genetic0ParametersBaseModel):
|
||||
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 Genetic0ElectricVehicleResult(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."}
|
||||
)
|
||||
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 Genetic0SimulationResult(Genetic0ParametersBaseModel):
|
||||
"""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",
|
||||
mode="before",
|
||||
)
|
||||
def convert_numpy(cls, field: Any) -> Any:
|
||||
return NumpyEncoder.convert_numpy(field)[0]
|
||||
|
||||
|
||||
# Legacy GENETIC solution dataset. To keep the /optimize endpoint compatible.
|
||||
class Genetic0SolutionLegacy(Genetic0ParametersBaseModel):
|
||||
"""GENETIC0 solution legacy dataset."""
|
||||
|
||||
model_config = ConfigDict(populate_by_name=True, extra="ignore")
|
||||
|
||||
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: Genetic0SimulationResult
|
||||
ev_obj: Optional[Genetic0ElectricVehicleResult] = Field(
|
||||
validation_alias=AliasChoices("ev_obj", "eauto_obj"),
|
||||
json_schema_extra={"description": "Electric vehicle state after optimization."},
|
||||
)
|
||||
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)."
|
||||
},
|
||||
)
|
||||
|
||||
# Computed fields for backward compatibility (deprecated German names)
|
||||
@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[Genetic0ElectricVehicleResult]:
|
||||
"""Deprecated: Use ev_obj instead."""
|
||||
return self.ev_obj
|
||||
|
||||
@field_validator(
|
||||
"ac_charge",
|
||||
"dc_charge",
|
||||
"discharge_allowed",
|
||||
mode="before",
|
||||
)
|
||||
def convert_numpy(cls, field: Any) -> Any:
|
||||
return NumpyEncoder.convert_numpy(field)[0]
|
||||
|
||||
@field_validator(
|
||||
"ev_obj",
|
||||
mode="before",
|
||||
)
|
||||
def convert_eauto(cls, field: Any) -> Any:
|
||||
if isinstance(field, Genetic0ElectricVehicleState):
|
||||
return Genetic0ElectricVehicleResult(**dataclasses.asdict(field))
|
||||
return field
|
||||
|
||||
|
||||
class Genetic0Solution(Genetic0ParametersBaseModel):
|
||||
"""**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: Genetic0Request = 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: Genetic0SimulationResult
|
||||
ev_obj: Optional[Genetic0ElectricVehicleResult] = 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, Union[list[int], list[float]]]] = 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 fields for backward compatibility (deprecated German names)
|
||||
@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[Genetic0ElectricVehicleResult]:
|
||||
"""Deprecated: Use ev_obj instead."""
|
||||
return self.ev_obj
|
||||
|
||||
@field_validator(
|
||||
"ac_charge",
|
||||
"dc_charge",
|
||||
"discharge_allowed",
|
||||
mode="before",
|
||||
)
|
||||
def convert_numpy(cls, field: Any) -> Any:
|
||||
return NumpyEncoder.convert_numpy(field)[0]
|
||||
|
||||
@field_validator(
|
||||
"ev_obj",
|
||||
mode="before",
|
||||
)
|
||||
def convert_eauto(cls, field: Any) -> Any:
|
||||
if isinstance(field, Genetic0ElectricVehicleState):
|
||||
return Genetic0ElectricVehicleResult(**dataclasses.asdict(field))
|
||||
return field
|
||||
|
||||
|
||||
def solution_response(parameters: Genetic0Parameters, result: Genetic0Result) -> Genetic0Solution:
|
||||
"""The public solution of a run.
|
||||
|
||||
Args:
|
||||
parameters: The optimization parameters of the run; their request is echoed.
|
||||
result: The result of the run.
|
||||
|
||||
Returns:
|
||||
The solution as the REST API returns it.
|
||||
"""
|
||||
return Genetic0Solution.model_validate(
|
||||
{
|
||||
"parameters": parameters.request,
|
||||
"ac_charge": result.ac_charge,
|
||||
"dc_charge": result.dc_charge,
|
||||
"discharge_allowed": result.discharge_allowed,
|
||||
"ev_charge_hours_float": result.ev_charge_hours_float,
|
||||
"result": dataclasses.asdict(result.result),
|
||||
"ev_obj": result.ev_obj,
|
||||
"start_hour": result.start_hour,
|
||||
"start_solution": result.start_solution,
|
||||
"washingstart": result.washingstart,
|
||||
"extra_data": result.extra_data,
|
||||
"fitness_history": result.fitness_history,
|
||||
"fixed_seed": result.fixed_seed,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def legacy_response(result: Genetic0Result) -> Genetic0SolutionLegacy:
|
||||
"""The solution of a run as the deprecated ``POST /optimize`` returns it.
|
||||
|
||||
Args:
|
||||
result: The result of the run.
|
||||
|
||||
Returns:
|
||||
The legacy solution.
|
||||
"""
|
||||
return Genetic0SolutionLegacy.model_validate(
|
||||
{
|
||||
"ac_charge": result.ac_charge,
|
||||
"dc_charge": result.dc_charge,
|
||||
"discharge_allowed": result.discharge_allowed,
|
||||
"ev_charge_hours_float": result.ev_charge_hours_float,
|
||||
"result": dataclasses.asdict(result.result),
|
||||
"ev_obj": result.ev_obj,
|
||||
"start_solution": result.start_solution,
|
||||
"washingstart": result.washingstart,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------
|
||||
# Router
|
||||
# ----------------------------------------------------------------------------------------------
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def last_run() -> Optional[OptimizerRun[Genetic0Parameters, Genetic0Result]]:
|
||||
"""Placeholder dependency: the latest GENETIC0 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 GENETIC0 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 GENETIC0 for the server.
|
||||
|
||||
Returns:
|
||||
The router and its placeholder dependencies.
|
||||
"""
|
||||
return OptimizerApi(router=router, last_run=last_run, run=run)
|
||||
|
||||
|
||||
@router.post("/optimize", tags=["optimize"])
|
||||
async def fastapi_optimize(
|
||||
parameters: Genetic0Request,
|
||||
start_hour: Annotated[
|
||||
Optional[int], Query(description="Defaults to current hour of the day.")
|
||||
] = None,
|
||||
ngen: Annotated[
|
||||
Optional[int], Query(description="Number of indivuals to generate for genetic algorithm.")
|
||||
] = None,
|
||||
trigger: RunTrigger = Depends(run),
|
||||
) -> Genetic0SolutionLegacy:
|
||||
"""Deprecated: Optimize.
|
||||
|
||||
Endpoint to handle optimization.
|
||||
|
||||
Uses the `classic` GENETIC0 optimisation algorithm (__NO__ 15-minutes slots).
|
||||
|
||||
Note:
|
||||
Use automatic optimization instead.
|
||||
"v1/energy-management/optimization/solution/GENETIC0"
|
||||
"""
|
||||
if start_hour is None:
|
||||
start_datetime = None
|
||||
else:
|
||||
start_datetime = to_datetime().set(hour=start_hour)
|
||||
|
||||
# Ensure there is only one optimization/ energy management run at a time
|
||||
result = await trigger(
|
||||
start_datetime=start_datetime,
|
||||
request=parameters,
|
||||
overrides={"generations": ngen},
|
||||
)
|
||||
|
||||
if result is None:
|
||||
raise OptimizerProblem(
|
||||
status=404,
|
||||
title="Optimization solution retrieval failed",
|
||||
detail="Can not get the 'GENETIC0' optimization solution.",
|
||||
)
|
||||
|
||||
# Create compatible solution.
|
||||
return legacy_response(result)
|
||||
|
||||
|
||||
@router.get("/v1/energy-management/optimization/solution/GENETIC0", tags=["energy-management"])
|
||||
async def fastapi_energy_management_optimization_solution_genetic0_get(
|
||||
latest: Optional[OptimizerRun[Genetic0Parameters, Genetic0Result]] = Depends(last_run),
|
||||
) -> Genetic0Solution:
|
||||
"""Get the latest GENETIC0 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 'GENETIC0' optimization solution.\n"
|
||||
"Did you configure automatic 'GENETIC0' optimization?\n"
|
||||
"Did you run the optimization/ energy management?"
|
||||
),
|
||||
)
|
||||
return solution_response(latest.parameters, latest.result)
|
||||
|
||||
|
||||
@router.get("/visualization_results.pdf", tags=["optimize"])
|
||||
def get_pdf(
|
||||
latest: Optional[OptimizerRun[Genetic0Parameters, Genetic0Result]] = Depends(last_run),
|
||||
) -> Response:
|
||||
"""PDF report of the latest GENETIC0 run."""
|
||||
if latest is None:
|
||||
raise OptimizerProblem(
|
||||
status=404,
|
||||
title="Optimization solution report retrieval failed",
|
||||
detail="Can not get the 'GENETIC0' optimization solution.",
|
||||
)
|
||||
|
||||
# matplotlib is only needed for the PDF report; import it on first use.
|
||||
from akkudoktoreos.optimization.genetic0.genetic0visualize import (
|
||||
genetic0_prepare_visualize,
|
||||
)
|
||||
|
||||
pdf = genetic0_prepare_visualize(parameters=latest.parameters, solution=latest.result)
|
||||
|
||||
return Response(
|
||||
content=pdf,
|
||||
media_type="application/pdf",
|
||||
headers={"Content-Disposition": 'inline; filename="optimization-report.pdf"'},
|
||||
)
|
||||
@@ -0,0 +1,647 @@
|
||||
"""Solution conversion of GENETIC0 (ADR 0003, 0006).
|
||||
|
||||
Turns the result of a run into the optimization solution and the energy management plan, from
|
||||
the optimization parameters and the result alone: the start, time zone, device IDs and
|
||||
prediction series come from the parameters' presentation data, not from the configuration,
|
||||
the predictions or the EMS.
|
||||
"""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
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.core.types import (
|
||||
FillMethod,
|
||||
)
|
||||
from akkudoktoreos.devices.devicesabc import (
|
||||
ApplianceOperationMode,
|
||||
BatteryOperationMode,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic0.genetic0parameters import Genetic0Parameters
|
||||
from akkudoktoreos.optimization.genetic0.genetic0request import (
|
||||
Genetic0InverterRequest,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic0.genetic0result import Genetic0Result
|
||||
from akkudoktoreos.optimization.optimization import OptimizationSolution
|
||||
from akkudoktoreos.utils.datetimeutil import to_datetime
|
||||
|
||||
|
||||
async def convert(
|
||||
parameters: Genetic0Parameters, result: Genetic0Result
|
||||
) -> 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_operation_from_solution(
|
||||
parameters: Genetic0Parameters,
|
||||
result: Genetic0Result,
|
||||
ac_charge: float,
|
||||
dc_charge: float,
|
||||
discharge_allowed: bool,
|
||||
) -> 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 is permitted.
|
||||
|
||||
Returns:
|
||||
tuple[BatteryOperationMode, float]: A tuple containing
|
||||
- `BatteryOperationMode`: the representative high-level operation mode.
|
||||
- `float`: the operation factor corresponding to the active signal.
|
||||
|
||||
Notes:
|
||||
- The mapping prioritizes 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:
|
||||
return BatteryOperationMode.IDLE, 1.0
|
||||
|
||||
# (0,0,1) → Discharge only
|
||||
if ac_charge <= 0.0 and dc_charge <= 0.0 and discharge_allowed:
|
||||
return BatteryOperationMode.PEAK_SHAVING, 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(parameters: Genetic0Parameters) -> Optional[Genetic0InverterRequest]:
|
||||
"""Return the inverter parameters the solution was computed with."""
|
||||
return parameters.request.inverter
|
||||
|
||||
|
||||
def _soc_clamped_operation_factors(
|
||||
parameters: Genetic0Parameters,
|
||||
result: Genetic0Result,
|
||||
ac_charge: float,
|
||||
dc_charge: float,
|
||||
discharge_allowed: bool,
|
||||
soc_pct: float,
|
||||
) -> tuple[float, float, 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 hour. 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.
|
||||
|
||||
The battery values are the optimizer parameters the solution was computed
|
||||
with (capacity, efficiency, power limit and SOC range as resolved from the
|
||||
battery profile), not the raw battery settings.
|
||||
"""
|
||||
bat = parameters.request.pv_battery
|
||||
if bat is None:
|
||||
return ac_charge, dc_charge, discharge_allowed
|
||||
|
||||
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)
|
||||
# Same fallback as the GENETIC0 battery simulation.
|
||||
bat_max_charge_power_w = (
|
||||
float(bat.max_charge_power_w) if bat.max_charge_power_w is not None else capacity_wh
|
||||
)
|
||||
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 = _inverter_parameters(parameters)
|
||||
ac_to_dc_eff = float(inv.ac_to_dc_efficiency) if inv else 1.0
|
||||
max_ac_cp_w = (
|
||||
float(inv.max_ac_charge_power_w)
|
||||
if inv and inv.max_ac_charge_power_w is not None
|
||||
else bat_max_charge_power_w
|
||||
)
|
||||
max_dc_per_h_wh = effective_ac * max_ac_cp_w * ac_to_dc_eff * ch_eff
|
||||
if max_dc_per_h_wh > headroom_wh:
|
||||
effective_ac = effective_ac * (headroom_wh / max_dc_per_h_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)
|
||||
|
||||
return effective_ac, effective_dc, effective_dis
|
||||
|
||||
|
||||
async def optimization_solution(
|
||||
parameters: Genetic0Parameters,
|
||||
result: Genetic0Result,
|
||||
) -> OptimizationSolution:
|
||||
"""Provide the genetic solution as a general optimization solution.
|
||||
|
||||
The battery modes are controlled by the grid control triggers:
|
||||
- ac_charge: charge from grid
|
||||
- discharge_allowed: discharge to grid
|
||||
|
||||
The following battery modes are supported:
|
||||
- SELF_CONSUMPTION: ac_charge == 0 and discharge_allowed == 0
|
||||
- GRID_SUPPORT_EXPORT: ac_charge == 0 and discharge_allowed == 1
|
||||
- GRID_SUPPORT_IMPORT: ac_charge > 0 and discharge_allowed == 0 or 1
|
||||
|
||||
Args:
|
||||
parameters: The optimization parameters of the run.
|
||||
result: The result of the run.
|
||||
|
||||
Returns:
|
||||
The optimization solution.
|
||||
"""
|
||||
start_datetime = parameters.presentation.start_datetime
|
||||
start_day_hour = to_datetime(start_datetime, in_timezone=parameters.presentation.timezone).hour
|
||||
interval_hours = 1
|
||||
power_to_energy_per_interval_factor = 1.0
|
||||
|
||||
# --- 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_hour)
|
||||
time_index = pd.date_range(
|
||||
start=start_datetime,
|
||||
periods=periods,
|
||||
freq=f"{interval_hours}h",
|
||||
)
|
||||
n_points = len(time_index)
|
||||
|
||||
# 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_hour
|
||||
"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,
|
||||
)
|
||||
|
||||
# Add battery data
|
||||
battery_device_id = parameters.presentation.battery_device_id
|
||||
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_hour
|
||||
]
|
||||
operation: dict[str, list[float]] = {
|
||||
"genetic_ac_charge_factor": [],
|
||||
"genetic_dc_charge_factor": [],
|
||||
"genetic_discharge_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_hour:
|
||||
continue
|
||||
if hour_idx >= start_day_hour + 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])
|
||||
|
||||
# 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))
|
||||
|
||||
# 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_hour
|
||||
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 = _soc_clamped_operation_factors(
|
||||
parameters, result, ac_charge_hour, dc_charge_hour, discharge_allowed_hour, soc_h_pct
|
||||
)
|
||||
operation_mode, operation_mode_factor = _battery_operation_from_solution(
|
||||
parameters, result, eff_ac, eff_dc, eff_dis
|
||||
)
|
||||
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
|
||||
# ev_charge_hours_float start at hour 0 of start day
|
||||
# result.ev_soc_per_hour start at start_datetime.hour
|
||||
if result.ev_obj:
|
||||
ev_device_id = parameters.presentation.ev_device_id
|
||||
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_hour:
|
||||
continue
|
||||
if hour_idx >= start_day_hour + n_points:
|
||||
break
|
||||
operation["genetic_ev_charge_factor"].append(rate)
|
||||
operation_mode, operation_mode_factor = _battery_operation_from_solution(
|
||||
parameters, result, 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
|
||||
if parameters.presentation.home_appliance_enabled:
|
||||
# Use the preparation's decision and not result.washingstart, as washingstart
|
||||
# may be None (no start)
|
||||
# even if configured to be started.
|
||||
homeappliance_device_id = parameters.presentation.home_appliance_device_id
|
||||
# result starts at start_day_hour
|
||||
solution[f"{homeappliance_device_id}_energy_wh"] = result.result.home_appliance_wh_per_hour[
|
||||
:n_points
|
||||
]
|
||||
operation = {
|
||||
f"{homeappliance_device_id}_run_op_mode": [],
|
||||
f"{homeappliance_device_id}_run_op_factor": [],
|
||||
f"{homeappliance_device_id}_off_op_mode": [],
|
||||
f"{homeappliance_device_id}_off_op_factor": [],
|
||||
}
|
||||
for hour_idx, energy in enumerate(solution[f"{homeappliance_device_id}_energy_wh"]):
|
||||
if energy > 0.0:
|
||||
operation[f"{homeappliance_device_id}_run_op_mode"].append(1.0)
|
||||
operation[f"{homeappliance_device_id}_run_op_factor"].append(1.0)
|
||||
operation[f"{homeappliance_device_id}_off_op_mode"].append(0.0)
|
||||
operation[f"{homeappliance_device_id}_off_op_factor"].append(0.0)
|
||||
else:
|
||||
operation[f"{homeappliance_device_id}_run_op_mode"].append(0.0)
|
||||
operation[f"{homeappliance_device_id}_run_op_factor"].append(0.0)
|
||||
operation[f"{homeappliance_device_id}_off_op_mode"].append(1.0)
|
||||
operation[f"{homeappliance_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,
|
||||
)
|
||||
|
||||
prediction_specs: list[tuple[str, FillMethod, str, float]] = [
|
||||
(
|
||||
"pvforecast_ac_power",
|
||||
"linear",
|
||||
"pvforecast_ac_energy_wh",
|
||||
power_to_energy_per_interval_factor,
|
||||
),
|
||||
(
|
||||
"pvforecast_dc_power",
|
||||
"linear",
|
||||
"pvforecast_dc_energy_wh",
|
||||
power_to_energy_per_interval_factor,
|
||||
),
|
||||
(
|
||||
"elecprice_marketprice_wh",
|
||||
"ffill",
|
||||
"elec_price_amt_kwh",
|
||||
1000.0,
|
||||
),
|
||||
(
|
||||
"feed_in_tariff_wh",
|
||||
"ffill",
|
||||
"feed_in_tariff_amt_kwh",
|
||||
1000.0,
|
||||
),
|
||||
(
|
||||
"weather_temp_air",
|
||||
"linear",
|
||||
"weather_air_temp_celcius",
|
||||
1.0,
|
||||
),
|
||||
(
|
||||
"loadforecast_power_w",
|
||||
"linear",
|
||||
"loadforecast_energy_wh",
|
||||
power_to_energy_per_interval_factor,
|
||||
),
|
||||
(
|
||||
"loadakkudoktor_std_power_w",
|
||||
"linear",
|
||||
"loadakkudoktor_std_energy_wh",
|
||||
power_to_energy_per_interval_factor,
|
||||
),
|
||||
(
|
||||
"loadakkudoktor_mean_power_w",
|
||||
"linear",
|
||||
"loadakkudoktor_mean_energy_wh",
|
||||
power_to_energy_per_interval_factor,
|
||||
),
|
||||
]
|
||||
|
||||
# The series were read by the parameter preparation, for exactly these hours.
|
||||
for pred_key, _, pred_solution_key, pred_solution_factor in prediction_specs:
|
||||
series = parameters.presentation.prediction_series.get(pred_key)
|
||||
if series is None:
|
||||
continue
|
||||
array = np.asarray(series[:n_points], dtype=float)
|
||||
if array.size == n_points and array.size > 0 and not np.any(pd.isna(array)):
|
||||
prediction[pred_solution_key] = (array * pred_solution_factor).tolist()
|
||||
|
||||
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=start_datetime.add(hours=parameters.settings.horizon_hours),
|
||||
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: Genetic0Parameters,
|
||||
result: Genetic0Result,
|
||||
) -> EnergyManagementPlan:
|
||||
"""Provide the genetic solution as an energy management plan.
|
||||
|
||||
Args:
|
||||
parameters: The optimization parameters of the run.
|
||||
result: The result of the run.
|
||||
|
||||
Returns:
|
||||
The energy management plan.
|
||||
"""
|
||||
start_datetime = parameters.presentation.start_datetime
|
||||
start_day_hour = to_datetime(start_datetime, in_timezone=parameters.presentation.timezone).hour
|
||||
plan = EnergyManagementPlan(
|
||||
id=f"plan-genetic@{to_datetime(as_string=True)}",
|
||||
generated_at=to_datetime(),
|
||||
instructions=[],
|
||||
comment="Energy management plan derived from GeneticSolution.",
|
||||
)
|
||||
|
||||
# Add battery instructions (fill rate based control)
|
||||
last_operation_mode: Optional[str] = None
|
||||
last_operation_mode_factor: Optional[float] = None
|
||||
resource_id = parameters.presentation.battery_device_id
|
||||
# ac_charge, dc_charge, discharge_allowed start at hour 0 of start day
|
||||
logger.debug("BAT: {} - {}", resource_id, result.ac_charge[start_day_hour:])
|
||||
for hour_idx, rate in enumerate(result.ac_charge):
|
||||
if hour_idx < start_day_hour:
|
||||
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_hour
|
||||
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 = _soc_clamped_operation_factors(
|
||||
parameters,
|
||||
result,
|
||||
result.ac_charge[hour_idx],
|
||||
result.dc_charge[hour_idx],
|
||||
bool(result.discharge_allowed[hour_idx]),
|
||||
soc_h_pct,
|
||||
)
|
||||
operation_mode, operation_mode_factor = _battery_operation_from_solution(
|
||||
parameters, result, eff_ac, eff_dc, eff_dis
|
||||
)
|
||||
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(hours=hour_idx - start_day_hour)
|
||||
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)
|
||||
# ev_charge_hours_float start at hour 0 of start day
|
||||
if result.ev_obj:
|
||||
resource_id = parameters.presentation.ev_device_id
|
||||
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_hour:])
|
||||
for hour_idx, rate in enumerate(result.ev_charge_hours_float):
|
||||
if hour_idx < start_day_hour:
|
||||
continue
|
||||
operation_mode, operation_mode_factor = _battery_operation_from_solution(
|
||||
parameters, result, 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(hours=hour_idx - start_day_hour)
|
||||
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)
|
||||
if parameters.presentation.home_appliance_enabled:
|
||||
# Use the preparation's decision and not result.washingstart, as washingstart
|
||||
# may be None (no start)
|
||||
# even if configured to be started.
|
||||
resource_id = parameters.presentation.home_appliance_device_id
|
||||
last_energy: Optional[float] = None
|
||||
for hours, energy in enumerate(result.result.home_appliance_wh_per_hour):
|
||||
# hours starts at start_datetime with 0
|
||||
if energy is None:
|
||||
raise ValueError(
|
||||
f"Unexpected value {energy} in {result.result.home_appliance_wh_per_hour}"
|
||||
)
|
||||
if last_energy is None or energy != last_energy:
|
||||
if energy > 0.0:
|
||||
operation_mode = ApplianceOperationMode.RUN # type: ignore[assignment]
|
||||
else:
|
||||
operation_mode = ApplianceOperationMode.OFF # type: ignore[assignment]
|
||||
operation_mode_factor = 1.0
|
||||
execution_time = start_datetime.add(hours=hours)
|
||||
plan.add_instruction(
|
||||
DDBCInstruction(
|
||||
resource_id=resource_id,
|
||||
execution_time=execution_time,
|
||||
actuator_id=resource_id,
|
||||
operation_mode_id=operation_mode,
|
||||
operation_mode_factor=operation_mode_factor,
|
||||
)
|
||||
)
|
||||
last_energy = energy
|
||||
|
||||
return plan
|
||||
@@ -1,19 +0,0 @@
|
||||
"""Genetic0 optimization algorithm device interfaces/ parameters."""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from akkudoktoreos.optimization.genetic0.genetic0abc import Genetic0ParametersBaseModel
|
||||
|
||||
|
||||
class Genetic0DeviceParameters(Genetic0ParametersBaseModel):
|
||||
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,26 @@
|
||||
"""Hourly forecasts and prices of a GENETIC0 run, as the simulation reads them.
|
||||
|
||||
A module of its own so that the request can derive them without importing the simulation.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Union
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Genetic0EnergyManagementParameters:
|
||||
"""Hourly forecasts and prices of the simulation, from midnight of the start day.
|
||||
|
||||
Attributes:
|
||||
pv_forecast_wh: PV energy per hour in watt-hours.
|
||||
electricity_price_per_wh: Electricity price per watt-hour.
|
||||
feed_in_tariff_per_wh: Feed-in tariff per watt-hour, per hour or one constant value.
|
||||
price_per_wh_battery: Cost of battery energy per watt-hour.
|
||||
total_load: Load energy per hour in watt-hours.
|
||||
"""
|
||||
|
||||
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, ...]
|
||||
@@ -1,27 +1,49 @@
|
||||
#!/usr/bin/env python
|
||||
"""Self-consumption probability of the GENETIC0 inverter simulation.
|
||||
|
||||
The backend comes from the run settings (``optimization.self_consumption_interpolator``, read by
|
||||
the parameter preparation), never from the configuration directly (ADR 0003).
|
||||
"""
|
||||
|
||||
import functools
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
import numpy as np
|
||||
|
||||
from akkudoktoreos.core.cache import cache_energy_management
|
||||
from akkudoktoreos.core.coreabc import SingletonMixin
|
||||
from akkudoktoreos.utils.gridinterpolator import (
|
||||
GridInterpolatorBackend,
|
||||
SwitchableGridInterpolator,
|
||||
configured_grid_interpolator_backend,
|
||||
load_grid_interpolator,
|
||||
)
|
||||
|
||||
# Distinct (load, PV) pairs remembered per interpolator; the values never change.
|
||||
_CACHE_SIZE = 1 << 16
|
||||
|
||||
|
||||
class SelfConsumptionProbabilityInterpolator:
|
||||
def __init__(self, filepath: str | Path):
|
||||
def __init__(
|
||||
self,
|
||||
filepath: str | Path,
|
||||
backend: GridInterpolatorBackend = GridInterpolatorBackend.SCIPY,
|
||||
) -> None:
|
||||
"""Load the self-consumption table.
|
||||
|
||||
Args:
|
||||
filepath: Pickled table.
|
||||
backend: How the table is evaluated.
|
||||
"""
|
||||
self.filepath = filepath
|
||||
self.backend = backend
|
||||
# The table is a pickled SciPy RegularGridInterpolator. It is read
|
||||
# without SciPy; optimization.self_consumption_interpolator decides
|
||||
# whether SciPy (default) or NumPy evaluates it.
|
||||
# without SciPy; the backend decides whether SciPy (default) or NumPy
|
||||
# evaluates it.
|
||||
self.interpolator = SwitchableGridInterpolator(
|
||||
load_grid_interpolator(self.filepath), configured_grid_interpolator_backend
|
||||
load_grid_interpolator(self.filepath), lambda: self.backend
|
||||
)
|
||||
# The table is static, so results can be kept across runs.
|
||||
self.calculate_self_consumption = functools.lru_cache(maxsize=_CACHE_SIZE)(
|
||||
self._calculate_self_consumption
|
||||
)
|
||||
|
||||
def _generate_points(
|
||||
@@ -32,11 +54,10 @@ class SelfConsumptionProbabilityInterpolator:
|
||||
points = np.array([np.full_like(partial_loads, load_1h_power), partial_loads]).T
|
||||
return points, partial_loads
|
||||
|
||||
@cache_energy_management
|
||||
def calculate_self_consumption(self, load_1h_power: float, pv_power: float) -> float:
|
||||
def _calculate_self_consumption(self, load_1h_power: float, pv_power: float) -> float:
|
||||
"""Calculate the PV self-consumption rate using RegularGridInterpolator.
|
||||
|
||||
The results are cached until the start of the next energy management run/ optimization.
|
||||
Called through ``calculate_self_consumption``, which caches the results.
|
||||
|
||||
Args:
|
||||
- last_1h_power: 1h power levels (W).
|
||||
@@ -88,27 +109,44 @@ class SelfConsumptionProbabilityInterpolator:
|
||||
# return self_consumption_rate
|
||||
|
||||
|
||||
class Genetic0LoadInterpolator(SelfConsumptionProbabilityInterpolator, SingletonMixin):
|
||||
def __init__(self) -> None:
|
||||
if hasattr(self, "_initialized"):
|
||||
return
|
||||
class Genetic0LoadInterpolator(SelfConsumptionProbabilityInterpolator):
|
||||
"""The self-consumption table shipped with EOS."""
|
||||
|
||||
def __init__(self, backend: GridInterpolatorBackend = GridInterpolatorBackend.SCIPY) -> None:
|
||||
"""Load the shipped table.
|
||||
|
||||
Args:
|
||||
backend: How the table is evaluated.
|
||||
"""
|
||||
filename = (
|
||||
Path(__file__).parent.parent.parent.resolve()
|
||||
/ "data"
|
||||
/ "genetic0_load_interpolator.pkl"
|
||||
)
|
||||
super().__init__(filename)
|
||||
super().__init__(filename, backend)
|
||||
|
||||
|
||||
# Created on first use.
|
||||
_genetic0_load_interpolator: Optional[Genetic0LoadInterpolator] = None
|
||||
# One interpolator per backend, created on first use.
|
||||
_genetic0_load_interpolators: dict[GridInterpolatorBackend, Genetic0LoadInterpolator] = {}
|
||||
_genetic0_load_interpolator_lock = threading.Lock()
|
||||
|
||||
|
||||
def get_genetic0_load_interpolator() -> Genetic0LoadInterpolator:
|
||||
global _genetic0_load_interpolator
|
||||
if _genetic0_load_interpolator is None:
|
||||
def get_genetic0_load_interpolator(
|
||||
backend: GridInterpolatorBackend = GridInterpolatorBackend.SCIPY,
|
||||
) -> Genetic0LoadInterpolator:
|
||||
"""Return the shared interpolator for ``backend``.
|
||||
|
||||
Args:
|
||||
backend: How the table is evaluated.
|
||||
|
||||
Returns:
|
||||
The interpolator, loaded on first use.
|
||||
"""
|
||||
interpolator = _genetic0_load_interpolators.get(backend)
|
||||
if interpolator is None:
|
||||
with _genetic0_load_interpolator_lock:
|
||||
if _genetic0_load_interpolator is None:
|
||||
_genetic0_load_interpolator = Genetic0LoadInterpolator()
|
||||
return _genetic0_load_interpolator
|
||||
interpolator = _genetic0_load_interpolators.get(backend)
|
||||
if interpolator is None:
|
||||
interpolator = Genetic0LoadInterpolator(backend)
|
||||
_genetic0_load_interpolators[backend] = interpolator
|
||||
return interpolator
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
"""GENETIC0 behind the optimizer interface (ADR 0006).
|
||||
|
||||
Runs ``Genetic0Optimization``; the result is the frozen ``Genetic0Result``.
|
||||
"""
|
||||
|
||||
from collections.abc import Mapping
|
||||
from typing import Any, Optional
|
||||
|
||||
from akkudoktoreos.core.emplan import EnergyManagementPlan
|
||||
from akkudoktoreos.optimization.genetic0 import genetic0convert, genetic0prepare
|
||||
from akkudoktoreos.optimization.genetic0.genetic0parameters import Genetic0Parameters
|
||||
from akkudoktoreos.optimization.genetic0.genetic0request import (
|
||||
Genetic0Request,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic0.genetic0result import Genetic0Result
|
||||
from akkudoktoreos.optimization.optimization import OptimizationSolution
|
||||
from akkudoktoreos.optimization.optimizer import OptimizerApi
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime
|
||||
|
||||
|
||||
class Genetic0Optimizer:
|
||||
"""The GENETIC0 optimizer."""
|
||||
|
||||
name = "GENETIC0"
|
||||
|
||||
async def prepare(
|
||||
self,
|
||||
start_datetime: DateTime,
|
||||
observation_datetime: DateTime,
|
||||
warm_start: Optional[Genetic0Result],
|
||||
overrides: Optional[Mapping[str, Any]] = None,
|
||||
) -> Genetic0Parameters:
|
||||
"""See ``Optimizer.prepare()``."""
|
||||
return await genetic0prepare.prepare(
|
||||
start_datetime, observation_datetime, warm_start, overrides
|
||||
)
|
||||
|
||||
async def prepare_from_request(
|
||||
self,
|
||||
request: Genetic0Request,
|
||||
start_datetime: DateTime,
|
||||
observation_datetime: DateTime,
|
||||
warm_start: Optional[Genetic0Result],
|
||||
overrides: Optional[Mapping[str, Any]] = None,
|
||||
) -> Genetic0Parameters:
|
||||
"""See ``Optimizer.prepare_from_request()``."""
|
||||
return await genetic0prepare.prepare_from_request(
|
||||
request, start_datetime, observation_datetime, warm_start, overrides
|
||||
)
|
||||
|
||||
def run(self, parameters: Genetic0Parameters) -> Genetic0Result:
|
||||
"""See ``Optimizer.run()``."""
|
||||
# Imported on first use: the simulation is only needed for a run.
|
||||
from akkudoktoreos.optimization.genetic0.genetic0algorithm import (
|
||||
Genetic0Optimization,
|
||||
)
|
||||
|
||||
optimization = Genetic0Optimization(parameters.settings)
|
||||
return optimization.optimize_ems(parameters)
|
||||
|
||||
def api(self) -> OptimizerApi:
|
||||
"""See ``Optimizer.api()``."""
|
||||
# Imported on first use: the router is only needed by the server.
|
||||
from akkudoktoreos.optimization.genetic0 import genetic0api
|
||||
|
||||
return genetic0api.api()
|
||||
|
||||
async def convert(
|
||||
self, parameters: Genetic0Parameters, result: Genetic0Result
|
||||
) -> tuple[OptimizationSolution, EnergyManagementPlan]:
|
||||
"""See ``Optimizer.convert()``."""
|
||||
return await genetic0convert.convert(parameters, result)
|
||||
@@ -0,0 +1,257 @@
|
||||
"""Optimization parameters of GENETIC0: the complete input of one run (ADR 0003, 0006, 0009).
|
||||
|
||||
A run reads nothing but these parameters: the algorithm settings, the forecast and device
|
||||
parameters, and the data the solution conversion presents (time zone, device IDs, prediction
|
||||
series). They are prepared once before the run by ``genetic0prepare``.
|
||||
|
||||
The simulation reads the forecast and device dataclasses, which are derived from the request
|
||||
(``Genetic0Request``). The request itself is kept because the result echoes it (until step 5); a
|
||||
replay file stores the request and the dataclasses are derived again when it is read.
|
||||
"""
|
||||
|
||||
import math
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Optional, Union
|
||||
|
||||
from akkudoktoreos.optimization.genetic0.devices.genetic0battery import (
|
||||
Genetic0BatteryParameters,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic0.devices.genetic0homeappliance import (
|
||||
Genetic0HomeApplianceParameters,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic0.devices.genetic0inverter import (
|
||||
Genetic0InverterParameters,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic0.genetic0energymanagement import (
|
||||
Genetic0EnergyManagementParameters,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic0.genetic0request import Genetic0Request
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime
|
||||
from akkudoktoreos.utils.gridinterpolator import GridInterpolatorBackend
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Genetic0RunSettings:
|
||||
"""Algorithm settings of one run, resolved from the configuration and overrides.
|
||||
|
||||
Attributes:
|
||||
prediction_hours: Length of the hourly arrays, from midnight of the start day.
|
||||
horizon_hours: Optimization horizon 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``).
|
||||
ev_charge_rates: Charge rates of the first configured electric vehicle, used when the
|
||||
request has none.
|
||||
battery_charge_rates: Charge rates of the first configured battery, used when the
|
||||
request has none.
|
||||
self_consumption_interpolator: How the inverter's self-consumption table is evaluated.
|
||||
verbose: Log the progress of the run.
|
||||
"""
|
||||
|
||||
prediction_hours: int
|
||||
horizon_hours: int
|
||||
individuals: Optional[int]
|
||||
generations: Optional[int]
|
||||
seed: Optional[int]
|
||||
penalties: Mapping[str, Union[float, int, str]]
|
||||
ev_charge_rates: Optional[tuple[float, ...]]
|
||||
battery_charge_rates: Optional[tuple[float, ...]]
|
||||
self_consumption_interpolator: GridInterpolatorBackend
|
||||
verbose: bool
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Genetic0Presentation:
|
||||
"""Data the solution conversion presents; not used by the run itself.
|
||||
|
||||
Attributes:
|
||||
start_datetime: Start of the run.
|
||||
timezone: Time zone the hours of the day refer to; ``None`` is the local time zone.
|
||||
battery_device_id: Device ID of the battery in the solution.
|
||||
ev_device_id: Device ID of the electric vehicle in the solution.
|
||||
home_appliance_device_id: Device ID of the home appliance in the solution.
|
||||
home_appliance_enabled: Whether the solution contains the home appliance.
|
||||
prediction_series: Hourly prediction series from the start of the run, by prediction key;
|
||||
a key without data is missing. Values may be NaN.
|
||||
"""
|
||||
|
||||
start_datetime: DateTime
|
||||
timezone: Optional[str]
|
||||
battery_device_id: str
|
||||
ev_device_id: str
|
||||
home_appliance_device_id: str
|
||||
home_appliance_enabled: bool
|
||||
prediction_series: Mapping[str, tuple[float, ...]]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Genetic0Parameters:
|
||||
"""Everything a GENETIC0 run and its solution conversion need.
|
||||
|
||||
Attributes:
|
||||
request: Forecast and device parameters of the run, as requested; echoed in the result.
|
||||
start_hour: Hour of the day the run starts at; indexes the hourly arrays.
|
||||
settings: Algorithm settings of the run.
|
||||
presentation: Data the solution conversion presents.
|
||||
ems: Hourly forecasts and prices of the simulation.
|
||||
pv_battery: The stationary battery, if any.
|
||||
ev: The electric vehicle, if any.
|
||||
inverter: The inverter, if any.
|
||||
dishwasher: The home appliance, if any.
|
||||
start_solution: Start solution of the previous run (warm start), if any.
|
||||
"""
|
||||
|
||||
request: Genetic0Request
|
||||
start_hour: int
|
||||
settings: Genetic0RunSettings
|
||||
presentation: Genetic0Presentation
|
||||
ems: Genetic0EnergyManagementParameters
|
||||
pv_battery: Optional[Genetic0BatteryParameters]
|
||||
ev: Optional[Genetic0BatteryParameters]
|
||||
inverter: Optional[Genetic0InverterParameters]
|
||||
dishwasher: Optional[Genetic0HomeApplianceParameters]
|
||||
start_solution: Optional[tuple[float, ...]]
|
||||
|
||||
@classmethod
|
||||
def from_request(
|
||||
cls,
|
||||
request: Genetic0Request,
|
||||
start_hour: int,
|
||||
settings: Genetic0RunSettings,
|
||||
presentation: Genetic0Presentation,
|
||||
) -> "Genetic0Parameters":
|
||||
"""Derive the simulation's dataclasses from the request.
|
||||
|
||||
Args:
|
||||
request: Forecast and device parameters of the run.
|
||||
start_hour: Hour of the day the run starts at.
|
||||
settings: Algorithm settings of the run.
|
||||
presentation: Data the solution conversion presents.
|
||||
|
||||
Returns:
|
||||
The parameters of the run.
|
||||
"""
|
||||
return cls(
|
||||
request=request,
|
||||
start_hour=start_hour,
|
||||
settings=settings,
|
||||
presentation=presentation,
|
||||
ems=request.ems.to_parameters(),
|
||||
pv_battery=None if request.pv_battery is None else request.pv_battery.to_parameters(),
|
||||
ev=None if request.ev is None else request.ev.to_parameters(),
|
||||
inverter=None if request.inverter is None else request.inverter.to_parameters(),
|
||||
dishwasher=(
|
||||
None
|
||||
if request.dishwasher is None
|
||||
else request.dishwasher.to_parameters(settings.prediction_hours)
|
||||
),
|
||||
start_solution=(
|
||||
None if request.start_solution is None else tuple(request.start_solution)
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def parameters_to_dict(parameters: Genetic0Parameters) -> dict[str, Any]:
|
||||
"""Serialize the parameters into plain JSON values, e.g. for a replay file.
|
||||
|
||||
A NaN or infinite value in the prediction series becomes ``None``.
|
||||
|
||||
Args:
|
||||
parameters: The parameters to serialize.
|
||||
|
||||
Returns:
|
||||
A dictionary that ``parameters_from_dict()`` turns back into equal parameters.
|
||||
"""
|
||||
settings = parameters.settings
|
||||
presentation = parameters.presentation
|
||||
return {
|
||||
"request": parameters.request.model_dump(mode="json"),
|
||||
"start_hour": parameters.start_hour,
|
||||
"settings": {
|
||||
"prediction_hours": settings.prediction_hours,
|
||||
"horizon_hours": settings.horizon_hours,
|
||||
"individuals": settings.individuals,
|
||||
"generations": settings.generations,
|
||||
"seed": settings.seed,
|
||||
"penalties": dict(settings.penalties),
|
||||
"ev_charge_rates": _list_or_none(settings.ev_charge_rates),
|
||||
"battery_charge_rates": _list_or_none(settings.battery_charge_rates),
|
||||
"self_consumption_interpolator": settings.self_consumption_interpolator.value,
|
||||
"verbose": settings.verbose,
|
||||
},
|
||||
"presentation": {
|
||||
"start_datetime": _datetime_to_dict(presentation.start_datetime),
|
||||
"timezone": presentation.timezone,
|
||||
"battery_device_id": presentation.battery_device_id,
|
||||
"ev_device_id": presentation.ev_device_id,
|
||||
"home_appliance_device_id": presentation.home_appliance_device_id,
|
||||
"home_appliance_enabled": presentation.home_appliance_enabled,
|
||||
"prediction_series": {
|
||||
key: [value if math.isfinite(value) else None for value in series]
|
||||
for key, series in presentation.prediction_series.items()
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def parameters_from_dict(data: Mapping[str, Any]) -> Genetic0Parameters:
|
||||
"""Deserialize parameters written by ``parameters_to_dict()``.
|
||||
|
||||
Args:
|
||||
data: The serialized parameters.
|
||||
|
||||
Returns:
|
||||
The parameters.
|
||||
"""
|
||||
settings = data["settings"]
|
||||
presentation = data["presentation"]
|
||||
return Genetic0Parameters.from_request(
|
||||
request=Genetic0Request.model_validate(data["request"]),
|
||||
start_hour=data["start_hour"],
|
||||
settings=Genetic0RunSettings(
|
||||
prediction_hours=settings["prediction_hours"],
|
||||
horizon_hours=settings["horizon_hours"],
|
||||
individuals=settings["individuals"],
|
||||
generations=settings["generations"],
|
||||
seed=settings["seed"],
|
||||
penalties=dict(settings["penalties"]),
|
||||
ev_charge_rates=_tuple_or_none(settings["ev_charge_rates"]),
|
||||
battery_charge_rates=_tuple_or_none(settings["battery_charge_rates"]),
|
||||
self_consumption_interpolator=GridInterpolatorBackend(
|
||||
settings["self_consumption_interpolator"]
|
||||
),
|
||||
verbose=settings["verbose"],
|
||||
),
|
||||
presentation=Genetic0Presentation(
|
||||
start_datetime=_datetime_from_dict(presentation["start_datetime"]),
|
||||
timezone=presentation["timezone"],
|
||||
battery_device_id=presentation["battery_device_id"],
|
||||
ev_device_id=presentation["ev_device_id"],
|
||||
home_appliance_device_id=presentation["home_appliance_device_id"],
|
||||
home_appliance_enabled=presentation["home_appliance_enabled"],
|
||||
prediction_series={
|
||||
key: tuple(math.nan if value is None else float(value) for value in series)
|
||||
for key, series in presentation["prediction_series"].items()
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
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)
|
||||
|
||||
|
||||
def _datetime_to_dict(value: DateTime) -> dict[str, Optional[str]]:
|
||||
# The offset alone would lose daylight saving time; keep the named zone as well. It is the
|
||||
# zone of the date-time itself, which may differ from the configured time zone.
|
||||
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"])
|
||||
@@ -1,825 +0,0 @@
|
||||
"""GENETIC0 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.
|
||||
"""
|
||||
|
||||
import math
|
||||
from typing import Optional, Union
|
||||
|
||||
import pandas as pd
|
||||
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,
|
||||
get_ems,
|
||||
)
|
||||
from akkudoktoreos.devices.genetic0.genetic0battery import (
|
||||
Genetic0ElectricVehicleParameters,
|
||||
Genetic0SolarPanelBatteryParameters,
|
||||
)
|
||||
from akkudoktoreos.devices.genetic0.genetic0homeappliance import (
|
||||
Genetic0HomeApplianceParameters,
|
||||
)
|
||||
from akkudoktoreos.devices.genetic0.genetic0inverter import Genetic0InverterParameters
|
||||
from akkudoktoreos.optimization.genetic0.genetic0abc import Genetic0ParametersBaseModel
|
||||
from akkudoktoreos.optimization.genetic.forecast import bounded_forecast_array
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime, to_duration
|
||||
|
||||
# Do not import directly from akkudoktoreos.core.coreabc
|
||||
# EnergyManagementSystemMixin - Creates circular dependency with ems.py
|
||||
# StartMixin - Creates circular dependency with ems.py
|
||||
|
||||
|
||||
# Demo devices: used if no device of a kind is configured.
|
||||
DEMO_BATTERY_SETTINGS: dict = {
|
||||
"device_id": "battery1",
|
||||
"profile_adjustment": {"nominal_capacity_wh": 8000},
|
||||
}
|
||||
DEMO_INVERTER_SETTINGS: dict = {
|
||||
"device_id": "inverter1",
|
||||
"profile_adjustment": {"nominal_power_w": 10000},
|
||||
}
|
||||
DEMO_ELECTRIC_VEHICLE_SETTINGS: dict = {
|
||||
"device_id": "ev1",
|
||||
"profile_adjustment": {"nominal_capacity_wh": 50000},
|
||||
"charge_rates": [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0],
|
||||
"min_soc_percentage": 70,
|
||||
}
|
||||
|
||||
|
||||
class Genetic0EnergyManagementParameters(Genetic0ParametersBaseModel):
|
||||
"""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 output in watts 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 watts 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_list_length(self) -> Self:
|
||||
"""Validate that all input lists are of the same length.
|
||||
|
||||
Raises:
|
||||
ValueError: If input list lengths differ.
|
||||
"""
|
||||
pv_forecast_length = len(self.pv_forecast_wh)
|
||||
if (
|
||||
pv_forecast_length != len(self.electricity_price_per_wh)
|
||||
or pv_forecast_length != len(self.total_load)
|
||||
or (
|
||||
isinstance(self.feed_in_tariff_per_wh, list)
|
||||
and pv_forecast_length != len(self.feed_in_tariff_per_wh)
|
||||
)
|
||||
):
|
||||
raise ValueError("Input lists have different lengths")
|
||||
return self
|
||||
|
||||
|
||||
class Genetic0OptimizationParameters(
|
||||
ConfigMixin,
|
||||
MeasurementMixin,
|
||||
PredictionMixin,
|
||||
# EnergyManagementSystemMixin, # Creates circular dependency with ems.py
|
||||
# StartMixin, # Creates circular dependency with ems.py
|
||||
Genetic0ParametersBaseModel,
|
||||
):
|
||||
"""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: Genetic0EnergyManagementParameters
|
||||
pv_battery: Optional[Genetic0SolarPanelBatteryParameters] = Field(
|
||||
validation_alias=AliasChoices("pv_battery", "pv_akku"),
|
||||
json_schema_extra={"description": "PV battery parameters."},
|
||||
)
|
||||
inverter: Optional[Genetic0InverterParameters]
|
||||
ev: Optional[Genetic0ElectricVehicleParameters] = Field(
|
||||
validation_alias=AliasChoices("ev", "eauto"),
|
||||
json_schema_extra={"description": "Electric vehicle parameters."},
|
||||
)
|
||||
dishwasher: Optional[Genetic0HomeApplianceParameters] = 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)."
|
||||
},
|
||||
)
|
||||
|
||||
# Computed fields for backward compatibility (deprecated German names)
|
||||
@computed_field(json_schema_extra={"deprecated": True})
|
||||
def pv_akku(self) -> Optional[Genetic0SolarPanelBatteryParameters]:
|
||||
"""Deprecated: Use pv_battery instead."""
|
||||
return self.pv_battery
|
||||
|
||||
@computed_field(json_schema_extra={"deprecated": True})
|
||||
def eauto(self) -> Optional[Genetic0ElectricVehicleParameters]:
|
||||
"""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 _nearest_soc_factor(cls, key: str, target: DateTime) -> float:
|
||||
"""SoC factor nearest to the run time within +/-24 h.
|
||||
|
||||
Readings carry their real time, not the slot start, and records without a
|
||||
SoC value (e.g. an adapter's meter reading) are skipped (#1447).
|
||||
"""
|
||||
window = to_duration("24 hours")
|
||||
dates, values = await cls.measurement.key_to_lists(
|
||||
key=key,
|
||||
start_datetime=target - window,
|
||||
end_datetime=target + window,
|
||||
dropna=False,
|
||||
)
|
||||
samples = [
|
||||
(abs(date.timestamp() - target.timestamp()), value)
|
||||
for date, value in zip(dates, values)
|
||||
if value is not None and value is not pd.NA
|
||||
]
|
||||
if not samples:
|
||||
raise ValueError(f"No SoC value for '{key}' within 24 hours of {target}.")
|
||||
# Convert only the selected sample: an unrelated older value must not fail.
|
||||
return float(min(samples, key=lambda sample: sample[0])[1])
|
||||
|
||||
@classmethod
|
||||
async def prepare(cls) -> "Optional[Genetic0OptimizationParameters]":
|
||||
"""Prepare optimization parameters from config, forecast and measurement data.
|
||||
|
||||
Fills in values needed for optimization from available configuration, predictions and
|
||||
measurements. If some data is missing, default or demo values are used.
|
||||
|
||||
Parameters start by definition of the genetic algorithm at hour 0 of the actual date
|
||||
(not at start datetime of energy management run)
|
||||
|
||||
Returns:
|
||||
Genetic0OptimizationParameters: The fully prepared optimization parameters.
|
||||
|
||||
Raises:
|
||||
ValueError: If required configuration values like start time are missing.
|
||||
"""
|
||||
ems = get_ems()
|
||||
|
||||
# The optimization paramters
|
||||
oparams: "Optional[Genetic0OptimizationParameters]" = None
|
||||
|
||||
# Check for run definitions
|
||||
if ems.start_datetime is None:
|
||||
error_msg = "Start datetime unknown."
|
||||
logger.error(error_msg)
|
||||
raise ValueError(error_msg)
|
||||
# Check for general predictions conditions
|
||||
if cls.config.general.latitude is None:
|
||||
default_latitude = 52.52
|
||||
logger.info(f"Latitude unknown - defaulting to {default_latitude}.")
|
||||
cls.config.general.latitude = default_latitude
|
||||
if cls.config.general.longitude is None:
|
||||
default_longitude = 13.405
|
||||
logger.info(f"Longitude unknown - defaulting to {default_longitude}.")
|
||||
cls.config.general.longitude = default_longitude
|
||||
if cls.config.prediction.hours is None:
|
||||
logger.info("Prediction hours unknown - defaulting to 48 hours.")
|
||||
cls.config.prediction.hours = 48
|
||||
if cls.config.prediction.historic_hours is None:
|
||||
logger.info("Prediction historic hours unknown - defaulting to 24 hours.")
|
||||
cls.config.prediction.historic_hours = 24
|
||||
# Check optimization definitions. interval_sec is fixed to 1 hour.
|
||||
if cls.config.optimization.genetic0.horizon_hours is None:
|
||||
logger.info("Optimization horizon unknown - defaulting to 24 hours.")
|
||||
cls.config.optimization.genetic0.horizon_hours = 24
|
||||
# Check genetic algorithm definitions
|
||||
if cls.config.optimization.genetic0.individuals is None:
|
||||
logger.info("Genetic individuals unknown - defaulting to 300.")
|
||||
cls.config.optimization.genetic0.individuals = 300
|
||||
if cls.config.optimization.genetic0.generations is None:
|
||||
logger.info("Genetic generations unknown - defaulting to 400.")
|
||||
cls.config.optimization.genetic0.generations = 400
|
||||
if "ev_soc_miss" not in cls.config.optimization.genetic0.penalties:
|
||||
logger.info("Genetic penalties unknown - defaulting to ev_soc_miss = 10.")
|
||||
cls.config.optimization.genetic0.penalties["ev_soc_miss"] = 10
|
||||
# Setup some basic providers if not set
|
||||
if not cls.config.weather.provider:
|
||||
cls.config.weather.provider = "OpenMeteo"
|
||||
if not cls.config.load.provider:
|
||||
cls.config.load.provider = "LoadAkkudoktor"
|
||||
|
||||
# Get start solution from last run
|
||||
start_solution = None
|
||||
last_solution = ems.genetic0_solution()
|
||||
if last_solution and last_solution.start_solution:
|
||||
start_solution = last_solution.start_solution
|
||||
|
||||
# Add forecast and device data
|
||||
interval = to_duration(cls.config.optimization.genetic0.interval_sec)
|
||||
power_to_energy_per_interval_factor = cls.config.optimization.genetic0.interval_sec / 3600
|
||||
# GENETIC0 indexes the parameter arrays by wall-clock hour (the simulation
|
||||
# starts at ``ems.start_datetime.hour``), while the arrays themselves are
|
||||
# sampled in elapsed time. On a DST transition day local midnight is 23 or
|
||||
# 25 elapsed hours away from the same wall-clock hour, so step back
|
||||
# ``hour`` elapsed hours instead of setting the hour to midnight. This keeps
|
||||
# array index ``ems.start_datetime.hour`` aligned with the start slot.
|
||||
parameter_start_datetime = ems.start_datetime.set(second=0, microsecond=0).subtract(
|
||||
hours=ems.start_datetime.hour
|
||||
)
|
||||
parameter_end_datetime = parameter_start_datetime.add(hours=cls.config.prediction.hours)
|
||||
max_retries = 10
|
||||
|
||||
for attempt in range(1, max_retries + 1):
|
||||
# Collect all the data for optimisation, but do not exceed max retries
|
||||
if attempt > max_retries:
|
||||
error_msg = f"Maximum retries {max_retries} for parameter collection exceeded. Parameter preparation attempt {attempt}."
|
||||
logger.error(error_msg)
|
||||
raise ValueError(error_msg)
|
||||
|
||||
# Assure predictions are uptodate
|
||||
await cls.prediction.update_data()
|
||||
|
||||
try: # Try first - predition is also needed by the default PV forecast
|
||||
array = await cls.prediction.key_to_array(
|
||||
key="weather_temp_air",
|
||||
start_datetime=parameter_start_datetime,
|
||||
end_datetime=parameter_end_datetime,
|
||||
interval=interval,
|
||||
fill_method="ffill",
|
||||
)
|
||||
weather_temp_air = array.tolist()
|
||||
except Exception as e:
|
||||
logger.info(
|
||||
"No weather forecast data available - defaulting to demo data. Parameter preparation attempt {}: {}",
|
||||
attempt,
|
||||
e,
|
||||
)
|
||||
cls.config.weather.provider = "OpenMeteo"
|
||||
# Retry
|
||||
continue
|
||||
# Try electricity fees next - predition is also needed by the default electricity price
|
||||
# If no provider is set the fees default to 0 anyway
|
||||
if cls.config.elecfee.provider:
|
||||
try:
|
||||
array = await cls.prediction.key_to_array(
|
||||
key="elecfee_consumption_amt_kwh",
|
||||
start_datetime=parameter_start_datetime,
|
||||
end_datetime=parameter_end_datetime,
|
||||
interval=interval,
|
||||
fill_method="ffill",
|
||||
)
|
||||
except Exception as e:
|
||||
logger.info(
|
||||
"No electricity fee data available - defaulting to demo data. Parameter preparation attempt {}: {}",
|
||||
attempt,
|
||||
e,
|
||||
)
|
||||
cls.config.merge_settings_from_dict(
|
||||
{
|
||||
"elecfee": {
|
||||
"provider": "ElecFeeFixed",
|
||||
"elecfeefixed": {
|
||||
"consumption_amt_kwh": {
|
||||
"windows": [
|
||||
{
|
||||
"start_time": "00:00",
|
||||
"duration": "24 hours",
|
||||
"value": 0.21,
|
||||
},
|
||||
]
|
||||
},
|
||||
"consumption_percent_amt": {
|
||||
"windows": [
|
||||
{
|
||||
"start_time": "00:00",
|
||||
"duration": "24 hours",
|
||||
"value": 19.0,
|
||||
},
|
||||
]
|
||||
},
|
||||
"feedin_amt_kwh": {
|
||||
"windows": [
|
||||
{
|
||||
"start_time": "00:00",
|
||||
"duration": "24 hours",
|
||||
"value": 0.0,
|
||||
},
|
||||
]
|
||||
},
|
||||
"feedin_percent_amt": {
|
||||
"windows": [
|
||||
{
|
||||
"start_time": "00:00",
|
||||
"duration": "24 hours",
|
||||
"value": 0.0,
|
||||
},
|
||||
]
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
)
|
||||
# Retry
|
||||
continue
|
||||
try:
|
||||
array = await cls.prediction.key_to_array(
|
||||
key="pvforecast_ac_power",
|
||||
start_datetime=parameter_start_datetime,
|
||||
end_datetime=parameter_end_datetime,
|
||||
interval=interval,
|
||||
fill_method="linear",
|
||||
)
|
||||
pvforecast_ac_power = (array * power_to_energy_per_interval_factor).tolist()
|
||||
except Exception as e:
|
||||
logger.info(
|
||||
"No PV forecast data available - defaulting to demo data. Parameter preparation attempt {}: {}",
|
||||
attempt,
|
||||
e,
|
||||
)
|
||||
cls.config.merge_settings_from_dict(
|
||||
{
|
||||
"pvforecast": {
|
||||
"provider": "PVForecastPVLib",
|
||||
"max_planes": 4,
|
||||
"planes": [
|
||||
{
|
||||
"surface_tilt": 7,
|
||||
"surface_azimuth": 170,
|
||||
"userhorizon": [20, 27, 22, 20],
|
||||
"peakpower": 5.0,
|
||||
"module_model": "AXITEC_AC_410MH_144S",
|
||||
"inverter_model": "Sungrow__SH25T",
|
||||
"inverter_paco": 10000,
|
||||
"modules_per_string": 12,
|
||||
"strings_per_inverter": 1,
|
||||
},
|
||||
{
|
||||
"surface_tilt": 7,
|
||||
"surface_azimuth": 90,
|
||||
"userhorizon": [30, 30, 30, 50],
|
||||
"peakpower": 4.8,
|
||||
"module_model": "AXITEC_AC_410MH_144S",
|
||||
"inverter_model": "Sungrow__SH25T",
|
||||
"inverter_paco": 10000,
|
||||
"modules_per_string": 12,
|
||||
"strings_per_inverter": 1,
|
||||
},
|
||||
{
|
||||
"surface_tilt": 60,
|
||||
"surface_azimuth": 140,
|
||||
"userhorizon": [60, 30, 0, 30],
|
||||
"peakpower": 1.4,
|
||||
"module_model": "AXITEC_AC_410MH_144S",
|
||||
"inverter_model": "Sungrow__SH25T",
|
||||
"inverter_paco": 2000,
|
||||
"modules_per_string": 5,
|
||||
"strings_per_inverter": 1,
|
||||
},
|
||||
{
|
||||
"surface_tilt": 45,
|
||||
"surface_azimuth": 185,
|
||||
"userhorizon": [45, 25, 30, 60],
|
||||
"peakpower": 1.6,
|
||||
"module_model": "AXITEC_AC_410MH_144S",
|
||||
"inverter_model": "Sungrow__SH25T",
|
||||
"inverter_paco": 1400,
|
||||
"modules_per_string": 4,
|
||||
"strings_per_inverter": 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
)
|
||||
# Retry
|
||||
continue
|
||||
try:
|
||||
array = await cls.prediction.key_to_array(
|
||||
key="elecprice_marketprice_wh",
|
||||
start_datetime=parameter_start_datetime,
|
||||
end_datetime=parameter_end_datetime,
|
||||
interval=interval,
|
||||
fill_method="ffill",
|
||||
)
|
||||
elecprice_marketprice_wh = array.tolist()
|
||||
except Exception as e:
|
||||
logger.info(
|
||||
"No Electricity Marketprice forecast data available - defaulting to demo data. Parameter preparation attempt {}: {}",
|
||||
attempt,
|
||||
e,
|
||||
)
|
||||
cls.config.merge_settings_from_dict(
|
||||
{
|
||||
"elecprice": {
|
||||
"elecpricefixed": {
|
||||
"elecprice_marketprice_amt_kwh": {
|
||||
"windows": [
|
||||
{
|
||||
"duration": "1 day",
|
||||
"start_time": "00:00:00.000000",
|
||||
"value": 0.288,
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"provider": "ElecPriceFixed",
|
||||
},
|
||||
},
|
||||
)
|
||||
# Retry
|
||||
continue
|
||||
try:
|
||||
array = await cls.prediction.key_to_array(
|
||||
key="loadforecast_power_w",
|
||||
start_datetime=parameter_start_datetime,
|
||||
end_datetime=parameter_end_datetime,
|
||||
interval=interval,
|
||||
fill_method="ffill",
|
||||
)
|
||||
loadforecast_power_w = array.tolist()
|
||||
except Exception as e:
|
||||
logger.info(
|
||||
"No Load forecast data available - defaulting to demo data. Parameter preparation attempt {}: {}",
|
||||
attempt,
|
||||
e,
|
||||
)
|
||||
cls.config.merge_settings_from_dict(
|
||||
{
|
||||
"load": {
|
||||
"provider": "LoadAkkudoktor",
|
||||
"loadakkudoktor": {
|
||||
"loadakkudoktor_year_energy_kwh": "3000",
|
||||
},
|
||||
},
|
||||
}
|
||||
)
|
||||
# Retry
|
||||
continue
|
||||
tariff_values = await bounded_forecast_array(
|
||||
cls.prediction,
|
||||
key="feed_in_tariff_wh",
|
||||
start_datetime=parameter_start_datetime,
|
||||
end_datetime=parameter_end_datetime,
|
||||
interval=interval,
|
||||
)
|
||||
first = int(
|
||||
(ems.start_datetime - parameter_start_datetime).total_seconds()
|
||||
/ interval.total_seconds()
|
||||
)
|
||||
last = first + cls.config.optimization.genetic0.horizon_hours
|
||||
if last > len(tariff_values) or not all(
|
||||
math.isfinite(value) for value in tariff_values[first:last]
|
||||
):
|
||||
logger.error(
|
||||
"Missing feed-in tariff within the GENETIC0 control horizon; "
|
||||
"canceling optimization with provider {}.",
|
||||
cls.config.feedintariff.provider,
|
||||
)
|
||||
return None
|
||||
feed_in_tariff_wh = tariff_values.tolist()
|
||||
|
||||
# Add device data
|
||||
|
||||
# Batteries
|
||||
# ---------
|
||||
if cls.config.devices.max_batteries is None:
|
||||
logger.info("Number of battery devices not configured - defaulting to 1.")
|
||||
cls.config.devices.max_batteries = 1
|
||||
if cls.config.devices.max_batteries == 0:
|
||||
battery_params = None
|
||||
battery_lcos_kwh = 0
|
||||
else:
|
||||
if cls.config.devices.batteries is None:
|
||||
logger.info("No battery device data available - defaulting to demo data.")
|
||||
cls.config.devices.batteries = {"battery1": dict(DEMO_BATTERY_SETTINGS)}
|
||||
# Take first battery
|
||||
battery_config = list(cls.config.devices.batteries.values())[0]
|
||||
try:
|
||||
# A configuration error gives default values, reported as error.
|
||||
(
|
||||
battery_parameters,
|
||||
_,
|
||||
) = await battery_config.resolve_current_operating_parameters_or_defaults()
|
||||
battery_params = battery_config.to_genetic0_pv_bat_param(battery_parameters)
|
||||
except Exception as e:
|
||||
# Never cancel the run, never change the user's configuration and
|
||||
# never invent a device: optimize without this battery.
|
||||
logger.error(
|
||||
"Battery '{}' cannot be prepared for the optimization: {} "
|
||||
"The battery is left out of this run.",
|
||||
battery_config.device_id,
|
||||
e,
|
||||
)
|
||||
battery_params = None
|
||||
battery_lcos_kwh = 0
|
||||
if battery_params is not None:
|
||||
# Levelized cost of ownership
|
||||
if battery_config.levelized_cost_of_storage_amt_kwh is None:
|
||||
logger.info(
|
||||
"No battery device LCOS data available - defaulting to 0 [amount/kWh]. Parameter preparation attempt {}.",
|
||||
attempt,
|
||||
)
|
||||
battery_config.levelized_cost_of_storage_amt_kwh = 0
|
||||
battery_lcos_kwh = battery_config.levelized_cost_of_storage_amt_kwh
|
||||
# Initial SOC
|
||||
try:
|
||||
initial_soc_factor = await cls._nearest_soc_factor(
|
||||
battery_config.measurement_key_soc_factor, ems.observation_datetime
|
||||
)
|
||||
if initial_soc_factor > 1.0 or initial_soc_factor < 0.0:
|
||||
logger.error(
|
||||
f"Invalid battery initial SoC factor {initial_soc_factor} - defaulting to 0.0."
|
||||
)
|
||||
initial_soc_factor = 0.0
|
||||
# genetic parameter is 0..100 as int
|
||||
initial_soc_percentage = int(initial_soc_factor * 100)
|
||||
except Exception:
|
||||
initial_soc_percentage = None
|
||||
if initial_soc_percentage is None:
|
||||
logger.info(
|
||||
f"No battery device SoC data (measurement key = '{battery_config.measurement_key_soc_factor}') available - defaulting to 0."
|
||||
)
|
||||
initial_soc_percentage = 0
|
||||
battery_params.initial_soc_percentage = initial_soc_percentage
|
||||
|
||||
# Electric Vehicles
|
||||
# -----------------
|
||||
if cls.config.devices.max_electric_vehicles is None:
|
||||
logger.info("Number of electric_vehicle devices not configured - defaulting to 1.")
|
||||
cls.config.devices.max_electric_vehicles = 1
|
||||
if cls.config.devices.max_electric_vehicles == 0:
|
||||
electric_vehicle_params = None
|
||||
else:
|
||||
if cls.config.devices.electric_vehicles is None:
|
||||
logger.info(
|
||||
"No electric vehicle device data available - defaulting to demo data."
|
||||
)
|
||||
cls.config.devices.max_electric_vehicles = 1
|
||||
cls.config.devices.electric_vehicles = {
|
||||
"ev1": dict(DEMO_ELECTRIC_VEHICLE_SETTINGS)
|
||||
}
|
||||
# Take first electric_vehicle
|
||||
electric_vehicle_config = list(cls.config.devices.electric_vehicles.values())[0]
|
||||
try:
|
||||
# A configuration error gives default values, reported as error.
|
||||
(
|
||||
ev_parameters,
|
||||
_,
|
||||
) = await electric_vehicle_config.resolve_current_operating_parameters_or_defaults()
|
||||
electric_vehicle_params = electric_vehicle_config.to_genetic0_ev_bat_param(
|
||||
ev_parameters
|
||||
)
|
||||
except Exception as e:
|
||||
# Never cancel the run, never change the user's configuration and
|
||||
# never invent a device: optimize without this electric vehicle.
|
||||
logger.error(
|
||||
"Electric vehicle '{}' cannot be prepared for the optimization: {} "
|
||||
"The electric vehicle is left out of this run.",
|
||||
electric_vehicle_config.device_id,
|
||||
e,
|
||||
)
|
||||
electric_vehicle_params = None
|
||||
if electric_vehicle_params is not None:
|
||||
# Initial SOC
|
||||
try:
|
||||
initial_soc_factor = await cls._nearest_soc_factor(
|
||||
electric_vehicle_config.measurement_key_soc_factor,
|
||||
ems.observation_datetime,
|
||||
)
|
||||
if initial_soc_factor > 1.0 or initial_soc_factor < 0.0:
|
||||
logger.error(
|
||||
f"Invalid electric vehicle initial SoC factor {initial_soc_factor} - defaulting to 0.0."
|
||||
)
|
||||
initial_soc_factor = 0.0
|
||||
# genetic parameter is 0..100 as int
|
||||
initial_soc_percentage = int(initial_soc_factor * 100)
|
||||
except Exception:
|
||||
initial_soc_percentage = None
|
||||
if initial_soc_percentage is None:
|
||||
logger.info(
|
||||
f"No electric vehicle device SoC data (measurement key = '{electric_vehicle_config.measurement_key_soc_factor}') available - defaulting to 0."
|
||||
)
|
||||
initial_soc_percentage = 0
|
||||
electric_vehicle_params.initial_soc_percentage = initial_soc_percentage
|
||||
|
||||
# Inverters
|
||||
# ---------
|
||||
if cls.config.devices.max_inverters is None:
|
||||
logger.info("Number of inverter devices not configured - defaulting to 1.")
|
||||
cls.config.devices.max_inverters = 1
|
||||
if cls.config.devices.max_inverters == 0:
|
||||
inverter_params = None
|
||||
else:
|
||||
if cls.config.devices.inverters is None:
|
||||
logger.info("No inverter device data available - defaulting to demo data.")
|
||||
cls.config.devices.inverters = {
|
||||
"inverter1": {
|
||||
**DEMO_INVERTER_SETTINGS,
|
||||
"battery_id": battery_config.device_id,
|
||||
},
|
||||
}
|
||||
# Take first inverter
|
||||
inverter_config = list(cls.config.devices.inverters.values())[0]
|
||||
try:
|
||||
# A configuration error gives default values, reported as error.
|
||||
inverter_params = inverter_config.to_genetic0_param(
|
||||
await inverter_config.resolve_current_operating_parameters_or_defaults()
|
||||
)
|
||||
except Exception as e:
|
||||
# Never cancel the run, never change the user's configuration and
|
||||
# never invent a device: optimize without this inverter.
|
||||
logger.error(
|
||||
"Inverter '{}' cannot be prepared for the optimization: {} "
|
||||
"The inverter is left out of this run.",
|
||||
inverter_config.device_id,
|
||||
e,
|
||||
)
|
||||
inverter_params = None
|
||||
|
||||
# Home Appliances
|
||||
# ---------------
|
||||
if cls.config.devices.max_home_appliances is None:
|
||||
logger.info("Number of home appliance devices not configured - defaulting to 1.")
|
||||
cls.config.devices.max_home_appliances = 1
|
||||
if cls.config.devices.max_home_appliances == 0:
|
||||
home_appliance_params = None
|
||||
else:
|
||||
home_appliance_params = None
|
||||
if cls.config.devices.home_appliances is None:
|
||||
logger.info(
|
||||
"No home appliance device data available - defaulting to demo data."
|
||||
)
|
||||
cls.config.devices.home_appliances = {
|
||||
"dishwasher1": {
|
||||
"device_id": "dishwasher1",
|
||||
"consumption_wh": 2000,
|
||||
"duration_h": 3.0,
|
||||
"cycle_time_windows": {
|
||||
"windows": [
|
||||
{
|
||||
"start_time": "08:00",
|
||||
"duration": "5 hours",
|
||||
},
|
||||
{
|
||||
"start_time": "15:00",
|
||||
"duration": "3 hours",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
}
|
||||
try:
|
||||
# Take first appliance
|
||||
home_appliance_config = list(cls.config.devices.home_appliances.values())[0]
|
||||
home_appliance_params = home_appliance_config.to_genetic0_param()
|
||||
except Exception as e:
|
||||
logger.info(
|
||||
"No home appliance device data available - defaulting to demo data. Parameter preparation attempt {}: {}",
|
||||
attempt,
|
||||
e,
|
||||
)
|
||||
cls.config.devices.home_appliances = {
|
||||
"dishwasher1": {
|
||||
"device_id": "dishwasher1",
|
||||
"consumption_wh": 2000,
|
||||
"duration_h": 3.0,
|
||||
"cycle_time_windows": None,
|
||||
},
|
||||
}
|
||||
# Retry
|
||||
continue
|
||||
|
||||
# We got all parameter data
|
||||
try:
|
||||
oparams = Genetic0OptimizationParameters(
|
||||
ems=Genetic0EnergyManagementParameters(
|
||||
pv_forecast_wh=pvforecast_ac_power,
|
||||
electricity_price_per_wh=elecprice_marketprice_wh,
|
||||
feed_in_tariff_per_wh=feed_in_tariff_wh,
|
||||
total_load=loadforecast_power_w,
|
||||
price_per_wh_battery=battery_lcos_kwh / 1000,
|
||||
),
|
||||
temperature_forecast=weather_temp_air,
|
||||
pv_battery=battery_params,
|
||||
ev=electric_vehicle_params,
|
||||
inverter=inverter_params,
|
||||
dishwasher=home_appliance_params,
|
||||
start_solution=start_solution,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.info(
|
||||
"Can not prepare optimization parameters - will retry. Parameter preparation attempt {}: {}",
|
||||
attempt,
|
||||
e,
|
||||
)
|
||||
oparams = None
|
||||
# Retry
|
||||
continue
|
||||
|
||||
# Parameters prepared
|
||||
break
|
||||
|
||||
return oparams
|
||||
@@ -0,0 +1,866 @@
|
||||
"""Parameter preparation of GENETIC0 (ADR 0003, 0006).
|
||||
|
||||
The only part of GENETIC0 that reads configuration, predictions and measurements. It prepares the
|
||||
optimization parameters once before each run: the request (forecasts and devices), the algorithm
|
||||
settings and the data the solution conversion presents. The energy management passes the run
|
||||
start, the observation time, the warm start and run-time overrides as arguments; the preparation
|
||||
reads no EMS state.
|
||||
|
||||
The preparation always creates a valid parameter set (energy-domain skill, "Optimization
|
||||
parameters are always valid"): it never fails, never cancels the run, never writes the
|
||||
configuration and never invents devices. A missing or invalid input is replaced by a fallback
|
||||
value, logged at error level with the input and the substitute.
|
||||
"""
|
||||
|
||||
import math
|
||||
from collections.abc import Mapping
|
||||
from typing import Any, Optional
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from loguru import logger
|
||||
|
||||
from akkudoktoreos.core.coreabc import get_config, get_measurement, get_prediction
|
||||
from akkudoktoreos.core.types import FillMethod
|
||||
from akkudoktoreos.devices.settings.batteryresolution import BatteryOperatingParameters
|
||||
from akkudoktoreos.devices.settings.batterysettings import BatteriesCommonSettings
|
||||
from akkudoktoreos.devices.settings.homeappliancesettings import (
|
||||
HomeApplianceCommonSettings,
|
||||
)
|
||||
from akkudoktoreos.devices.settings.inverterresolution import (
|
||||
InverterOperatingParameters,
|
||||
)
|
||||
from akkudoktoreos.devices.settings.invertersettings import InverterCommonSettings
|
||||
from akkudoktoreos.optimization.genetic0.genetic0parameters import (
|
||||
Genetic0Parameters,
|
||||
Genetic0Presentation,
|
||||
Genetic0RunSettings,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic0.genetic0request import (
|
||||
Genetic0ElectricVehicleRequest,
|
||||
Genetic0EnergyManagementRequest,
|
||||
Genetic0HomeApplianceRequest,
|
||||
Genetic0InverterRequest,
|
||||
Genetic0Request,
|
||||
Genetic0SolarPanelBatteryRequest,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic0.genetic0result import Genetic0Result
|
||||
from akkudoktoreos.utils.datetimeutil import (
|
||||
DateTime,
|
||||
Duration,
|
||||
to_datetime,
|
||||
to_duration,
|
||||
)
|
||||
from akkudoktoreos.utils.gridinterpolator import configured_grid_interpolator_backend
|
||||
|
||||
# Settings that a run can override.
|
||||
OVERRIDE_KEYS = ("generations", "seed")
|
||||
|
||||
# Prediction series the solution conversion presents: key and fill method.
|
||||
PRESENTATION_PREDICTIONS: tuple[tuple[str, FillMethod], ...] = (
|
||||
("pvforecast_ac_power", "linear"),
|
||||
("pvforecast_dc_power", "linear"),
|
||||
("elecprice_marketprice_wh", "ffill"),
|
||||
("feed_in_tariff_wh", "ffill"),
|
||||
("weather_temp_air", "linear"),
|
||||
("loadforecast_power_w", "linear"),
|
||||
("loadakkudoktor_std_power_w", "linear"),
|
||||
("loadakkudoktor_mean_power_w", "linear"),
|
||||
)
|
||||
|
||||
# Device IDs of the solution. GENETIC0 looks the configured EV and home appliance up with
|
||||
# ``dict.values()[0]``, which always fails, so their IDs were always these fallbacks; kept as they
|
||||
# are (GENETIC0 is frozen, ADR 0008).
|
||||
FALLBACK_BATTERY_DEVICE_ID = "battery1"
|
||||
EV_DEVICE_ID = "ev1"
|
||||
HOME_APPLIANCE_DEVICE_ID = "homeappliance1"
|
||||
|
||||
# Fallback values of the preparation (energy-domain skill). Settings use their defaults.
|
||||
FALLBACK_PREDICTION_HOURS = 48
|
||||
# The algorithm needs at least two hours after the start hour of the run.
|
||||
MIN_HOURS_AFTER_START = 2
|
||||
FALLBACK_INDIVIDUALS = 300
|
||||
FALLBACK_GENERATIONS = 400
|
||||
# No price known at all: 0, like a fixed-price provider without time windows.
|
||||
FALLBACK_PRICE_PER_WH = 0.0
|
||||
# No feed-in tariff known at all: no feed-in revenue.
|
||||
FALLBACK_FEED_IN_TARIFF_PER_WH = 0.0
|
||||
# No load forecast: 3000 kWh per year, spread evenly over the hours of the year.
|
||||
FALLBACK_LOAD_W = 3000.0 * 1000.0 / 8760.0
|
||||
|
||||
|
||||
async def prepare(
|
||||
start_datetime: DateTime,
|
||||
observation_datetime: DateTime,
|
||||
warm_start: Optional[Genetic0Result],
|
||||
overrides: Optional[Mapping[str, Any]] = None,
|
||||
) -> Genetic0Parameters:
|
||||
"""Prepare the parameters of a run from configuration, predictions and measurements.
|
||||
|
||||
Args:
|
||||
start_datetime: Start of the optimization run.
|
||||
observation_datetime: Moment of the run that measurements refer to.
|
||||
warm_start: Result of the previous GENETIC0 run, if any.
|
||||
overrides: Run-time overrides of ``generations`` and ``seed``.
|
||||
|
||||
Returns:
|
||||
The optimization parameters of the run; always valid, never ``None``.
|
||||
"""
|
||||
start_solution = None
|
||||
if warm_start is not None and warm_start.start_solution:
|
||||
start_solution = warm_start.start_solution
|
||||
request = await prepare_request(start_datetime, observation_datetime, start_solution)
|
||||
# The solution shows the home appliance the preparation put into the request.
|
||||
return await _complete(
|
||||
request, start_datetime, overrides, home_appliance_enabled=request.dishwasher is not None
|
||||
)
|
||||
|
||||
|
||||
async def prepare_from_request(
|
||||
request: Genetic0Request,
|
||||
start_datetime: DateTime,
|
||||
observation_datetime: DateTime,
|
||||
warm_start: Optional[Genetic0Result],
|
||||
overrides: Optional[Mapping[str, Any]] = None,
|
||||
) -> Genetic0Parameters:
|
||||
"""Complete a client's optimization request into the parameters of a run.
|
||||
|
||||
Args:
|
||||
request: The client's forecast and device parameters, used as they are.
|
||||
start_datetime: Start of the optimization run.
|
||||
observation_datetime: Moment of the run; not used, the request carries the device state.
|
||||
warm_start: Result of the previous GENETIC0 run; not used, the request carries its own
|
||||
start solution.
|
||||
overrides: Run-time overrides of ``generations`` and ``seed``.
|
||||
|
||||
Returns:
|
||||
The optimization parameters of the run.
|
||||
"""
|
||||
# A client's request is shown with the configured home appliances, as before.
|
||||
max_home_appliances = get_config().devices.max_home_appliances
|
||||
return await _complete(
|
||||
request,
|
||||
start_datetime,
|
||||
overrides,
|
||||
home_appliance_enabled=bool(max_home_appliances and max_home_appliances > 0),
|
||||
)
|
||||
|
||||
|
||||
async def _complete(
|
||||
request: Genetic0Request,
|
||||
start_datetime: DateTime,
|
||||
overrides: Optional[Mapping[str, Any]],
|
||||
home_appliance_enabled: bool,
|
||||
) -> Genetic0Parameters:
|
||||
settings = _run_settings(overrides, start_datetime.hour)
|
||||
return Genetic0Parameters.from_request(
|
||||
request=request,
|
||||
start_hour=start_datetime.hour,
|
||||
settings=settings,
|
||||
presentation=await _presentation(start_datetime, settings, home_appliance_enabled),
|
||||
)
|
||||
|
||||
|
||||
def _run_settings(overrides: Optional[Mapping[str, Any]], start_hour: int) -> Genetic0RunSettings:
|
||||
"""Algorithm settings from the configuration, as the algorithm read them before."""
|
||||
config = get_config()
|
||||
genetic0 = config.optimization.genetic0
|
||||
values: dict[str, Any] = {"generations": genetic0.generations, "seed": genetic0.seed}
|
||||
for key, value in (overrides or {}).items():
|
||||
if key not in OVERRIDE_KEYS:
|
||||
logger.error("GENETIC0: Unknown override '{}' ignored.", key)
|
||||
elif value is not None:
|
||||
values[key] = value
|
||||
|
||||
prediction_hours = _prediction_hours(start_hour)
|
||||
horizon_hours = genetic0.horizon_hours
|
||||
individuals = genetic0.individuals
|
||||
if individuals is None:
|
||||
individuals = FALLBACK_INDIVIDUALS
|
||||
logger.error("GENETIC0: optimization.genetic0.individuals not set, using {}.", individuals)
|
||||
if values["generations"] is None:
|
||||
values["generations"] = FALLBACK_GENERATIONS
|
||||
logger.error(
|
||||
"GENETIC0: optimization.genetic0.generations not set, using {}.", values["generations"]
|
||||
)
|
||||
|
||||
ev_charge_rates = None
|
||||
electric_vehicles = config.devices.electric_vehicles
|
||||
if electric_vehicles:
|
||||
rates = list(electric_vehicles.values())[0].charge_rates
|
||||
if rates is not None:
|
||||
ev_charge_rates = tuple(rates)
|
||||
|
||||
battery_charge_rates = None
|
||||
batteries = config.devices.batteries
|
||||
if batteries:
|
||||
battery_rates = list(batteries.values())[0].charge_rates
|
||||
if battery_rates:
|
||||
battery_charge_rates = tuple(battery_rates)
|
||||
|
||||
return Genetic0RunSettings(
|
||||
prediction_hours=prediction_hours,
|
||||
horizon_hours=horizon_hours,
|
||||
individuals=individuals,
|
||||
generations=values["generations"],
|
||||
seed=values["seed"],
|
||||
penalties=dict(genetic0.penalties),
|
||||
ev_charge_rates=ev_charge_rates,
|
||||
battery_charge_rates=battery_charge_rates,
|
||||
self_consumption_interpolator=configured_grid_interpolator_backend(),
|
||||
verbose=bool(config.server.verbose),
|
||||
)
|
||||
|
||||
|
||||
async def _presentation(
|
||||
start_datetime: DateTime, settings: Genetic0RunSettings, home_appliance_enabled: bool
|
||||
) -> Genetic0Presentation:
|
||||
"""The data the solution conversion presents, read once before the run."""
|
||||
config = get_config()
|
||||
batteries = config.devices.batteries
|
||||
if batteries:
|
||||
battery_device_id = list(batteries.values())[0].device_id
|
||||
else:
|
||||
battery_device_id = FALLBACK_BATTERY_DEVICE_ID
|
||||
|
||||
# The window the conversion covers: from the start to the end of the prediction day(s). The
|
||||
# conversion counts its hours from the start hour of the run or from the start hour in the
|
||||
# configured time zone (``None`` means the local zone); read from the earlier of the two, so
|
||||
# that the series cover every hour the conversion shows. It slices them to its own count.
|
||||
timezone = config.general.timezone
|
||||
hours = settings.prediction_hours - min(
|
||||
start_datetime.hour, to_datetime(start_datetime, in_timezone=timezone).hour
|
||||
)
|
||||
end_datetime = start_datetime.add(hours=max(hours, 0))
|
||||
prediction = get_prediction()
|
||||
series: dict[str, tuple[float, ...]] = {}
|
||||
for key, fill_method in PRESENTATION_PREDICTIONS:
|
||||
if hours <= 0 or key not in prediction.record_keys:
|
||||
continue
|
||||
try:
|
||||
array = await prediction.key_to_array(
|
||||
key=key,
|
||||
start_datetime=start_datetime,
|
||||
end_datetime=end_datetime,
|
||||
interval=to_duration("1 hours"),
|
||||
fill_method=fill_method,
|
||||
)
|
||||
except Exception as error:
|
||||
logger.error("GENETIC0: Prediction '{}' not readable, not presented: {}", key, error)
|
||||
continue
|
||||
if array is not None:
|
||||
series[key] = tuple(float(value) for value in np.asarray(array, dtype=float))
|
||||
|
||||
return Genetic0Presentation(
|
||||
start_datetime=start_datetime,
|
||||
timezone=timezone,
|
||||
battery_device_id=battery_device_id,
|
||||
ev_device_id=EV_DEVICE_ID,
|
||||
home_appliance_device_id=HOME_APPLIANCE_DEVICE_ID,
|
||||
home_appliance_enabled=home_appliance_enabled,
|
||||
prediction_series=series,
|
||||
)
|
||||
|
||||
|
||||
async def bounded_forecast_array(
|
||||
prediction: Any,
|
||||
*,
|
||||
key: str,
|
||||
start_datetime: DateTime,
|
||||
end_datetime: DateTime,
|
||||
interval: Duration,
|
||||
) -> np.ndarray:
|
||||
"""Integrate stored interval averages only across completely covered target slots.
|
||||
|
||||
Copied from GENETIC's ``forecast`` module: optimizers share no code (ADR 0004).
|
||||
|
||||
Source timestamps are interval starts. Infer their smallest positive cadence,
|
||||
capped at one hour. A missing source interval, explicit NaN or the end of the
|
||||
available forecast remains missing. UTC elapsed time handles DST transitions.
|
||||
The returned values retain the input units; callers convert W to slot Wh once.
|
||||
"""
|
||||
seconds = int(interval.total_seconds())
|
||||
start = start_datetime.timestamp()
|
||||
end = end_datetime.timestamp()
|
||||
if seconds <= 0 or end <= start or (end - start) % seconds:
|
||||
raise ValueError("Forecast bounds must contain a positive whole number of slots.")
|
||||
result = np.full(int((end - start) / seconds), np.nan)
|
||||
try:
|
||||
series = await prediction.key_to_raw_series(key=key, dropna=False)
|
||||
except KeyError:
|
||||
return result
|
||||
if series.empty:
|
||||
return result
|
||||
series = pd.to_numeric(series, errors="coerce").sort_index()
|
||||
series = series[~series.index.duplicated(keep="last")]
|
||||
stamps = pd.to_datetime(series.index, utc=True).as_unit("ns").asi8 / 1e9
|
||||
values = series.to_numpy(dtype=float)
|
||||
differences = np.diff(stamps)
|
||||
cadence = min(3600.0, float(np.min(differences))) if len(differences) else 3600.0
|
||||
for slot in range(len(result)):
|
||||
left = start + slot * seconds
|
||||
right = left + seconds
|
||||
position = max(0, int(np.searchsorted(stamps, left, side="right")) - 1)
|
||||
covered = 0.0
|
||||
weighted = 0.0
|
||||
while position < len(stamps) and stamps[position] < right:
|
||||
source_end = stamps[position] + cadence
|
||||
if position + 1 < len(stamps):
|
||||
source_end = min(source_end, stamps[position + 1])
|
||||
overlap = max(0.0, min(right, source_end) - max(left, stamps[position]))
|
||||
if overlap and np.isfinite(values[position]):
|
||||
covered += overlap
|
||||
weighted += (overlap / seconds) * values[position]
|
||||
position += 1
|
||||
if abs(covered - seconds) < 1e-6:
|
||||
result[slot] = weighted
|
||||
return result
|
||||
|
||||
|
||||
async def _nearest_soc_factor(key: str, target: DateTime) -> float:
|
||||
"""SoC factor nearest to the run time within +/-24 h.
|
||||
|
||||
Readings carry their real time, not the slot start, and records without a
|
||||
SoC value (e.g. an adapter's meter reading) are skipped (#1447).
|
||||
"""
|
||||
window = to_duration("24 hours")
|
||||
dates, values = await get_measurement().key_to_lists(
|
||||
key=key,
|
||||
start_datetime=target - window,
|
||||
end_datetime=target + window,
|
||||
dropna=False,
|
||||
)
|
||||
samples = [
|
||||
(abs(date.timestamp() - target.timestamp()), value)
|
||||
for date, value in zip(dates, values)
|
||||
if value is not None and value is not pd.NA
|
||||
]
|
||||
if not samples:
|
||||
raise ValueError(f"No SoC value for '{key}' within 24 hours of {target}.")
|
||||
# Convert only the selected sample: an unrelated older value must not fail.
|
||||
return float(min(samples, key=lambda sample: sample[0])[1])
|
||||
|
||||
|
||||
async def prepare_request(
|
||||
start_datetime: DateTime,
|
||||
observation_datetime: DateTime,
|
||||
start_solution: Optional[list[float]] = None,
|
||||
) -> Genetic0Request:
|
||||
"""Prepare the forecast and device parameters from configuration, predictions and measurements.
|
||||
|
||||
Never fails: a missing or invalid input is replaced by a fallback value and logged at error
|
||||
level. The configuration is never changed and no device is invented.
|
||||
|
||||
The parameter arrays start at hour 0 of the start day, not at the start of the run; the
|
||||
run starts at index ``start_datetime.hour``.
|
||||
|
||||
Args:
|
||||
start_datetime: Start of the optimization run.
|
||||
observation_datetime: Moment of the run that measured states of charge refer to.
|
||||
start_solution: Start solution of the previous run (warm start), passed in by the
|
||||
parameter preparation.
|
||||
|
||||
Returns:
|
||||
The forecast and device parameters of the run.
|
||||
"""
|
||||
config = get_config()
|
||||
prediction = get_prediction()
|
||||
|
||||
interval = to_duration(config.optimization.genetic0.interval_sec)
|
||||
power_to_energy_per_interval_factor = config.optimization.genetic0.interval_sec / 3600
|
||||
# GENETIC0 indexes the parameter arrays by wall-clock hour (the simulation
|
||||
# starts at ``start_datetime.hour``), while the arrays themselves are
|
||||
# sampled in elapsed time. On a DST transition day local midnight is 23 or
|
||||
# 25 elapsed hours away from the same wall-clock hour, so step back
|
||||
# ``hour`` elapsed hours instead of setting the hour to midnight. This keeps
|
||||
# array index ``start_datetime.hour`` aligned with the start slot.
|
||||
parameter_start_datetime = start_datetime.set(second=0, microsecond=0).subtract(
|
||||
hours=start_datetime.hour
|
||||
)
|
||||
parameter_end_datetime = parameter_start_datetime.add(
|
||||
hours=_prediction_hours(start_datetime.hour)
|
||||
)
|
||||
slots = int(
|
||||
(parameter_end_datetime - parameter_start_datetime).total_seconds()
|
||||
/ interval.total_seconds()
|
||||
)
|
||||
|
||||
# Assure predictions are up to date; stored predictions are used if the update fails.
|
||||
try:
|
||||
await prediction.update_data()
|
||||
except Exception as error:
|
||||
logger.error("GENETIC0: Prediction update failed, using the stored predictions: {}", error)
|
||||
|
||||
async def read(key: str, fill_method: FillMethod) -> Optional[np.ndarray]:
|
||||
try:
|
||||
array = await prediction.key_to_array(
|
||||
key=key,
|
||||
start_datetime=parameter_start_datetime,
|
||||
end_datetime=parameter_end_datetime,
|
||||
interval=interval,
|
||||
fill_method=fill_method,
|
||||
)
|
||||
except Exception as error:
|
||||
logger.error("GENETIC0: Prediction '{}' not available: {}", key, error)
|
||||
return None
|
||||
if array is None or len(array) != slots:
|
||||
logger.error("GENETIC0: Prediction '{}' does not cover the run.", key)
|
||||
return None
|
||||
return np.asarray(array, dtype=float)
|
||||
|
||||
# Temperature: optional, only presented.
|
||||
temperature = await read("weather_temp_air", "ffill")
|
||||
weather_temp_air: Optional[list[Optional[float]]] = None
|
||||
if temperature is None:
|
||||
logger.error("GENETIC0: No temperature forecast; the run has none.")
|
||||
else:
|
||||
weather_temp_air = [value if math.isfinite(value) else None for value in temperature]
|
||||
|
||||
# PV: missing values are 0.
|
||||
pv = await read("pvforecast_ac_power", "linear")
|
||||
if pv is None:
|
||||
logger.error("GENETIC0: No PV forecast; using 0 Wh.")
|
||||
pv = np.zeros(slots)
|
||||
elif not np.isfinite(pv).all():
|
||||
# NaN or infinite: missing.
|
||||
logger.error("GENETIC0: PV forecast incomplete; using 0 Wh for the missing hours.")
|
||||
pv = np.where(np.isfinite(pv), pv, 0.0)
|
||||
pvforecast_ac_power = (pv * power_to_energy_per_interval_factor).tolist()
|
||||
|
||||
# Prices: the last known price carried forward.
|
||||
price = await read("elecprice_marketprice_wh", "ffill")
|
||||
price_unknown = price is None or not np.isfinite(price).any()
|
||||
elecprice_marketprice_wh = _carry_forward(
|
||||
price, slots, FALLBACK_PRICE_PER_WH, "electricity price"
|
||||
).tolist()
|
||||
|
||||
# Load: the load default.
|
||||
load = await read("loadforecast_power_w", "ffill")
|
||||
loadforecast_power_w = _carry_forward(load, slots, FALLBACK_LOAD_W, "load forecast").tolist()
|
||||
|
||||
# Feed-in tariff: a covered control horizon is used as it is, otherwise carried forward.
|
||||
try:
|
||||
tariff_values = await bounded_forecast_array(
|
||||
prediction,
|
||||
key="feed_in_tariff_wh",
|
||||
start_datetime=parameter_start_datetime,
|
||||
end_datetime=parameter_end_datetime,
|
||||
interval=interval,
|
||||
)
|
||||
except Exception as error:
|
||||
logger.error("GENETIC0: Feed-in tariff not available: {}", error)
|
||||
tariff_values = np.full(slots, np.nan)
|
||||
first = int(
|
||||
(start_datetime - parameter_start_datetime).total_seconds() / interval.total_seconds()
|
||||
)
|
||||
last = first + config.optimization.genetic0.horizon_hours
|
||||
if last > len(tariff_values) or not all(
|
||||
math.isfinite(value) for value in tariff_values[first:last]
|
||||
):
|
||||
logger.error(
|
||||
"GENETIC0: Missing feed-in tariff within the control horizon (provider {}); "
|
||||
"carrying the last known tariff forward.",
|
||||
config.feedintariff.provider,
|
||||
)
|
||||
tariff_values = _carry_forward(
|
||||
tariff_values, slots, FALLBACK_FEED_IN_TARIFF_PER_WH, "feed-in tariff"
|
||||
)
|
||||
feed_in_tariff_wh = tariff_values.tolist()
|
||||
|
||||
battery_params, battery_lcos_kwh = await _battery(observation_datetime)
|
||||
electric_vehicle_params = await _electric_vehicle(observation_datetime)
|
||||
inverter_params = await _inverter()
|
||||
if (
|
||||
battery_params is not None
|
||||
and inverter_params is not None
|
||||
and inverter_params.battery_id != battery_params.device_id
|
||||
):
|
||||
# The simulation reaches the battery only through its inverter.
|
||||
logger.error(
|
||||
"GENETIC0: Battery '{}' is not connected to the inverter (battery_id {}), left out.",
|
||||
battery_params.device_id,
|
||||
inverter_params.battery_id,
|
||||
)
|
||||
battery_params = None
|
||||
if price_unknown and inverter_params is not None and inverter_params.max_ac_charge_power_w != 0:
|
||||
# With the fallback price of 0 charging from the grid would look free.
|
||||
logger.error(
|
||||
"GENETIC0: No electricity price known; no charging from the grid in this run "
|
||||
"(inverter '{}' max_ac_charge_power_w 0).",
|
||||
inverter_params.device_id,
|
||||
)
|
||||
inverter_params = inverter_params.model_copy(update={"max_ac_charge_power_w": 0.0})
|
||||
home_appliance_params = _home_appliance()
|
||||
|
||||
ems = {
|
||||
"pv_forecast_wh": pvforecast_ac_power,
|
||||
"electricity_price_per_wh": elecprice_marketprice_wh,
|
||||
"feed_in_tariff_per_wh": feed_in_tariff_wh,
|
||||
"total_load": loadforecast_power_w,
|
||||
}
|
||||
try:
|
||||
return Genetic0Request(
|
||||
ems=Genetic0EnergyManagementRequest(
|
||||
**ems, price_per_wh_battery=battery_lcos_kwh / 1000
|
||||
),
|
||||
temperature_forecast=weather_temp_air,
|
||||
pv_battery=battery_params,
|
||||
ev=electric_vehicle_params,
|
||||
inverter=inverter_params,
|
||||
dishwasher=home_appliance_params,
|
||||
start_solution=start_solution,
|
||||
)
|
||||
except Exception as error:
|
||||
logger.error(
|
||||
"GENETIC0: Parameters with devices are invalid ({}); optimizing without devices, "
|
||||
"temperature forecast and start solution.",
|
||||
error,
|
||||
)
|
||||
try:
|
||||
return Genetic0Request(
|
||||
ems=Genetic0EnergyManagementRequest(**ems, price_per_wh_battery=0.0),
|
||||
temperature_forecast=None,
|
||||
pv_battery=None,
|
||||
ev=None,
|
||||
inverter=None,
|
||||
dishwasher=None,
|
||||
)
|
||||
except Exception as error:
|
||||
logger.error(
|
||||
"GENETIC0: Forecast parameters are invalid ({}); using 0 Wh PV, price and feed-in "
|
||||
"tariff 0 and the fallback load.",
|
||||
error,
|
||||
)
|
||||
zeros = [0.0] * slots
|
||||
return Genetic0Request(
|
||||
ems=Genetic0EnergyManagementRequest(
|
||||
pv_forecast_wh=zeros,
|
||||
electricity_price_per_wh=zeros,
|
||||
feed_in_tariff_per_wh=zeros,
|
||||
total_load=[FALLBACK_LOAD_W * power_to_energy_per_interval_factor] * slots,
|
||||
price_per_wh_battery=0.0,
|
||||
),
|
||||
temperature_forecast=None,
|
||||
pv_battery=None,
|
||||
ev=None,
|
||||
inverter=None,
|
||||
dishwasher=None,
|
||||
)
|
||||
|
||||
|
||||
def _prediction_hours(start_hour: int) -> int:
|
||||
"""``prediction.hours``, or its fallback.
|
||||
|
||||
The hours count from midnight of the start day. If fewer than ``MIN_HOURS_AFTER_START``
|
||||
of them remain after the start hour, the run covers its control horizon instead.
|
||||
|
||||
Args:
|
||||
start_hour: Hour of the day the run starts at.
|
||||
|
||||
Returns:
|
||||
The hours the parameter arrays cover, from midnight of the start day.
|
||||
"""
|
||||
config = get_config()
|
||||
hours = config.prediction.hours
|
||||
if hours is None:
|
||||
logger.error(
|
||||
"GENETIC0: prediction.hours not configured, using {}.", FALLBACK_PREDICTION_HOURS
|
||||
)
|
||||
hours = FALLBACK_PREDICTION_HOURS
|
||||
if hours < start_hour + MIN_HOURS_AFTER_START:
|
||||
substitute = start_hour + max(
|
||||
config.optimization.genetic0.horizon_hours, MIN_HOURS_AFTER_START
|
||||
)
|
||||
logger.error(
|
||||
"GENETIC0: prediction.hours {} leaves fewer than {} hours after the start hour {}; "
|
||||
"using {}.",
|
||||
hours,
|
||||
MIN_HOURS_AFTER_START,
|
||||
start_hour,
|
||||
substitute,
|
||||
)
|
||||
hours = substitute
|
||||
return hours
|
||||
|
||||
|
||||
def _carry_forward(
|
||||
values: Optional[np.ndarray], slots: int, fallback: float, name: str
|
||||
) -> np.ndarray:
|
||||
"""Fill gaps with the last known value, leading gaps with the first known one.
|
||||
|
||||
Args:
|
||||
values: The series, or ``None`` if it is missing.
|
||||
slots: Length of the series.
|
||||
fallback: Value if nothing is known.
|
||||
name: Name of the series for the error log.
|
||||
|
||||
Returns:
|
||||
A series of ``slots`` finite values.
|
||||
"""
|
||||
if values is None or len(values) != slots:
|
||||
values = np.full(slots, np.nan)
|
||||
series = pd.Series(np.asarray(values, dtype=float)).replace([np.inf, -np.inf], np.nan)
|
||||
if not series.isna().any():
|
||||
return series.to_numpy()
|
||||
if series.isna().all():
|
||||
logger.error("GENETIC0: No {} known; using {}.", name, fallback)
|
||||
return np.full(slots, fallback)
|
||||
logger.error("GENETIC0: {} incomplete; carrying the last known value forward.", name)
|
||||
return series.ffill().bfill().to_numpy()
|
||||
|
||||
|
||||
async def _battery(observation_datetime: DateTime) -> tuple[Optional[Any], float]:
|
||||
"""Parameters and levelized cost per kWh of the first configured battery, if it can be prepared."""
|
||||
config = get_config()
|
||||
batteries = config.devices.batteries
|
||||
if config.devices.max_batteries == 0 or not batteries:
|
||||
logger.info("GENETIC0: No battery configured; optimizing without battery.")
|
||||
return None, 0.0
|
||||
battery_config = list(batteries.values())[0]
|
||||
try:
|
||||
# A configuration error gives default values, reported as error.
|
||||
(
|
||||
battery_parameters,
|
||||
_,
|
||||
) = await battery_config.resolve_current_operating_parameters_or_defaults()
|
||||
battery_params = battery_request(battery_config, battery_parameters)
|
||||
except Exception as error:
|
||||
logger.error(
|
||||
"Battery '{}' cannot be prepared for the optimization: {} "
|
||||
"The battery is left out of this run.",
|
||||
battery_config.device_id,
|
||||
error,
|
||||
)
|
||||
return None, 0.0
|
||||
|
||||
battery_lcos_kwh = battery_config.levelized_cost_of_storage_amt_kwh
|
||||
if battery_lcos_kwh is None:
|
||||
logger.error(
|
||||
"GENETIC0: Battery '{}' has no levelized cost of storage; using 0 per kWh.",
|
||||
battery_config.device_id,
|
||||
)
|
||||
battery_lcos_kwh = 0.0
|
||||
battery_params.initial_soc_percentage = await _initial_soc_percentage(
|
||||
"battery", battery_config.measurement_key_soc_factor, observation_datetime
|
||||
)
|
||||
return battery_params, float(battery_lcos_kwh)
|
||||
|
||||
|
||||
async def _electric_vehicle(observation_datetime: DateTime) -> Optional[Any]:
|
||||
"""Parameters of the first configured electric vehicle, if it can be prepared."""
|
||||
config = get_config()
|
||||
electric_vehicles = config.devices.electric_vehicles
|
||||
if config.devices.max_electric_vehicles == 0 or not electric_vehicles:
|
||||
logger.info("GENETIC0: No electric vehicle configured; optimizing without one.")
|
||||
return None
|
||||
electric_vehicle_config = list(electric_vehicles.values())[0]
|
||||
try:
|
||||
# A configuration error gives default values, reported as error.
|
||||
(
|
||||
ev_parameters,
|
||||
_,
|
||||
) = await electric_vehicle_config.resolve_current_operating_parameters_or_defaults()
|
||||
electric_vehicle_params = electric_vehicle_request(electric_vehicle_config, ev_parameters)
|
||||
except Exception as error:
|
||||
logger.error(
|
||||
"Electric vehicle '{}' cannot be prepared for the optimization: {} "
|
||||
"The electric vehicle is left out of this run.",
|
||||
electric_vehicle_config.device_id,
|
||||
error,
|
||||
)
|
||||
return None
|
||||
electric_vehicle_params.initial_soc_percentage = await _initial_soc_percentage(
|
||||
"electric vehicle", electric_vehicle_config.measurement_key_soc_factor, observation_datetime
|
||||
)
|
||||
return electric_vehicle_params
|
||||
|
||||
|
||||
async def _inverter() -> Optional[Any]:
|
||||
"""Parameters of the first configured inverter, if it can be prepared."""
|
||||
config = get_config()
|
||||
inverters = config.devices.inverters
|
||||
if config.devices.max_inverters == 0 or not inverters:
|
||||
logger.info("GENETIC0: No inverter configured; optimizing without inverter.")
|
||||
return None
|
||||
inverter_config = list(inverters.values())[0]
|
||||
try:
|
||||
# A configuration error gives default values, reported as error.
|
||||
return inverter_request(
|
||||
inverter_config,
|
||||
await inverter_config.resolve_current_operating_parameters_or_defaults(),
|
||||
)
|
||||
except Exception as error:
|
||||
logger.error(
|
||||
"Inverter '{}' cannot be prepared for the optimization: {} "
|
||||
"The inverter is left out of this run.",
|
||||
inverter_config.device_id,
|
||||
error,
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def _home_appliance() -> Optional[Any]:
|
||||
"""Parameters of the first configured home appliance, if it can be prepared."""
|
||||
config = get_config()
|
||||
home_appliances = config.devices.home_appliances
|
||||
if config.devices.max_home_appliances == 0 or not home_appliances:
|
||||
logger.info("GENETIC0: No home appliance configured; optimizing without one.")
|
||||
return None
|
||||
home_appliance_config = list(home_appliances.values())[0]
|
||||
try:
|
||||
return home_appliance_request(home_appliance_config)
|
||||
except Exception as error:
|
||||
logger.error(
|
||||
"Home appliance '{}' cannot be prepared for the optimization: {} "
|
||||
"The home appliance is left out of this run.",
|
||||
home_appliance_config.device_id,
|
||||
error,
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
async def _initial_soc_percentage(kind: str, key: str, observation_datetime: DateTime) -> int:
|
||||
"""Measured state of charge in percent, or 0 if none is known or it is invalid."""
|
||||
try:
|
||||
initial_soc_factor = await _nearest_soc_factor(key, observation_datetime)
|
||||
except Exception as error:
|
||||
logger.error(
|
||||
"GENETIC0: No {} state of charge (measurement key '{}'): {}; using 0 %.",
|
||||
kind,
|
||||
key,
|
||||
error,
|
||||
)
|
||||
return 0
|
||||
if not math.isfinite(initial_soc_factor) or not 0.0 <= initial_soc_factor <= 1.0:
|
||||
logger.error(
|
||||
"GENETIC0: Invalid {} state of charge factor {}; using 0 %.", kind, initial_soc_factor
|
||||
)
|
||||
return 0
|
||||
# genetic parameter is 0..100 as int
|
||||
return int(initial_soc_factor * 100)
|
||||
|
||||
|
||||
def battery_request(
|
||||
settings: BatteriesCommonSettings,
|
||||
operating_parameters: Optional[BatteryOperatingParameters] = None,
|
||||
) -> Genetic0SolarPanelBatteryRequest:
|
||||
"""GENETIC0 parameters of a stationary battery from its settings.
|
||||
|
||||
Args:
|
||||
settings: The battery settings.
|
||||
operating_parameters: Resolved snapshot to convert, e.g. from
|
||||
``resolve_current_operating_parameters``. None resolves at the reference operating
|
||||
point.
|
||||
|
||||
Returns:
|
||||
The battery parameters of the request.
|
||||
|
||||
Raises:
|
||||
BatteryResolutionError: See ``resolve_operating_parameters``.
|
||||
"""
|
||||
p = (
|
||||
operating_parameters
|
||||
if operating_parameters is not None
|
||||
else settings.resolve_operating_parameters()
|
||||
)
|
||||
return Genetic0SolarPanelBatteryRequest(
|
||||
device_id=settings.device_id,
|
||||
capacity_wh=p.capacity_wh,
|
||||
charging_efficiency=p.charging_efficiency,
|
||||
discharging_efficiency=p.discharging_efficiency,
|
||||
max_charge_power_w=p.max_charge_power_w,
|
||||
max_discharge_power_w=p.max_discharge_power_w,
|
||||
min_soc_percentage=p.min_soc_percentage,
|
||||
max_soc_percentage=p.max_soc_percentage,
|
||||
)
|
||||
|
||||
|
||||
def electric_vehicle_request(
|
||||
settings: BatteriesCommonSettings,
|
||||
operating_parameters: Optional[BatteryOperatingParameters] = None,
|
||||
) -> Genetic0ElectricVehicleRequest:
|
||||
"""GENETIC0 parameters of an electric vehicle from its settings.
|
||||
|
||||
Args:
|
||||
settings: The electric vehicle's battery settings.
|
||||
operating_parameters: Resolved snapshot to convert, e.g. from
|
||||
``resolve_current_operating_parameters``. None resolves at the reference operating
|
||||
point.
|
||||
|
||||
Returns:
|
||||
The electric vehicle parameters of the request.
|
||||
|
||||
Raises:
|
||||
BatteryResolutionError: See ``resolve_operating_parameters``.
|
||||
"""
|
||||
p = (
|
||||
operating_parameters
|
||||
if operating_parameters is not None
|
||||
else settings.resolve_operating_parameters()
|
||||
)
|
||||
return Genetic0ElectricVehicleRequest(
|
||||
device_id=settings.device_id,
|
||||
capacity_wh=p.capacity_wh,
|
||||
charging_efficiency=p.charging_efficiency,
|
||||
discharging_efficiency=p.discharging_efficiency,
|
||||
charge_rates=settings.charge_rates,
|
||||
max_charge_power_w=p.max_charge_power_w,
|
||||
max_discharge_power_w=p.max_discharge_power_w,
|
||||
min_soc_percentage=p.min_soc_percentage,
|
||||
max_soc_percentage=p.max_soc_percentage,
|
||||
)
|
||||
|
||||
|
||||
def inverter_request(
|
||||
settings: InverterCommonSettings,
|
||||
operating_parameters: Optional[InverterOperatingParameters] = None,
|
||||
) -> Genetic0InverterRequest:
|
||||
"""GENETIC0 parameters of an inverter from its settings.
|
||||
|
||||
GENETIC0 uses constant efficiencies: the DC->AC efficiency at the reference load fraction and
|
||||
the AC->DC efficiency at the AC charge limit.
|
||||
|
||||
Args:
|
||||
settings: The inverter settings.
|
||||
operating_parameters: Resolved operating parameters; None resolves them.
|
||||
|
||||
Returns:
|
||||
The inverter parameters of the request.
|
||||
|
||||
Raises:
|
||||
InverterResolutionError: See ``InverterCommonSettings.to_genetic_param``.
|
||||
"""
|
||||
p = operating_parameters or settings.resolve_operating_parameters()
|
||||
return Genetic0InverterRequest(
|
||||
device_id=settings.device_id,
|
||||
max_power_wh=p.max_power_w,
|
||||
battery_id=settings.battery_id,
|
||||
ac_to_dc_efficiency=p.ac_to_dc_efficiency,
|
||||
dc_to_ac_efficiency=p.dc_to_ac_efficiency,
|
||||
max_ac_charge_power_w=p.max_ac_charge_power_w,
|
||||
)
|
||||
|
||||
|
||||
def home_appliance_request(settings: HomeApplianceCommonSettings) -> Genetic0HomeApplianceRequest:
|
||||
"""GENETIC0 parameters of a home appliance from its settings.
|
||||
|
||||
Args:
|
||||
settings: The home appliance settings.
|
||||
|
||||
Returns:
|
||||
The home appliance parameters of the request.
|
||||
|
||||
Raises:
|
||||
ValueError: The appliance needs the GENETIC optimizer (explicit load profile) or has no
|
||||
flat load definition.
|
||||
"""
|
||||
if settings.load_profile_power_w is not None:
|
||||
raise ValueError("Explicit appliance load profiles require the GENETIC optimizer.")
|
||||
if settings.consumption_wh is None or settings.duration_h is None:
|
||||
raise ValueError("GENETIC0 requires a flat appliance load definition.")
|
||||
return Genetic0HomeApplianceRequest(
|
||||
device_id=settings.device_id,
|
||||
consumption_wh=settings.consumption_wh,
|
||||
duration_h=settings.duration_h,
|
||||
time_windows=settings.cycle_time_windows,
|
||||
)
|
||||
@@ -0,0 +1,513 @@
|
||||
"""GENETIC0 optimization request: the forecast and device parameters a client sends.
|
||||
|
||||
This module defines the Pydantic models of the request, including photovoltaic forecasts,
|
||||
electricity pricing, and system component parameters. The parameter preparation
|
||||
(``genetic0prepare``) assembles a request from configuration, predictions and measurements.
|
||||
"""
|
||||
|
||||
from typing import Any, Optional, Union
|
||||
|
||||
from pydantic import (
|
||||
AliasChoices,
|
||||
ConfigDict,
|
||||
Field,
|
||||
computed_field,
|
||||
field_validator,
|
||||
model_validator,
|
||||
)
|
||||
from typing_extensions import Self
|
||||
|
||||
from akkudoktoreos.config.configabc import TimeWindow, TimeWindowSequence
|
||||
from akkudoktoreos.core.pydantic import PydanticBaseModel
|
||||
from akkudoktoreos.optimization.genetic0.devices.genetic0battery import (
|
||||
Genetic0BatteryParameters,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic0.devices.genetic0homeappliance import (
|
||||
Genetic0HomeApplianceParameters,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic0.devices.genetic0inverter import (
|
||||
Genetic0InverterParameters,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic0.genetic0energymanagement import (
|
||||
Genetic0EnergyManagementParameters,
|
||||
)
|
||||
from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration, to_time
|
||||
|
||||
|
||||
class Genetic0ParametersBaseModel(PydanticBaseModel):
|
||||
"""Pydantic base model of the request and response models of GENETIC0."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
|
||||
class Genetic0DeviceRequest(Genetic0ParametersBaseModel):
|
||||
"""Fields every device of the request has."""
|
||||
|
||||
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],
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def max_charging_power_field(description: Optional[str] = None) -> Any:
|
||||
"""Pydantic field of a maximum charging power in watts.
|
||||
|
||||
Args:
|
||||
description: Field description; ``None`` uses a generic one.
|
||||
|
||||
Returns:
|
||||
The field definition.
|
||||
"""
|
||||
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) -> Any:
|
||||
"""Pydantic field of an initial state of charge in percent.
|
||||
|
||||
Args:
|
||||
description: Field description.
|
||||
|
||||
Returns:
|
||||
The field definition.
|
||||
"""
|
||||
return Field(
|
||||
default=0, ge=0, le=100, json_schema_extra={"description": description, "examples": [42]}
|
||||
)
|
||||
|
||||
|
||||
def discharging_efficiency_field(default_value: float) -> Any:
|
||||
"""Pydantic field of a discharging efficiency (0, 1].
|
||||
|
||||
Args:
|
||||
default_value: Default efficiency.
|
||||
|
||||
Returns:
|
||||
The field definition.
|
||||
"""
|
||||
return Field(
|
||||
default=default_value,
|
||||
gt=0,
|
||||
le=1,
|
||||
json_schema_extra={
|
||||
"description": "A float representing the discharge efficiency of the battery."
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
class Genetic0BaseBatteryRequest(Genetic0DeviceRequest):
|
||||
"""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: the battery may not discharge. "
|
||||
"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],
|
||||
},
|
||||
)
|
||||
|
||||
def to_parameters(self) -> Genetic0BatteryParameters:
|
||||
"""The parameters of the simulated battery.
|
||||
|
||||
Returns:
|
||||
The battery parameters; a stationary battery keeps its minimum state of charge.
|
||||
"""
|
||||
return Genetic0BatteryParameters(
|
||||
device_id=self.device_id,
|
||||
capacity_wh=self.capacity_wh,
|
||||
charging_efficiency=self.charging_efficiency,
|
||||
discharging_efficiency=self.discharging_efficiency,
|
||||
max_charge_power_w=self.max_charge_power_w,
|
||||
max_discharge_power_w=self.max_discharge_power_w,
|
||||
initial_soc_percentage=self.initial_soc_percentage,
|
||||
min_soc_percentage=self.min_soc_percentage,
|
||||
max_soc_percentage=self.max_soc_percentage,
|
||||
charge_rates=None if self.charge_rates is None else tuple(self.charge_rates),
|
||||
stationary=isinstance(self, Genetic0SolarPanelBatteryRequest),
|
||||
)
|
||||
|
||||
|
||||
class Genetic0SolarPanelBatteryRequest(Genetic0BaseBatteryRequest):
|
||||
"""PV battery device simulation configuration."""
|
||||
|
||||
max_charge_power_w: Optional[float] = max_charging_power_field()
|
||||
|
||||
|
||||
class Genetic0ElectricVehicleRequest(Genetic0BaseBatteryRequest):
|
||||
"""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."
|
||||
)
|
||||
|
||||
|
||||
class Genetic0InverterRequest(Genetic0DeviceRequest):
|
||||
"""Inverter Device Simulation Configuration."""
|
||||
|
||||
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],
|
||||
},
|
||||
)
|
||||
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],
|
||||
},
|
||||
)
|
||||
|
||||
def to_parameters(self) -> Genetic0InverterParameters:
|
||||
"""The parameters of the simulated inverter.
|
||||
|
||||
Returns:
|
||||
The inverter parameters.
|
||||
"""
|
||||
return Genetic0InverterParameters(
|
||||
device_id=self.device_id,
|
||||
max_power_wh=self.max_power_wh,
|
||||
battery_id=self.battery_id,
|
||||
ac_to_dc_efficiency=self.ac_to_dc_efficiency,
|
||||
dc_to_ac_efficiency=self.dc_to_ac_efficiency,
|
||||
max_ac_charge_power_w=self.max_ac_charge_power_w,
|
||||
)
|
||||
|
||||
|
||||
class Genetic0HomeApplianceRequest(Genetic0DeviceRequest):
|
||||
"""Home Appliance Device Simulation Configuration."""
|
||||
|
||||
device_id: str = Field(
|
||||
json_schema_extra={"description": "ID of home appliance", "examples": ["dishwasher"]}
|
||||
)
|
||||
consumption_wh: int = Field(
|
||||
gt=0,
|
||||
json_schema_extra={
|
||||
"description": "An integer representing the energy consumption of a household device in watt-hours.",
|
||||
"examples": [2000],
|
||||
},
|
||||
)
|
||||
duration_h: int = Field(
|
||||
gt=0,
|
||||
json_schema_extra={
|
||||
"description": "An integer representing the usage duration of a household device in hours.",
|
||||
"examples": [3],
|
||||
},
|
||||
)
|
||||
time_windows: Optional[TimeWindowSequence] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": "List of allowed time windows. Defaults to optimization general time window.",
|
||||
"examples": [
|
||||
[
|
||||
{"start_time": "10:00", "duration": "3 hours"},
|
||||
],
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
def to_parameters(self, prediction_hours: int) -> Genetic0HomeApplianceParameters:
|
||||
"""The parameters of the simulated home appliance.
|
||||
|
||||
Evaluates the time windows into the hours a run may start, relative to midnight of
|
||||
today, as the simulation device did before. Without time windows the request gets a
|
||||
window over all prediction hours, which the result echoes.
|
||||
|
||||
Args:
|
||||
prediction_hours: Length of the simulated arrays.
|
||||
|
||||
Returns:
|
||||
The home appliance parameters.
|
||||
"""
|
||||
if self.time_windows is None:
|
||||
self.time_windows = TimeWindowSequence(
|
||||
windows=[
|
||||
TimeWindow(
|
||||
start_time=to_time("00:00"),
|
||||
duration=to_duration(f"{prediction_hours} hours"),
|
||||
),
|
||||
]
|
||||
)
|
||||
start_datetime = to_datetime().set(hour=0, minute=0, second=0)
|
||||
duration = to_duration(f"{self.duration_h} hours")
|
||||
start_allowed = tuple(
|
||||
self.time_windows.contains(start_datetime.add(hours=hour), duration=duration)
|
||||
for hour in range(0, prediction_hours)
|
||||
)
|
||||
start_earliest = self.time_windows.earliest_start_time(duration, start_datetime)
|
||||
start_latest = self.time_windows.latest_start_time(duration, start_datetime)
|
||||
return Genetic0HomeApplianceParameters(
|
||||
device_id=self.device_id,
|
||||
consumption_wh=self.consumption_wh,
|
||||
duration_h=self.duration_h,
|
||||
start_allowed=start_allowed,
|
||||
start_earliest=start_earliest.hour if start_earliest else 0,
|
||||
start_latest=start_latest.hour if start_latest else 23,
|
||||
)
|
||||
|
||||
|
||||
class Genetic0EnergyManagementRequest(Genetic0ParametersBaseModel):
|
||||
"""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 output in watts 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 watts 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_list_length(self) -> Self:
|
||||
"""Validate that all input lists are of the same length.
|
||||
|
||||
Raises:
|
||||
ValueError: If input list lengths differ.
|
||||
"""
|
||||
pv_forecast_length = len(self.pv_forecast_wh)
|
||||
if (
|
||||
pv_forecast_length != len(self.electricity_price_per_wh)
|
||||
or pv_forecast_length != len(self.total_load)
|
||||
or (
|
||||
isinstance(self.feed_in_tariff_per_wh, list)
|
||||
and pv_forecast_length != len(self.feed_in_tariff_per_wh)
|
||||
)
|
||||
):
|
||||
raise ValueError("Input lists have different lengths")
|
||||
return self
|
||||
|
||||
def to_parameters(self) -> Genetic0EnergyManagementParameters:
|
||||
"""The forecasts and prices of the simulation.
|
||||
|
||||
Returns:
|
||||
The energy management parameters; a constant feed-in tariff stays a single value.
|
||||
"""
|
||||
tariff = self.feed_in_tariff_per_wh
|
||||
return Genetic0EnergyManagementParameters(
|
||||
pv_forecast_wh=tuple(self.pv_forecast_wh),
|
||||
electricity_price_per_wh=tuple(self.electricity_price_per_wh),
|
||||
feed_in_tariff_per_wh=tuple(tariff) if isinstance(tariff, list) else tariff,
|
||||
price_per_wh_battery=self.price_per_wh_battery,
|
||||
total_load=tuple(self.total_load),
|
||||
)
|
||||
|
||||
|
||||
class Genetic0Request(Genetic0ParametersBaseModel):
|
||||
"""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: Genetic0EnergyManagementRequest
|
||||
pv_battery: Optional[Genetic0SolarPanelBatteryRequest] = Field(
|
||||
validation_alias=AliasChoices("pv_battery", "pv_akku"),
|
||||
json_schema_extra={"description": "PV battery parameters."},
|
||||
)
|
||||
inverter: Optional[Genetic0InverterRequest]
|
||||
ev: Optional[Genetic0ElectricVehicleRequest] = Field(
|
||||
validation_alias=AliasChoices("ev", "eauto"),
|
||||
json_schema_extra={"description": "Electric vehicle parameters."},
|
||||
)
|
||||
dishwasher: Optional[Genetic0HomeApplianceRequest] = 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)."
|
||||
},
|
||||
)
|
||||
|
||||
# Computed fields for backward compatibility (deprecated German names)
|
||||
@computed_field(json_schema_extra={"deprecated": True})
|
||||
def pv_akku(self) -> Optional[Genetic0SolarPanelBatteryRequest]:
|
||||
"""Deprecated: Use pv_battery instead."""
|
||||
return self.pv_battery
|
||||
|
||||
@computed_field(json_schema_extra={"deprecated": True})
|
||||
def eauto(self) -> Optional[Genetic0ElectricVehicleRequest]:
|
||||
"""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
|
||||
@@ -0,0 +1,180 @@
|
||||
"""Optimization result of GENETIC0: the output of one run (ADR 0006, 0009, 0010).
|
||||
|
||||
Plain frozen dataclasses. Their values are normalised as the public response models validate them
|
||||
(``genetic0api``): NumPy arrays become lists, NaN becomes ``None`` and values get the field's
|
||||
number type, so that a response built from a result is the same as before the result became a
|
||||
dataclass (ADR 0008).
|
||||
"""
|
||||
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Optional, Union
|
||||
|
||||
from akkudoktoreos.utils.utils import NumpyEncoder
|
||||
|
||||
# German keys of the simulation output 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",
|
||||
}
|
||||
|
||||
|
||||
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 Genetic0SimulationOutput:
|
||||
"""Hourly and total values of the simulated best solution, from the start hour."""
|
||||
|
||||
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]
|
||||
|
||||
@classmethod
|
||||
def from_simulation(cls, output: Mapping[str, Any]) -> "Genetic0SimulationOutput":
|
||||
"""Build the output from the simulation's dictionary (German keys).
|
||||
|
||||
Args:
|
||||
output: The dictionary ``Genetic0Simulation.simulate()`` returns.
|
||||
|
||||
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)
|
||||
else:
|
||||
fields[key] = float_list(value)
|
||||
return cls(**fields)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Genetic0ElectricVehicleState:
|
||||
"""The electric vehicle at the end of the simulated best solution."""
|
||||
|
||||
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
|
||||
soc_wh: float
|
||||
initial_soc_percentage: int
|
||||
|
||||
@classmethod
|
||||
def from_battery(cls, state: Mapping[str, Any]) -> "Genetic0ElectricVehicleState":
|
||||
"""Build the state from ``Genetic0Battery.to_dict()``.
|
||||
|
||||
Args:
|
||||
state: The battery's dictionary.
|
||||
|
||||
Returns:
|
||||
The normalised electric vehicle state.
|
||||
"""
|
||||
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"]),
|
||||
soc_wh=_float(state["soc_wh"]),
|
||||
initial_soc_percentage=_int(state["initial_soc_percentage"]),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Genetic0Result:
|
||||
"""Output of one GENETIC0 run.
|
||||
|
||||
Attributes:
|
||||
ac_charge: AC charging factor per hour of the arrays.
|
||||
dc_charge: DC charging factor per hour of the arrays.
|
||||
discharge_allowed: 1 where discharging is allowed, per hour of the arrays.
|
||||
ev_charge_hours_float: EV charging factor per hour, 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: Start hour of the home appliance, if any.
|
||||
extra_data: Extra data of the run.
|
||||
fitness_history: Fitness per generation.
|
||||
fixed_seed: Seed of the run.
|
||||
"""
|
||||
|
||||
ac_charge: list[float]
|
||||
dc_charge: list[float]
|
||||
discharge_allowed: list[int]
|
||||
ev_charge_hours_float: Optional[list[float]]
|
||||
result: Genetic0SimulationOutput
|
||||
ev_obj: Optional[Genetic0ElectricVehicleState]
|
||||
start_hour: int
|
||||
start_solution: Optional[list[float]]
|
||||
washingstart: Optional[int]
|
||||
extra_data: Optional[dict[str, Union[list[int], list[float]]]]
|
||||
fitness_history: Optional[dict[str, Union[list[int], list[float]]]]
|
||||
fixed_seed: Optional[int]
|
||||
@@ -10,7 +10,7 @@ from pydantic import Field, computed_field
|
||||
from akkudoktoreos.config.configabc import SettingsBaseModel
|
||||
|
||||
|
||||
class Genetic0CommonSettings(SettingsBaseModel):
|
||||
class Genetic0Settings(SettingsBaseModel):
|
||||
"""GENETIC0 Optimization Algorithm Configuration."""
|
||||
|
||||
horizon_hours: int = Field(
|
||||
|
||||
@@ -0,0 +1,364 @@
|
||||
"""GENETIC0 simulation of one individual over the horizon."""
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
import numpy as np
|
||||
from loguru import logger
|
||||
|
||||
from akkudoktoreos.optimization.genetic0.devices.genetic0battery import Genetic0Battery
|
||||
from akkudoktoreos.optimization.genetic0.devices.genetic0homeappliance import (
|
||||
Genetic0HomeAppliance,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic0.devices.genetic0inverter import (
|
||||
Genetic0Inverter,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic0.genetic0energymanagement import (
|
||||
Genetic0EnergyManagementParameters,
|
||||
)
|
||||
|
||||
|
||||
class Genetic0Simulation:
|
||||
"""Device simulation for GENETIC optimization algorithm."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
"""Create an empty simulation; ``prepare()`` sets it up for a run."""
|
||||
self.start_hour: int = 0
|
||||
self.optimization_hours: Optional[int] = 24
|
||||
self.prediction_hours: Optional[int] = 48
|
||||
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
|
||||
self.battery: Optional[Genetic0Battery] = None
|
||||
self.ev: Optional[Genetic0Battery] = None
|
||||
self.home_appliance: Optional[Genetic0HomeAppliance] = None
|
||||
self.inverter: Optional[Genetic0Inverter] = None
|
||||
self.ac_charge_hours: Optional[np.ndarray] = None
|
||||
self.dc_charge_hours: Optional[np.ndarray] = None
|
||||
self.bat_discharge_hours: Optional[np.ndarray] = None
|
||||
self.ev_charge_hours: Optional[np.ndarray] = None
|
||||
self.ev_discharge_hours: Optional[np.ndarray] = None
|
||||
self.home_appliance_start_hour: Optional[int] = None
|
||||
|
||||
def prepare(
|
||||
self,
|
||||
parameters: Genetic0EnergyManagementParameters,
|
||||
optimization_hours: int,
|
||||
prediction_hours: int,
|
||||
ev: Optional[Genetic0Battery] = None,
|
||||
home_appliance: Optional[Genetic0HomeAppliance] = None,
|
||||
inverter: Optional[Genetic0Inverter] = None,
|
||||
) -> None:
|
||||
"""Prepare simulation runs.
|
||||
|
||||
Populate internal arrays and device references used during simulation.
|
||||
"""
|
||||
self.optimization_hours = optimization_hours
|
||||
self.prediction_hours = prediction_hours
|
||||
|
||||
# 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.asarray(parameters.feed_in_tariff_per_wh, dtype=float)
|
||||
if isinstance(parameters.feed_in_tariff_per_wh, 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
|
||||
self.home_appliance = home_appliance
|
||||
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.ev_charge_hours = np.full(self.prediction_hours, 0.0)
|
||||
self.ev_discharge_hours = np.full(self.prediction_hours, 0.0)
|
||||
self.home_appliance_start_hour = None
|
||||
|
||||
def reset(self) -> None:
|
||||
if self.ev:
|
||||
self.ev.reset()
|
||||
if self.battery:
|
||||
self.battery.reset()
|
||||
self.home_appliance_start_hour = None
|
||||
|
||||
def simulate(self, start_hour: int) -> dict[str, Any]:
|
||||
"""Simulate energy usage and costs for the given start hour.
|
||||
|
||||
battery_soc_per_hour begin of the hour, initial hour state!
|
||||
load_wh_per_hour 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
|
||||
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_appliance_fast = self.home_appliance
|
||||
inverter_fast = self.inverter
|
||||
|
||||
# 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 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("Genetic0Battery Discharge 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 = len(load_energy_array_fast)
|
||||
total_hours = end_hour - start_hour
|
||||
|
||||
# Pre-allocate arrays for the results, optimized for speed
|
||||
loads_energy_per_hour = np.full((total_hours), np.nan)
|
||||
feedin_energy_per_hour = np.full((total_hours), np.nan)
|
||||
consumption_energy_per_hour = np.full((total_hours), np.nan)
|
||||
costs_per_hour = np.full((total_hours), np.nan)
|
||||
revenue_per_hour = np.full((total_hours), np.nan)
|
||||
losses_wh_per_hour = np.full((total_hours), np.nan)
|
||||
electricity_price_per_hour = np.full((total_hours), np.nan)
|
||||
|
||||
# Set initial state
|
||||
if battery_fast:
|
||||
# Pre-allocate arrays for the results, optimized for speed
|
||||
soc_per_hour = np.full((total_hours), np.nan)
|
||||
|
||||
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
|
||||
if not ac_charging_possible:
|
||||
ac_charge_hours_fast = np.zeros_like(ac_charge_hours_fast)
|
||||
|
||||
# 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
|
||||
battery_fast.discharge_array = bat_discharge_hours_fast
|
||||
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:
|
||||
# Pre-allocate arrays for the results, optimized for speed
|
||||
soc_ev_per_hour = np.full((total_hours), np.nan)
|
||||
|
||||
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_appliance_fast and self.home_appliance_start_hour is not None:
|
||||
home_appliance_enabled = True
|
||||
# Pre-allocate arrays for the results, optimized for speed
|
||||
home_appliance_wh_per_hour = np.full((total_hours), np.nan)
|
||||
|
||||
self.home_appliance_start_hour = home_appliance_fast.set_starting_time(
|
||||
self.home_appliance_start_hour, start_hour
|
||||
)
|
||||
else:
|
||||
home_appliance_enabled = False
|
||||
# Default return if no home appliance is available
|
||||
home_appliance_wh_per_hour = np.full((total_hours), 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]
|
||||
losses_wh_per_hour[hour_idx] = 0.0
|
||||
|
||||
# Home appliances
|
||||
if home_appliance_enabled:
|
||||
ha_load = home_appliance_fast.get_load_for_hour(hour) # type: ignore[union-attr]
|
||||
consumption += ha_load
|
||||
home_appliance_wh_per_hour[hour_idx] = ha_load
|
||||
|
||||
# E-Auto handling
|
||||
if ev_fast:
|
||||
soc_ev_per_hour[hour_idx] = ev_fast.current_soc_percentage() # save begin state
|
||||
if ev_charge_hours_fast[hour] > 0:
|
||||
loaded_energy_ev, ev_charge_losses = ev_fast.charge_energy(
|
||||
wh=None, hour=hour, charge_factor=ev_charge_hours_fast[hour]
|
||||
)
|
||||
consumption += loaded_energy_ev
|
||||
losses_wh_per_hour[hour_idx] += ev_charge_losses
|
||||
|
||||
# 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:
|
||||
soc_per_hour[hour_idx] = battery_fast.current_soc_percentage()
|
||||
|
||||
# Process inverter logic
|
||||
energy_feedin_grid_actual = energy_consumption_grid_actual = losses = (
|
||||
self_consumption
|
||||
) = 0.0
|
||||
|
||||
if inverter_fast:
|
||||
energy_produced = pv_prediction_wh_fast[hour]
|
||||
(
|
||||
energy_feedin_grid_actual,
|
||||
energy_consumption_grid_actual,
|
||||
losses,
|
||||
self_consumption,
|
||||
) = inverter_fast.process_energy(energy_produced, consumption, hour)
|
||||
else:
|
||||
# Without an inverter the grid supplies the whole load; PV is not converted.
|
||||
energy_consumption_grid_actual = consumption
|
||||
|
||||
# AC PV Battery Charge
|
||||
if battery_fast:
|
||||
hour_ac_charge = ac_charge_hours_fast[hour]
|
||||
if hour_ac_charge > 0.0 and ac_charging_possible:
|
||||
# Cap charge factor by max_ac_charge_power_w if set
|
||||
effective_charge_factor = hour_ac_charge
|
||||
if max_ac_charge_w_fast is not None and battery_fast.max_charge_power_w > 0:
|
||||
# DC power = max_charge_power_w * factor
|
||||
# AC power = DC power / ac_to_dc_eff
|
||||
# AC power must be <= max_ac_charge_power_w
|
||||
max_dc_factor = (
|
||||
max_ac_charge_w_fast * ac_to_dc_eff_fast
|
||||
) / battery_fast.max_charge_power_w
|
||||
effective_charge_factor = min(effective_charge_factor, max_dc_factor)
|
||||
|
||||
if effective_charge_factor > 0:
|
||||
battery_charged_energy_actual, battery_losses_actual = (
|
||||
battery_fast.charge_energy(
|
||||
None, hour, charge_factor=effective_charge_factor
|
||||
)
|
||||
)
|
||||
|
||||
# DC energy entering the battery (before battery internal efficiency)
|
||||
dc_energy = battery_charged_energy_actual + battery_losses_actual
|
||||
# AC energy consumed from grid (accounts for AC→DC conversion loss)
|
||||
ac_energy = dc_energy / ac_to_dc_eff_fast
|
||||
# Genetic0Inverter AC→DC conversion losses
|
||||
inverter_charge_losses = ac_energy - dc_energy
|
||||
|
||||
consumption += ac_energy
|
||||
energy_consumption_grid_actual += ac_energy
|
||||
losses_wh_per_hour[hour_idx] += (
|
||||
battery_losses_actual + inverter_charge_losses
|
||||
)
|
||||
|
||||
# Update hourly arrays
|
||||
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] += 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
|
||||
|
||||
# Financial calculations
|
||||
costs_per_hour[hour_idx] = energy_consumption_grid_actual * hourly_electricity_price
|
||||
revenue_per_hour[hour_idx] = (
|
||||
energy_feedin_grid_actual * elect_revenue_per_hour_arr_fast[hour]
|
||||
)
|
||||
|
||||
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,
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,3 +1,5 @@
|
||||
"""PDF report of a GENETIC0 run, drawn from its optimization parameters and result."""
|
||||
|
||||
import json
|
||||
import textwrap
|
||||
from collections.abc import Sequence
|
||||
@@ -8,11 +10,10 @@ import matplotlib
|
||||
import matplotlib.dates as mdates
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
import pendulum
|
||||
from matplotlib.backends.backend_pdf import PdfPages
|
||||
|
||||
from akkudoktoreos.core.coreabc import ConfigMixin, get_ems
|
||||
from akkudoktoreos.optimization.genetic0.genetic0solution import Genetic0Solution
|
||||
from akkudoktoreos.optimization.genetic0.genetic0parameters import Genetic0Parameters
|
||||
from akkudoktoreos.optimization.genetic0.genetic0result import Genetic0Result
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime
|
||||
|
||||
matplotlib.use(
|
||||
@@ -23,11 +24,19 @@ matplotlib.use(
|
||||
debug_visualize: bool = False
|
||||
|
||||
|
||||
class Genetic0VisualizationReport(ConfigMixin):
|
||||
class Genetic0VisualizationReport:
|
||||
def __init__(
|
||||
self,
|
||||
version: str = "0.0.1",
|
||||
timezone: Optional[str] = None,
|
||||
) -> None:
|
||||
"""Create an empty report.
|
||||
|
||||
Args:
|
||||
version: Version shown in the report.
|
||||
timezone: Time zone of the charts' hours; ``None`` is the local time zone.
|
||||
"""
|
||||
self.timezone = timezone
|
||||
# Initialize the report with empty groups
|
||||
self.groups: list[list[Callable[[], None]]] = [] # Store groups of charts
|
||||
self.current_group: list[
|
||||
@@ -39,9 +48,7 @@ class Genetic0VisualizationReport(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."""
|
||||
@@ -150,18 +157,14 @@ class Genetic0VisualizationReport(ConfigMixin):
|
||||
|
||||
# Format the time axis
|
||||
plt.gca().xaxis.set_major_formatter(
|
||||
mdates.DateFormatter("%Y-%m-%d", tz=self.config.general.timezone)
|
||||
mdates.DateFormatter("%Y-%m-%d", tz=self.timezone)
|
||||
) # Show date and time
|
||||
plt.gca().xaxis.set_major_locator(
|
||||
mdates.DayLocator(interval=1, tz=self.config.general.timezone)
|
||||
mdates.DayLocator(interval=1, tz=self.timezone)
|
||||
) # Major ticks every day
|
||||
plt.gca().xaxis.set_minor_locator(
|
||||
mdates.HourLocator(interval=2, tz=self.config.general.timezone)
|
||||
)
|
||||
plt.gca().xaxis.set_minor_locator(mdates.HourLocator(interval=2, tz=self.timezone))
|
||||
# Minor ticks every 6 hours
|
||||
plt.gca().xaxis.set_minor_formatter(
|
||||
mdates.DateFormatter("%H", tz=self.config.general.timezone)
|
||||
)
|
||||
plt.gca().xaxis.set_minor_formatter(mdates.DateFormatter("%H", tz=self.timezone))
|
||||
# plt.gcf().autofmt_xdate(rotation=45, which="major")
|
||||
# Auto-format the x-axis for readability
|
||||
|
||||
@@ -180,7 +183,7 @@ class Genetic0VisualizationReport(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(
|
||||
@@ -202,11 +205,11 @@ class Genetic0VisualizationReport(ConfigMixin):
|
||||
# ax2.set_xticks(timestamps[::48]) # Set ticks every 12 hours
|
||||
# ax2.set_xticklabels([f"{int(h)}" for h in hours_since_start[::48]])
|
||||
# ax2.set_xticks(timestamps[:: len(timestamps) // 24]) # Select 10 evenly spaced ticks
|
||||
ax2.set_xticks(
|
||||
mdates.date2num(timestamps[:: len(timestamps) // 12])
|
||||
) # Select 10 evenly spaced ticks
|
||||
# About 12 ticks; every timestamp when there are fewer than 24.
|
||||
tick_step = max(1, len(timestamps) // 12)
|
||||
ax2.set_xticks(mdates.date2num(timestamps[::tick_step]))
|
||||
# ax2.set_xticklabels([f"{int(h)}" for h in hours_since_start[:: len(timestamps) // 24]])
|
||||
ax2.set_xticklabels([f"{int(h)}" for h in hours_since_start[:: len(timestamps) // 12]])
|
||||
ax2.set_xticklabels([f"{int(h)}" for h in hours_since_start[::tick_step]])
|
||||
if x2label:
|
||||
ax2.set_xlabel(x2label)
|
||||
|
||||
@@ -451,18 +454,28 @@ class Genetic0VisualizationReport(ConfigMixin):
|
||||
|
||||
|
||||
def genetic0_prepare_visualize(
|
||||
solution: Genetic0Solution,
|
||||
parameters: Genetic0Parameters,
|
||||
solution: Genetic0Result,
|
||||
) -> bytes:
|
||||
"""Render the PDF report of a run.
|
||||
|
||||
Args:
|
||||
parameters: The optimization parameters of the run; give the start and the time zone.
|
||||
solution: The result of the run.
|
||||
|
||||
Returns:
|
||||
The PDF document.
|
||||
"""
|
||||
global debug_visualize
|
||||
|
||||
report = Genetic0VisualizationReport()
|
||||
next_full_hour_date = get_ems().start_datetime
|
||||
report = Genetic0VisualizationReport(timezone=parameters.presentation.timezone)
|
||||
next_full_hour_date = parameters.presentation.start_datetime
|
||||
start_hour = solution.start_hour
|
||||
# Group 1:
|
||||
report.create_line_chart_date(
|
||||
next_full_hour_date,
|
||||
[
|
||||
solution.parameters.ems.total_load[start_hour:],
|
||||
parameters.request.ems.total_load[start_hour:],
|
||||
],
|
||||
title="Load Profile",
|
||||
# xlabel="Hours", # not enough space
|
||||
@@ -472,7 +485,7 @@ def genetic0_prepare_visualize(
|
||||
report.create_line_chart_date(
|
||||
next_full_hour_date,
|
||||
[
|
||||
solution.parameters.ems.pv_forecast_wh[start_hour:],
|
||||
parameters.request.ems.pv_forecast_wh[start_hour:],
|
||||
],
|
||||
title="PV Forecast",
|
||||
# xlabel="Hours", # not enough space
|
||||
@@ -483,10 +496,10 @@ def genetic0_prepare_visualize(
|
||||
next_full_hour_date,
|
||||
[
|
||||
np.full(
|
||||
len(solution.parameters.ems.total_load) - start_hour,
|
||||
solution.parameters.ems.feed_in_tariff_per_wh[start_hour:]
|
||||
if isinstance(solution.parameters.ems.feed_in_tariff_per_wh, list)
|
||||
else solution.parameters.ems.feed_in_tariff_per_wh,
|
||||
len(parameters.request.ems.total_load) - start_hour,
|
||||
parameters.request.ems.feed_in_tariff_per_wh[start_hour:]
|
||||
if isinstance(parameters.request.ems.feed_in_tariff_per_wh, list)
|
||||
else parameters.request.ems.feed_in_tariff_per_wh,
|
||||
)
|
||||
],
|
||||
title="Remuneration",
|
||||
@@ -494,11 +507,11 @@ def genetic0_prepare_visualize(
|
||||
ylabel="amount/Wh",
|
||||
x2label=None, # not enough space
|
||||
)
|
||||
if solution.parameters.temperature_forecast:
|
||||
if parameters.request.temperature_forecast:
|
||||
report.create_line_chart_date(
|
||||
next_full_hour_date,
|
||||
[
|
||||
solution.parameters.temperature_forecast[start_hour:],
|
||||
parameters.request.temperature_forecast[start_hour:],
|
||||
],
|
||||
title="Temperature Forecast",
|
||||
# xlabel="Hours", # not enough space
|
||||
@@ -547,21 +560,18 @@ def genetic0_prepare_visualize(
|
||||
)
|
||||
report.create_line_chart_date(
|
||||
start_date=next_full_hour_date, # start_date
|
||||
y_list=[solution.parameters.ems.electricity_price_per_wh[start_hour:]],
|
||||
y_list=[parameters.request.ems.electricity_price_per_wh[start_hour:]],
|
||||
# title="Electricity Price", # not enough space
|
||||
# xlabel="Date", # not enough space
|
||||
ylabel="Electricity Price (amount/Wh)",
|
||||
x2label=None, # not enough space
|
||||
)
|
||||
|
||||
labels = list(
|
||||
item
|
||||
for sublist in zip(
|
||||
list(str(i) for i in range(0, 23, 2)), list(str(" ") for i in range(0, 23, 2))
|
||||
)
|
||||
for item in sublist
|
||||
)
|
||||
labels = labels[start_hour:] + labels
|
||||
# One label per shown hour: the hour of the day for even hours, blank for odd ones.
|
||||
labels = [
|
||||
str(hour % 24) if hour % 2 == 0 else " "
|
||||
for hour in range(start_hour, start_hour + len(solution.ac_charge[start_hour:]))
|
||||
]
|
||||
|
||||
report.create_bar_chart(
|
||||
labels=labels,
|
||||
@@ -801,7 +811,7 @@ def genetic0_generate_example_report(filename: str = "example_report.pdf") -> No
|
||||
report.finalize_group()
|
||||
|
||||
report.create_line_chart_date(
|
||||
pendulum.now().subtract(hours=0),
|
||||
to_datetime().subtract(hours=0),
|
||||
[list(np.random.random(840))],
|
||||
title="test",
|
||||
xlabel="test",
|
||||
|
||||
@@ -9,7 +9,7 @@ from akkudoktoreos.core.pydantic import (
|
||||
PydanticBaseModel,
|
||||
PydanticDateTimeDataFrame,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic0.genetic0settings import Genetic0CommonSettings
|
||||
from akkudoktoreos.optimization.genetic0 import Genetic0Settings
|
||||
from akkudoktoreos.optimization.genetic.geneticsettings import (
|
||||
GeneticCommonSettings,
|
||||
normalize_genetic_settings,
|
||||
@@ -59,8 +59,8 @@ class OptimizationCommonSettings(SettingsBaseModel):
|
||||
},
|
||||
)
|
||||
|
||||
genetic0: Genetic0CommonSettings = Field(
|
||||
default_factory=Genetic0CommonSettings,
|
||||
genetic0: Genetic0Settings = Field(
|
||||
default_factory=Genetic0Settings,
|
||||
json_schema_extra={
|
||||
"description": "GENETIC0 optimization algorithm configuration.",
|
||||
"examples": [{"individuals": 400, "seed": None, "penalties": {"ev_soc_miss": 10}}],
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
"""The interface every optimizer implements (ADR 0006).
|
||||
|
||||
The energy management drives an optimizer only through this interface and the optimizer
|
||||
registry (ADR 0005): it prepares the optimization parameters once, runs the optimizer on them and
|
||||
converts the result into the optimization solution and the energy management plan.
|
||||
"""
|
||||
|
||||
from collections.abc import Callable, Mapping
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Generic, Optional, Protocol, TypeVar
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
from akkudoktoreos.core.emplan import EnergyManagementPlan
|
||||
from akkudoktoreos.optimization.optimization import OptimizationSolution
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime
|
||||
|
||||
ParametersT = TypeVar("ParametersT")
|
||||
RequestT_contra = TypeVar("RequestT_contra", contravariant=True)
|
||||
ResultT = TypeVar("ResultT")
|
||||
|
||||
|
||||
class Optimizer(Protocol[ParametersT, RequestT_contra, ResultT]):
|
||||
"""An optimizer, driven by the energy management.
|
||||
|
||||
``ParametersT`` are the optimizer's optimization parameters, ``RequestT_contra`` its optimization
|
||||
request from clients and ``ResultT`` its optimization result.
|
||||
"""
|
||||
|
||||
name: str
|
||||
|
||||
async def prepare(
|
||||
self,
|
||||
start_datetime: DateTime,
|
||||
observation_datetime: DateTime,
|
||||
warm_start: Optional[ResultT],
|
||||
overrides: Optional[Mapping[str, Any]] = None,
|
||||
) -> ParametersT:
|
||||
"""Prepare the optimization parameters from configuration, predictions and measurements.
|
||||
|
||||
Args:
|
||||
start_datetime: Start of the optimization run.
|
||||
observation_datetime: Moment of the run that measurements refer to (the start is
|
||||
this moment rounded down to the optimizer's slot).
|
||||
warm_start: Result of the optimizer's previous run, if any.
|
||||
overrides: Run-time overrides of settings (e.g. ``{"generations": 10}``). Keys the
|
||||
optimizer does not know are logged as errors and ignored.
|
||||
|
||||
Returns:
|
||||
Complete optimization parameters for one run.
|
||||
"""
|
||||
...
|
||||
|
||||
async def prepare_from_request(
|
||||
self,
|
||||
request: RequestT_contra,
|
||||
start_datetime: DateTime,
|
||||
observation_datetime: DateTime,
|
||||
warm_start: Optional[ResultT],
|
||||
overrides: Optional[Mapping[str, Any]] = None,
|
||||
) -> ParametersT:
|
||||
"""Complete a client's optimization request into optimization parameters.
|
||||
|
||||
Args:
|
||||
request: The optimization request of a client.
|
||||
start_datetime: Start of the optimization run.
|
||||
observation_datetime: Moment of the run that measurements refer to.
|
||||
warm_start: Result of the optimizer's previous run, if any.
|
||||
overrides: Run-time overrides of settings, as for ``prepare()``.
|
||||
|
||||
Returns:
|
||||
Complete optimization parameters for one run.
|
||||
"""
|
||||
...
|
||||
|
||||
def run(self, parameters: ParametersT) -> ResultT:
|
||||
"""Run the optimization; CPU-bound and deterministic for the same parameters.
|
||||
|
||||
Args:
|
||||
parameters: The optimization parameters of this run.
|
||||
|
||||
Returns:
|
||||
The optimization result.
|
||||
"""
|
||||
...
|
||||
|
||||
def api(self) -> Optional["OptimizerApi"]:
|
||||
"""The optimizer's REST API, if it has one (ADR 0005, 0011).
|
||||
|
||||
Returns:
|
||||
The router and its placeholder dependencies, which the server fills.
|
||||
"""
|
||||
...
|
||||
|
||||
async def convert(
|
||||
self, parameters: ParametersT, result: ResultT
|
||||
) -> 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 optimization result of the run.
|
||||
|
||||
Returns:
|
||||
The optimization solution and the energy management plan.
|
||||
"""
|
||||
...
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class OptimizerRun(Generic[ParametersT, ResultT]):
|
||||
"""The optimization parameters and the result of an optimizer's latest run."""
|
||||
|
||||
parameters: ParametersT
|
||||
result: ResultT
|
||||
|
||||
|
||||
# Starts an optimization run of one optimizer: (request, overrides, start datetime) -> result.
|
||||
RunTrigger = Callable[..., Any]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class OptimizerApi:
|
||||
"""The REST API an optimizer contributes (ADR 0005, 0011).
|
||||
|
||||
The router fetches nothing itself. The server includes it and fills the placeholder
|
||||
dependencies through ``app.dependency_overrides``:
|
||||
|
||||
Attributes:
|
||||
router: The optimizer's endpoints.
|
||||
last_run: Placeholder dependency that gives the optimizer's latest ``OptimizerRun`` or
|
||||
None.
|
||||
run: Placeholder dependency that gives a ``RunTrigger`` starting a run of the optimizer.
|
||||
"""
|
||||
|
||||
router: APIRouter
|
||||
last_run: Callable[[], Optional[OptimizerRun[Any, Any]]]
|
||||
run: Callable[[], RunTrigger]
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class OptimizerProblem(Exception):
|
||||
"""An error of an optimizer endpoint, returned as RFC 7807 Problem Details by the server.
|
||||
|
||||
Same fields as the server's ``EOSProblem``; optimizers do not import the server (ADR 0011).
|
||||
"""
|
||||
|
||||
status: int
|
||||
title: str
|
||||
detail: str
|
||||
type: str = "about:blank"
|
||||
cause: Optional[Exception] = None
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.detail
|
||||
@@ -0,0 +1,53 @@
|
||||
"""The registry of optimizers (ADR 0005).
|
||||
|
||||
The energy management, the server and EOSdash find an optimizer only here, by its name (the
|
||||
value of ``optimization.algorithm``). Optimizers are imported on first use, so a server that runs
|
||||
one optimizer never loads another.
|
||||
"""
|
||||
|
||||
from collections.abc import Callable
|
||||
from typing import Any, Optional
|
||||
|
||||
from akkudoktoreos.optimization.optimizer import Optimizer
|
||||
|
||||
|
||||
def _genetic0() -> Optimizer[Any, Any, Any]:
|
||||
from akkudoktoreos.optimization.genetic0 import Genetic0Optimizer
|
||||
|
||||
return Genetic0Optimizer()
|
||||
|
||||
|
||||
# Optimizer name -> factory. GENETIC joins when it is migrated.
|
||||
_FACTORIES: dict[str, Callable[[], Optimizer[Any, Any, Any]]] = {
|
||||
"GENETIC0": _genetic0,
|
||||
}
|
||||
|
||||
_optimizers: dict[str, Optimizer[Any, Any, Any]] = {}
|
||||
|
||||
|
||||
def get_optimizer(name: str) -> Optional[Optimizer[Any, Any, Any]]:
|
||||
"""Return the optimizer registered under ``name``.
|
||||
|
||||
Args:
|
||||
name: The optimizer's name, e.g. ``"GENETIC0"``.
|
||||
|
||||
Returns:
|
||||
The optimizer, or ``None`` if no optimizer is registered under that name.
|
||||
"""
|
||||
optimizer = _optimizers.get(name)
|
||||
if optimizer is None:
|
||||
factory = _FACTORIES.get(name)
|
||||
if factory is None:
|
||||
return None
|
||||
optimizer = factory()
|
||||
_optimizers[name] = optimizer
|
||||
return optimizer
|
||||
|
||||
|
||||
def optimizer_names() -> list[str]:
|
||||
"""Names of all registered optimizers.
|
||||
|
||||
Returns:
|
||||
The names, e.g. ``["GENETIC0"]``.
|
||||
"""
|
||||
return list(_FACTORIES)
|
||||
@@ -1,6 +1,7 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import asyncio
|
||||
import functools
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
@@ -56,19 +57,14 @@ from akkudoktoreos.core.types import (
|
||||
)
|
||||
from akkudoktoreos.core.version import __version__
|
||||
from akkudoktoreos.devices.devices import ResourceKey
|
||||
from akkudoktoreos.optimization.genetic0.genetic0params import (
|
||||
Genetic0OptimizationParameters,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic0.genetic0solution import (
|
||||
Genetic0Solution,
|
||||
Genetic0SolutionLegacy,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.configrequest import ConfigOptimizationRequest
|
||||
from akkudoktoreos.optimization.genetic.geneticsolution import GeneticSolution
|
||||
from akkudoktoreos.optimization.optimization import (
|
||||
OptimizationAlgorithm,
|
||||
OptimizationSolution,
|
||||
)
|
||||
from akkudoktoreos.optimization.optimizer import OptimizerRun, RunTrigger
|
||||
from akkudoktoreos.optimization.optimizerregistry import get_optimizer, optimizer_names
|
||||
from akkudoktoreos.prediction.elecprice import ElecPriceCommonSettings
|
||||
from akkudoktoreos.prediction.load import LoadCommonSettings
|
||||
from akkudoktoreos.prediction.loadakkudoktor import LoadAkkudoktorCommonSettings
|
||||
@@ -275,6 +271,31 @@ app.include_router(measurement_router)
|
||||
app.include_router(profile_router)
|
||||
app.include_router(pvadaptive_router)
|
||||
|
||||
|
||||
def _optimizer_last_run(name: str) -> Optional[OptimizerRun[Any, Any]]:
|
||||
"""The latest run of the optimizer ``name``; fills its ``last_run`` placeholder."""
|
||||
return get_ems().optimizer_run(name)
|
||||
|
||||
|
||||
def _optimizer_run_trigger(name: str) -> RunTrigger:
|
||||
"""Starts a run of the optimizer ``name``; fills its ``run`` placeholder."""
|
||||
return functools.partial(
|
||||
get_ems().run,
|
||||
mode=EnergyManagementMode.OPTIMIZATION,
|
||||
algorithm=OptimizationAlgorithm(name),
|
||||
)
|
||||
|
||||
|
||||
# Optimizers contribute their own endpoints (ADR 0005, 0011). They are included before the
|
||||
# server's routes, so an optimizer's specific path takes precedence over a generic one.
|
||||
for _name in optimizer_names():
|
||||
_optimizer = get_optimizer(_name)
|
||||
_api = None if _optimizer is None else _optimizer.api()
|
||||
if _api is not None:
|
||||
app.include_router(_api.router)
|
||||
app.dependency_overrides[_api.last_run] = functools.partial(_optimizer_last_run, _name)
|
||||
app.dependency_overrides[_api.run] = functools.partial(_optimizer_run_trigger, _name)
|
||||
|
||||
register_problem_handlers(app)
|
||||
|
||||
|
||||
@@ -1851,13 +1872,15 @@ def fastapi_energy_management_optimization_solution_get() -> OptimizationSolutio
|
||||
@app.get("/v1/energy-management/optimization/solution/{algorithm}", tags=["energy-management"])
|
||||
async def fastapi_energy_management_optimization_solution_algorithm_get(
|
||||
algorithm: OptimizationAlgorithm,
|
||||
) -> Union[GeneticSolution, Genetic0Solution]:
|
||||
) -> GeneticSolution:
|
||||
"""Get the latest algorithm specific solution of the optimization.
|
||||
|
||||
Optimizers of the registry serve their own solution path (e.g. ``.../solution/GENETIC0``).
|
||||
|
||||
Args:
|
||||
algorithm: Optimization algorithm
|
||||
"""
|
||||
solution: Optional[Union[GeneticSolution, Genetic0Solution]] = None
|
||||
solution: Optional[GeneticSolution] = None
|
||||
|
||||
if algorithm not in get_config().optimization.algorithms:
|
||||
raise EOSProblem(
|
||||
@@ -1868,8 +1891,6 @@ async def fastapi_energy_management_optimization_solution_algorithm_get(
|
||||
|
||||
if algorithm == OptimizationAlgorithm.GENETIC:
|
||||
solution = get_ems().genetic_solution()
|
||||
elif algorithm == OptimizationAlgorithm.GENETIC0:
|
||||
solution = get_ems().genetic0_solution()
|
||||
|
||||
if solution is None:
|
||||
raise EOSProblem(
|
||||
@@ -2266,88 +2287,6 @@ async def fastapi_optimize_config(
|
||||
return solution
|
||||
|
||||
|
||||
@app.post("/optimize", tags=["optimize"])
|
||||
async def fastapi_optimize(
|
||||
parameters: Genetic0OptimizationParameters,
|
||||
start_hour: Annotated[
|
||||
Optional[int], Query(description="Defaults to current hour of the day.")
|
||||
] = None,
|
||||
ngen: Annotated[
|
||||
Optional[int], Query(description="Number of indivuals to generate for genetic algorithm.")
|
||||
] = None,
|
||||
) -> Genetic0SolutionLegacy:
|
||||
"""Deprecated: Optimize.
|
||||
|
||||
Endpoint to handle optimization.
|
||||
|
||||
Uses the `classic` GENETIC0 optimisation algorithm (__NO__ 15-minutes slots).
|
||||
|
||||
Note:
|
||||
Use automatic optimization instead.
|
||||
"v1/energy-management/optimization/solution/GENETIC0"
|
||||
"""
|
||||
if start_hour is None:
|
||||
start_datetime = None
|
||||
else:
|
||||
start_datetime = to_datetime().set(hour=start_hour)
|
||||
|
||||
# Ensure there is only one optimization/ energy management run at a time
|
||||
solution = await get_ems().run(
|
||||
start_datetime=start_datetime,
|
||||
mode=EnergyManagementMode.OPTIMIZATION,
|
||||
algorithm=OptimizationAlgorithm.GENETIC0,
|
||||
genetic0_parameters=parameters,
|
||||
genetic0_generations=ngen,
|
||||
)
|
||||
|
||||
if solution is None:
|
||||
raise EOSProblem(
|
||||
status=404,
|
||||
title="Optimization solution retrieval failed",
|
||||
detail="Can not get the 'GENETIC0' optimization solution.",
|
||||
)
|
||||
|
||||
# Create compatible solution.
|
||||
legacy_solution = Genetic0SolutionLegacy.model_validate(
|
||||
{
|
||||
"ac_charge": solution.ac_charge,
|
||||
"dc_charge": solution.dc_charge,
|
||||
"discharge_allowed": solution.discharge_allowed,
|
||||
"ev_charge_hours_float": solution.ev_charge_hours_float,
|
||||
"result": solution.result,
|
||||
"ev_obj": solution.ev_obj,
|
||||
"start_solution": solution.start_solution,
|
||||
"washingstart": solution.washingstart,
|
||||
}
|
||||
)
|
||||
return legacy_solution
|
||||
|
||||
|
||||
@app.get("/visualization_results.pdf", tags=["optimize"])
|
||||
def get_pdf() -> Response:
|
||||
# Endpoint to serve the generated PDF with visualization results
|
||||
genetic0_solution = get_ems().genetic0_solution()
|
||||
if genetic0_solution is None:
|
||||
raise EOSProblem(
|
||||
status=404,
|
||||
title="Optimization solution report retrieval failed",
|
||||
detail="Can not get the 'GENETIC0' optimization solution.",
|
||||
)
|
||||
|
||||
# matplotlib is only needed for the PDF report; import it on first use.
|
||||
from akkudoktoreos.optimization.genetic0.genetic0visualize import (
|
||||
genetic0_prepare_visualize,
|
||||
)
|
||||
|
||||
pdf = genetic0_prepare_visualize(solution=genetic0_solution)
|
||||
|
||||
return Response(
|
||||
content=pdf,
|
||||
media_type="application/pdf",
|
||||
headers={"Content-Disposition": 'inline; filename="optimization-report.pdf"'},
|
||||
)
|
||||
|
||||
|
||||
@app.get("/site-map", include_in_schema=False)
|
||||
def site_map() -> RedirectResponse:
|
||||
return RedirectResponse(url="/docs")
|
||||
|
||||
@@ -7,6 +7,8 @@ from fastapi.exceptions import HTTPException, RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from loguru import logger
|
||||
|
||||
from akkudoktoreos.optimization.optimizer import OptimizerProblem
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class EOSProblem(Exception):
|
||||
@@ -101,6 +103,8 @@ async def validation_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||
|
||||
def register_problem_handlers(app: FastAPI) -> None:
|
||||
app.add_exception_handler(EOSProblem, eos_problem_handler)
|
||||
# Errors of optimizer endpoints carry the same fields (ADR 0011).
|
||||
app.add_exception_handler(OptimizerProblem, eos_problem_handler)
|
||||
app.add_exception_handler(HTTPException, http_exception_handler)
|
||||
app.add_exception_handler(Exception, unexpected_exception_handler)
|
||||
app.add_exception_handler(RequestValidationError, validation_handler)
|
||||
|
||||
Reference in New Issue
Block a user