chore: prepare for update of genetic algorithm (#1190)
Bump Version / Bump Version Workflow (push) Has been cancelled
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
docker-build / platform-excludes (push) Has been cancelled
docker-build / build (push) Has been cancelled
docker-build / merge (push) Has been cancelled
pre-commit / pre-commit (push) Has been cancelled
Run Pytest on Pull Request / test (push) Has been cancelled

Andreas will update the genetic algorithm for 15-minutes optimization
intervals.

Copy the current GENETIC optimization algorithm to GENETIC0 to enable
to keep the algorithm with the current functionality. Also copy resources
like the load interpolator to the GENETIC0 algorithm to keep them despite
possible later changes to the interpolator.

Make the deprecated legacy /optimize endpoint use the GENETIC0 optimization
algorithm to in-fact behave the same way even if there will later be changes
to the GENETIC algorithm by Andreas. Add a new REST endpoint to provide
the unprocessed optimisation results of the GENETIC and GENETIC0 algorithm
in case one wants to use them as done with the deprecated /optimize endpoint.

Adapt the optimization configuration to have distinct configurations for the
GENETIC and the GENETIC0 algorithm.

Create a copy of the current tests for the GENETIC algorithm to be used
for the GENETIC0 algorithm. This avoids the tests for the GENETIC0
algorithm to be influenced by later changes by Andreas.

Signed-off-by: Bobby Noelte <b0661n0e17e@gmail.com>
This commit is contained in:
Bobby Noelte
2026-07-29 12:56:08 +02:00
committed by GitHub
parent 7e5aa2f218
commit e23bb7b497
51 changed files with 13086 additions and 955 deletions
@@ -435,7 +435,9 @@ class GeneticOptimization(OptimizationBase):
):
"""Initialize the optimization problem with the required parameters."""
self.opti_param: dict[str, Any] = {}
self.fixed_ev_hours = self.config.prediction.hours - self.config.optimization.horizon_hours
self.fixed_ev_hours = (
self.config.prediction.hours - self.config.optimization.genetic.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.
@@ -1148,7 +1150,7 @@ class GeneticOptimization(OptimizationBase):
dishwasher = (
HomeAppliance(
parameters=parameters.dishwasher,
optimization_hours=self.config.optimization.horizon_hours,
optimization_hours=self.config.optimization.genetic.horizon_hours,
prediction_hours=self.config.prediction.hours,
)
if parameters.dishwasher is not None
@@ -1166,7 +1168,7 @@ class GeneticOptimization(OptimizationBase):
# Prepare device simulation
self.simulation.prepare(
parameters=parameters.ems,
optimization_hours=self.config.optimization.horizon_hours,
optimization_hours=self.config.optimization.genetic.horizon_hours,
prediction_hours=self.config.prediction.hours,
inverter=inverter, # battery is part of inverter
ev=ev,
@@ -247,17 +247,18 @@ class GeneticOptimizationParameters(
logger.info("Prediction historic hours unknown - defaulting to 24 hours.")
cls.config.prediction.historic_hours = 24
# Check optimization definitions
if cls.config.optimization.horizon_hours is None:
if cls.config.optimization.genetic.horizon_hours is None:
logger.info("Optimization horizon unknown - defaulting to 24 hours.")
cls.config.optimization.horizon_hours = 24
if cls.config.optimization.interval is None:
cls.config.optimization.genetic.horizon_hours = 24
if cls.config.optimization.genetic.interval_sec is None:
logger.info("Optimization interval unknown - defaulting to 3600 seconds.")
cls.config.optimization.interval = 3600
if cls.config.optimization.interval != 3600:
cls.config.optimization.genetic.interval_sec = 3600
if cls.config.optimization.genetic.interval_sec != 3600:
logger.info(
"Optimization interval '{}' seconds not supported - forced to 3600 seconds."
f"Optimization interval '{cls.config.optimization.genetic.interval_sec}' seconds "
"not supported - forced to 3600 seconds."
)
cls.config.optimization.interval = 3600
cls.config.optimization.genetic.interval_sec = 3600
# Check genetic algorithm definitions
if cls.config.optimization.genetic.individuals is None:
logger.info("Genetic individuals unknown - defaulting to 300.")
@@ -276,8 +277,8 @@ class GeneticOptimizationParameters(
start_solution = last_solution.start_solution
# Add forecast and device data
interval = to_duration(cls.config.optimization.interval)
power_to_energy_per_interval_factor = cls.config.optimization.interval / 3600
interval = to_duration(cls.config.optimization.genetic.interval_sec)
power_to_energy_per_interval_factor = cls.config.optimization.genetic.interval_sec / 3600
parameter_start_datetime = ems.start_datetime.set(hour=0, second=0, microsecond=0)
parameter_end_datetime = parameter_start_datetime.add(hours=cls.config.prediction.hours)
max_retries = 10
@@ -0,0 +1,82 @@
"""Settings for the GENETIC optimization algorithm.
Kept in an extra module to avoid cyclic dependencies on package import.
"""
from typing import Optional, Union
from pydantic import Field, computed_field
from akkudoktoreos.config.configabc import SettingsBaseModel
class GeneticCommonSettings(SettingsBaseModel):
"""GENETIC Optimization Algorithm Configuration."""
interval_sec: int = Field(
default=3600,
ge=15 * 60,
le=60 * 60,
json_schema_extra={
"description": "The optimization interval [sec]. Defaults to 3600 seconds (1 hour)",
"examples": [60 * 60, 15 * 60],
},
)
horizon_hours: int = Field(
default=24,
ge=0,
json_schema_extra={
"description": "The general time window within which the energy optimization goal shall be achieved [h]. Defaults to 24 hours.",
"examples": [24],
},
)
individuals: Optional[int] = Field(
default=300,
ge=10,
json_schema_extra={
"description": "Number of individuals (solutions) in the population [>= 10]. Defaults to 300.",
"examples": [300],
},
)
generations: Optional[int] = Field(
default=400,
ge=10,
json_schema_extra={
"description": "Number of generations to evolve [>= 10]. Defaults to 400.",
"examples": [400],
},
)
seed: Optional[int] = Field(
default=None,
ge=0,
json_schema_extra={
"description": "Random seed for reproducibility. None = random.",
"examples": [None, 42],
},
)
# --- Penalties (existing) -------------------------------------------------
penalties: dict[str, Union[float, int, str]] = Field(
default_factory=lambda: {
"ev_soc_miss": 10,
"ac_charge_break_even": 1.0,
},
json_schema_extra={
"description": "Penalty parameters used in fitness evaluation.",
"examples": [{"ev_soc_miss": 10}],
},
)
@computed_field # type: ignore[prop-decorator]
@property
def horizon(self) -> int:
"""Number of optimization steps."""
if self.interval_sec is None or self.interval_sec == 0 or self.horizon_hours is None:
return 0
num_steps = int(float(self.horizon_hours * 3600) / self.interval_sec)
return num_steps
@@ -740,7 +740,7 @@ class GeneticSolution(ConfigMixin, GeneticParametersBaseModel):
generated_at=to_datetime(),
comment="Optimization solution derived from GeneticSolution.",
valid_from=start_datetime,
valid_until=start_datetime.add(hours=self.config.optimization.horizon_hours),
valid_until=start_datetime.add(hours=self.config.optimization.genetic.horizon_hours),
total_losses_energy_wh=self.result.total_losses,
total_revenues_amt=self.result.total_revenue,
total_costs_amt=self.result.total_costs,