Files
EOS/tests/test_genetic0optimize.py
T
Bobby NoelteandGitHub e23bb7b497
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
chore: prepare for update of genetic algorithm (#1190)
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>
2026-07-29 12:56:08 +02:00

156 lines
5.5 KiB
Python

import json
from pathlib import Path
from typing import Any
from unittest.mock import patch
import pytest
from akkudoktoreos.config.config import ConfigEOS
from akkudoktoreos.core.cache import CacheEnergyManagementStore
from akkudoktoreos.core.coreabc import get_ems
from akkudoktoreos.optimization.genetic0.genetic0 import Genetic0Optimization
from akkudoktoreos.optimization.genetic0.genetic0params import (
Genetic0OptimizationParameters,
)
from akkudoktoreos.optimization.genetic0.genetic0solution import Genetic0Solution
from akkudoktoreos.utils.datetimeutil import to_datetime
from akkudoktoreos.utils.visualize import (
prepare_visualize, # Import the new prepare_visualize
)
ems_eos = get_ems(init=True) # init once
DIR_TESTDATA = Path(__file__).parent / "testdata"
def compare_dict(actual: dict[str, Any], expected: dict[str, Any]):
assert set(actual) == set(expected)
for key, value in expected.items():
if isinstance(value, dict):
assert isinstance(actual[key], dict)
compare_dict(actual[key], value)
elif isinstance(value, list):
assert isinstance(actual[key], list)
assert actual[key] == pytest.approx(value)
else:
assert actual[key] == pytest.approx(value)
@pytest.mark.asyncio
@pytest.mark.parametrize(
"fn_in, fn_out, ngen, break_even",
[
("genetic0optimize_input_1.json", "genetic0optimize_result_1.json", 3, 0),
("genetic0optimize_input_2.json", "genetic0optimize_result_2.json", 3, 0),
("genetic0optimize_input_2.json", "genetic0optimize_result_2_full.json", 400, 0),
("genetic0optimize_input_1.json", "genetic0optimize_result_1_be.json", 3, 1),
("genetic0optimize_input_2.json", "genetic0optimize_result_2_be.json", 3, 1),
],
)
async def test_optimize(
fn_in: str,
fn_out: str,
ngen: int,
break_even: int,
config_eos: ConfigEOS,
is_finalize: bool,
):
"""Test optimize_ems."""
# Test parameters
fixed_start_hour = 10
fixed_seed = 42
# Assure configuration holds the correct values
config_eos.merge_settings_from_dict(
{
"prediction": {
"hours": 48
},
"optimization": {
"algorithm": "GENETIC0",
"genetic0": {
"horizon_hours": 48,
"individuals": 300,
"generations": 10,
"penalties": {
"ev_soc_miss": 10,
"ac_charge_break_even": break_even,
}
}
},
"devices": {
"max_electric_vehicles": 1,
"electric_vehicles": [
{
"charge_rates": [0.0, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0],
}
],
}
}
)
# Load input and output data
file = DIR_TESTDATA / fn_in
with file.open("r") as f_in:
input_data = Genetic0OptimizationParameters(**json.load(f_in))
file = DIR_TESTDATA / fn_out
# In case a new test case is added, we don't want to fail here, so the new output is written
# to disk before
try:
with file.open("r") as f_out:
expected_data = json.load(f_out)
expected_result = Genetic0Solution(**expected_data)
except FileNotFoundError:
pass
# Fake energy management run start datetime
ems_eos.set_start_datetime(to_datetime().set(hour=fixed_start_hour))
# Throw away any cached results of the last energy management run.
CacheEnergyManagementStore().clear()
genetic0_optimization = Genetic0Optimization(fixed_seed=fixed_seed)
# Activate with pytest --finalize
if ngen > 10 and not is_finalize:
pytest.skip()
visualize_filename = str((DIR_TESTDATA / f"new_{fn_out}").with_suffix(".pdf"))
with patch(
"akkudoktoreos.utils.visualize.prepare_visualize",
side_effect=lambda parameters, results, *args, **kwargs: prepare_visualize(
parameters, results, filename=visualize_filename, **kwargs
),
) as prepare_visualize_patch:
# Call the optimization function
genetic0_solution = genetic0_optimization.optimize_ems(
parameters=input_data, start_hour=fixed_start_hour, ngen=ngen
)
# The function creates a visualization result PDF as a side-effect.
prepare_visualize_patch.assert_called_once()
assert Path(visualize_filename).exists()
# Write test output to file, so we can take it as new data on intended change
TESTDATA_FILE = DIR_TESTDATA / f"new_{fn_out}"
with TESTDATA_FILE.open("w", encoding="utf-8", newline="\n") as f_out:
f_out.write(genetic0_solution.model_dump_json(indent=4, exclude_unset=True))
assert genetic0_solution.result.Gesamtbilanz_Euro == pytest.approx(
expected_result.result.Gesamtbilanz_Euro
)
# Assert that the output contains all expected entries.
# This does not assert that the optimization always gives the same result!
# Reproducibility and mathematical accuracy should be tested on the level of individual components.
compare_dict(genetic0_solution.model_dump(), expected_result.model_dump())
# Check the correct generic optimization solution is created
optimization_solution = await genetic0_solution.optimization_solution()
# @TODO
# Check the correct generic energy management plan is created
plan = genetic0_solution.energy_management_plan()
# @TODO