refactor(genetic): refactor GENETIC to the consolidated optimizer architecture

Pin result, conversion, plan and visualization of golden runs.
Drive GENETIC through the optimizer interface and registry.
Move GENETIC into one directory with role-named modules.
Prepare every run input once, run from the parameters.
Fall back instead of cancelling the optimization run.
Simulate battery, EV and inverter from frozen dataclasses.
Simulate the home appliance from frozen dataclasses.
Convert and visualize from the parameters and result only.
Serve GENETIC from its own router.
Return a frozen result, build responses in the API.
Echo the request as sent, not with an invented time window.

Additional changes
- Pin that the result does not depend on the number of evaluation workers.
- Run the golden module in UTC: until the request date-times are held in UTC they render in the host time zone.
- Add Optimizer.run_clock(), so the EMS gets slot length and time zone without GENETIC settings.
- Rename ConfigOptimizationRequest, RuntimeForecasts and GeneticCommonSettings as ADR 0010 asks.
- Correct the request example in ADR 0010.
- Record the renamed OpenAPI schemas in CHANGELOG.md and the upgrade guide.
- Add replay files that reproduce each golden result from its parameters.
- Drop OptimizationBase from the algorithm.
- Give the replay and worker tests own review files against xdist races.
- Handle a failing preparation in the EMS like a failing run, no separate cancel path.
- Record the fallbacks in CHANGELOG.md and the upgrade guide.
- Without an inverter, buy the whole load from the grid instead of planning it at no cost.
- Do not charge from the grid without any known price.
- Treat an infinite value after the control horizon as a gap.
- Correct the documentation that said missing forecasts cancel the run.
- Copy the efficiency helpers and the self-consumption table evaluation into GENETIC.
- Add CycleTimeWindowSequence, ConsumerScheduleMode and ConsumerDeadlinePolicy as contract names.
- Hold the date-times of battery, EV and home appliance requests in UTC, so they render the same on every host.
- Drop the UTC pin of the GENETIC golden module; the request date-times no longer depend on the host.
- Copy the time window logic GENETIC needs into genetictimewindow.py.
- Add ValueTimeWindow as a contract name.
- Move the settings' to_genetic_*() converters into the preparation.
- Drop the conversion's prediction reads and configuration fallbacks, which runs never reached.
- Make the moved docstrings valid reST.
- Remove the generic optimization solution route; each optimizer serves its own path.
- Import the GENETIC settings from the package.
- Record the removed route in CHANGELOG.md and the upgrade guide.
- Make the terminal and tail value models frozen dataclasses.
- Move the response models into geneticapi; remove geneticsolution and geneticabc.
- Remove the legacy appliance start arrays and API, which read the wall clock.
- Remove the time window helpers only they used.
- Echo a start_solution without start_solution_datetime as sent.
- Carry the previous solution's start in the run parameters.
- Plan the home appliance cycles that fit, or leave the appliance out, instead of failing.
- Move the appliance layout rules into geneticappliancelayout for the preparation.
- Leave out a DAILY home appliance whose open windows leave no room for a run, with an error log, instead of silently.
- Name the reason of the SoC fallback instead of Python's exception text.
- Answer a solution request for an unknown algorithm with a 404 problem response.
- Record the fixes in CHANGELOG.md and the upgrade guide.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Assisted-by: Claude Code (claude-opus-5-5)
This commit is contained in:
Bobby Noelte
2026-11-27 13:55:41 +01:00
co-authored by Claude Opus 5.5
parent b108335ee4
commit b3d5334d3e
156 changed files with 146594 additions and 7766 deletions
+123
View File
@@ -16,6 +16,7 @@ from http import HTTPStatus
from pathlib import Path
from typing import (
TYPE_CHECKING,
Any,
Callable,
Generator,
Iterator,
@@ -43,6 +44,8 @@ from akkudoktoreos.server.server import get_default_host
if TYPE_CHECKING:
from playwright.sync_api import Browser
from akkudoktoreos.optimization.genetic.geneticalgorithm import GeneticOptimization
# -----------------------------------------------
# Adapt pytest logging handling to Loguru logging
# -----------------------------------------------
@@ -926,3 +929,123 @@ def set_other_timezone():
# Restore the original timezone
cast(Callable[[pendulum.Timezone | pendulum.FixedTimezone], None], pendulum.set_local_timezone)(original_timezone)
assert pendulum.local_timezone() == original_timezone
def genetic_optimization(seed: Optional[int] = None) -> "GeneticOptimization":
"""GENETIC algorithm with the run settings of the configuration and EMS run start.
Before migration step 3 the algorithm read the configuration and the run start of the
energy management itself; tests that build it directly get the same settings here.
Args:
seed: Random seed of the run; ``None`` gives a random seed.
Returns:
A ``GeneticOptimization`` for the current configuration and run start.
"""
from dataclasses import replace
from akkudoktoreos.core.coreabc import get_ems
from akkudoktoreos.optimization.genetic.geneticalgorithm import GeneticOptimization
from akkudoktoreos.optimization.genetic.geneticprepare import run_settings
ems = get_ems()
settings = run_settings(ems.start_datetime, ems.observation_datetime)
return GeneticOptimization(replace(settings, seed=seed, verbose=False))
def genetic_run_parameters(request: Any, optimization: Any = None) -> Any:
"""GENETIC optimization parameters for the conversion and visualization tests.
Args:
request: The forecast and device parameters (``GeneticOptimizationParameters``), e.g. the
ones a result echoes.
optimization: The ``GeneticOptimization`` of the run, whose settings are used; without it,
the settings of the configuration and EMS run start.
Returns:
A ``GeneticParameters``.
"""
from akkudoktoreos.core.coreabc import get_ems
from akkudoktoreos.optimization.genetic.geneticparameters import GeneticParameters
from akkudoktoreos.optimization.genetic.geneticprepare import run_settings
if optimization is not None:
settings = optimization.settings
else:
ems = get_ems()
settings = run_settings(ems.start_datetime, ems.observation_datetime)
return GeneticParameters(
request=request, start_hour=settings.start_datetime.hour, settings=settings
)
def genetic_result_of(solution: Any) -> Any:
"""The GENETIC result a public solution was built from.
Tests keep stored solutions (``GeneticSolution`` JSON); the conversion and the visualization
take the result of a run (``GeneticResult``).
Args:
solution: A ``GeneticSolution`` response.
Returns:
A ``GeneticResult`` with the solution's values; its request is the echoed ``parameters``.
"""
import dataclasses
from akkudoktoreos.optimization.genetic import geneticterminalvalue
from akkudoktoreos.optimization.genetic.geneticresult import (
GeneticElectricVehicleState,
GeneticResult,
GeneticSimulationOutput,
)
def curve(value: Any) -> Any:
if value is None:
return None
return geneticterminalvalue.TerminalValueCurve(**value.model_dump())
terminal_value = None
if solution.terminal_value is not None:
tv = solution.terminal_value
terminal_value = geneticterminalvalue.TerminalValueResult(
**{
name: getattr(tv, name)
for name in type(tv).model_fields
if name not in ("curve", "continuation_curve", "tail_diagnostics", "tail_plan")
},
curve=curve(tv.curve),
continuation_curve=curve(tv.continuation_curve),
tail_diagnostics=None
if tv.tail_diagnostics is None
else geneticterminalvalue.TailDiagnostics(**tv.tail_diagnostics.model_dump()),
tail_plan=[
geneticterminalvalue.TailPlanSlot(**slot.model_dump()) for slot in tv.tail_plan
],
)
simulation = GeneticSimulationOutput(
**{
field.name: getattr(solution.result, field.name)
for field in dataclasses.fields(GeneticSimulationOutput)
}
)
ev = None
if solution.ev_obj is not None:
ev = GeneticElectricVehicleState(
**{
field.name: getattr(solution.ev_obj, field.name)
for field in dataclasses.fields(GeneticElectricVehicleState)
}
)
return GeneticResult(
**{
field.name: getattr(solution, field.name)
for field in dataclasses.fields(GeneticResult)
if field.name not in ("request", "result", "ev_obj", "terminal_value")
},
request=solution.parameters,
result=simulation,
ev_obj=ev,
terminal_value=terminal_value,
)
+14 -16
View File
@@ -7,17 +7,19 @@ import json
import pstats
import sys
import time
from dataclasses import replace
from typing import Any
import numpy as np
from loguru import logger
from akkudoktoreos.core.coreabc import get_config, get_ems, get_prediction
from akkudoktoreos.core.emsettings import EnergyManagementMode
from akkudoktoreos.optimization.genetic.geneticparams import (
from akkudoktoreos.optimization.genetic import GeneticOptimizer, geneticapi
from akkudoktoreos.optimization.genetic.geneticparameters import GeneticParameters
from akkudoktoreos.optimization.genetic.geneticprepare import run_settings
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticOptimizationParameters,
)
from akkudoktoreos.optimization.optimization import OptimizationAlgorithm
from akkudoktoreos.utils.datetimeutil import to_datetime
config_eos = get_config()
@@ -425,21 +427,17 @@ def run_optimization(
else:
start_datetime = to_datetime().set(hour=start_hour)
asyncio.run(
ems_eos.run(
start_datetime=start_datetime,
mode=EnergyManagementMode.OPTIMIZATION,
algorithm=OptimizationAlgorithm.GENETIC,
genetic_parameters=parameters,
genetic_generations=ngen,
genetic_seed=seed,
# The parameters are complete already: add the run settings, then run the optimizer.
start = ems_eos.set_start_datetime(start_datetime)
settings = run_settings(start, ems_eos.observation_datetime, {"generations": ngen, "seed": seed})
solution = GeneticOptimizer().run(
GeneticParameters(
request=parameters,
start_hour=start.hour,
settings=replace(settings, verbose=verbose),
)
)
solution = ems_eos.genetic_solution()
if solution is None:
return None
return solution.model_dump_json()
return geneticapi.solution_response(solution).model_dump_json()
def main():
+11 -14
View File
@@ -30,9 +30,11 @@ from akkudoktoreos.config.configabc import (
ValueTimeWindow,
ValueTimeWindowSequence,
)
from akkudoktoreos.devices.genetic.homeappliance import (
HomeAppliance,
HomeApplianceParameters,
from akkudoktoreos.optimization.genetic.devices.genetichomeappliance import (
GeneticHomeAppliance,
)
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticHomeApplianceRequest,
)
from akkudoktoreos.utils.datetimeutil import Time, to_datetime, to_duration
@@ -2412,27 +2414,22 @@ class TestTimeWindowBoundaries:
)
# Exercise the serialized settings used by the dashboard/API as well.
sequence = CycleTimeWindowSequence.model_validate_json(sequence.model_dump_json())
appliance = HomeAppliance(
parameters=HomeApplianceParameters(
appliance = GeneticHomeAppliance(
parameters=GeneticHomeApplianceRequest(
device_id="dishwasher",
duration_h=2,
consumption_wh=2000,
num_cycles=1,
time_windows=sequence,
),
).to_parameters(),
prediction_hours=24,
optimization_hours=24,
)
start = pendulum.datetime(2026, 10, 26)
appliance.start_allowed = []
appliance.start_earliest = []
appliance.start_latest = []
appliance._build_cycle_start_allowed(
sequence, start, start.add(days=1), pendulum.duration(hours=1)
)
np.testing.assert_array_equal(np.flatnonzero(appliance.start_allowed[0]), [8, 9, 10])
assert appliance.allowed_start_slots(
slot0_datetime=start, earliest_slot=0, horizon_end_slot=24, cycle_index=0
) == [8, 9, 10]
class TestTimeWindowDST:
+3 -1
View File
@@ -1015,7 +1015,9 @@ class TestDataSequence:
assert pd.isna(values_keep[1])
async def test_raw_none_record_keeps_forecast_gap_and_true_interval_length(self, sequence):
from akkudoktoreos.optimization.genetic.forecast import bounded_forecast_array
from akkudoktoreos.optimization.genetic.geneticforecast import (
bounded_forecast_array,
)
start = to_datetime("2026-09-16T10:00:00Z", in_timezone="UTC")
for minute, value in [(0, 100.0), (15, None), (30, 100.0)]:
+28 -19
View File
@@ -43,6 +43,7 @@ from akkudoktoreos.devices.settings.batterysettings import (
BatteryProfileAdjustment,
BatteryResolutionError,
)
from akkudoktoreos.optimization.genetic import geneticprepare
# The real measurement accessor, captured before any fixture replaces it.
REAL_GET_MEASURED_VALUE = batterymeasurement.get_measured_value
@@ -77,7 +78,12 @@ PARAMETER_METHODS = [
]
# GENETIC0's conversions live in its parameter preparation (ADR 0004), not in the settings.
# The optimizers' conversions live in their parameter preparation (ADR 0004), not in the
# settings.
GENETIC_CONVERSIONS = {
"to_genetic_pv_bat_param": "battery_request",
"to_genetic_ev_bat_param": "electric_vehicle_request",
}
GENETIC0_CONVERSIONS = {
"to_genetic0_pv_bat_param": "battery_request",
"to_genetic0_ev_bat_param": "electric_vehicle_request",
@@ -85,13 +91,14 @@ GENETIC0_CONVERSIONS = {
def converter(settings, method):
"""The conversion ``method`` of the settings, or GENETIC0's function for them."""
"""The conversion function named ``method`` of GENETIC or GENETIC0, bound to the settings."""
if method in GENETIC0_CONVERSIONS:
from akkudoktoreos.optimization.genetic0 import genetic0prepare
function = getattr(genetic0prepare, GENETIC0_CONVERSIONS[method])
return lambda *args, **kwargs: function(settings, *args, **kwargs)
return getattr(settings, method)
else:
function = getattr(geneticprepare, GENETIC_CONVERSIONS[method])
return lambda *args, **kwargs: function(settings, *args, **kwargs)
COMPUTED_FIELDS = [
@@ -816,7 +823,7 @@ class TestGetBatteryProfile:
settings.resolve_operating_parameters()
_ = settings.effective_nominal_capacity_wh
_ = settings.effective_max_charge_power_w
settings.to_genetic_pv_bat_param()
geneticprepare.battery_request(settings)
assert calls == ["generic-lfp"] * 5
def test_dump_resolves_the_battery_once(self, install_profile, monkeypatch):
@@ -968,7 +975,7 @@ class TestMaxChargePower:
measurements["battery1-temperature-degc"] = -12.0
parameters = await current(settings)
assert parameters.max_charge_power_w == 0.0
assert settings.to_genetic_pv_bat_param(parameters).max_charge_power_w == 0.0
assert geneticprepare.battery_request(settings, parameters).max_charge_power_w == 0.0
assert converter(settings, "to_genetic0_pv_bat_param")(parameters).max_charge_power_w == 0.0
def test_zero_charge_power_yields_zero(self, make_profiled_settings):
@@ -1037,7 +1044,7 @@ class TestMaxDischargePower:
def test_inhibited_discharging_does_not_block_conversions(self, make_profiled_settings):
profile = make_profile(hard_cutoffs=discharge_inhibited_below_30())
settings = make_profiled_settings(profile, capacity_wh=10000)
assert settings.to_genetic_pv_bat_param().max_charge_power_w == pytest.approx(5000.0)
assert geneticprepare.battery_request(settings).max_charge_power_w == pytest.approx(5000.0)
# --- Efficiencies ----------------------------------------------------------------
@@ -1429,11 +1436,11 @@ class TestOptimizationParameters:
assert converter(settings, method)().max_charge_power_w == 0.0
def test_genetic_pv_receives_storage_cost(self):
params = make_settings(levelized_cost_of_storage_amt_kwh=0.12).to_genetic_pv_bat_param()
params = geneticprepare.battery_request(make_settings(levelized_cost_of_storage_amt_kwh=0.12))
assert params.levelized_cost_of_storage_kwh == pytest.approx(0.12)
def test_genetic_ev_receives_soc_deadline_settings(self):
params = make_settings(min_soc_max_duration_h=6.0).to_genetic_ev_bat_param()
params = geneticprepare.electric_vehicle_request(make_settings(min_soc_max_duration_h=6.0))
assert params.min_soc_max_duration_h == pytest.approx(6.0)
assert params.min_soc_deadline_datetime is None
@@ -1536,11 +1543,11 @@ class TestGeneticPowerCurves:
max_soc_percentage=100,
)
@pytest.mark.parametrize("converter", ["to_genetic_pv_bat_param", "to_genetic_ev_bat_param"])
def test_tables_follow_soc(self, make_profiled_settings, converter):
@pytest.mark.parametrize("method", ["to_genetic_pv_bat_param", "to_genetic_ev_bat_param"])
def test_tables_follow_soc(self, make_profiled_settings, method):
profile = make_profile(charge=[list(self.TAPER) for _ in range(10)], discharge=0.4)
settings = make_profiled_settings(profile, capacity_wh=10000)
parameters = getattr(settings, converter)()
parameters = converter(settings, method)()
charge = parameters.charge_power_limit_w_by_soc
discharge = parameters.discharge_power_limit_w_by_soc
@@ -1564,8 +1571,9 @@ class TestGeneticPowerCurves:
snapshot = await current(settings)
assert snapshot.max_charge_power_w == pytest.approx(5000.0)
parameters = settings.to_genetic_pv_bat_param(snapshot)
parameters = geneticprepare.battery_request(settings, snapshot)
assert parameters.max_charge_power_w == pytest.approx(10000.0)
assert parameters.charge_power_limit_w_by_soc is not None
assert parameters.charge_power_limit_w_by_soc[100] == pytest.approx(5000.0)
@pytest.mark.asyncio
@@ -1583,7 +1591,7 @@ class TestGeneticPowerCurves:
if temperature is not None:
measurements["battery1-temperature-degc"] = temperature
parameters = settings.to_genetic_pv_bat_param(await current(settings))
parameters = geneticprepare.battery_request(settings, await current(settings))
assert parameters.charge_power_limit_w_by_soc == pytest.approx([expected_w] * 101)
assert parameters.discharge_power_limit_w_by_soc == pytest.approx([expected_w] * 101)
@@ -1595,7 +1603,8 @@ class TestGeneticPowerCurves:
charge_limit_w=6000,
discharge_limit_w=1000,
)
parameters = settings.to_genetic_pv_bat_param()
parameters = geneticprepare.battery_request(settings)
assert parameters.charge_power_limit_w_by_soc is not None
assert max(parameters.charge_power_limit_w_by_soc) == pytest.approx(6000.0)
assert parameters.charge_power_limit_w_by_soc[100] == pytest.approx(5000.0)
assert parameters.discharge_power_limit_w_by_soc == pytest.approx([1000.0] * 101)
@@ -1604,7 +1613,7 @@ class TestGeneticPowerCurves:
def test_efficiency_curves_over_power_fraction(self, make_profiled_settings, full_profile):
settings = make_profiled_settings(full_profile, capacity_wh=10000)
parameters = settings.to_genetic_pv_bat_param()
parameters = geneticprepare.battery_request(settings)
charging = parameters.charging_efficiency_curve
discharging = parameters.discharging_efficiency_curve
@@ -1617,7 +1626,7 @@ class TestGeneticPowerCurves:
assert discharging[-1][1] == pytest.approx(0.9375)
def test_efficiency_curves_come_from_the_profile(self):
parameters = make_settings(capacity_wh=10000).to_genetic_pv_bat_param()
parameters = geneticprepare.battery_request(make_settings(capacity_wh=10000))
assert parameters.charge_power_limit_w_by_soc is not None
assert parameters.charging_efficiency_curve is not None
assert parameters.discharging_efficiency_curve is not None
@@ -1629,7 +1638,7 @@ class TestGeneticPowerCurves:
snapshot = self.snapshot(temperature_degC=20.0)
assert settings.resolve_power_curves(snapshot) is None
parameters = settings.to_genetic_pv_bat_param(snapshot)
parameters = geneticprepare.battery_request(settings, snapshot)
assert parameters.charge_power_limit_w_by_soc is None
assert parameters.max_charge_power_w == pytest.approx(snapshot.max_charge_power_w)
@@ -1637,7 +1646,7 @@ class TestGeneticPowerCurves:
"""A snapshot resolved without profile is converted as is: no load, no abort."""
snapshot = self.snapshot()
settings = make_settings(battery_profile="does-not-exist")
converted = settings.to_genetic_pv_bat_param(snapshot)
converted = geneticprepare.battery_request(settings, snapshot)
assert converted.max_charge_power_w == snapshot.max_charge_power_w
assert converted.max_discharge_power_w == snapshot.max_discharge_power_w
assert converted.charge_power_limit_w_by_soc is None
+5 -4
View File
@@ -23,6 +23,7 @@ from akkudoktoreos.devices.settings.invertersettings import (
InverterCommonSettings,
InverterProfileAdjustment,
)
from akkudoktoreos.optimization.genetic import geneticprepare
from akkudoktoreos.optimization.genetic0 import genetic0prepare
@@ -141,7 +142,7 @@ class TestResolution:
curve = settings.resolve_operating_parameters().dc_to_ac_efficiency_curve
assert [x for x, _ in curve] == [0.0, 1.0]
assert [y for _, y in curve] == pytest.approx([0.88, 0.88])
settings.to_genetic_param()
geneticprepare.inverter_request(settings)
def test_no_power_at_the_operating_point(self, generic):
settings = make_settings(nominal_power_w=10000)
@@ -166,7 +167,7 @@ class TestResolution:
parameters = settings.resolve_operating_parameters()
assert parameters.max_ac_charge_power_w == 0
assert math.isfinite(parameters.ac_to_dc_efficiency)
assert settings.to_genetic_param().max_ac_charge_power_w == 0
assert geneticprepare.inverter_request(settings).max_ac_charge_power_w == 0
def test_model_ac_charge_limit_is_derated(self, generic, use_profile):
use_profile(dataclasses.replace(generic, nominal_power_w=10000, max_ac_charge_power_w=5000))
@@ -232,7 +233,7 @@ class TestConversion:
def test_genetic_parameters(self, generic):
settings = make_settings(nominal_power_w=10000, max_ac_charge_power_w=4000)
parameters = settings.resolve_operating_parameters(InverterOperatingPoint(60.0))
genetic = settings.to_genetic_param(parameters)
genetic = geneticprepare.inverter_request(settings, parameters)
assert genetic.device_id == "inverter1"
assert genetic.battery_id == "battery1"
assert genetic.max_power_wh == pytest.approx(6000)
@@ -279,7 +280,7 @@ class TestOptimizationDefaults:
assert len(logged_errors) == 1
assert "allows no power at 70.0 degC" in logged_errors[0]
# The conversion gets valid parameters.
assert settings.to_genetic_param(parameters).max_power_wh == pytest.approx(10000)
assert geneticprepare.inverter_request(settings, parameters).max_power_wh == pytest.approx(10000)
def test_missing_nominal_power_gives_the_fallback(self, generic, logged_errors):
parameters = make_settings().resolve_operating_parameters_or_defaults()
+85 -65
View File
@@ -3,17 +3,20 @@
from asyncio import Lock
from types import SimpleNamespace
from typing import Any
from unittest.mock import AsyncMock, Mock
from unittest.mock import ANY, AsyncMock, Mock
import pytest
from akkudoktoreos.core import ems as ems_module
from akkudoktoreos.core.emsettings import EnergyManagementMode
from akkudoktoreos.optimization.genetic import geneticalgorithm as genetic_module
from akkudoktoreos.optimization.genetic import geneticconvert, geneticprepare
from akkudoktoreos.optimization.genetic0 import genetic0algorithm as genetic0_module
from akkudoktoreos.optimization.genetic0 import genetic0convert, genetic0prepare
from akkudoktoreos.optimization.genetic0.genetic0request import (
Genetic0Request,
)
from akkudoktoreos.optimization.genetic.geneticrequest import GeneticRequest
from akkudoktoreos.optimization.optimization import OptimizationAlgorithm
from akkudoktoreos.optimization.optimizer import OptimizerRun
from akkudoktoreos.utils.datetimeutil import to_datetime
@@ -21,20 +24,24 @@ from akkudoktoreos.utils.gridinterpolator import GridInterpolatorBackend
def _patch_optimizer(monkeypatch, prefix: str, constructor: Any) -> None:
"""Replace the optimizer class that EnergyManagement.run() instantiates.
"""Replace the optimizer class that the optimizer's ``run()`` instantiates.
GENETIC0 is imported on first use inside its optimizer, so it is patched at its source.
Both are imported on first use inside their optimizer, so they are patched at their source.
"""
module = genetic0_module if prefix == "Genetic0" else ems_module
module = genetic0_module if prefix == "Genetic0" else genetic_module
monkeypatch.setattr(module, prefix + "Optimization", constructor)
def _patch_prepare(monkeypatch, prefix: str, prepare: Any) -> None:
"""Replace the legacy parameter preparation of GENETIC or GENETIC0."""
"""Replace the forecast and device preparation of GENETIC or GENETIC0.
GENETIC resolves every request, the configured default one included, through
``resolve_request()``; GENETIC0's legacy preparation serves runs without a request only.
"""
if prefix == "Genetic0":
monkeypatch.setattr(genetic0prepare, "prepare_request", prepare)
else:
monkeypatch.setattr(ems_module.GeneticOptimizationParameters, "prepare", prepare)
monkeypatch.setattr(geneticprepare, "resolve_request", prepare)
def _warm_start_of(call: Any) -> Any:
@@ -44,12 +51,14 @@ def _warm_start_of(call: Any) -> Any:
def _assert_prepared_without_request(prefix: str, prepare: Any) -> None:
"""GENETIC0 passes start, observation time and warm start (none here) into its preparation."""
"""Both pass the warm start (none here) into their preparation; GENETIC a default request."""
prepare.assert_awaited_once()
if prefix == "Genetic0":
prepare.assert_awaited_once()
assert _warm_start_of(prepare.await_args) is None
else:
prepare.assert_awaited_once_with()
request, start, observation, warm_start = prepare.await_args.args
assert request.model_dump() == GeneticRequest().model_dump()
assert warm_start is None
def _conversion_arguments(prefix: str) -> dict[str, Any]:
@@ -59,31 +68,32 @@ def _conversion_arguments(prefix: str) -> dict[str, Any]:
def _native_solution(prefix: str) -> Any:
"""The native solution the latest run published for GENETIC or GENETIC0."""
cls = ems_module.EnergyManagement
if prefix == "Genetic0":
return cls.optimizer_result("GENETIC0")
return cls._genetic_solution
return ems_module.EnergyManagement.optimizer_result(prefix.upper())
def _set_native_solution(monkeypatch, prefix: str, solution: Any) -> None:
"""Publish ``solution`` as the result of a previous run of GENETIC or GENETIC0."""
cls = ems_module.EnergyManagement
if prefix == "Genetic0":
runs = {"GENETIC0": OptimizerRun(parameters=object(), result=solution)}
monkeypatch.setattr(cls, "_optimizer_runs", runs)
else:
monkeypatch.setattr(cls, "_genetic_solution", solution)
runs = {prefix.upper(): OptimizerRun(parameters=object(), result=solution)}
monkeypatch.setattr(ems_module.EnergyManagement, "_optimizer_runs", runs)
def _supplied(prefix: str, parameters: Any, generations: int, seed: int) -> dict[str, Any]:
def _stand_in_request() -> SimpleNamespace:
"""A request both preparations accept.
GENETIC0's preparation looks at its home appliance, GENETIC's at its start solution and its
home appliances.
"""
return SimpleNamespace(
dishwasher=None,
start_solution=None,
start_solution_datetime=None,
resolved_home_appliances=lambda: [],
)
def _supplied(parameters: Any, generations: int, seed: int) -> dict[str, Any]:
"""Run arguments that supply the parameters, generations and seed of a run."""
if prefix == "Genetic0":
return {"request": parameters, "overrides": {"generations": generations, "seed": seed}}
return {
"genetic_parameters": parameters,
"genetic_generations": generations,
"genetic_seed": seed,
}
return {"request": parameters, "overrides": {"generations": generations, "seed": seed}}
@pytest.fixture
@@ -96,7 +106,6 @@ def offline_ems(monkeypatch):
"_last_run_datetime",
"_plan",
"_optimization_solution",
"_genetic_solution",
):
monkeypatch.setattr(cls, name, None)
monkeypatch.setattr(cls, "_optimizer_runs", {})
@@ -109,12 +118,27 @@ def offline_ems(monkeypatch):
ems=SimpleNamespace(mode=EnergyManagementMode.OPTIMIZATION),
optimization=SimpleNamespace(
algorithm=OptimizationAlgorithm.GENETIC,
genetic=SimpleNamespace(generations=3, seed=17, interval_sec=3600, individuals=31),
self_consumption_interpolator="scipy",
genetic=SimpleNamespace(
generations=3,
seed=17,
interval_sec=3600,
individuals=31,
horizon_hours=24,
tail_horizon_hours=0,
penalties={},
workers=None,
pin_workers=True,
fitness_cache_max_entries=None,
terminal_value_mode="AUTO",
terminal_value_window_hours=24,
),
genetic0=SimpleNamespace(
generations=5, seed=29, horizon_hours=24, individuals=13, penalties={}
),
),
prediction=SimpleNamespace(hours=48),
feedintariff=SimpleNamespace(provider=None, direct_marketing_enabled=False),
devices=SimpleNamespace(
batteries=None, electric_vehicles=None, max_home_appliances=0
),
@@ -124,7 +148,12 @@ def offline_ems(monkeypatch):
adapter=SimpleNamespace(update_data=AsyncMock()),
set_start_datetime=cls.set_start_datetime,
)
# GENETIC0's parameter preparation reads the settings and predictions itself.
# The parameter preparations read the settings (and GENETIC0's the predictions) themselves.
monkeypatch.setattr(geneticprepare, "get_config", lambda: ems.config)
# Stand-in requests are already resolved.
monkeypatch.setattr(
geneticprepare, "resolve_request", AsyncMock(side_effect=lambda request, *args: request)
)
monkeypatch.setattr(genetic0prepare, "get_config", lambda: ems.config)
monkeypatch.setattr(
genetic0prepare, "get_prediction", lambda: SimpleNamespace(record_keys=[])
@@ -139,6 +168,12 @@ def offline_ems(monkeypatch):
return await result.optimization_solution()
monkeypatch.setattr(genetic0convert, "optimization_solution", optimization_solution)
monkeypatch.setattr(geneticconvert, "optimization_solution", optimization_solution)
monkeypatch.setattr(
geneticconvert,
"energy_management_plan",
lambda parameters, result: result.energy_management_plan(),
)
monkeypatch.setattr(
genetic0convert,
"energy_management_plan",
@@ -202,8 +237,7 @@ async def test_optimization_routes_only_selected_algorithm(
other_name = "Genetic0" if selected_name == "Genetic" else "Genetic"
suffix = "genetic" if algorithm == OptimizationAlgorithm.GENETIC else "genetic0"
other_suffix = "genetic0" if suffix == "genetic" else "genetic"
# GENETIC0's preparation looks at the request's home appliance.
sentinel_parameters = SimpleNamespace(dishwasher=None)
sentinel_parameters = _stand_in_request()
sentinel_result, sentinel_plan = object(), object()
solution = SimpleNamespace(
optimization_solution=AsyncMock(return_value=sentinel_result),
@@ -228,9 +262,9 @@ async def test_optimization_routes_only_selected_algorithm(
offline_ems.config.optimization.algorithm = OptimizationAlgorithm(other_suffix.upper())
kwargs["algorithm"] = algorithm
if supplied:
kwargs.update(_supplied(selected_name, sentinel_parameters, 7, 43))
kwargs.update(_supplied(sentinel_parameters, 7, 43))
if algorithm == OptimizationAlgorithm.GENETIC:
kwargs["genetic_individuals"] = 11
kwargs["overrides"]["individuals"] = 11
run_result = await ems_module.EnergyManagement.run(offline_ems, **kwargs)
assert run_result is solution
selected = constructors[selected_name]
@@ -241,19 +275,18 @@ async def test_optimization_routes_only_selected_algorithm(
"start_hour": expected_hour,
"parameters": sentinel_parameters,
}
# Both get their algorithm settings from the parameters (step 3).
(settings,) = selected.call_args.args
assert (settings.seed, settings.generations, settings.verbose) == (
expected_seed,
expected_generations,
False,
)
if algorithm == OptimizationAlgorithm.GENETIC:
selected.assert_called_once_with(verbose=False, fixed_seed=expected_seed)
expected_arguments["ngen"] = expected_generations
else:
# GENETIC0 gets its algorithm settings from the parameters (step 3).
(settings,) = selected.call_args.args
assert (settings.seed, settings.generations, settings.verbose) == (
expected_seed,
expected_generations,
False,
)
if algorithm == OptimizationAlgorithm.GENETIC:
expected_arguments["individuals"] = 11 if supplied else None
expected_arguments["individuals"] = 11 if supplied else expected_config.individuals
# The start of the start solution comes from the parameters, not their request.
expected_arguments["start_solution_datetime"] = None
selected.return_value.optimize_ems.assert_called_once_with(**expected_arguments)
else:
# GENETIC0 runs from its parameters, which carry the request and the start hour.
@@ -262,7 +295,12 @@ async def test_optimization_routes_only_selected_algorithm(
assert parameters.start_hour == expected_hour
constructors[other_name].assert_not_called()
preparers[other_name].assert_not_awaited()
if supplied:
if supplied and algorithm == OptimizationAlgorithm.GENETIC:
# GENETIC completes the supplied request.
preparers[selected_name].assert_awaited_once_with(
sentinel_parameters, ANY, ANY, None
)
elif supplied:
preparers[selected_name].assert_not_awaited()
else:
_assert_prepared_without_request(selected_name, preparers[selected_name])
@@ -298,24 +336,6 @@ async def test_non_optimization_modes_never_optimize(monkeypatch, offline_ems, m
assert ems_module.EnergyManagement.plan() is None
@pytest.mark.asyncio
@pytest.mark.parametrize("prefix", ["Genetic"])
async def test_missing_preparation_does_not_dispatch_controls(monkeypatch, offline_ems, prefix):
"""GENETIC may still cancel; GENETIC0's preparation never does (TestGenetic0AlwaysValid)."""
constructor = Mock()
_patch_optimizer(monkeypatch, prefix, constructor)
prepare = AsyncMock(return_value=None)
_patch_prepare(monkeypatch, prefix, prepare)
await ems_module.EnergyManagement.run(
offline_ems, algorithm=OptimizationAlgorithm(prefix.upper())
)
_assert_prepared_without_request(prefix, prepare)
constructor.assert_not_called()
assert offline_ems.adapter.update_data.await_count == 1 # acquisition only
assert ems_module.EnergyManagement.plan() is None
assert ems_module.EnergyManagement.stage() == ems_module.EnergyManagementStage.IDLE
@pytest.mark.asyncio
@pytest.mark.parametrize("start_hour", [None, 11])
async def test_legacy_optimize_explicitly_uses_genetic0(monkeypatch, start_hour):
@@ -434,7 +454,7 @@ async def test_conversion_failure_preserves_consistent_previous_results(
constructor = Mock()
constructor.return_value.optimize_ems.return_value = solution
_patch_optimizer(monkeypatch, prefix, constructor)
supplied_parameters = _supplied(prefix, SimpleNamespace(dishwasher=None), 3, 17)
supplied_parameters = _supplied(_stand_in_request(), 3, 17)
result = await cls.run(
offline_ems,
algorithm=OptimizationAlgorithm(prefix.upper()),
+35 -24
View File
@@ -13,21 +13,30 @@ from unittest.mock import Mock, patch
import numpy as np
import pytest
from akkudoktoreos.devices.genetic.battery import Battery, SolarPanelBatteryParameters
from akkudoktoreos.devices.genetic.inverter import Inverter, InverterParameters
from akkudoktoreos.devices.profile.inverterprofile import InverterProfileSettings
from akkudoktoreos.devices.profile.profilestore import get_profile_store
from akkudoktoreos.devices.settings.invertersettings import (
InverterCommonSettings,
InverterProfileAdjustment,
)
from akkudoktoreos.optimization.genetic import geneticprepare
from akkudoktoreos.optimization.genetic.devices.geneticbattery import (
GeneticBattery,
)
from akkudoktoreos.optimization.genetic.devices.geneticinverter import (
GeneticInverter,
)
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticBatteryRequest,
GeneticInverterRequest,
)
MAX_CHARGE_W = 5000
def _build(limits_total: bool, max_ac_charge_power_w=None) -> tuple[Inverter, Battery]:
battery = Battery(
SolarPanelBatteryParameters(
def _build(limits_total: bool, max_ac_charge_power_w=None) -> tuple[GeneticInverter, GeneticBattery]:
battery = GeneticBattery(
GeneticBatteryRequest(
device_id="battery1",
capacity_wh=20000,
initial_soc_percentage=20,
@@ -36,7 +45,7 @@ def _build(limits_total: bool, max_ac_charge_power_w=None) -> tuple[Inverter, Ba
min_soc_percentage=0,
max_soc_percentage=100,
max_charge_power_w=MAX_CHARGE_W,
),
).to_parameters(),
prediction_hours=4,
)
battery.reset()
@@ -45,24 +54,24 @@ def _build(limits_total: bool, max_ac_charge_power_w=None) -> tuple[Inverter, Ba
predictor = Mock()
predictor.calculate_expected_direct_consumption.side_effect = min
with patch(
"akkudoktoreos.devices.genetic.inverter.get_eos_load_interpolator",
"akkudoktoreos.optimization.genetic.devices.geneticinverter.get_genetic_load_interpolator",
return_value=predictor,
):
inverter = Inverter(
InverterParameters(
inverter = GeneticInverter(
GeneticInverterRequest(
device_id="inverter1",
max_power_wh=10000,
battery_id="battery1",
ac_to_dc_efficiency=1.0,
max_ac_charge_power_w=max_ac_charge_power_w,
ac_charge_limits_total_charge=limits_total,
),
).to_parameters(),
battery=battery,
)
return inverter, battery
def _run_ac_slot(inverter: Inverter, battery: Battery, pv_wh: float, factor: float):
def _run_ac_slot(inverter: GeneticInverter, battery: GeneticBattery, pv_wh: float, factor: float):
"""Run one AC slot the way GeneticSimulation.simulate() does."""
battery.charge_array[0] = factor
battery.discharge_array[0] = 0
@@ -150,9 +159,11 @@ class TestGeneticSimulation:
@pytest.fixture
def simulate(self, config_eos):
from akkudoktoreos.optimization.genetic.genetic import GeneticSimulation
from akkudoktoreos.optimization.genetic.geneticparams import (
GeneticEnergyManagementParameters,
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticEnergyManagementRequest,
)
from akkudoktoreos.optimization.genetic.geneticsimulation import (
GeneticSimulation,
)
config_eos.merge_settings_from_dict(
@@ -161,8 +172,8 @@ class TestGeneticSimulation:
hours = config_eos.prediction.hours
def _simulate(limits_total: bool, ac_factor: float, dc_factor: float):
battery = Battery(
SolarPanelBatteryParameters(
battery = GeneticBattery(
GeneticBatteryRequest(
device_id="battery1",
capacity_wh=30000,
initial_soc_percentage=20,
@@ -171,22 +182,22 @@ class TestGeneticSimulation:
min_soc_percentage=0,
max_soc_percentage=100,
max_charge_power_w=MAX_CHARGE_W,
),
).to_parameters(),
prediction_hours=hours,
)
battery.reset()
inverter = Inverter(
InverterParameters(
inverter = GeneticInverter(
GeneticInverterRequest(
device_id="inverter1",
max_power_wh=10000,
battery_id="battery1",
ac_charge_limits_total_charge=limits_total,
),
).to_parameters(),
battery=battery,
)
sim = GeneticSimulation()
sim.prepare(
GeneticEnergyManagementParameters.model_validate(
GeneticEnergyManagementRequest.model_validate(
dict(
pv_prognose_wh=[8000.0] * hours,
strompreis_euro_pro_wh=[0.0003] * hours,
@@ -194,7 +205,7 @@ class TestGeneticSimulation:
preis_euro_pro_wh_akku=0.0001,
gesamtlast=[0.0] * hours,
)
),
).to_parameters(),
optimization_hours=config_eos.optimization.genetic.horizon_hours,
prediction_hours=hours,
inverter=inverter,
@@ -244,11 +255,11 @@ class TestConfigOption:
battery_id="battery1",
profile_adjustment=InverterProfileAdjustment(nominal_power_w=10000),
)
assert settings.to_genetic_param().ac_charge_limits_total_charge is enabled
assert geneticprepare.inverter_request(settings).ac_charge_limits_total_charge is enabled
def test_default_profile_keeps_the_existing_model(self, config_eos):
settings = InverterCommonSettings(
device_id="inverter",
profile_adjustment=InverterProfileAdjustment(nominal_power_w=10000),
)
assert settings.to_genetic_param().ac_charge_limits_total_charge is False
assert geneticprepare.inverter_request(settings).ac_charge_limits_total_charge is False
+128
View File
@@ -0,0 +1,128 @@
"""Tests for the appliance gene layout of the GENETIC optimizer."""
from typing import Any
import pytest
from akkudoktoreos.optimization.genetic.devices.genetichomeappliance import (
GeneticHomeAppliance,
)
from akkudoktoreos.optimization.genetic.geneticappliancelayout import (
ApplianceGeneLayout,
build_appliance_layout,
)
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticHomeApplianceRequest,
)
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime
def _layout(
slot0_datetime: DateTime, horizon_slots: int, **fields: Any
) -> ApplianceGeneLayout:
"""Lay out one DAILY appliance on an hourly grid starting at ``slot0_datetime``."""
request = GeneticHomeApplianceRequest(
**{
"device_id": "dishwasher",
"consumption_wh": 1000,
"duration_h": 1,
"num_cycles": 1,
"schedule_mode": "DAILY",
**fields,
}
)
appliance = GeneticHomeAppliance(
parameters=request.to_parameters(),
optimization_hours=horizon_slots,
prediction_hours=horizon_slots,
)
return build_appliance_layout(
[appliance],
slot0_datetime,
start_slot=0,
horizon_end_slot=horizon_slots,
control_end_slot=horizon_slots,
slot_duration_h=1.0,
order_cache={},
)
class TestBuildApplianceLayout:
"""A DAILY appliance whose open windows leave no room for a cycle it owes is unschedulable."""
@pytest.mark.parametrize(
"fields",
[
{
"duration_h": 5,
"shared_time_windows": {"windows": [{"start_time": "10:00", "end_time": "13:00"}]},
},
# The first hourly start in the window is 11:00; the run would end after 12:30.
{
"duration_h": 2,
"shared_time_windows": {"windows": [{"start_time": "10:30", "end_time": "12:30"}]},
},
{"deadline_datetime": "2026-09-11T12:00:00Z", "deadline_policy": "STRICT"},
],
ids=["run-longer-than-window", "window-off-the-slot-grid", "past-strict-deadline"],
)
def test_daily_appliance_without_any_start_is_rejected(self, fields: dict[str, Any]) -> None:
with pytest.raises(ValueError, match="has no valid start"):
_layout(to_datetime("2026-09-12T00:00:00+00:00", in_timezone="UTC"), 48, **fields)
@pytest.mark.parametrize(
"start, horizon_slots, fields",
[
# 2026-09-14 is a Monday; the only window opens on Saturdays.
(
"2026-09-14T00:00:00+00:00",
48,
{
"shared_time_windows": {
"windows": [{"start_time": "10:00", "end_time": "13:00", "day_of_week": 5}]
}
},
),
("2026-09-14T00:00:00+00:00", 48, {"earliest_start_datetime": "2026-09-20T10:00:00Z"}),
# Today's cycle is done; the horizon ends at 11:00, inside tomorrow's window.
(
"2026-09-12T11:00:00+00:00",
24,
{
"duration_h": 2,
"completed_cycles": 1,
"shared_time_windows": {
"windows": [{"start_time": "10:00", "end_time": "13:00"}]
},
},
),
],
ids=[
"window-on-another-weekday",
"earliest-start-after-the-horizon",
"horizon-ends-in-the-window",
],
)
def test_daily_appliance_without_an_open_window_is_kept_without_runs(
self, start: str, horizon_slots: int, fields: dict[str, Any]
) -> None:
"""Nothing to plan in this horizon is not an unschedulable appliance."""
layout = _layout(to_datetime(start, in_timezone="UTC"), horizon_slots, **fields)
assert layout.n_genes == 0
def test_daily_appliance_done_for_a_horizon_within_the_day_is_kept_without_runs(self) -> None:
layout = _layout(
to_datetime("2026-09-12T00:00:00+00:00", in_timezone="UTC"),
24,
completed_cycles=1,
shared_time_windows={"windows": [{"start_time": "10:00", "end_time": "13:00"}]},
)
assert layout.n_genes == 0
def test_daily_appliance_past_todays_window_runs_tomorrow(self) -> None:
layout = _layout(
to_datetime("2026-09-12T14:00:00+00:00", in_timezone="UTC"),
24,
shared_time_windows={"windows": [{"start_time": "10:00", "end_time": "13:00"}]},
)
assert [str(gene.run_date) for gene in layout.genes] == ["2026-09-13"]
+49 -40
View File
@@ -5,13 +5,22 @@ import pytest
from pydantic import ValidationError
from akkudoktoreos.devices.devices import BatteriesCommonSettings
from akkudoktoreos.devices.genetic.battery import (
Battery,
ElectricVehicleParameters,
SolarPanelBatteryParameters,
)
from akkudoktoreos.devices.settings.batterysettings import BatteryProfileAdjustment
from akkudoktoreos.optimization.genetic import geneticprepare
from akkudoktoreos.optimization.genetic0 import genetic0prepare
from akkudoktoreos.optimization.genetic.devices.geneticbattery import (
GeneticBattery,
)
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticBatteryRequest,
GeneticElectricVehicleRequest,
)
# GENETIC's conversions of the battery settings, in its parameter preparation.
CONVERSIONS = {
"to_genetic_pv_bat_param": "battery_request",
"to_genetic_ev_bat_param": "electric_vehicle_request",
}
@pytest.fixture
@@ -26,7 +35,7 @@ def setup_pv_battery():
max_charge_power_w=8000
hours=24
params = SolarPanelBatteryParameters(
params = GeneticBatteryRequest(
device_id=device_id,
capacity_wh=capacity_wh,
initial_soc_percentage=initial_soc_percentage,
@@ -37,8 +46,8 @@ def setup_pv_battery():
max_charge_power_w=max_charge_power_w,
hours=hours,
)
battery = Battery(
params,
battery = GeneticBattery(
params.to_parameters(),
prediction_hours=48,
)
battery.reset()
@@ -122,13 +131,13 @@ def test_battery_discharge_when_empty(setup_pv_battery):
def test_discharge_preserves_energy_at_or_below_min_soc(
slot_duration_h, initial_soc, requested_wh
):
battery = Battery(
SolarPanelBatteryParameters(
battery = GeneticBattery(
GeneticBatteryRequest(
device_id="battery1",
capacity_wh=26_400,
initial_soc_percentage=initial_soc,
min_soc_percentage=6,
),
).to_parameters(),
prediction_hours=2,
slot_duration_h=slot_duration_h,
)
@@ -278,11 +287,11 @@ def test_charge_energy_with_charge_factor(setup_pv_battery, wh, charge_factor, e
@pytest.fixture
def setup_car_battery():
from akkudoktoreos.optimization.genetic.geneticparams import (
ElectricVehicleParameters,
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticElectricVehicleRequest,
)
params = ElectricVehicleParameters(
params = GeneticElectricVehicleRequest(
device_id="ev1",
capacity_wh=40000,
initial_soc_percentage=60,
@@ -291,8 +300,8 @@ def setup_car_battery():
max_charge_power_w=7000,
hours=24,
)
battery = Battery(
params,
battery = GeneticBattery(
params.to_parameters(),
prediction_hours=48,
)
battery.reset()
@@ -332,7 +341,7 @@ def test_car_and_pv_battery_discharge_and_max_charge_power(setup_pv_battery, set
def test_quarter_hour_charge_calls_share_one_power_budget():
params = SolarPanelBatteryParameters(
params = GeneticBatteryRequest(
device_id="battery1",
capacity_wh=10_000,
initial_soc_percentage=0,
@@ -342,7 +351,7 @@ def test_quarter_hour_charge_calls_share_one_power_budget():
charging_efficiency=1.0,
discharging_efficiency=1.0,
)
battery = Battery(params, prediction_hours=4, slot_duration_h=0.25)
battery = GeneticBattery(params.to_parameters(), prediction_hours=4, slot_duration_h=0.25)
battery.set_charge_per_hour(np.ones(4))
first_stored, _ = battery.charge_energy(200.0, 0)
@@ -354,7 +363,7 @@ def test_quarter_hour_charge_calls_share_one_power_budget():
def test_quarter_hour_discharge_calls_share_one_power_budget():
params = SolarPanelBatteryParameters(
params = GeneticBatteryRequest(
device_id="battery1",
capacity_wh=10_000,
initial_soc_percentage=100,
@@ -364,7 +373,7 @@ def test_quarter_hour_discharge_calls_share_one_power_budget():
charging_efficiency=1.0,
discharging_efficiency=1.0,
)
battery = Battery(params, prediction_hours=4, slot_duration_h=0.25)
battery = GeneticBattery(params.to_parameters(), prediction_hours=4, slot_duration_h=0.25)
battery.set_discharge_per_hour(np.ones(4))
first_delivered, _ = battery.discharge_energy(200.0, 0)
@@ -425,12 +434,12 @@ def test_pv_converter_preserves_id_lcos_charge_and_export_rates():
levelized_cost_of_storage_amt_kwh=0.123,
)
assert isinstance(BatteriesCommonSettings.validate_and_sort_charge_rates(None), np.ndarray)
parameters = settings.to_genetic_pv_bat_param()
parameters = geneticprepare.battery_request(settings)
assert parameters.device_id == "house"
assert parameters.charge_rates == [0.0, 0.5, 1.0]
assert parameters.grid_export_rates == [0.25, 1.0]
assert parameters.levelized_cost_of_storage_kwh == pytest.approx(0.123)
battery = Battery(parameters, prediction_hours=4, slot_duration_h=0.25)
battery = GeneticBattery(parameters.to_parameters(), prediction_hours=4, slot_duration_h=0.25)
assert battery.levelized_cost_of_storage_kwh == pytest.approx(0.123)
@@ -439,7 +448,7 @@ def test_equal_soc_limits_are_valid(target):
settings = BatteriesCommonSettings(device_id="ev", min_soc_percentage=target,
max_soc_percentage=target,
profile_adjustment=BatteryProfileAdjustment(nominal_capacity_wh=8000))
assert settings.to_genetic_ev_bat_param().min_soc_percentage == target
assert geneticprepare.electric_vehicle_request(settings).min_soc_percentage == target
assert genetic0prepare.electric_vehicle_request(settings).min_soc_percentage == target
@@ -456,9 +465,9 @@ def test_full_target_charges_to_capacity_without_overcharge():
nominal_capacity_wh=1000, max_charge_power_w=1000
),
min_soc_percentage=100, max_soc_percentage=100)
params = settings.to_genetic_ev_bat_param()
params = geneticprepare.electric_vehicle_request(settings)
params.initial_soc_percentage = 70
battery = Battery(params, prediction_hours=4, slot_duration_h=0.25)
battery = GeneticBattery(params.to_parameters(), prediction_hours=4, slot_duration_h=0.25)
battery.charge_array = np.ones(4)
for slot in range(4):
battery.charge_energy(wh=1000, hour=slot)
@@ -470,14 +479,14 @@ def test_full_target_charges_to_capacity_without_overcharge():
_EV_CHARGE_RATES = [0.0] + [amps / 16 for amps in range(6, 17)]
def _minimum_current_battery(kind=ElectricVehicleParameters, soc=99, maximum=100):
def _minimum_current_battery(kind=GeneticElectricVehicleRequest, soc=99, maximum=100):
parameters = kind(
device_id="ev-test", capacity_wh=60000,
initial_soc_percentage=int(soc), charging_efficiency=0.95,
discharging_efficiency=1.0, max_charge_power_w=11040,
max_soc_percentage=maximum, charge_rates=_EV_CHARGE_RATES,
)
value = Battery(parameters, prediction_hours=4, slot_duration_h=0.25)
value = GeneticBattery(parameters.to_parameters(), prediction_hours=4, slot_duration_h=0.25)
value.reset()
value.soc_wh = soc / 100 * value.capacity_wh
value.charge_array = np.full(4, 0.375)
@@ -514,7 +523,7 @@ class TestEVMinimumCurrent(unittest.TestCase):
self.assertAlmostEqual(value.soc_wh, 60000 * 0.96)
def test_stationary_battery_keeps_discrete_rate_behavior(self):
value = _minimum_current_battery(SolarPanelBatteryParameters, soc=99)
value = _minimum_current_battery(GeneticBatteryRequest, soc=99)
self.assertEqual(value.charge_energy(None, 0, charge_factor=0.375), (0.0, 0.0))
self.assertEqual(value.soc_wh, 59400)
self.assertEqual(value.charge_array[0], 0)
@@ -538,7 +547,7 @@ class TestMaxDischargePower:
@staticmethod
def _battery(max_discharge_power_w=None, slot_duration_h=1.0):
params = SolarPanelBatteryParameters(
params = GeneticBatteryRequest(
device_id="battery1",
capacity_wh=10_000,
initial_soc_percentage=100,
@@ -548,7 +557,7 @@ class TestMaxDischargePower:
charging_efficiency=1.0,
discharging_efficiency=1.0,
)
battery = Battery(params, prediction_hours=4, slot_duration_h=slot_duration_h)
battery = GeneticBattery(params.to_parameters(), prediction_hours=4, slot_duration_h=slot_duration_h)
battery.set_discharge_per_hour(np.ones(4))
return battery
@@ -584,7 +593,7 @@ class TestMaxDischargePower:
def test_negative_is_rejected(self):
with pytest.raises(ValidationError):
SolarPanelBatteryParameters(
GeneticBatteryRequest(
device_id="battery1", capacity_wh=10_000, max_discharge_power_w=-1
)
@@ -598,7 +607,7 @@ class TestMaxDischargePower:
settings = BatteriesCommonSettings(
device_id="battery1", profile_adjustment=BatteryProfileAdjustment(nominal_capacity_wh=8_000)
)
parameters = getattr(settings, converter)()
parameters = getattr(geneticprepare, CONVERSIONS[converter])(settings)
assert parameters.max_charge_power_w == pytest.approx(5_000.0)
assert parameters.max_discharge_power_w == pytest.approx(4_000.0)
@@ -611,7 +620,7 @@ class TestMaxDischargePower:
nominal_capacity_wh=8_000, max_charge_power_w=10_000, max_discharge_power_w=10_000
),
)
parameters = getattr(settings, converter)()
parameters = getattr(geneticprepare, CONVERSIONS[converter])(settings)
assert parameters.max_charge_power_w == pytest.approx(8_000.0)
assert parameters.max_discharge_power_w == pytest.approx(4_000.0)
@@ -621,7 +630,7 @@ class TestPowerCurves:
@staticmethod
def _battery(soc_percentage=50, slot_duration_h=1.0, **curves):
params = SolarPanelBatteryParameters(
params = GeneticBatteryRequest(
device_id="battery1",
capacity_wh=10_000,
initial_soc_percentage=soc_percentage,
@@ -633,7 +642,7 @@ class TestPowerCurves:
discharging_efficiency=1.0,
**curves,
)
battery = Battery(params, prediction_hours=4, slot_duration_h=slot_duration_h)
battery = GeneticBattery(params.to_parameters(), prediction_hours=4, slot_duration_h=slot_duration_h)
battery.set_charge_per_hour(np.ones(4))
battery.set_discharge_per_hour(np.ones(4))
return battery
@@ -760,7 +769,7 @@ class TestPowerCurves:
)
def test_invalid_curves_are_rejected(self, field, value):
with pytest.raises(ValidationError):
SolarPanelBatteryParameters(device_id="battery1", capacity_wh=10_000, **{field: value})
GeneticBatteryRequest(device_id="battery1", capacity_wh=10_000, **{field: value})
class TestFirstSlotFraction:
@@ -768,7 +777,7 @@ class TestFirstSlotFraction:
@staticmethod
def _battery(first_slot_fraction=1.0, soc=50, **curves):
params = SolarPanelBatteryParameters(
params = GeneticBatteryRequest(
device_id="battery1",
capacity_wh=40_000,
initial_soc_percentage=soc,
@@ -780,8 +789,8 @@ class TestFirstSlotFraction:
discharging_efficiency=1.0,
**curves,
)
battery = Battery(
params, prediction_hours=4, slot_duration_h=1.0, first_slot_fraction=first_slot_fraction
battery = GeneticBattery(
params.to_parameters(), prediction_hours=4, slot_duration_h=1.0, first_slot_fraction=first_slot_fraction
)
battery.set_charge_per_hour(np.ones(4))
battery.set_discharge_per_hour(np.ones(4))
@@ -810,7 +819,7 @@ class TestFirstSlotFraction:
def test_full_fraction_is_the_plain_slot(self):
partial = self._battery(first_slot_fraction=1.0)
plain = Battery(partial.parameters, prediction_hours=4, slot_duration_h=1.0)
plain = GeneticBattery(partial.parameters, prediction_hours=4, slot_duration_h=1.0)
plain.set_charge_per_hour(np.ones(4))
assert partial.charge_energy(None, 0, charge_factor=1.0) == plain.charge_energy(
None, 0, charge_factor=1.0
+62 -28
View File
@@ -8,12 +8,12 @@ from unittest.mock import AsyncMock, MagicMock, Mock
import numpy as np
import pytest
from conftest import genetic_optimization
from pydantic import ValidationError
from akkudoktoreos.config.config import ConfigEOS
from akkudoktoreos.core.cache import CacheEnergyManagementStore
from akkudoktoreos.core.coreabc import get_ems
from akkudoktoreos.devices.genetic.battery import Battery, SolarPanelBatteryParameters
from akkudoktoreos.devices.profile.batteryprofile import BatteryProfileSettings
from akkudoktoreos.devices.profile.batteryprofileruntime import BatteryProfile
from akkudoktoreos.devices.profile.profilestore import get_profile_store
@@ -26,19 +26,35 @@ from akkudoktoreos.devices.settings.batterysettings import (
BatteriesCommonSettings,
BatteryProfileAdjustment,
)
from akkudoktoreos.optimization.genetic import configrequest
from akkudoktoreos.optimization.genetic.configrequest import ConfigOptimizationRequest
from akkudoktoreos.optimization.genetic.fullcharge import (
from akkudoktoreos.optimization.genetic import geneticprepare
from akkudoktoreos.optimization.genetic.devices.geneticbattery import (
GeneticBattery,
)
from akkudoktoreos.optimization.genetic.geneticalgorithm import (
GeneticOptimization,
)
from akkudoktoreos.optimization.genetic.geneticfullcharge import (
FULL_CHARGE_MIN_LEAD_HOURS,
enforced_full_charge_deadline,
full_charge_deadline,
)
from akkudoktoreos.optimization.genetic.genetic import GeneticOptimization
from akkudoktoreos.optimization.genetic.geneticparams import (
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticBatteryRequest,
GeneticOptimizationParameters,
GeneticRequest,
)
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime
# Run start and observation time of the run the tests prepare; the fixture sets them.
RUN = SimpleNamespace(ems=None)
async def resolve(request: GeneticRequest, warm_start: Any = None) -> GeneticOptimizationParameters:
"""Prepare ``request`` at the run start and observation time of ``RUN.ems``."""
return await geneticprepare.resolve_request(
request, RUN.ems.start_datetime, RUN.ems.observation_datetime, warm_start
)
ems_eos = get_ems(init=True) # init once
NOW = to_datetime("2026-11-20T12:00:00+01:00")
@@ -206,7 +222,7 @@ def test_resolve_full_charge_caps_target_and_threshold(config_eos):
def test_parameters_reject_target_above_max_soc():
with pytest.raises(ValidationError):
SolarPanelBatteryParameters(
GeneticBatteryRequest(
device_id="battery1",
capacity_wh=10000,
max_soc_percentage=90,
@@ -215,7 +231,7 @@ def test_parameters_reject_target_above_max_soc():
def test_parameters_parse_naive_deadline_as_local_time():
parameters = SolarPanelBatteryParameters.model_validate(
parameters = GeneticBatteryRequest.model_validate(
{
"device_id": "battery1",
"capacity_wh": 10000,
@@ -226,6 +242,26 @@ def test_parameters_parse_naive_deadline_as_local_time():
assert parameters.full_charge_deadline_datetime == to_datetime("2026-11-21T07:00:00")
@pytest.mark.parametrize("host_timezone", ["UTC", "Europe/Berlin", "America/New_York"])
@pytest.mark.parametrize("deadline_timezone", ["UTC", "Asia/Tokyo"])
def test_parameters_hold_the_deadline_in_utc(
set_other_timezone, host_timezone, deadline_timezone
):
set_other_timezone(host_timezone)
deadline = to_datetime("2026-11-21T07:00:00", in_timezone=deadline_timezone)
parameters = GeneticBatteryRequest(
device_id="battery1",
capacity_wh=10000,
full_charge_soc_percentage=100,
full_charge_deadline_datetime=deadline,
)
assert parameters.full_charge_deadline_datetime == deadline
assert parameters.full_charge_deadline_datetime.timezone_name == "UTC"
# The serialized deadline reads back the same.
dumped = parameters.model_dump(mode="json")
assert GeneticBatteryRequest.model_validate(dumped).model_dump(mode="json") == dumped
# ---------------------------------------------------------------------------
# Resolving the configuration
# ---------------------------------------------------------------------------
@@ -272,12 +308,10 @@ def full_charge_request(config_eos, monkeypatch):
}
)
start = to_datetime("2026-09-12T10:15:00Z", in_timezone="UTC")
ems = SimpleNamespace(
start_datetime=start, observation_datetime=start, genetic_solution=lambda: None
)
monkeypatch.setattr(configrequest, "get_ems", lambda: ems)
ems = SimpleNamespace(start_datetime=start, observation_datetime=start)
monkeypatch.setattr(RUN, "ems", ems)
measurement = Mock(key_to_lists=AsyncMock(return_value=([], [])))
monkeypatch.setattr(ConfigOptimizationRequest, "measurement", measurement)
monkeypatch.setattr(geneticprepare, "get_measurement", Mock(return_value=measurement))
data = {
"soc": {"storage": 40},
"forecasts": {
@@ -302,7 +336,7 @@ async def test_cold_battery_does_not_cancel_the_request(full_charge_request, mon
monkeypatch.setattr(BatteriesCommonSettings, "measure_operating_point", cold)
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
parameters = await resolve(GeneticRequest.model_validate(data))
assert parameters.pv_battery is not None
assert parameters.pv_battery.max_charge_power_w == 0.0
@@ -324,7 +358,7 @@ async def test_hot_inverter_does_not_cancel_the_request(full_charge_request, mon
monkeypatch.setattr(InverterCommonSettings, "measure_operating_point", hot)
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
parameters = await resolve(GeneticRequest.model_validate(data))
assert parameters.inverter is not None
assert parameters.inverter.max_power_wh > 0.0
@@ -343,7 +377,7 @@ def _history(start: DateTime, full_days_ago: Optional[float]) -> tuple[list[Date
async def test_feature_disabled_reads_no_history(full_charge_request):
config, _, measurement, data = full_charge_request
config.devices.batteries["storage"].profile_adjustment.full_charge_interval_days = None
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
parameters = await resolve(GeneticRequest.model_validate(data))
assert parameters.pv_battery is not None
assert parameters.pv_battery.max_soc_percentage == 90
assert parameters.pv_battery.full_charge_soc_percentage is None
@@ -354,7 +388,7 @@ async def test_feature_disabled_reads_no_history(full_charge_request):
async def test_not_due_within_horizon_leaves_battery_unchanged(full_charge_request):
_, start, measurement, data = full_charge_request
measurement.key_to_lists.return_value = _history(start, full_days_ago=5)
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
parameters = await resolve(GeneticRequest.model_validate(data))
assert parameters.pv_battery is not None
assert parameters.pv_battery.max_soc_percentage == 90
assert parameters.pv_battery.full_charge_soc_percentage is None
@@ -369,7 +403,7 @@ async def test_not_due_within_horizon_leaves_battery_unchanged(full_charge_reque
async def test_due_without_grid_only_raises_the_maximum(full_charge_request):
_, start, measurement, data = full_charge_request
measurement.key_to_lists.return_value = _history(start, full_days_ago=20.5)
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
parameters = await resolve(GeneticRequest.model_validate(data))
assert parameters.pv_battery is not None
assert parameters.pv_battery.max_soc_percentage == 100
assert parameters.pv_battery.full_charge_soc_percentage is None
@@ -381,7 +415,7 @@ async def test_due_with_grid_enforces_target_and_deadline(full_charge_request):
config, start, measurement, data = full_charge_request
config.devices.batteries["storage"].full_charge_allow_grid = True
measurement.key_to_lists.return_value = _history(start, full_days_ago=None)
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
parameters = await resolve(GeneticRequest.model_validate(data))
assert parameters.pv_battery is not None
assert parameters.pv_battery.max_soc_percentage == 100
assert parameters.pv_battery.full_charge_soc_percentage == 100
@@ -400,7 +434,7 @@ async def test_overdue_full_charge_is_due_with_a_horizon_shorter_than_the_lead_t
config.merge_settings_from_dict({"optimization": {"genetic": {"horizon_hours": 12}}})
config.devices.batteries["storage"].full_charge_allow_grid = True
measurement.key_to_lists.return_value = _history(start, full_days_ago=None)
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
parameters = await resolve(GeneticRequest.model_validate(data))
assert parameters.pv_battery is not None
assert parameters.pv_battery.max_soc_percentage == 100
assert parameters.pv_battery.full_charge_soc_percentage == 100
@@ -414,7 +448,7 @@ async def test_missing_history_does_not_schedule_a_full_charge(full_charge_reque
config, _, measurement, data = full_charge_request
config.devices.batteries["storage"].full_charge_allow_grid = True
measurement.key_to_lists.side_effect = KeyError("storage-soc-factor")
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
parameters = await resolve(GeneticRequest.model_validate(data))
assert parameters.pv_battery is not None
assert parameters.pv_battery.max_soc_percentage == 90
assert parameters.pv_battery.full_charge_soc_percentage is None
@@ -430,7 +464,7 @@ async def test_profile_interval_schedules_the_full_charge(full_charge_request, m
profile = _profile(full_charge_interval_days=21.0)
monkeypatch.setattr(BatteriesCommonSettings, "get_battery_profile", lambda self: profile)
measurement.key_to_lists.return_value = _history(start, full_days_ago=None)
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
parameters = await resolve(GeneticRequest.model_validate(data))
assert parameters.pv_battery is not None
assert parameters.pv_battery.max_soc_percentage == 100
assert parameters.pv_battery.full_charge_soc_percentage == 100
@@ -443,7 +477,7 @@ async def test_full_charge_target_stays_within_technical_bounds(full_charge_requ
profile = _profile(technical_max_soc_percent=95.0)
monkeypatch.setattr(BatteriesCommonSettings, "get_battery_profile", lambda self: profile)
measurement.key_to_lists.return_value = _history(start, full_days_ago=None)
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
parameters = await resolve(GeneticRequest.model_validate(data))
assert parameters.pv_battery is not None
assert parameters.pv_battery.max_soc_percentage == 95
assert parameters.pv_battery.full_charge_soc_percentage == 95
@@ -511,8 +545,8 @@ def _full_charge_parameters(hours: int, **battery_extra) -> GeneticOptimizationP
def test_full_charge_slot_resolution(config_eos: ConfigEOS):
_optimizer_config(config_eos, 24)
ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0, second=0, microsecond=0))
optimization = GeneticOptimization(fixed_seed=1)
optimization._slot0_datetime = optimization.ems.start_datetime
optimization = genetic_optimization(seed=1)
optimization._slot0_datetime = optimization.settings.start_datetime
slot0 = optimization._slot0_datetime
assert optimization._full_charge_slot(_full_charge_parameters(24)) is None
@@ -531,8 +565,8 @@ def test_full_charge_slot_resolution(config_eos: ConfigEOS):
def test_maximum_soc_before_deadline_counts(config_eos: ConfigEOS):
_optimizer_config(config_eos, 24)
ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0, second=0, microsecond=0))
optimization = GeneticOptimization(fixed_seed=1)
optimization.simulation.battery = MagicMock(spec=Battery)
optimization = genetic_optimization(seed=1)
optimization.simulation.battery = MagicMock(spec=GeneticBattery)
optimization.simulation.battery.current_soc_percentage.return_value = 40.0
result = {"akku_soc_pro_stunde": [30.0, 100.0, 60.0, 50.0]}
@@ -557,7 +591,7 @@ def _run(config_eos: ConfigEOS, **battery_extra) -> list[float]:
_optimizer_config(config_eos, hours)
ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0, second=0, microsecond=0))
CacheEnergyManagementStore().clear()
solution = GeneticOptimization(fixed_seed=42).optimize_ems(
solution = genetic_optimization(seed=42).optimize_ems(
parameters=_full_charge_parameters(hours, **battery_extra), start_hour=0, ngen=40
)
return list(solution.result.battery_soc_per_hour)
+61 -29
View File
@@ -10,30 +10,37 @@ from akkudoktoreos.devices.devicesabc import (
ConsumerDeadlinePolicy,
ConsumerScheduleMode,
)
from akkudoktoreos.devices.genetic.battery import Battery, ElectricVehicleParameters
from akkudoktoreos.devices.genetic.homeappliance import (
HomeAppliance,
HomeApplianceParameters,
resample_power_to_slot_energy,
)
from akkudoktoreos.devices.settings.batterysettings import BatteriesCommonSettings
from akkudoktoreos.devices.settings.homeappliancesettings import (
HomeApplianceCommonSettings,
)
from akkudoktoreos.optimization.genetic import geneticprepare
from akkudoktoreos.optimization.genetic0 import genetic0prepare
from akkudoktoreos.optimization.genetic.devices.geneticbattery import (
GeneticBattery,
)
from akkudoktoreos.optimization.genetic.devices.genetichomeappliance import (
GeneticDeadlinePolicy,
GeneticHomeAppliance,
resample_power_to_slot_energy,
)
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticElectricVehicleRequest,
GeneticHomeApplianceRequest,
)
from akkudoktoreos.utils.datetimeutil import to_datetime
def appliance(*, slots: int = 192, slot_h: float = 0.25, **kwargs: Any) -> HomeAppliance:
return HomeAppliance(
HomeApplianceParameters.model_validate(
def appliance(*, slots: int = 192, slot_h: float = 0.25, **kwargs: Any) -> GeneticHomeAppliance:
return GeneticHomeAppliance(
GeneticHomeApplianceRequest.model_validate(
{
"device_id": "washer",
"load_profile_power_w": [1200.0, 600.0, 300.0],
"load_profile_interval_seconds": 600,
**kwargs,
}
),
).to_parameters(),
optimization_hours=48,
prediction_hours=slots,
slot_duration_h=slot_h,
@@ -58,7 +65,7 @@ def test_profile_energy_independent_of_slot_grid(input_s: int, slot_s: int) -> N
@pytest.mark.parametrize("profile", [[], [-1], [float("nan")], [float("inf")]])
def test_invalid_profiles_rejected_in_parameters_and_settings(profile: list[float]) -> None:
for model in (HomeApplianceParameters, HomeApplianceCommonSettings):
for model in (GeneticHomeApplianceRequest, HomeApplianceCommonSettings):
with pytest.raises(ValidationError):
model.model_validate({"device_id": "bad", "load_profile_power_w": profile})
@@ -67,14 +74,14 @@ def test_invalid_profiles_rejected_in_parameters_and_settings(profile: list[floa
"fields", [{"duration_h": 2}, {"consumption_wh": 500}, {"duration_h": 2, "consumption_wh": 500}]
)
def test_profile_cannot_silently_override_explicit_flat_definition(fields: dict[str, int]) -> None:
for model in (HomeApplianceParameters, HomeApplianceCommonSettings):
for model in (GeneticHomeApplianceRequest, HomeApplianceCommonSettings):
with pytest.raises(ValidationError, match="Conflicting"):
model.model_validate({"device_id": "bad", "load_profile_power_w": [100.0], **fields})
def test_settings_profile_roundtrip_and_legacy_defaults() -> None:
defaults = HomeApplianceCommonSettings(device_id="legacy")
assert defaults.to_genetic_param().consumption_wh == 3000
assert geneticprepare.home_appliance_request(defaults).consumption_wh == 3000
assert genetic0prepare.home_appliance_request(defaults).duration_h == 3
settings = HomeApplianceCommonSettings.model_validate(
{
@@ -88,7 +95,7 @@ def test_settings_profile_roundtrip_and_legacy_defaults() -> None:
}
)
restored = HomeApplianceCommonSettings.model_validate_json(settings.model_dump_json())
params = restored.to_genetic_param()
params = geneticprepare.home_appliance_request(restored)
assert params.load_profile_power_w == [1200.0, 600.0]
assert params.consumption_wh is None and params.duration_h is None
assert params.num_cycles == 2 and params.min_cycle_gap_h == 1
@@ -114,10 +121,10 @@ def test_cycle_and_shared_windows_intersect_after_completed_cycle() -> None:
"time_windows": {"windows": [{"start_time": "18:30", "duration": "1 hour"}]},
}
)
device = HomeAppliance(settings.to_genetic_param(), 48, 192, 0.25)
device = GeneticHomeAppliance(geneticprepare.home_appliance_request(settings).to_parameters(), 48, 192, 0.25)
device.set_completed_cycles(1)
zero = to_datetime("2026-09-16T00:00:00+02:00", in_timezone="Europe/Berlin")
assert device.remaining_cycle_indices == [1]
assert device.num_remaining_cycles == 1
assert device.allowed_start_slots(
slot0_datetime=zero, earliest_slot=0, horizon_end_slot=96, cycle_index=1
) == [74, 75, 76]
@@ -133,12 +140,6 @@ def test_cycle_and_shared_windows_intersect_after_completed_cycle() -> None:
) == [170, 171, 172]
def test_legacy_multiple_cycles_use_slots_and_physical_idle_gap() -> None:
device = appliance(slots=96, num_cycles=2, min_cycle_gap_h=1)
assert device.set_starting_times([4, 4]) == [4, 10]
assert device.get_load_curve().sum() == pytest.approx(700)
def test_touching_cycle_windows_preserve_union() -> None:
device = appliance(
time_windows={
@@ -180,7 +181,7 @@ def test_best_effort_relaxes_only_deadline_not_window_or_earliest() -> None:
slot0_datetime=zero, earliest_slot=0, horizon_end_slot=96
) == [36]
assert device.deadline_relaxed and device.deadline_missed([36], zero)
device.deadline_policy = ConsumerDeadlinePolicy.STRICT
device.deadline_policy = GeneticDeadlinePolicy.STRICT
assert (
device.allowed_start_slots(slot0_datetime=zero, earliest_slot=0, horizon_end_slot=96) == []
)
@@ -233,13 +234,13 @@ def test_ev_deadlines_roundtrip_without_changing_slot_physics() -> None:
"min_soc_max_duration_h": 2.5,
}
)
params = settings.to_genetic_ev_bat_param()
params = geneticprepare.electric_vehicle_request(settings)
assert params.min_soc_max_duration_h == 2.5
assert params.min_soc_deadline_datetime is not None
assert params.min_soc_deadline_datetime.in_timezone("Europe/Berlin").hour == 7
assert params.capacity_wh == 10000
assert params.max_charge_power_w == pytest.approx(4000)
battery = Battery(params, prediction_hours=16, slot_duration_h=0.25)
battery = GeneticBattery(params.to_parameters(), prediction_hours=16, slot_duration_h=0.25)
battery.charge_array[0] = 1
# 4000 W for a 0.25 h slot caps the 2000 Wh request at 1000 Wh; the charging
# efficiency comes from the battery profile.
@@ -253,20 +254,19 @@ def test_ev_deadlines_roundtrip_without_changing_slot_physics() -> None:
def test_ev_invalid_departure_durations_rejected(duration: float) -> None:
# Optimizer parameters take "capacity_wh", settings a profile adjustment.
for model, capacity in (
(ElectricVehicleParameters, {"capacity_wh": 10000}),
(GeneticElectricVehicleRequest, {"capacity_wh": 10000}),
(BatteriesCommonSettings, {"profile_adjustment": {"nominal_capacity_wh": 10000}}),
):
with pytest.raises(ValidationError):
model.model_validate({"device_id": "car", **capacity, "min_soc_max_duration_h": duration})
def test_completed_cycles_parameter_initializes_remaining_global_ids() -> None:
def test_completed_cycles_parameter_initializes_remaining_cycles() -> None:
device = appliance(num_cycles=3, completed_cycles=2)
assert device.completed_cycles == 2
assert device.remaining_cycle_indices == [2]
assert device.num_remaining_cycles == 1
done = appliance(num_cycles=3, completed_cycles=3)
assert done.remaining_cycle_indices == []
assert done.num_remaining_cycles == 0
with pytest.raises(ValidationError, match="completed_cycles"):
appliance(num_cycles=2, completed_cycles=3)
@@ -296,3 +296,35 @@ def test_absolute_deadline_offsets_describe_same_instant(deadline: str) -> None:
) == [0, 1, 2]
assert not device.deadline_missed([2], zero)
assert device.deadline_missed([3], zero)
APPLIANCE_REQUEST: dict[str, Any] = {
"device_id": "dishwasher",
"consumption_wh": 2000,
"duration_h": 2,
"num_cycles": 1,
}
@pytest.mark.parametrize("host_timezone", ["Europe/Berlin", "America/New_York"])
@pytest.mark.parametrize(
"model, field, request_data",
[
(GeneticElectricVehicleRequest, "min_soc_deadline_datetime", {"device_id": "car", "capacity_wh": 10000}),
(GeneticHomeApplianceRequest, "earliest_start_datetime", APPLIANCE_REQUEST),
(GeneticHomeApplianceRequest, "deadline_datetime", APPLIANCE_REQUEST),
(GeneticHomeApplianceRequest, "run_started_datetime", APPLIANCE_REQUEST),
],
)
def test_request_date_times_are_held_in_utc(
set_other_timezone, host_timezone, model, field, request_data
) -> None:
"""Request date-times render the same on every host and read back the same."""
set_other_timezone(host_timezone)
moment = to_datetime("2026-09-16T09:30:00", in_timezone="Asia/Tokyo")
request = model.model_validate({**request_data, field: moment})
assert getattr(request, field) == moment
assert getattr(request, field).timezone_name == "UTC"
dumped = request.model_dump(mode="json")
assert dumped[field] == "2026-09-16T00:30:00Z"
assert model.model_validate(dumped).model_dump(mode="json") == dumped
+17 -14
View File
@@ -3,16 +3,19 @@ from typing import Optional
from unittest.mock import MagicMock
import pytest
from conftest import genetic_optimization
from akkudoktoreos.config.config import ConfigEOS
from akkudoktoreos.core.cache import CacheEnergyManagementStore
from akkudoktoreos.core.coreabc import get_ems
from akkudoktoreos.devices.genetic.battery import Battery
from akkudoktoreos.optimization.genetic.genetic import GeneticOptimization
from akkudoktoreos.optimization.genetic.geneticparams import (
from akkudoktoreos.optimization.genetic.devices.geneticbattery import GeneticBattery
from akkudoktoreos.optimization.genetic.geneticalgorithm import (
GeneticOptimization,
)
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticOptimizationParameters,
)
from akkudoktoreos.optimization.genetic.geneticsolution import GeneticSolution
from akkudoktoreos.optimization.genetic.geneticresult import GeneticResult
from akkudoktoreos.utils.datetimeutil import to_datetime
ems_eos = get_ems(init=True) # init once
@@ -39,7 +42,7 @@ def test_direct_marketing_preserves_constant_supplied_feed_in_tariff(config_eos:
)
)
adjusted = GeneticOptimization()._parameters_for_config(parameters)
adjusted = genetic_optimization()._parameters_for_config(parameters)
assert adjusted.ems.einspeiseverguetung_euro_pro_wh == [0.00007, 0.00007]
assert parameters.ems.einspeiseverguetung_euro_pro_wh == [0.00007, 0.00007]
@@ -62,7 +65,7 @@ def test_direct_marketing_keeps_variable_feed_in_tariff(config_eos: ConfigEOS):
)
)
adjusted = GeneticOptimization()._parameters_for_config(parameters)
adjusted = genetic_optimization()._parameters_for_config(parameters)
assert adjusted.ems.einspeiseverguetung_euro_pro_wh == [0.0001, -0.00005]
@@ -120,7 +123,7 @@ def test_grid_export_rates_reach_the_solution(config_eos: ConfigEOS):
)
)
optimization = GeneticOptimization(fixed_seed=42)
optimization = genetic_optimization(seed=42)
solution = optimization.optimize_ems(parameters=parameters, start_hour=0, ngen=3)
# Full power first, so the full-power state keeps the lowest export index.
@@ -173,8 +176,8 @@ def test_ev_deadline_slot_resolution(config_eos: ConfigEOS):
}
)
ems_eos.set_start_datetime(to_datetime().set(hour=10, minute=0, second=0, microsecond=0))
optimization = GeneticOptimization(fixed_seed=1)
optimization._slot0_datetime = optimization.ems.start_datetime
optimization = genetic_optimization(seed=1)
optimization._slot0_datetime = optimization.settings.start_datetime
slot0 = optimization._slot0_datetime
# Duration only: 6 h after the start hour 10.
@@ -214,10 +217,10 @@ def test_ev_soc_penalty_reads_the_deadline_slot(config_eos: ConfigEOS):
}
)
ems_eos.set_start_datetime(to_datetime().set(hour=10, minute=0, second=0, microsecond=0))
optimization = GeneticOptimization(fixed_seed=1)
optimization = genetic_optimization(seed=1)
simulation_result = {"EAuto_SoC_pro_Stunde": [20.0, 35.0, 50.0, 80.0]}
optimization.simulation.ev = MagicMock(spec=Battery)
optimization.simulation.ev = MagicMock(spec=GeneticBattery)
optimization.simulation.ev.current_soc_percentage.return_value = 80.0
# Without a deadline the final SoC counts.
@@ -254,7 +257,7 @@ def test_ev_deadline_charges_before_departure(config_eos: ConfigEOS):
CacheEnergyManagementStore().clear()
parameters = _ev_deadline_parameters(hours, min_soc_max_duration_h=6)
solution = GeneticOptimization(fixed_seed=42).optimize_ems(
solution = genetic_optimization(seed=42).optimize_ems(
parameters=parameters, start_hour=0, ngen=40
)
@@ -266,7 +269,7 @@ def test_ev_deadline_charges_before_departure(config_eos: ConfigEOS):
def _terminal_value_run(
config_eos: ConfigEOS, mode: str, prices: Optional[list[float]] = None
) -> GeneticSolution:
) -> GeneticResult:
"""48 h with expensive energy and two dirt-cheap slots at the very end.
Charging in those last slots only pays off when the stored energy keeps a
@@ -324,7 +327,7 @@ def _terminal_value_run(
ev=None,
)
)
return GeneticOptimization(fixed_seed=7).optimize_ems(
return genetic_optimization(seed=7).optimize_ems(
parameters=parameters, start_hour=0, ngen=20
)
+55 -50
View File
@@ -3,19 +3,24 @@ from unittest.mock import Mock
import numpy as np
import pytest
from akkudoktoreos.devices.genetic.battery import (
Battery,
ElectricVehicleParameters,
SolarPanelBatteryParameters,
from akkudoktoreos.optimization.genetic.devices.geneticbattery import (
GeneticBattery,
)
from akkudoktoreos.devices.genetic.homeappliance import (
HomeAppliance,
HomeApplianceParameters,
from akkudoktoreos.optimization.genetic.devices.genetichomeappliance import (
GeneticHomeAppliance,
)
from akkudoktoreos.devices.genetic.inverter import Inverter, InverterParameters
from akkudoktoreos.optimization.genetic.genetic import GeneticSimulation
from akkudoktoreos.optimization.genetic.geneticparams import (
GeneticEnergyManagementParameters,
from akkudoktoreos.optimization.genetic.devices.geneticinverter import (
GeneticInverter,
)
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticBatteryRequest,
GeneticElectricVehicleRequest,
GeneticEnergyManagementRequest,
GeneticHomeApplianceRequest,
GeneticInverterRequest,
)
from akkudoktoreos.optimization.genetic.geneticsimulation import (
GeneticSimulation,
)
start_hour = 1
@@ -36,42 +41,42 @@ def genetic_simulation(config_eos) -> GeneticSimulation:
assert config_eos.optimization.genetic.horizon_hours == 24
# Initialize the battery and the inverter
akku = Battery(
SolarPanelBatteryParameters(
akku = GeneticBattery(
GeneticBatteryRequest(
device_id="battery1",
capacity_wh=5000,
initial_soc_percentage=80,
min_soc_percentage=10,
),
).to_parameters(),
prediction_hours=config_eos.prediction.hours,
)
akku.reset()
inverter = Inverter(
InverterParameters(
inverter = GeneticInverter(
GeneticInverterRequest(
device_id="inverter1", max_power_wh=10000, battery_id=akku.parameters.device_id
),
).to_parameters(),
battery=akku,
)
# Flexible consumer (fixed start at slot 2 for this deterministic test)
home_appliance = HomeAppliance(
HomeApplianceParameters(
home_appliance = GeneticHomeAppliance(
GeneticHomeApplianceRequest(
device_id="dishwasher1",
consumption_wh=2000,
duration_h=2,
time_windows=None,
),
).to_parameters(),
optimization_hours=config_eos.optimization.genetic.horizon_hours,
prediction_hours=config_eos.prediction.hours,
)
home_appliance.build_load_curve([2])
# Example initialization of electric car battery
eauto = Battery(
ElectricVehicleParameters(
eauto = GeneticBattery(
GeneticElectricVehicleRequest(
device_id="ev1", capacity_wh=26400, initial_soc_percentage=10, min_soc_percentage=10
),
).to_parameters(),
prediction_hours=config_eos.prediction.hours,
)
eauto.set_charge_per_hour(np.full(config_eos.prediction.hours, 1))
@@ -236,7 +241,7 @@ def genetic_simulation(config_eos) -> GeneticSimulation:
# Initialize the energy management system with the respective parameters
simulation = GeneticSimulation()
simulation.prepare(
GeneticEnergyManagementParameters.model_validate(
GeneticEnergyManagementRequest.model_validate(
dict(
pv_prognose_wh=pv_prognose_wh,
strompreis_euro_pro_wh=strompreis_euro_pro_wh,
@@ -244,7 +249,7 @@ def genetic_simulation(config_eos) -> GeneticSimulation:
preis_euro_pro_wh_akku=preis_euro_pro_wh_akku,
gesamtlast=gesamtlast,
)
),
).to_parameters(),
optimization_hours=config_eos.optimization.genetic.horizon_hours,
prediction_hours=config_eos.prediction.hours,
inverter=inverter,
@@ -273,21 +278,21 @@ def test_ev_charging_uses_raw_input_energy_for_load_and_grid(config_eos):
"optimization": {"genetic": {"tail_horizon_hours": 0, "horizon_hours": 1}},
}
)
ev = Battery(
ElectricVehicleParameters(
ev = GeneticBattery(
GeneticElectricVehicleRequest(
device_id="ev1",
capacity_wh=1000,
charging_efficiency=0.8,
max_charge_power_w=100,
initial_soc_percentage=0,
min_soc_percentage=0,
),
).to_parameters(),
prediction_hours=1,
)
inverter = Inverter(InverterParameters(device_id="inverter1", max_power_wh=1000.0))
inverter = GeneticInverter(GeneticInverterRequest(device_id="inverter1", max_power_wh=1000.0).to_parameters())
simulation = GeneticSimulation()
simulation.prepare(
GeneticEnergyManagementParameters.model_validate(
GeneticEnergyManagementRequest.model_validate(
dict(
pv_prognose_wh=[0.0],
strompreis_euro_pro_wh=[0.001],
@@ -295,7 +300,7 @@ def test_ev_charging_uses_raw_input_energy_for_load_and_grid(config_eos):
preis_euro_pro_wh_akku=0.0,
gesamtlast=[0.0],
)
),
).to_parameters(),
optimization_hours=1,
prediction_hours=1,
inverter=inverter,
@@ -320,7 +325,7 @@ def test_direct_marketing_curtails_negative_feed_in(config_eos, monkeypatch):
}
)
inverter = Inverter(InverterParameters(device_id="inverter1", max_power_wh=1000.0))
inverter = GeneticInverter(GeneticInverterRequest(device_id="inverter1", max_power_wh=1000.0).to_parameters())
monkeypatch.setattr(
inverter.self_consumption_predictor,
"calculate_expected_direct_consumption",
@@ -329,7 +334,7 @@ def test_direct_marketing_curtails_negative_feed_in(config_eos, monkeypatch):
simulation = GeneticSimulation()
simulation.prepare(
GeneticEnergyManagementParameters.model_validate(
GeneticEnergyManagementRequest.model_validate(
dict(
pv_prognose_wh=[500.0, 500.0],
strompreis_euro_pro_wh=[-0.0001, -0.0001],
@@ -337,7 +342,7 @@ def test_direct_marketing_curtails_negative_feed_in(config_eos, monkeypatch):
preis_euro_pro_wh_akku=0.0,
gesamtlast=[0.0, 0.0],
)
),
).to_parameters(),
optimization_hours=config_eos.optimization.genetic.horizon_hours,
prediction_hours=config_eos.prediction.hours,
inverter=inverter,
@@ -363,8 +368,8 @@ def _direct_marketing_battery_export_simulation(
}
)
battery = Battery(
SolarPanelBatteryParameters(
battery = GeneticBattery(
GeneticBatteryRequest(
device_id="battery1",
capacity_wh=1000,
initial_soc_percentage=100,
@@ -373,22 +378,22 @@ def _direct_marketing_battery_export_simulation(
discharging_efficiency=1.0,
levelized_cost_of_storage_kwh=levelized_cost_of_storage_kwh,
max_charge_power_w=500,
),
).to_parameters(),
prediction_hours=config_eos.prediction.hours,
)
inverter = Inverter(
InverterParameters(
inverter = GeneticInverter(
GeneticInverterRequest(
device_id="inverter1",
max_power_wh=500.0,
battery_id=battery.parameters.device_id,
dc_to_ac_efficiency=dc_to_ac_efficiency,
),
).to_parameters(),
battery=battery,
)
simulation = GeneticSimulation()
simulation.prepare(
GeneticEnergyManagementParameters.model_validate(
GeneticEnergyManagementRequest.model_validate(
dict(
pv_prognose_wh=[0.0, 0.0],
strompreis_euro_pro_wh=[0.0, 0.0],
@@ -396,7 +401,7 @@ def _direct_marketing_battery_export_simulation(
preis_euro_pro_wh_akku=0.0,
gesamtlast=[0.0, 0.0],
)
),
).to_parameters(),
optimization_hours=config_eos.optimization.genetic.horizon_hours,
prediction_hours=config_eos.prediction.hours,
inverter=inverter,
@@ -479,8 +484,8 @@ def test_disabled_ac_charging_clears_the_reported_plan(config_eos):
}
)
battery = Battery(
SolarPanelBatteryParameters(
battery = GeneticBattery(
GeneticBatteryRequest(
device_id="battery1",
capacity_wh=10000,
initial_soc_percentage=50,
@@ -488,22 +493,22 @@ def test_disabled_ac_charging_clears_the_reported_plan(config_eos):
charging_efficiency=1.0,
discharging_efficiency=1.0,
max_charge_power_w=5000,
),
).to_parameters(),
prediction_hours=config_eos.prediction.hours,
)
inverter = Inverter(
InverterParameters(
inverter = GeneticInverter(
GeneticInverterRequest(
device_id="inverter1",
max_power_wh=5000.0,
battery_id=battery.parameters.device_id,
max_ac_charge_power_w=0, # Netzladen deaktiviert
),
).to_parameters(),
battery=battery,
)
simulation = GeneticSimulation()
simulation.prepare(
GeneticEnergyManagementParameters.model_validate(
GeneticEnergyManagementRequest.model_validate(
dict(
pv_prognose_wh=[0.0, 0.0],
strompreis_euro_pro_wh=[0.0003, 0.0003],
@@ -511,7 +516,7 @@ def test_disabled_ac_charging_clears_the_reported_plan(config_eos):
preis_euro_pro_wh_akku=0.0,
gesamtlast=[0.0, 0.0],
)
),
).to_parameters(),
optimization_hours=config_eos.optimization.genetic.horizon_hours,
prediction_hours=config_eos.prediction.hours,
inverter=inverter,
+14 -14
View File
@@ -1,17 +1,19 @@
# ruff: noqa: S101
import numpy as np
from conftest import genetic_optimization
from akkudoktoreos.devices.devicesabc import BatteryOperationMode
from akkudoktoreos.optimization.genetic.genetic import GeneticOptimization
from akkudoktoreos.optimization.genetic.geneticsolution import GeneticSolution
from akkudoktoreos.optimization.genetic import geneticconvert
from akkudoktoreos.optimization.genetic.geneticalgorithm import (
GeneticOptimization,
)
def test_battery_discharge_allowed_remains_local_load_mode(config_eos):
config_eos.merge_settings_from_dict({"feedintariff": {"direct_marketing_enabled": True}})
solution = GeneticSolution
operation_mode, operation_mode_factor = solution._battery_operation_from_solution(
operation_mode, operation_mode_factor = geneticconvert._battery_operation_from_solution(
ac_charge=0.0,
dc_charge=0.0,
discharge_allowed=True,
@@ -23,9 +25,8 @@ def test_battery_discharge_allowed_remains_local_load_mode(config_eos):
def test_battery_grid_export_signal_maps_to_grid_support_export(config_eos):
config_eos.merge_settings_from_dict({"feedintariff": {"direct_marketing_enabled": True}})
solution = GeneticSolution
operation_mode, operation_mode_factor = solution._battery_operation_from_solution(
operation_mode, operation_mode_factor = geneticconvert._battery_operation_from_solution(
ac_charge=0.0,
dc_charge=0.0,
discharge_allowed=False,
@@ -37,7 +38,7 @@ def test_battery_grid_export_signal_maps_to_grid_support_export(config_eos):
def test_decode_charge_discharge_has_separate_battery_grid_export_state():
optimization = GeneticOptimization()
optimization = genetic_optimization()
optimization.bat_possible_charge_values = [1.0]
optimization.optimize_dc_charge = True
optimization.optimize_battery_grid_export = True
@@ -53,7 +54,7 @@ def test_decode_charge_discharge_has_separate_battery_grid_export_state():
def test_decode_charge_discharge_has_self_consumption_state_after_legacy_export():
optimization = GeneticOptimization()
optimization = genetic_optimization()
optimization.bat_possible_charge_values = [1.0]
optimization.optimize_dc_charge = True
optimization.optimize_battery_grid_export = True
@@ -74,7 +75,7 @@ def test_decode_charge_discharge_has_self_consumption_state_after_legacy_export(
def test_graded_grid_export_states_decode_to_rates():
"""Each configured export rate gets its own state; state 5 stays full power."""
optimization = GeneticOptimization()
optimization = genetic_optimization()
optimization.bat_possible_charge_values = [1.0]
optimization.bat_possible_grid_export_values = [1.0, 0.5, 0.25]
optimization.optimize_dc_charge = True
@@ -94,7 +95,7 @@ def test_graded_grid_export_states_decode_to_rates():
def test_single_export_rate_keeps_all_or_nothing_layout():
"""Without configured rates the state space is the one from before grading."""
optimization = GeneticOptimization()
optimization = genetic_optimization()
optimization.bat_possible_charge_values = [1.0]
optimization.optimize_dc_charge = True
optimization.optimize_battery_grid_export = True
@@ -108,9 +109,8 @@ def test_single_export_rate_keeps_all_or_nothing_layout():
def test_battery_grid_export_factor_becomes_operation_factor(config_eos):
"""A partial export level is reported as the GRID_SUPPORT_EXPORT factor."""
config_eos.merge_settings_from_dict({"feedintariff": {"direct_marketing_enabled": True}})
solution = GeneticSolution
operation_mode, operation_mode_factor = solution._battery_operation_from_solution(
operation_mode, operation_mode_factor = geneticconvert._battery_operation_from_solution(
ac_charge=0.0,
dc_charge=0.0,
discharge_allowed=False,
@@ -124,7 +124,7 @@ def test_battery_grid_export_factor_becomes_operation_factor(config_eos):
def test_disjoint_cycle_masks_keep_feasible_non_deadline_order(config_eos):
from akkudoktoreos.core.coreabc import get_ems
from akkudoktoreos.optimization.genetic.geneticparams import (
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticOptimizationParameters,
)
from akkudoktoreos.utils.datetimeutil import to_datetime
@@ -174,7 +174,7 @@ def test_disjoint_cycle_masks_keep_feasible_non_deadline_order(config_eos):
],
}
)
optimizer = GeneticOptimization(fixed_seed=42)
optimizer = genetic_optimization(seed=42)
solution = optimizer.optimize_ems(params, ngen=1, individuals=6)
assert [(item.hour, item.minute) for item in solution.appliance_starts["washer"]] == [
(0, 0),
+66 -48
View File
@@ -1,52 +1,65 @@
"""Economic tail scenarios and hard control/forecast boundaries."""
from dataclasses import replace
from unittest.mock import patch
import numpy as np
import pandas as pd
import pytest
from conftest import genetic_optimization, genetic_run_parameters
from loguru import logger
from akkudoktoreos.config.config import SettingsEOSDefaults
from akkudoktoreos.core.coreabc import get_ems
from akkudoktoreos.devices.genetic.battery import Battery, SolarPanelBatteryParameters
from akkudoktoreos.devices.genetic.homeappliance import HomeApplianceParameters
from akkudoktoreos.devices.genetic.inverter import Inverter, InverterParameters
from akkudoktoreos.optimization.genetic.forecast import bounded_forecast_array
from akkudoktoreos.optimization.genetic.genetic import GeneticOptimization
from akkudoktoreos.optimization.genetic.geneticparams import (
from akkudoktoreos.optimization.genetic import geneticconvert
from akkudoktoreos.optimization.genetic.devices.geneticbattery import (
GeneticBattery,
)
from akkudoktoreos.optimization.genetic.devices.geneticinverter import (
GeneticInverter,
)
from akkudoktoreos.optimization.genetic.geneticalgorithm import (
GeneticOptimization,
)
from akkudoktoreos.optimization.genetic.geneticforecast import bounded_forecast_array
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticBatteryRequest,
GeneticHomeApplianceRequest,
GeneticInverterRequest,
GeneticOptimizationParameters,
)
from akkudoktoreos.optimization.genetic.tailvalue import build_tail_value_curve
from akkudoktoreos.optimization.genetic.terminalvalue import TerminalValueCurve
from akkudoktoreos.optimization.genetic.genetictailvalue import build_tail_value_curve
from akkudoktoreos.optimization.genetic.geneticterminalvalue import TerminalValueCurve
from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration
def devices(power=1000, efficiency=1.0, lcos=0, ac_limit=None, export_power=5000):
bat = Battery(
SolarPanelBatteryParameters(
device_id="battery1",
capacity_wh=1000,
max_charge_power_w=power,
charging_efficiency=efficiency,
discharging_efficiency=efficiency,
initial_soc_percentage=50,
levelized_cost_of_storage_kwh=lcos,
charge_rates=[0, 0.5, 1],
),
prediction_hours=1,
def device_requests(power=1000, efficiency=1.0, lcos=0, ac_limit=None, export_power=5000):
"""The battery and inverter requests of the tail tests."""
battery = GeneticBatteryRequest(
device_id="battery1",
capacity_wh=1000,
max_charge_power_w=power,
charging_efficiency=efficiency,
discharging_efficiency=efficiency,
initial_soc_percentage=50,
levelized_cost_of_storage_kwh=lcos,
charge_rates=[0, 0.5, 1],
)
inv = Inverter(
InverterParameters(
device_id="inverter1",
battery_id="battery1",
max_power_wh=export_power,
dc_to_ac_efficiency=1,
ac_to_dc_efficiency=1,
max_ac_charge_power_w=ac_limit,
),
battery=bat,
inverter = GeneticInverterRequest(
device_id="inverter1",
battery_id="battery1",
max_power_wh=export_power,
dc_to_ac_efficiency=1,
ac_to_dc_efficiency=1,
max_ac_charge_power_w=ac_limit,
)
return battery, inverter
def devices(**kwargs):
battery, inverter = device_requests(**kwargs)
bat = GeneticBattery(battery.to_parameters(), prediction_hours=1)
inv = GeneticInverter(inverter.to_parameters(), battery=bat)
return bat, inv
@@ -184,7 +197,7 @@ def setup_run(config, interval=3600, start_hour=0, hours=72, prediction_hours=72
)
ems = get_ems(init=True)
ems.set_start_datetime(to_datetime("2026-09-05T00:00:00").set(hour=start_hour))
bat, inv = devices()
bat, inv = device_requests()
params = GeneticOptimizationParameters.model_validate(
dict(
ems={
@@ -194,12 +207,12 @@ def setup_run(config, interval=3600, start_hour=0, hours=72, prediction_hours=72
"einspeiseverguetung_euro_pro_wh": [0.0001] * hours,
"preis_euro_pro_wh_akku": 0,
},
pv_battery=bat.parameters,
inverter=inv.parameters,
pv_battery=bat,
inverter=inv,
ev=None,
)
)
return GeneticOptimization(fixed_seed=42), params
return genetic_optimization(seed=42), params
@pytest.mark.parametrize("interval", [3600, 900])
@@ -219,7 +232,7 @@ async def test_genome_output_and_final_control_state(config_eos, interval, start
with (
patch.object(opt, "optimize", side_effect=choose),
patch(
"akkudoktoreos.optimization.genetic.genetic.build_tail_value_curve",
"akkudoktoreos.optimization.genetic.geneticalgorithm.build_tail_value_curve",
wraps=build_tail_value_curve,
) as builder,
):
@@ -229,7 +242,7 @@ async def test_genome_output_and_final_control_state(config_eos, interval, start
assert len(result.dc_charge) == opt.control_slots
assert len(result.discharge_allowed) == opt.control_slots
assert len(result.battery_grid_export_factor) == opt.control_slots
assert len(result.result.Kosten_Euro_pro_Stunde) == opt.control_slots
assert len(result.result.costs_per_hour) == opt.control_slots
assert result.terminal_value.mode == "TAIL"
assert result.terminal_value.battery_energy_wh == pytest.approx(
max(500 - 1000 * opt.slot_duration_h, 0)
@@ -246,7 +259,7 @@ async def test_genome_output_and_final_control_state(config_eos, interval, start
assert result.terminal_value.tail_plan[0].hour_from_start == 24
assert len(result.terminal_value.curve.operating_value_euro) == 101
assert len(result.terminal_value.curve.continuation_value_euro) == 101
assert len((await result.optimization_solution()).solution.to_dataframe()) == opt.control_slots
assert len((await geneticconvert.optimization_solution(genetic_run_parameters(result.request), result)).solution.to_dataframe()) == opt.control_slots
def test_short_tail_is_reported(config_eos, caplog):
@@ -289,13 +302,16 @@ async def test_provider_values_are_not_extrapolated():
def test_future_opportunity_changes_optimal_control_soc(config_eos):
final_energy = []
for negative_price in (0.5, -1.0):
opt, params = setup_run(config_eos, hours=3)
_, params = setup_run(config_eos, hours=3)
config_eos.merge_settings_from_dict(
{"optimization": {"genetic": {"horizon_hours": 1, "tail_horizon_hours": 2}}}
)
# The run settings are taken when the algorithm is created.
opt = genetic_optimization(seed=42)
params.ems.electricity_price_per_wh = [0.0005, negative_price / 1000, 0.0003]
params.ems.feed_in_tariff_per_wh = [0.00002, 0, 0.0003]
result = opt.optimize_ems(params, ngen=3, individuals=20)
assert result.terminal_value is not None
final_energy.append(result.terminal_value.battery_energy_wh)
assert final_energy[0] > final_energy[1]
@@ -334,10 +350,12 @@ def test_missing_price_inside_tail_stops_at_first_gap(config_eos):
def test_ev_genome_and_output_are_control_only(config_eos):
from akkudoktoreos.devices.genetic.battery import ElectricVehicleParameters
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticElectricVehicleRequest,
)
opt, params = setup_run(config_eos, interval=900, start_hour=10, hours=82)
params.ev = ElectricVehicleParameters(
params.ev = GeneticElectricVehicleRequest(
device_id="ev1",
capacity_wh=5000,
initial_soc_percentage=0,
@@ -367,7 +385,7 @@ def test_rejected_config_update_is_atomic(config_eos):
def test_disabled_ac_conversion_cannot_earn_negative_price_revenue():
bat, inv = devices()
inv.parameters.ac_to_dc_efficiency = 0
inv = GeneticInverter(replace(inv.parameters, ac_to_dc_efficiency=0), battery=bat)
c = build_tail_value_curve(
battery=bat,
inverter=inv,
@@ -455,7 +473,7 @@ def test_daily_appliance_load_values_stored_energy_in_tail(config_eos):
params.ems.feed_in_tariff_per_wh = [0.0] * 72
if with_appliance:
params.home_appliances = [
HomeApplianceParameters.model_validate(
GeneticHomeApplianceRequest.model_validate(
dict(
device_id="water_heater",
consumption_wh=6000,
@@ -519,7 +537,7 @@ def test_daily_appliance_day_planned_in_control_is_not_counted_again_in_tail(
"""
opt, params = setup_run(config_eos, start_hour=start_hour, hours=72 + start_hour)
params.home_appliances = [
HomeApplianceParameters.model_validate(
GeneticHomeApplianceRequest.model_validate(
dict(
device_id="water_heater",
consumption_wh=3000,
@@ -543,7 +561,7 @@ def test_daily_appliance_day_planned_in_control_is_not_counted_again_in_tail(
with (
patch.object(opt, "optimize", side_effect=choose),
patch(
"akkudoktoreos.optimization.genetic.genetic.build_tail_value_curve",
"akkudoktoreos.optimization.genetic.geneticalgorithm.build_tail_value_curve",
wraps=build_tail_value_curve,
) as builder,
):
@@ -582,7 +600,7 @@ def test_daily_appliance_run_in_progress_counts_for_its_day_in_estimate(config_e
)
if running:
appliance["run_started_datetime"] = to_datetime("2026-09-05T01:30:00")
params.home_appliances = [HomeApplianceParameters.model_validate(appliance)]
params.home_appliances = [GeneticHomeApplianceRequest.model_validate(appliance)]
def choose(*args, **kwargs):
genome = opt.create_individual()
@@ -610,7 +628,7 @@ def test_daily_appliance_deadline_does_not_cap_tail(config_eos, policy):
"""
opt, params = setup_run(config_eos, start_hour=22, hours=72 + 22)
params.home_appliances = [
HomeApplianceParameters.model_validate(
GeneticHomeApplianceRequest.model_validate(
dict(
device_id="water_heater",
consumption_wh=3000,
@@ -637,7 +655,7 @@ def test_daily_appliance_deadline_does_not_cap_tail(config_eos, policy):
with (
patch.object(opt, "optimize", side_effect=choose),
patch(
"akkudoktoreos.optimization.genetic.genetic.build_tail_value_curve",
"akkudoktoreos.optimization.genetic.geneticalgorithm.build_tail_value_curve",
wraps=build_tail_value_curve,
) as builder,
):
+24 -19
View File
@@ -4,10 +4,15 @@ from unittest.mock import patch
import numpy as np
import pytest
from conftest import genetic_optimization, genetic_run_parameters
from akkudoktoreos.core.coreabc import get_ems
from akkudoktoreos.optimization.genetic.genetic import GeneticOptimization
from akkudoktoreos.optimization.genetic.geneticparams import (
from akkudoktoreos.core.emplan import FRBCInstruction
from akkudoktoreos.optimization.genetic import geneticconvert
from akkudoktoreos.optimization.genetic.geneticalgorithm import (
GeneticOptimization,
)
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticOptimizationParameters,
)
from akkudoktoreos.utils.datetimeutil import to_datetime
@@ -60,24 +65,22 @@ async def test_native_result_retains_dst_grid_and_owned_inputs(config_eos, times
"ev": None,
}
)
optimizer = GeneticOptimization(fixed_seed=42)
optimizer = genetic_optimization(seed=42)
native = optimizer.optimize_ems(parameters, ngen=1, individuals=6)
repeat = GeneticOptimization(fixed_seed=42).optimize_ems(parameters, ngen=1, individuals=6)
repeat = genetic_optimization(seed=42).optimize_ems(parameters, ngen=1, individuals=6)
assert native.start_solution == repeat.start_solution
assert native.interval_seconds == 900
assert native.start_solution_datetime == start
assert native.controls_start_at_now
assert len(native.result.load_wh_per_hour) == 4
assert native.parameters.ems.total_load == [25.0] * 4
assert native.request.ems.total_load == [25.0] * 4
parameters.ems.total_load[elapsed_slots] = 999.0
get_ems().set_start_datetime(start.add(days=1))
config_eos.optimization.genetic.interval_sec = 3600
with patch(
"akkudoktoreos.optimization.genetic.geneticsolution.get_prediction",
side_effect=AssertionError("Native serialization must not reread providers"),
):
generic = await native.optimization_solution()
plan = native.energy_management_plan()
# The conversion reads no prediction store: it converts from parameters and result only.
run_parameters = genetic_run_parameters(native.request, optimizer)
generic = await geneticconvert.optimization_solution(run_parameters, native)
plan = geneticconvert.energy_management_plan(run_parameters, native)
assert generic.valid_from == start
assert generic.valid_until == start.add(hours=1)
assert plan.valid_from == start
@@ -119,7 +122,7 @@ def test_native_quarter_hour_temperatures_average_when_coarsened(config_eos):
"inverter": None,
}
)
normalized = GeneticOptimization()._parameters_for_slot_grid(parameters)
normalized = genetic_optimization()._parameters_for_slot_grid(parameters)
assert normalized.temperature_forecast == [13.0]
assert normalized.ems.pv_forecast_wh == [100.0]
assert normalized.ems.total_load == [200.0]
@@ -134,10 +137,10 @@ def test_snapshot_and_warm_start_preserve_aware_instants(
import json
from pathlib import Path
from akkudoktoreos.optimization.genetic.configrequest import (
ConfigOptimizationRequest,
from akkudoktoreos.optimization.genetic.geneticapi import GeneticSolution
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticRequest,
)
from akkudoktoreos.optimization.genetic.geneticsolution import GeneticSolution
set_other_timezone(host_timezone)
expected = to_datetime(f"2026-10-25T02:30:00{offset}", in_timezone="Europe/Berlin")
@@ -150,7 +153,7 @@ def test_snapshot_and_warm_start_preserve_aware_instants(
parameters = GeneticOptimizationParameters.model_validate(
native.parameters.model_dump() | {"start_solution_datetime": supplied}
)
request = ConfigOptimizationRequest.model_validate({"start_solution_datetime": supplied})
request = GeneticRequest.model_validate({"start_solution_datetime": supplied})
for model in (native, parameters, request):
value = model.start_solution_datetime
assert value is not None
@@ -218,7 +221,7 @@ def _partial_first_slot_run(config_eos, timestamp: str, initial_soc_percentage:
"ev": None,
}
)
optimizer = GeneticOptimization(fixed_seed=42)
optimizer = genetic_optimization(seed=42)
def full_ac_charge_in_first_slot(*args, **kwargs):
genome = optimizer.create_individual()
@@ -274,8 +277,10 @@ def test_running_slot_ac_charge_factor_is_not_cut_for_a_full_slot(config_eos):
config_eos, "2026-09-16T10:45:00+02:00", initial_soc_percentage=90
)
assert solution.result.battery_soc_per_hour[:2] == pytest.approx([90.0, 95.0])
plan = solution.energy_management_plan()
plan = geneticconvert.energy_management_plan(genetic_run_parameters(solution.request), solution)
battery_instructions = [
instruction for instruction in plan.instructions if instruction.resource_id == "battery1"
instruction
for instruction in plan.instructions
if isinstance(instruction, FRBCInstruction) and instruction.resource_id == "battery1"
]
assert battery_instructions[0].operation_mode_factor == pytest.approx(1.0)
+12 -9
View File
@@ -5,16 +5,20 @@ price horizon moves on during the night) may update the configuration while a
run is in progress. Genomes and device arrays are sized when the run starts, so
a mid-run change of horizon, tail or prediction hours must not reach the final
evaluation - before the snapshot it failed with
``IndexError: index 84 is out of bounds for axis 0 with size 84``.
``IndexError: index 84 is out of bounds for axis 0 with size 84``. The run reads
its settings from the optimization parameters, prepared before it starts.
"""
import pytest
from conftest import genetic_optimization
from akkudoktoreos.config.config import ConfigEOS
from akkudoktoreos.core.cache import CacheEnergyManagementStore
from akkudoktoreos.core.coreabc import get_ems
from akkudoktoreos.optimization.genetic.genetic import GeneticOptimization
from akkudoktoreos.optimization.genetic.geneticparams import (
from akkudoktoreos.optimization.genetic.geneticalgorithm import (
GeneticOptimization,
)
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticOptimizationParameters,
)
from akkudoktoreos.utils.datetimeutil import to_datetime
@@ -79,7 +83,7 @@ def test_horizon_change_during_run_does_not_reach_the_run(
config_eos: ConfigEOS, start_horizon: int, changed_horizon: int
):
parameters = _setup(config_eos, start_horizon)
optimization = GeneticOptimization(fixed_seed=42)
optimization = genetic_optimization(seed=42)
original_optimize = optimization.optimize
@@ -99,12 +103,12 @@ def test_horizon_change_during_run_does_not_reach_the_run(
assert len(solution.battery_grid_export_factor) == start_horizon
# ... and the new value is live for the next run.
assert config_eos.optimization.genetic.horizon_hours == changed_horizon
assert optimization._run_genetic_cfg is None
assert optimization.settings.horizon_hours == start_horizon
def test_snapshot_is_released_when_the_run_fails(config_eos: ConfigEOS):
def test_run_state_is_released_when_the_run_fails(config_eos: ConfigEOS):
parameters = _setup(config_eos, 24)
optimization = GeneticOptimization(fixed_seed=42)
optimization = genetic_optimization(seed=42)
def failing_optimize(*args, **kwargs):
raise RuntimeError("boom")
@@ -112,5 +116,4 @@ def test_snapshot_is_released_when_the_run_fails(config_eos: ConfigEOS):
optimization.optimize = failing_optimize # type: ignore[method-assign]
with pytest.raises(RuntimeError):
optimization.optimize_ems(parameters=parameters, start_hour=0, ngen=1)
assert optimization._run_genetic_cfg is None
assert optimization._run_prediction_hours is None
assert optimization._run_control_end_slot is None
+433 -75
View File
@@ -1,7 +1,7 @@
"""Configuration-owned requests and the real automatic GENETIC path."""
from types import SimpleNamespace
from typing import Any, Optional
from typing import Any, Optional, cast
from unittest.mock import AsyncMock, Mock, patch
import httpx
@@ -16,8 +16,12 @@ from akkudoktoreos.config.configmigrate import migrate_config_data
from akkudoktoreos.core.coreabc import get_measurement
from akkudoktoreos.core.ems import EnergyManagement, EnergyManagementStage
from akkudoktoreos.core.emsettings import EnergyManagementMode
from akkudoktoreos.optimization.genetic import configrequest
from akkudoktoreos.optimization.genetic.configrequest import ConfigOptimizationRequest
from akkudoktoreos.optimization.genetic import geneticprepare
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticHomeApplianceRequest,
GeneticOptimizationParameters,
GeneticRequest,
)
from akkudoktoreos.optimization.optimization import (
OptimizationAlgorithm,
OptimizationCommonSettings,
@@ -25,6 +29,16 @@ from akkudoktoreos.optimization.optimization import (
from akkudoktoreos.prediction.pvforecastforecastsolar import PVForecastForecastSolar
from akkudoktoreos.utils.datetimeutil import to_datetime
# Run start and observation time of the run the tests prepare; the fixture sets them.
RUN = SimpleNamespace(ems=None)
async def resolve(request: GeneticRequest, warm_start: Any = None) -> GeneticOptimizationParameters:
"""Prepare ``request`` at the run start and observation time of ``RUN.ems``."""
return await geneticprepare.resolve_request(
request, RUN.ems.start_datetime, RUN.ems.observation_datetime, warm_start
)
@pytest_asyncio.fixture
async def isolated_measurement(config_eos):
@@ -79,12 +93,10 @@ def configured_request(config_eos, monkeypatch):
}
)
start = to_datetime("2026-09-12T10:15:00Z", in_timezone="UTC")
ems = SimpleNamespace(
start_datetime=start, observation_datetime=start, genetic_solution=lambda: None
)
monkeypatch.setattr(configrequest, "get_ems", lambda: ems)
ems = SimpleNamespace(start_datetime=start, observation_datetime=start)
monkeypatch.setattr(RUN, "ems", ems)
measurement = Mock(key_to_lists=AsyncMock(return_value=([], [])))
monkeypatch.setattr(ConfigOptimizationRequest, "measurement", measurement)
monkeypatch.setattr(geneticprepare, "get_measurement", Mock(return_value=measurement))
data = {
"soc": {"storage": 42},
"forecasts": {
@@ -155,14 +167,14 @@ async def test_forecastsolar_resolves_without_runtime_override(
await pv._update_data(force_update=True)
prediction = SimpleNamespace(update_data=AsyncMock(side_effect=update), key_to_raw_series=read)
monkeypatch.setattr(ConfigOptimizationRequest, "prediction", prediction)
monkeypatch.setattr(geneticprepare, "get_prediction", Mock(return_value=prediction))
response = Mock()
response.json.return_value = {
"result": {"watts": watts},
"message": {"info": {"timezone": "Europe/Berlin"}},
}
with patch("requests.get", return_value=response):
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
parameters = await resolve(GeneticRequest.model_validate(data))
prediction.update_data.assert_awaited_once()
energy = parameters.ems.pv_forecast_wh
assert energy[10 * 3600 // interval] == pytest.approx(1000 * interval / 3600)
@@ -171,11 +183,110 @@ async def test_forecastsolar_resolves_without_runtime_override(
await pv.delete_by_datetime()
@pytest.mark.asyncio
async def test_echoed_warm_start_gets_the_start_of_the_last_solution(configured_request):
"""A client that only echoes the genome of this server's last solution keeps its start.
The run gets the start of the last solution; the request is echoed as the client sent it.
"""
_, ems, _, data = configured_request
last_start = ems.start_datetime.subtract(minutes=15)
warm_start = SimpleNamespace(start_solution=[19.0, 32.0, 14.0], start_solution_datetime=last_start)
explicit_start = ems.start_datetime.subtract(minutes=30)
async def resolved_start(**fields: Any) -> tuple[Any, Any]:
"""The start of the run's start solution, and the one echoed in its request."""
request = GeneticRequest.model_validate({**data, **fields})
parameters = await geneticprepare.prepare_from_request(
request, RUN.ems.start_datetime, RUN.ems.observation_datetime, cast(Any, warm_start)
)
return parameters.start_solution_datetime, parameters.request.start_solution_datetime
assert await resolved_start(start_solution=[19, 32, 14]) == (last_start, None)
assert await resolved_start(start_solution=[19, 32, 15]) == (None, None)
assert await resolved_start(
start_solution=[19, 32, 14], start_solution_datetime=explicit_start
) == (explicit_start, explicit_start)
# Without a genome of its own the run starts from the last solution, as the echo shows.
assert await resolved_start() == (last_start, last_start)
class TestSchedulableAppliances:
"""Preparation keeps only what the run can schedule of each home appliance."""
@pytest.mark.asyncio
@pytest.mark.parametrize(
"fields, cycles",
[
({}, 1), # fits
({"deadline_datetime": "2026-09-12T09:00:00Z", "deadline_policy": "BEST_EFFORT"}, 1),
({"deadline_datetime": "2026-09-12T09:00:00Z", "deadline_policy": "STRICT"}, None),
({"shared_time_windows": {"windows": [{"start_time": "12:00", "end_time": "12:30"}]}}, None),
(
{
"duration_h": 2,
"num_cycles": 3,
"shared_time_windows": {"windows": [{"start_time": "11:00", "end_time": "15:30"}]},
},
2,
),
(
{
"duration_h": 5,
"schedule_mode": "DAILY",
"shared_time_windows": {"windows": [{"start_time": "11:00", "end_time": "14:00"}]},
},
None,
),
],
ids=[
"fits",
"best-effort-late",
"strict-late",
"window-too-short",
"too-many-cycles",
"daily-window-too-short",
],
)
async def test_appliance_is_capped_or_left_out(
self, configured_request, monkeypatch, caplog, fields, cycles
):
"""STRICT past its deadline, a window shorter than a run or too many cycles: no 503."""
config, ems, _, data = configured_request
config.merge_settings_from_dict({"general": {"timezone_override": "UTC"}})
monkeypatch.setattr(config.optimization.genetic, "horizon_hours", 6) # 10:15 to 16:15
resolved = await resolve(GeneticRequest.model_validate(data))
appliance = GeneticHomeApplianceRequest(
**{
"device_id": "dishwasher",
"consumption_wh": 1000,
"duration_h": 1,
"num_cycles": 1,
**fields,
}
)
request = resolved.model_copy(update={"home_appliances": [appliance]})
parameters = geneticprepare._complete(
request, ems.start_datetime, ems.observation_datetime, None, None
)
appliances = parameters.request.resolved_home_appliances()
if cycles is None:
assert appliances == []
assert "Home appliance 'dishwasher' cannot be scheduled" in caplog.text
elif cycles == appliance.num_cycles:
assert parameters.request is request
else:
assert [a.num_cycles for a in appliances] == [cycles]
assert "fits 2 of its 3 cycles" in caplog.text
@pytest.mark.asyncio
async def test_hardware_costs_and_state_are_resolved_without_config_changes(configured_request):
config, _, _, data = configured_request
before = config.model_dump_json()
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
parameters = await resolve(GeneticRequest.model_validate(data))
assert parameters.pv_battery is not None
assert parameters.pv_battery.device_id == "storage"
assert parameters.pv_battery.capacity_wh == 2000
@@ -189,7 +300,7 @@ async def test_hardware_costs_and_state_are_resolved_without_config_changes(conf
@pytest.mark.parametrize("field", ["devices", "optimization", "pv_battery", "inverter", "ems"])
def test_static_http_overrides_are_rejected(field):
with pytest.raises(ValidationError):
ConfigOptimizationRequest.model_validate({field: {}})
GeneticRequest.model_validate({field: {}})
@pytest.mark.parametrize("host_timezone", ["UTC", "Europe/Berlin"])
@@ -198,11 +309,11 @@ def test_warmstart_timestamp_retains_explicit_zone_and_json_instant(
):
set_other_timezone(host_timezone)
previous = to_datetime("2026-10-25T02:30:00+01:00", in_timezone="Europe/Berlin")
request = ConfigOptimizationRequest(start_solution_datetime=previous)
request = GeneticRequest(start_solution_datetime=previous)
assert request.start_solution_datetime is not None
assert request.start_solution_datetime.timezone_name == "Europe/Berlin"
assert request.start_solution_datetime.timestamp() == previous.timestamp()
restored = ConfigOptimizationRequest.model_validate_json(request.model_dump_json())
restored = GeneticRequest.model_validate_json(request.model_dump_json())
assert restored.start_solution_datetime is not None
assert restored.start_solution_datetime.timestamp() == previous.timestamp()
assert restored.start_solution_datetime.utcoffset() == previous.utcoffset()
@@ -222,7 +333,7 @@ async def test_stale_future_or_invalid_soc_defaults_to_zero(
[ems.observation_datetime.subtract(seconds=age)],
[value],
)
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
parameters = await resolve(GeneticRequest.model_validate(data))
assert parameters.pv_battery is not None
assert parameters.pv_battery.initial_soc_percentage == 0
@@ -236,7 +347,7 @@ async def test_soc_freshness_uses_actual_run_time_inside_quarter_hour(configured
[ems.observation_datetime.subtract(seconds=30)],
[0.456],
)
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
parameters = await resolve(GeneticRequest.model_validate(data))
assert parameters.pv_battery is not None
assert parameters.pv_battery.initial_soc_percentage == 45
assert measurement.key_to_lists.call_args.kwargs[
@@ -253,22 +364,29 @@ async def test_future_soc_in_repeated_hour_defaults_to_zero(configured_request):
[to_datetime("2026-10-25T02:15:00+01:00", in_timezone="Europe/Berlin")],
[0.8],
)
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
parameters = await resolve(GeneticRequest.model_validate(data))
assert parameters.pv_battery is not None
assert parameters.pv_battery.initial_soc_percentage == 0
@pytest.mark.asyncio
async def test_unknown_soc_and_mismatched_device_link_are_rejected(configured_request):
async def test_unknown_soc_and_mismatched_device_link_fall_back(configured_request, caplog):
"""An unknown SoC is ignored; a battery its inverter does not reach is left out."""
config, _, _, data = configured_request
request = ConfigOptimizationRequest.model_validate(data)
request = GeneticRequest.model_validate(data)
request.soc["unknown"] = 20
with pytest.raises(ValueError, match="unconfigured"):
await request.resolve()
parameters = await resolve(request)
assert parameters.pv_battery is not None
assert parameters.pv_battery.initial_soc_percentage == 42
assert "SoC 20% supplied for unconfigured device 'unknown', ignored" in caplog.text
assert config.devices.inverters is not None
config.devices.inverters["inverter"].battery_id = "missing"
with pytest.raises(ValueError, match="battery_id"):
await ConfigOptimizationRequest.model_validate(data).resolve()
parameters = await resolve(GeneticRequest.model_validate(data))
assert parameters.pv_battery is None
assert parameters.inverter is not None
assert "Battery 'storage' is not connected to the inverter (battery_id missing)" in caplog.text
# The configuration is never changed.
assert config.devices.inverters["inverter"].battery_id == "missing"
@pytest.mark.asyncio
@@ -278,21 +396,28 @@ async def test_direct_marketing_keeps_explicit_imported_sale_prices(configured_r
config.feedintariff.direct_marketing_enabled = True
config.feedintariff.provider = "FeedInTariffImport"
data["forecasts"]["feed_in_tariff_per_wh"] = [tariff] * 96
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
parameters = await resolve(GeneticRequest.model_validate(data))
assert parameters.ems.feed_in_tariff_per_wh == [tariff] * 96
@pytest.mark.asyncio
async def test_control_gaps_fail_but_shorter_tail_is_accepted(configured_request):
async def test_control_gaps_are_filled_and_shorter_tail_is_accepted(configured_request, caplog):
_, _, _, data = configured_request
data["forecasts"]["electricity_price_per_wh"] = [0.0003] * 50
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
parameters = await resolve(GeneticRequest.model_validate(data))
assert len(parameters.ems.total_load) == 50
data["forecasts"]["electricity_price_per_wh"][41] = 0.0004
data["forecasts"]["electricity_price_per_wh"][42] = np.nan
with pytest.raises(ValueError, match="control horizon") as error:
await ConfigOptimizationRequest.model_validate(data).resolve()
assert "2026-09-12T10:30:00+00:00, 2026-09-12T10:45:00+00:00" in str(error.value)
assert "1 invalid interval(s)" in str(error.value)
data["forecasts"]["electricity_price_per_wh"][48] = np.inf # after the control horizon
parameters = await resolve(GeneticRequest.model_validate(data))
# The last known price is carried forward.
assert parameters.ems.electricity_price_per_wh[42] == 0.0004
# After the control horizon an infinite value is a gap, as NaN is: it shortens the tail.
assert np.isnan(parameters.ems.electricity_price_per_wh[48])
assert (
"electricity price missing or invalid in 1 slot(s) of the control horizon, first at "
"2026-09-12T10:30:00+00:00 (nan), replaced by 0.0004" in caplog.text
)
@pytest.mark.asyncio
@@ -314,8 +439,8 @@ async def test_provider_power_is_integrated_once_and_update_is_awaited(
)
prediction = Mock(update_data=AsyncMock(), key_to_raw_series=AsyncMock(side_effect=read))
monkeypatch.setattr(ConfigOptimizationRequest, "prediction", prediction)
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
monkeypatch.setattr(geneticprepare, "get_prediction", Mock(return_value=prediction))
parameters = await resolve(GeneticRequest.model_validate(data))
assert parameters.ems.pv_forecast_wh == [250.0] * len(parameters.ems.pv_forecast_wh)
assert parameters.ems.total_load == [500.0] * len(parameters.ems.total_load)
assert parameters.ems.feed_in_tariff_per_wh == [-0.00005] * len(parameters.ems.total_load)
@@ -376,7 +501,7 @@ def test_http_empty_body_is_configuration_request_and_failure_cannot_return_cach
client = TestClient(eos.app)
response = client.post("/v1/optimize")
assert response.status_code == 503
assert isinstance(run.call_args.kwargs["genetic_parameters"], ConfigOptimizationRequest)
assert isinstance(run.call_args.kwargs["request"], GeneticRequest)
assert run.call_args.kwargs["algorithm"] == OptimizationAlgorithm.GENETIC
response = client.post("/v1/optimize", json={"devices": {}})
assert response.status_code == 422
@@ -391,7 +516,9 @@ def test_http_configuration_request_rejects_query_overrides(monkeypatch, query):
monkeypatch.setattr(eos, "get_ems", lambda: SimpleNamespace(run=run))
response = TestClient(eos.app).post(f"/v1/optimize?{query}", json={})
assert response.status_code == 422
assert "query overrides are not supported" in response.text
assert response.headers["content-type"] == "application/problem+json"
assert response.json()["title"] == "HTTP Error"
assert "query overrides are not supported" in response.json()["detail"]
run.assert_not_awaited()
@@ -402,26 +529,24 @@ async def test_real_ems_returns_coherent_quarter_hour_solution_and_plan(
):
_, fake, _, data = configured_request
ems = EnergyManagement()
monkeypatch.setattr(configrequest, "get_ems", lambda: ems)
monkeypatch.setattr(EnergyManagement, "prediction", Mock(update_data=AsyncMock()))
monkeypatch.setattr(EnergyManagement, "adapter", Mock(update_data=AsyncMock()))
request = ConfigOptimizationRequest.model_validate(data)
request = GeneticRequest.model_validate(data)
if automatic:
original = ConfigOptimizationRequest.resolve
original = geneticprepare.resolve_request
async def resolve_default(self):
return await original(request)
async def resolve_default(_default: GeneticRequest, *args: Any) -> Any:
return await original(request, *args)
monkeypatch.setattr(ConfigOptimizationRequest, "resolve", resolve_default)
monkeypatch.setattr(geneticprepare, "resolve_request", resolve_default)
solution = await ems.run(
start_datetime=fake.start_datetime.add(minutes=2),
mode=EnergyManagementMode.OPTIMIZATION,
genetic_parameters=None if automatic else request,
genetic_generations=10,
genetic_seed=42,
request=None if automatic else request,
overrides={"generations": 10, "seed": 42},
)
assert solution is not None
assert solution is ems.genetic_solution()
assert solution is ems.optimizer_result("GENETIC")
assert solution is not None # run() returns Any; `is` narrowed to Optional
assert solution.start_solution_datetime == fake.start_datetime
assert len(solution.ac_charge) == 4
@@ -436,8 +561,7 @@ async def test_automatic_run_reads_real_resolver_provider_units_and_measured_soc
):
_, fake, measurement, _ = configured_request
ems = EnergyManagement()
monkeypatch.setattr(configrequest, "get_ems", lambda: ems)
monkeypatch.setattr(EnergyManagement, "_genetic_solution", None)
monkeypatch.setattr(EnergyManagement, "_optimizer_runs", {})
measurement.key_to_lists.return_value = ([fake.start_datetime], [0.42])
values = {
"pvforecast_ac_power": 1000.0,
@@ -453,20 +577,19 @@ async def test_automatic_run_reads_real_resolver_provider_units_and_measured_soc
prediction = Mock(update_data=AsyncMock(), key_to_raw_series=AsyncMock(side_effect=read))
monkeypatch.setattr(EnergyManagement, "prediction", prediction)
monkeypatch.setattr(ConfigOptimizationRequest, "prediction", prediction)
monkeypatch.setattr(geneticprepare, "get_prediction", Mock(return_value=prediction))
monkeypatch.setattr(EnergyManagement, "adapter", Mock(update_data=AsyncMock()))
solution = await ems.run(
start_datetime=fake.start_datetime,
mode=EnergyManagementMode.OPTIMIZATION,
genetic_generations=10,
genetic_seed=42,
overrides={"generations": 10, "seed": 42},
)
assert solution is not None
assert solution.parameters is not None
assert solution.parameters.pv_battery is not None
assert solution.parameters.pv_battery.initial_soc_percentage == 42
assert solution.parameters.ems.pv_forecast_wh[:4] == [250.0] * 4
assert solution.parameters.ems.total_load[:4] == [500.0] * 4
assert solution.request is not None
assert solution.request.pv_battery is not None
assert solution.request.pv_battery.initial_soc_percentage == 42
assert solution.request.ems.pv_forecast_wh[:4] == [250.0] * 4
assert solution.request.ems.total_load[:4] == [500.0] * 4
assert len(solution.ac_charge) == 4
prediction.key_to_raw_series.assert_awaited()
@@ -482,8 +605,7 @@ async def test_http_real_genetic_result_serializes_native_quarter_hour_contract(
if missing_soc:
data["soc"] = {}
ems = EnergyManagement()
monkeypatch.setattr(configrequest, "get_ems", lambda: ems)
monkeypatch.setattr(EnergyManagement, "_genetic_solution", None)
monkeypatch.setattr(EnergyManagement, "_optimizer_runs", {})
monkeypatch.setattr(EnergyManagement, "prediction", Mock(update_data=AsyncMock()))
monkeypatch.setattr(EnergyManagement, "adapter", Mock(update_data=AsyncMock()))
@@ -516,7 +638,7 @@ async def test_missing_soc_defaults_to_zero_without_mutating_inputs(
before = config.model_dump_json()
if missing_key:
measurement.key_to_lists.side_effect = KeyError("SoC channel unavailable")
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
parameters = await resolve(GeneticRequest.model_validate(data))
assert parameters.pv_battery is not None
assert parameters.pv_battery.initial_soc_percentage == 0
assert config.model_dump_json() == before
@@ -530,7 +652,7 @@ async def test_missing_soc_defaults_to_zero_without_mutating_inputs(
async def test_explicit_soc_overrides_measurements(configured_request, soc):
_, _, measurement, data = configured_request
data["soc"] = {"storage": soc}
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
parameters = await resolve(GeneticRequest.model_validate(data))
assert parameters.pv_battery is not None
assert parameters.pv_battery.initial_soc_percentage == soc
measurement.key_to_lists.assert_not_awaited()
@@ -543,7 +665,7 @@ async def test_missing_ev_soc_does_not_replace_explicit_battery_soc(configured_r
{"devices": {"max_electric_vehicles": 1,
"electric_vehicles": {"car": {"profile_adjustment": {"nominal_capacity_wh": 60000}}}}}
)
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
parameters = await resolve(GeneticRequest.model_validate(data))
assert parameters.pv_battery is not None
assert parameters.ev is not None
assert parameters.pv_battery.initial_soc_percentage == 42
@@ -563,8 +685,7 @@ async def test_http_config_and_real_optimizer_allow_full_ev_target(configured_re
"max_soc_percentage": 100}}}})
data["soc"]["ev"] = soc
ems = EnergyManagement()
monkeypatch.setattr(configrequest, "get_ems", lambda: ems)
monkeypatch.setattr(EnergyManagement, "_genetic_solution", None)
monkeypatch.setattr(EnergyManagement, "_optimizer_runs", {})
monkeypatch.setattr(EnergyManagement, "prediction", Mock(update_data=AsyncMock()))
monkeypatch.setattr(EnergyManagement, "adapter", Mock(update_data=AsyncMock()))
@@ -604,7 +725,7 @@ async def test_explicit_ev_soc_has_no_measurement_age_limit(configured_request,
measurement.key_to_lists.return_value = ([old_sample], [0.35])
data["soc"]["car"] = 70
config_before = config.model_dump_json()
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
parameters = await resolve(GeneticRequest.model_validate(data))
assert parameters.ev is not None
assert parameters.ev.initial_soc_percentage == 70
assert parameters.ev.min_soc_percentage == 100
@@ -635,18 +756,18 @@ async def test_home_assistant_soc_read_mid_slot_is_fresh_for_resolver(
monkeypatch.setattr(EnergyManagement, "_observation_datetime", None)
monkeypatch.setattr(EnergyManagement, "_stage", EnergyManagementStage.DATA_ACQUISITION)
ems = EnergyManagement()
monkeypatch.setattr(configrequest, "get_ems", lambda: ems)
monkeypatch.setattr(RUN, "ems", ems)
# Run 11 minutes into the 10:15 slot: older than measurement_max_age_seconds (300 s)
# if the reading were stamped with the slot start.
run_time = to_datetime("2026-09-12T10:26:00Z", in_timezone="UTC")
ems.set_start_datetime(run_time, interval_seconds=900)
assert ems.start_datetime == run_time.subtract(minutes=11)
monkeypatch.setattr(ConfigOptimizationRequest, "measurement", isolated_measurement)
monkeypatch.setattr(geneticprepare, "get_measurement", Mock(return_value=isolated_measurement))
monkeypatch.setattr(HomeAssistantAdapter, "get_entity_state", lambda self, entity_id: "0.42")
await HomeAssistantAdapter()._update_data()
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
parameters = await resolve(GeneticRequest.model_validate(data))
assert parameters.pv_battery is not None
assert parameters.pv_battery.initial_soc_percentage == 42
@@ -667,20 +788,20 @@ async def test_meter_only_adapter_reading_does_not_mask_api_soc(
monkeypatch.setattr(EnergyManagement, "_observation_datetime", None)
monkeypatch.setattr(EnergyManagement, "_stage", EnergyManagementStage.DATA_ACQUISITION)
ems = EnergyManagement()
monkeypatch.setattr(configrequest, "get_ems", lambda: ems)
monkeypatch.setattr(RUN, "ems", ems)
# Run one minute into the 10:15 slot: the adapter's meter reading (slot start)
# is newer than the SoC supplied four minutes earlier, still within 300 s.
run_time = to_datetime("2026-09-12T10:16:00Z", in_timezone="UTC")
ems.set_start_datetime(run_time, interval_seconds=900)
measurement = isolated_measurement
monkeypatch.setattr(ConfigOptimizationRequest, "measurement", measurement)
monkeypatch.setattr(geneticprepare, "get_measurement", Mock(return_value=measurement))
# SoC arrives through the measurement API, the meter through Home Assistant.
await measurement.update_value(run_time.subtract(minutes=4), "storage-soc-factor", 0.42)
monkeypatch.setattr(HomeAssistantAdapter, "get_entity_state", lambda self, entity_id: "1234.5")
await HomeAssistantAdapter()._update_data()
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
parameters = await resolve(GeneticRequest.model_validate(data))
assert parameters.pv_battery is not None
assert parameters.pv_battery.initial_soc_percentage == 42
@@ -727,14 +848,14 @@ async def test_missing_newest_soc_value_falls_back_to_older_fresh_sample(
monkeypatch.setattr(EnergyManagement, "_start_datetime", None)
monkeypatch.setattr(EnergyManagement, "_observation_datetime", None)
ems = EnergyManagement()
monkeypatch.setattr(configrequest, "get_ems", lambda: ems)
monkeypatch.setattr(RUN, "ems", ems)
run_time = to_datetime("2026-09-12T10:26:00Z", in_timezone="UTC")
ems.set_start_datetime(run_time, interval_seconds=900)
monkeypatch.setattr(ConfigOptimizationRequest, "measurement", isolated_measurement)
monkeypatch.setattr(geneticprepare, "get_measurement", Mock(return_value=isolated_measurement))
await isolated_measurement.update_value(run_time.subtract(minutes=2), "storage-soc-factor", 0.42)
await isolated_measurement.update_value(run_time.subtract(minutes=1), "storage-soc-factor", pd.NA)
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
parameters = await resolve(GeneticRequest.model_validate(data))
assert parameters.pv_battery is not None
assert parameters.pv_battery.initial_soc_percentage == 42
@@ -751,7 +872,7 @@ async def test_battery_configuration_error_uses_defaults_and_logs_error(configur
messages: list[str] = []
sink_id = logger.add(lambda message: messages.append(message.record["message"]), level="ERROR")
try:
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
parameters = await resolve(GeneticRequest.model_validate(data))
finally:
logger.remove(sink_id)
assert parameters.pv_battery is not None
@@ -784,7 +905,7 @@ async def test_inverter_is_derated_at_measured_temperature(
return temperature_degc if key == "inverter-temperature-degc" else None
monkeypatch.setattr(invertermeasurement, "get_measured_value", measured)
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
parameters = await resolve(GeneticRequest.model_validate(data))
assert parameters.inverter is not None
assert parameters.inverter.max_power_wh == pytest.approx(expected_max_power_w)
assert parameters.inverter.max_ac_charge_power_w == pytest.approx(expected_max_power_w)
@@ -803,7 +924,7 @@ async def test_unusable_inverter_profile_falls_back_to_generic(configured_reques
messages: list[str] = []
sink_id = logger.add(lambda message: messages.append(message.record["message"]), level="ERROR")
try:
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
parameters = await resolve(GeneticRequest.model_validate(data))
finally:
logger.remove(sink_id)
assert parameters.inverter is not None
@@ -830,9 +951,246 @@ async def test_inverter_without_nominal_power_uses_the_fallback_power(configured
messages: list[str] = []
sink_id = logger.add(lambda message: messages.append(message.record["message"]), level="ERROR")
try:
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
parameters = await resolve(GeneticRequest.model_validate(data))
finally:
logger.remove(sink_id)
assert parameters.inverter is not None
assert parameters.inverter.max_power_wh == pytest.approx(INVERTER_FALLBACK_NOMINAL_POWER_W)
assert any("nominal_power_w" in m for m in messages)
# The preparation always creates valid parameters (energy-domain skill): every input that
# cannot serve the run is replaced by a fallback and logged at error level.
@pytest.mark.asyncio
async def test_surplus_and_duplicate_devices_are_left_out(configured_request, caplog):
config, _, _, data = configured_request
config.merge_settings_from_dict(
{
"devices": {
"max_batteries": 2,
"max_electric_vehicles": 1,
"batteries": {
"second": {"profile_adjustment": {"nominal_capacity_wh": 1000}},
},
"electric_vehicles": {
"storage": {"profile_adjustment": {"nominal_capacity_wh": 1000}},
},
}
}
)
parameters = await resolve(GeneticRequest.model_validate(data))
assert parameters.pv_battery is not None
assert parameters.pv_battery.device_id == "storage"
assert parameters.ev is None
assert "devices.batteries holds more than 1 device(s), 'second' left out" in caplog.text
assert "Device ID 'storage' in devices.electric_vehicles is not unique" in caplog.text
assert list(config.devices.batteries) == ["storage", "second"]
@pytest.mark.asyncio
@pytest.mark.parametrize(
"group, key, method, field, message",
[
("batteries", "storage", "battery_request", "pv_battery", "Battery 'storage'"),
("electric_vehicles", "car", "electric_vehicle_request", "ev", "Electric vehicle 'car'"),
("inverters", "inverter", "inverter_request", "inverter", "Inverter 'inverter'"),
],
)
async def test_unresolvable_device_is_left_out(
configured_request, monkeypatch, caplog, group, key, method, field, message
):
config, _, _, data = configured_request
config.merge_settings_from_dict(
{
"devices": {
"max_electric_vehicles": 1,
"electric_vehicles": {
"car": {"profile_adjustment": {"nominal_capacity_wh": 1000}},
},
}
}
)
def fail(*args: Any, **kwargs: Any) -> Any:
raise ValueError("no profile")
monkeypatch.setattr(geneticprepare, method, fail)
parameters = await resolve(GeneticRequest.model_validate(data))
assert getattr(parameters, field) is None
assert f"{message} cannot be resolved, left out: no profile" in caplog.text
@pytest.mark.asyncio
async def test_without_inverter_the_run_plans_grid_energy_only(
configured_request, monkeypatch, caplog
):
config, _, _, data = configured_request
monkeypatch.setattr(config.devices, "inverters", {})
parameters = await resolve(GeneticRequest.model_validate(data))
assert parameters.inverter is None
assert parameters.pv_battery is None
assert "No usable inverter; planning grid energy only" in caplog.text
assert "Battery 'storage' is not connected to the inverter (battery_id None)" in caplog.text
@pytest.mark.asyncio
async def test_unreadable_predictions_use_fallback_values(configured_request, monkeypatch, caplog):
_, _, _, data = configured_request
data["forecasts"] = {}
prediction = Mock(
update_data=AsyncMock(side_effect=RuntimeError("offline")),
key_to_raw_series=AsyncMock(side_effect=RuntimeError("no data")),
)
monkeypatch.setattr(geneticprepare, "get_prediction", Mock(return_value=prediction))
parameters = await resolve(GeneticRequest.model_validate(data))
first, last = 41, 45 # 10:15 to 11:15 in quarter-hour slots
ems = parameters.ems
assert ems.pv_forecast_wh[first:last] == [0.0] * 4
load = geneticprepare.FALLBACK_LOAD_W * 900 / 3600
assert ems.total_load[first:last] == pytest.approx([load] * 4)
assert ems.electricity_price_per_wh[first:last] == [0.0] * 4
assert isinstance(ems.feed_in_tariff_per_wh, list)
assert ems.feed_in_tariff_per_wh[first:last] == [0.0] * 4
assert "Prediction update failed, using stored data: offline" in caplog.text
assert "Prediction 'pvforecast_ac_power' not readable, treated as missing" in caplog.text
assert "load forecast missing or invalid in 4 slot(s)" in caplog.text
# The fallback price 0 would make charging from the grid look free.
assert parameters.inverter is not None
assert parameters.inverter.max_ac_charge_power_w == 0.0
assert "No electricity price known; no charging from the grid" in caplog.text
@pytest.mark.asyncio
async def test_negative_energy_and_short_genome_are_replaced(configured_request, caplog):
_, _, _, data = configured_request
data["forecasts"]["pv_forecast_wh"][42] = -5.0
data["start_solution"] = [1.0]
parameters = await resolve(GeneticRequest.model_validate(data))
assert parameters.ems.pv_forecast_wh[42] == 0.0
assert parameters.start_solution is None
assert parameters.inverter is not None
assert parameters.inverter.max_ac_charge_power_w != 0 # prices are known
assert "PV forecast missing or invalid in 1 slot(s)" in caplog.text
assert "start_solution of the request [1.0] has fewer than two genes" in caplog.text
def test_unset_settings_use_their_defaults(configured_request, monkeypatch, caplog):
config, ems, _, _ = configured_request
monkeypatch.setattr(config.prediction, "hours", None)
monkeypatch.setattr(config.optimization.genetic, "horizon_hours", 0)
monkeypatch.setattr(config.optimization.genetic, "generations", None)
monkeypatch.setattr(config.optimization.genetic, "individuals", None)
settings = geneticprepare.run_settings(ems.start_datetime, ems.observation_datetime)
assert settings.prediction_hours == geneticprepare.FALLBACK_PREDICTION_HOURS
assert settings.horizon_hours == geneticprepare.FALLBACK_HORIZON_HOURS
assert settings.generations == geneticprepare.FALLBACK_GENERATIONS
assert settings.individuals == geneticprepare.FALLBACK_INDIVIDUALS
assert "prediction.hours not set, using 48" in caplog.text
assert "horizon_hours 0 is not positive, using 24" in caplog.text
assert "optimization.genetic.generations not set, using 400" in caplog.text
assert "optimization.genetic.individuals not set, using 300" in caplog.text
def test_prediction_hours_shorter_than_the_control_horizon(configured_request, monkeypatch, caplog):
config, ems, _, _ = configured_request
monkeypatch.setattr(config.prediction, "hours", 2)
monkeypatch.setattr(config.optimization.genetic, "horizon_hours", 6)
settings = geneticprepare.run_settings(ems.start_datetime, ems.observation_datetime)
assert settings.prediction_hours == 6
assert "prediction.hours 2 is shorter than the control horizon, using 6" in caplog.text
@pytest.mark.asyncio
async def test_automatic_run_without_inverter_or_predictions_is_not_cancelled(
configured_request, monkeypatch, caplog
):
"""Inputs that cancelled a run before now fall back; the run publishes a plan."""
config, fake, _, _ = configured_request
monkeypatch.setattr(config.devices, "inverters", {})
ems = EnergyManagement()
monkeypatch.setattr(EnergyManagement, "_optimizer_runs", {})
monkeypatch.setattr(EnergyManagement, "_plan", None)
prediction = Mock(
update_data=AsyncMock(), key_to_raw_series=AsyncMock(side_effect=KeyError("none"))
)
monkeypatch.setattr(EnergyManagement, "prediction", prediction)
monkeypatch.setattr(geneticprepare, "get_prediction", Mock(return_value=prediction))
monkeypatch.setattr(EnergyManagement, "adapter", Mock(update_data=AsyncMock()))
solution = await ems.run(
start_datetime=fake.start_datetime,
mode=EnergyManagementMode.OPTIMIZATION,
overrides={"generations": 10, "seed": 42},
)
assert solution is not None
assert ems.plan() is not None
assert "Energy management run canceled" not in caplog.text
assert "No usable inverter" in caplog.text
@pytest.mark.asyncio
async def test_inverter_without_its_battery(configured_request, monkeypatch, caplog):
config, _, _, data = configured_request
monkeypatch.setattr(config.devices, "batteries", {})
data["soc"] = {}
parameters = await resolve(GeneticRequest.model_validate(data))
assert parameters.pv_battery is None
assert parameters.inverter is not None
assert "Battery 'storage' of inverter 'inverter' is not available" in caplog.text
@pytest.mark.asyncio
async def test_invalid_energy_and_leading_price_gap_are_replaced(configured_request, caplog):
_, _, _, data = configured_request
forecasts = data["forecasts"]
forecasts["total_load"][41] = -3.0
forecasts["pv_forecast_wh"][43] = np.inf
forecasts["electricity_price_per_wh"] = [np.nan] * 42 + [0.0005] * 54
parameters = await resolve(GeneticRequest.model_validate(data))
ems = parameters.ems
assert ems.total_load[41] == 0.0
assert ems.pv_forecast_wh[43] == 0.0
# No price known before the start: the next known one.
assert ems.electricity_price_per_wh[41] == 0.0005
assert "load forecast missing or invalid in 1 slot(s)" in caplog.text
assert "PV forecast missing or invalid in 1 slot(s)" in caplog.text
assert "electricity price missing or invalid in 1 slot(s)" in caplog.text
@pytest.mark.asyncio
@pytest.mark.parametrize(
"age_seconds, values, reason",
[
(0, [], "(no measurement)"),
(0, [None], "(no measurement)"),
(0, [1.5], "(measured SoC factor 1.5 not a number within 0 to 1)"),
(0, [float("nan")], "(measured SoC factor nan not a number within 0 to 1)"),
(0, ["full"], "(measured SoC factor 'full' not a number within 0 to 1)"),
(7200, [0.5], "(latest measurement 7200 s old, limit 3600 s)"),
],
ids=["none", "no-value", "out-of-range", "nan", "non-numeric", "stale"],
)
async def test_soc_fallback_names_the_reason(
configured_request, monkeypatch, caplog, age_seconds, values, reason
):
"""The fallback log says why no SoC is usable, not Python's exception text."""
config, fake, measurement, data = configured_request
data["soc"] = {}
monkeypatch.setattr(config.optimization.genetic, "measurement_max_age_seconds", 3600)
sample_time = fake.observation_datetime.subtract(seconds=age_seconds)
measurement.key_to_lists.return_value = ([sample_time] * len(values), values)
parameters = await resolve(GeneticRequest.model_validate(data))
assert parameters.pv_battery is not None
assert parameters.pv_battery.initial_soc_percentage == 0
assert f"No usable fresh SoC for storage {reason}; assuming 0% initial SoC" in caplog.text
assert "iterable argument is empty" not in caplog.text
@pytest.mark.asyncio
async def test_short_genome_of_the_last_run_is_not_used(configured_request, caplog):
_, _, _, data = configured_request
warm_start = SimpleNamespace(start_solution=[3.0], start_solution_datetime=None)
parameters = await resolve(GeneticRequest.model_validate(data), warm_start)
assert parameters.start_solution is None
assert "start_solution of the last run [3.0] has fewer than two genes" in caplog.text
+125 -20
View File
@@ -6,20 +6,32 @@ from typing import Any
import numpy as np
import pytest
import pytest_asyncio
from conftest import genetic_optimization, genetic_run_parameters
from akkudoktoreos.config.config import ConfigEOS
from akkudoktoreos.core.coreabc import get_ems, get_measurement
from akkudoktoreos.core.emplan import DDBCInstruction
from akkudoktoreos.measurement.measurement import Measurement
from akkudoktoreos.optimization.genetic.configrequest import ConfigOptimizationRequest
from akkudoktoreos.optimization.genetic.genetic import GeneticOptimization
from akkudoktoreos.optimization.genetic.geneticparams import (
GeneticOptimizationParameters,
from akkudoktoreos.optimization.genetic import geneticconvert, geneticprepare
from akkudoktoreos.optimization.genetic.geneticalgorithm import (
GeneticOptimization,
)
from akkudoktoreos.optimization.genetic.geneticsolution import GeneticSolution
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticOptimizationParameters,
GeneticRequest,
)
from akkudoktoreos.optimization.genetic.geneticresult import GeneticResult
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime
async def resolve(request: GeneticRequest) -> GeneticOptimizationParameters:
"""Prepare ``request`` at the run start and observation time of the energy management."""
ems = get_ems()
return await geneticprepare.resolve_request(
request, ems.start_datetime, ems.observation_datetime, None
)
@pytest.fixture(autouse=True, params=["UTC", "Europe/Berlin"])
def local_clock(request: pytest.FixtureRequest, set_other_timezone: Callable[[str], str]) -> None:
"""Run the same local-wall-clock schedules in UTC and a DST-observing zone.
@@ -91,13 +103,13 @@ def parameters(
)
def run(params: GeneticOptimizationParameters) -> tuple[GeneticOptimization, GeneticSolution]:
optimizer = GeneticOptimization(fixed_seed=42)
def run(params: GeneticOptimizationParameters) -> tuple[GeneticOptimization, GeneticResult]:
optimizer = genetic_optimization(seed=42)
solution = optimizer.optimize_ems(params, ngen=1, individuals=12)
return optimizer, solution
def run_local_starts(solution: GeneticSolution) -> list[DateTime]:
def run_local_starts(solution: GeneticResult) -> list[DateTime]:
"""Compare scheduled instants in the run zone, independently of output zone."""
timezone = get_ems().start_datetime.timezone_name
assert timezone is not None
@@ -113,6 +125,18 @@ def profile(**kwargs: Any) -> dict[str, Any]:
}
def test_real_run_echoes_the_request_without_inventing_windows(config_eos: ConfigEOS) -> None:
"""A consumer without windows stays without windows in the request the result echoes."""
configure(config_eos)
request = parameters(consumers=[profile()])
_, solution = run(request)
assert request.home_appliances is not None
assert request.home_appliances[0].time_windows is None
assert solution.request.home_appliances is not None
assert solution.request.home_appliances[0].time_windows is None
assert len(run_local_starts(solution)) == 1
def test_real_optimizer_keeps_reverse_cycle_window_identity(config_eos: ConfigEOS) -> None:
configure(config_eos)
consumer = profile(
@@ -346,7 +370,7 @@ async def test_real_measurement_completed_cycles_reach_request_and_optimizer(
key=key, start_datetime=zero, end_datetime=zero.add(seconds=1)
)
assert len(dates) == 1 and counts == [1.0]
prepared = await ConfigOptimizationRequest.model_validate(
prepared = await resolve(GeneticRequest.model_validate(
{
"forecasts": {
"pv_forecast_wh": [0.0] * 16,
@@ -355,7 +379,7 @@ async def test_real_measurement_completed_cycles_reach_request_and_optimizer(
"feed_in_tariff_per_wh": [0.0001] * 16,
}
}
).resolve()
))
assert prepared.home_appliances is not None
assert prepared.home_appliances[0].completed_cycles == 1
_, solution = run(prepared)
@@ -363,6 +387,87 @@ async def test_real_measurement_completed_cycles_reach_request_and_optimizer(
assert sum(solution.result.home_appliance_energy_wh["washer"]) == pytest.approx(350.0)
@pytest.mark.asyncio
@pytest.mark.parametrize("count", [3.0, 1.5, -1.0, "two"])
async def test_invalid_completed_cycle_count_is_ignored(
config_eos: ConfigEOS,
isolated_measurement: Measurement,
count: Any,
caplog: pytest.LogCaptureFixture,
) -> None:
"""A count that is no whole number of the appliance's cycles is logged and ignored."""
configure(config_eos)
config_eos.merge_settings_from_dict(
{
"devices": {
"max_batteries": 0,
"batteries": {},
"max_electric_vehicles": 0,
"electric_vehicles": {},
"max_inverters": 1,
"inverters": {"inv": {"profile_adjustment": {"nominal_power_w": 10000}}},
"max_home_appliances": 1,
"home_appliances": {"washer": profile(num_cycles=2)},
}
}
)
await isolated_measurement.update_value(
get_ems().start_datetime, "washer.cycles_completed", count
)
prepared = await resolve(GeneticRequest.model_validate(
{
"forecasts": {
"pv_forecast_wh": [0.0] * 16,
"total_load": [0.0] * 16,
"electricity_price_per_wh": [0.0003] * 16,
"feed_in_tariff_per_wh": [0.0001] * 16,
}
}
))
assert prepared.home_appliances is not None
assert prepared.home_appliances[0].completed_cycles == 0
assert f"Invalid completed cycle count {count!r}" in caplog.text
@pytest.mark.asyncio
async def test_unresolvable_home_appliance_is_left_out(
config_eos: ConfigEOS, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
"""A home appliance whose parameters cannot be derived is left out, logged."""
configure(config_eos)
config_eos.merge_settings_from_dict(
{
"devices": {
"max_batteries": 0,
"batteries": {},
"max_electric_vehicles": 0,
"electric_vehicles": {},
"max_inverters": 1,
"inverters": {"inv": {"profile_adjustment": {"nominal_power_w": 10000}}},
"max_home_appliances": 1,
"home_appliances": {"washer": profile(num_cycles=1)},
}
}
)
def fail(*args: Any, **kwargs: Any) -> Any:
raise ValueError("no profile")
monkeypatch.setattr(geneticprepare, "home_appliance_request", fail)
prepared = await resolve(GeneticRequest.model_validate(
{
"forecasts": {
"pv_forecast_wh": [0.0] * 16,
"total_load": [0.0] * 16,
"electricity_price_per_wh": [0.0003] * 16,
"feed_in_tariff_per_wh": [0.0001] * 16,
}
}
))
assert not prepared.home_appliances
assert "Home appliance 'washer' cannot be resolved, left out: no profile" in caplog.text
@pytest.mark.asyncio
async def test_real_multiple_consumers_keep_separate_solution_channels(
config_eos: ConfigEOS,
@@ -383,7 +488,7 @@ async def test_real_multiple_consumers_keep_separate_solution_channels(
assert sum(solution.result.home_appliance_energy_wh["washer"]) == pytest.approx(350.0)
assert sum(solution.result.home_appliance_energy_wh["dryer"]) == pytest.approx(500.0)
assert sum(solution.result.grid_consumption_wh_per_hour) == pytest.approx(850.0)
exported = await solution.optimization_solution()
exported = await geneticconvert.optimization_solution(genetic_run_parameters(solution.request), solution)
table = exported.solution.to_dataframe()
assert table["washer_energy_wh"].sum() == pytest.approx(350.0)
assert table["dryer_energy_wh"].sum() == pytest.approx(500.0)
@@ -403,11 +508,11 @@ async def test_profile_zero_power_phase_keeps_device_running_until_complete(
shared_time_windows={"windows": [{"start_time": "01:00", "duration": "45 minutes"}]},
)
_, solution = run(parameters(consumers=[consumer]))
exported = await solution.optimization_solution()
exported = await geneticconvert.optimization_solution(genetic_run_parameters(solution.request), solution)
table = exported.solution.to_dataframe()
assert table["washer_energy_wh"].tolist()[4:7] == [300.0, 0.0, 300.0]
assert table["washer_run_op_mode"].tolist()[4:7] == [1.0, 1.0, 1.0]
plan = solution.energy_management_plan()
plan = geneticconvert.energy_management_plan(genetic_run_parameters(solution.request), solution)
assert {item.resource_id for item in plan.instructions} == {"washer"}
commands = [
(item.execution_time.hour, item.execution_time.minute, str(item.operation_mode_id))
@@ -454,7 +559,7 @@ async def test_meter_only_record_does_not_hide_completed_cycles(
# Cycle count through the measurement API, then the adapter's meter reading.
await measurement.update_value(run_time.subtract(seconds=30), "washer.cycles_completed", 1.0)
await measurement.update_value(run_time, "load_meter", 1234.5)
prepared = await ConfigOptimizationRequest.model_validate(
prepared = await resolve(GeneticRequest.model_validate(
{
"forecasts": {
"pv_forecast_wh": [0.0] * 20,
@@ -463,7 +568,7 @@ async def test_meter_only_record_does_not_hide_completed_cycles(
"feed_in_tariff_per_wh": [0.0001] * 20,
}
}
).resolve()
))
assert prepared.home_appliances is not None
assert prepared.home_appliances[0].completed_cycles == 1
@@ -497,7 +602,7 @@ def run_zone() -> str:
return timezone
def heater_commands(solution: GeneticSolution) -> list[tuple[int, int, str]]:
def heater_commands(solution: GeneticResult) -> list[tuple[int, int, str]]:
timezone = run_zone()
return [
(
@@ -505,12 +610,12 @@ def heater_commands(solution: GeneticSolution) -> list[tuple[int, int, str]]:
item.execution_time.in_timezone(timezone).minute,
str(item.operation_mode_id),
)
for item in solution.energy_management_plan().instructions
for item in geneticconvert.energy_management_plan(genetic_run_parameters(solution.request), solution).instructions
if isinstance(item, DDBCInstruction) and item.resource_id == "heater"
]
def heater_starts(solution: GeneticSolution) -> list[tuple[int, int]]:
def heater_starts(solution: GeneticResult) -> list[tuple[int, int]]:
timezone = run_zone()
return [
(moment.in_timezone(timezone).hour, moment.in_timezone(timezone).minute)
@@ -628,7 +733,7 @@ def configure_heater_device(config: ConfigEOS, **kwargs: Any) -> None:
async def resolve_heater() -> GeneticOptimizationParameters:
prepared = await ConfigOptimizationRequest.model_validate(
prepared = await resolve(GeneticRequest.model_validate(
{
"forecasts": {
"pv_forecast_wh": [0.0] * 24,
@@ -637,7 +742,7 @@ async def resolve_heater() -> GeneticOptimizationParameters:
"feed_in_tariff_per_wh": [0.0001] * 24,
}
}
).resolve()
))
assert prepared.home_appliances is not None
return prepared
+15 -11
View File
@@ -9,17 +9,21 @@ from unittest.mock import patch
import numpy as np
import pytest
from conftest import genetic_optimization
from deap import creator
from pydantic import ValidationError
from akkudoktoreos.config.config import ConfigEOS
from akkudoktoreos.core.cache import CacheEnergyManagementStore
from akkudoktoreos.core.coreabc import get_ems
from akkudoktoreos.optimization.genetic.genetic import GeneticOptimization
from akkudoktoreos.optimization.genetic.geneticparams import (
from akkudoktoreos.optimization.genetic import geneticapi
from akkudoktoreos.optimization.genetic.geneticalgorithm import (
GeneticOptimization,
)
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticOptimizationParameters,
)
from akkudoktoreos.optimization.genetic.geneticsettings import GeneticCommonSettings
from akkudoktoreos.optimization.genetic.geneticsettings import GeneticSettings
from akkudoktoreos.utils.datetimeutil import to_datetime
DIR_TESTDATA = Path(__file__).parent / "testdata" / "genetic"
@@ -38,17 +42,17 @@ def _configure_hourly_grid(config_eos: ConfigEOS) -> None:
def test_fitness_cache_max_entries_setting_defaults_to_unbounded():
assert GeneticCommonSettings().fitness_cache_max_entries is None
assert GeneticCommonSettings(fitness_cache_max_entries=0).fitness_cache_max_entries == 0
assert GeneticCommonSettings(fitness_cache_max_entries=5000).fitness_cache_max_entries == 5000
assert GeneticSettings().fitness_cache_max_entries is None
assert GeneticSettings(fitness_cache_max_entries=0).fitness_cache_max_entries == 0
assert GeneticSettings(fitness_cache_max_entries=5000).fitness_cache_max_entries == 5000
with pytest.raises(ValidationError):
GeneticCommonSettings(fitness_cache_max_entries=-1)
GeneticSettings(fitness_cache_max_entries=-1)
@pytest.mark.parametrize("max_entries", [1, 2, 3, 10])
def test_bounded_fitness_cache_evicts_oldest_keys(config_eos: ConfigEOS, max_entries: int):
_configure_hourly_grid(config_eos)
opt = GeneticOptimization(fixed_seed=42)
opt = genetic_optimization(seed=42)
opt.optimize_ev = False
opt.setup_deap_environment({"home_appliance": 0}, start_hour=0)
parameters = SimpleNamespace(ems=SimpleNamespace(price_per_wh_battery=0.0), ev=None)
@@ -80,7 +84,7 @@ def test_bounded_fitness_cache_evicts_oldest_keys(config_eos: ConfigEOS, max_ent
def test_evict_fitness_cache_also_bounds_a_plain_dict(config_eos: ConfigEOS):
opt = GeneticOptimization(fixed_seed=42)
opt = genetic_optimization(seed=42)
opt._fitness_cache = {(bytes([value]),): None for value in range(10)} # type: ignore[misc]
opt._evict_fitness_cache(3)
assert list(opt._fitness_cache) == [(bytes([value]),) for value in (7, 8, 9)]
@@ -121,7 +125,7 @@ def _run_optimization(
)
CacheEnergyManagementStore().clear()
opt = GeneticOptimization(fixed_seed=42)
opt = genetic_optimization(seed=42)
max_cache_size = 0
uncached = opt._evaluate_uncached
@@ -133,7 +137,7 @@ def _run_optimization(
with patch.object(opt, "_evaluate_uncached", side_effect=spy):
solution = opt.optimize_ems(parameters=parameters, start_hour=10, ngen=12)
dump = solution.model_dump(mode="json")
dump = geneticapi.solution_response(solution).model_dump(mode="json")
history = dump.pop("fitness_history")
cache_stats = history.pop("fitness_cache")
max_cache_size = max(max_cache_size, cache_stats["keys"])
+1 -1
View File
@@ -6,7 +6,7 @@ import numpy as np
import pandas as pd
import pytest
from akkudoktoreos.optimization.genetic.forecast import bounded_forecast_array
from akkudoktoreos.optimization.genetic.geneticforecast import bounded_forecast_array
from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration
+25 -281
View File
@@ -1,27 +1,23 @@
"""Regression test suite for the repaired HomeAppliance module.
TODO: fix this import to match wherever HomeApplianceParameters / HomeAppliance
actually live in the repo.
"""
"""Regression test suite for the repaired GENETIC home appliance simulation."""
from typing import Any
from unittest.mock import Mock
import numpy as np
import pendulum
import pytest
from akkudoktoreos.config.configabc import CycleTimeWindowSequence, ValueTimeWindow
from akkudoktoreos.devices.genetic.homeappliance import (
HomeAppliance,
HomeApplianceParameters,
from akkudoktoreos.optimization.genetic.devices.genetichomeappliance import (
GeneticHomeAppliance,
)
from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration, to_time
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticHomeApplianceRequest,
)
from akkudoktoreos.utils.datetimeutil import to_datetime
# ---------------------------------------------------------------------------
# Fixtures / factories
# ---------------------------------------------------------------------------
def make_params(**overrides) -> HomeApplianceParameters:
def make_params(**overrides) -> GeneticHomeApplianceRequest:
defaults: dict[str, Any] = dict(
device_id="dishwasher",
consumption_wh=2000,
@@ -31,76 +27,34 @@ def make_params(**overrides) -> HomeApplianceParameters:
time_windows=None,
)
defaults.update(overrides)
return HomeApplianceParameters(**defaults)
return GeneticHomeApplianceRequest(**defaults)
def make_appliance(
prediction_hours: int = 24,
optimization_hours: int = 24,
**param_overrides,
) -> HomeAppliance:
) -> GeneticHomeAppliance:
"""Build the simulated appliance from a request."""
params = make_params(**param_overrides)
return HomeAppliance(
parameters=params,
return GeneticHomeAppliance(
parameters=params.to_parameters(),
optimization_hours=optimization_hours,
prediction_hours=prediction_hours,
)
def cycle_window(cycle: int, start: str, duration: str) -> CycleTimeWindowSequence:
"""Build a CycleTimeWindowSequence with a single window for one cycle."""
return CycleTimeWindowSequence(
windows=[
ValueTimeWindow(
start_time=to_time(start),
duration=to_duration(duration),
value=float(cycle),
)
]
)
def mock_cycle_windows(cycle_matrix: dict[int, np.ndarray]) -> Mock:
"""Build a Mock standing in for CycleTimeWindowSequence.
``Mock(spec=CycleTimeWindowSequence)`` satisfies both the pydantic
field-type check on ``HomeApplianceParameters.time_windows`` and any
isinstance check in the module, without needing real windows/pendulum
datetimes -- useful for isolating _build_duration_feasibility and the
scheduling/repair logic from the real cycles_to_matrix() implementation.
"""
cycle_indices = list(cycle_matrix.keys())
matrix = np.array([cycle_matrix[c] for c in cycle_indices])
mock = Mock(spec=CycleTimeWindowSequence)
mock.cycles_to_matrix = Mock(return_value=(cycle_indices, matrix))
return mock
# ---------------------------------------------------------------------------
# Setup / defaults
# ---------------------------------------------------------------------------
class TestSetup:
def test_default_time_windows_created_when_none_given(self):
appliance = make_appliance(time_windows=None, num_cycles=1)
assert appliance.parameters.time_windows is not None
assert isinstance(appliance.parameters.time_windows, CycleTimeWindowSequence)
"""Building the appliance."""
def test_default_time_window_value_left_unset(self):
# A None-valued window is invisible to cycles_to_matrix() and so
# never masquerades as a real per-cycle window; every remaining
# cycle instead falls through to the "unconstrained" fallback.
appliance = make_appliance(time_windows=None, num_cycles=3)
assert appliance.parameters.time_windows is not None
windows = appliance.parameters.time_windows.windows
assert len(windows) == 1
assert windows[0].value is None
def test_default_time_window_serializes_without_a_cycle_value(self):
appliance = make_appliance(time_windows=None, num_cycles=1)
assert appliance.parameters.time_windows is not None
dumped = appliance.parameters.time_windows.model_dump()
assert dumped["windows"][0]["value"] is None
def test_simulation_leaves_the_request_unchanged(self):
params = make_params(time_windows=None, num_cycles=1)
GeneticHomeAppliance(params.to_parameters(), 24, 24)
assert params.time_windows is None
def test_num_remaining_cycles_initial(self):
appliance = make_appliance(num_cycles=3)
@@ -113,76 +67,9 @@ class TestSetup:
# ---------------------------------------------------------------------------
# Allowed-start computation: default (unconstrained) per-cycle windows
# Allowed start slots: daylight saving time
# ---------------------------------------------------------------------------
class TestDefaultStartAllowed:
def test_starts_allowed_up_to_horizon_minus_duration(self):
appliance = make_appliance(prediction_hours=10, duration_h=3)
max_start = 10 - 3
allowed = appliance.start_allowed[0]
assert allowed[: max_start + 1].all()
def test_starts_beyond_horizon_minus_duration_forbidden(self):
appliance = make_appliance(prediction_hours=10, duration_h=3)
max_start = 10 - 3
allowed = appliance.start_allowed[0]
assert not allowed[max_start + 1 :].any()
def test_start_earliest_and_latest(self):
appliance = make_appliance(prediction_hours=10, duration_h=3)
assert appliance.start_earliest[0] == 0
assert appliance.start_latest[0] == 10 - 3
def test_each_cycle_gets_its_own_unconstrained_mask(self):
appliance = make_appliance(prediction_hours=10, duration_h=2, num_cycles=2)
max_start = 10 - 2
assert appliance.start_allowed[0][: max_start + 1].all()
assert appliance.start_allowed[1][: max_start + 1].all()
# ---------------------------------------------------------------------------
# Allowed-start computation: explicit single-cycle window
# ---------------------------------------------------------------------------
class TestExplicitCycleWindow:
def test_only_hours_inside_window_allowed(self):
appliance = make_appliance(
prediction_hours=24,
duration_h=2,
num_cycles=1,
time_windows=cycle_window(0, "10:00", "3 hours"),
)
allowed = appliance.start_allowed[0]
# Window is 10:00-13:00, appliance needs 2h -> valid starts 10, 11.
assert allowed[10] and allowed[11]
assert not allowed[9]
assert not allowed[12]
def test_earliest_latest_reflect_window(self):
appliance = make_appliance(
prediction_hours=24,
duration_h=2,
num_cycles=1,
time_windows=cycle_window(0, "10:00", "3 hours"),
)
assert appliance.start_earliest[0] == 10
assert appliance.start_latest[0] == 11
def test_window_with_no_valid_start_falls_back(self):
# Window shorter than the appliance's own duration -> nothing fits.
appliance = make_appliance(
prediction_hours=24,
duration_h=3,
num_cycles=1,
time_windows=cycle_window(0, "10:00", "1 hour"),
)
allowed = appliance.start_allowed[0]
assert not allowed.any()
assert appliance.start_earliest[0] == 0
assert appliance.start_latest[0] == 24 - 3
class TestDSTAllowedStartSlots:
"""The optimizer must distinguish both occurrences of the autumn hour."""
@@ -190,15 +77,15 @@ class TestDSTAllowedStartSlots:
def _appliance(window_field, windows, run_minutes=15):
if window_field == "time_windows":
windows = [{**window, "value": 0} for window in windows]
return HomeAppliance(
parameters=HomeApplianceParameters.model_validate(
return GeneticHomeAppliance(
parameters=GeneticHomeApplianceRequest.model_validate(
{
"device_id": "dishwasher",
"load_profile_power_w": [1000],
"load_profile_interval_seconds": run_minutes * 60,
window_field: {"windows": windows},
}
),
).to_parameters(),
optimization_hours=25,
prediction_hours=100,
slot_duration_h=0.25,
@@ -260,52 +147,6 @@ class TestDSTAllowedStartSlots:
assert allowed == expected
# ---------------------------------------------------------------------------
# Allowed-start computation: mocked per-cycle windows (CycleTimeWindowSequence)
# ---------------------------------------------------------------------------
class TestCycleStartAllowed:
def test_missing_cycle_row_is_unconstrained(self):
# num_cycles=2 but the mock only provides a window for cycle 0.
prediction_hours = 10
duration_h = 2
steps = np.zeros(prediction_hours)
steps[2:6] = 1.0
windows = mock_cycle_windows({0: steps})
appliance = make_appliance(
prediction_hours=prediction_hours,
duration_h=duration_h,
num_cycles=2,
time_windows=windows,
)
max_start = prediction_hours - duration_h
# Cycle 1 has no matrix row -> should be allowed everywhere it fits.
assert appliance.start_allowed[1][: max_start + 1].all()
def test_duration_feasibility_uses_correct_window(self):
# Steps 2,3,4,5 are inside the window (1.0); everything else is 0.
# duration_h=2 -> valid starts are 2, 3, 4 (each 2h block fully inside).
prediction_hours = 10
duration_h = 2
steps = np.zeros(prediction_hours)
steps[2:6] = 1.0
windows = mock_cycle_windows({0: steps})
appliance = make_appliance(
prediction_hours=prediction_hours,
duration_h=duration_h,
num_cycles=1,
time_windows=windows,
)
allowed = appliance.start_allowed[0]
expected = np.zeros(prediction_hours, dtype=bool)
expected[2:5] = True # starts 2, 3, 4
np.testing.assert_array_equal(allowed, expected)
# ---------------------------------------------------------------------------
# set_completed_cycles
# ---------------------------------------------------------------------------
@@ -321,12 +162,6 @@ class TestSetCompletedCycles:
assert appliance.start_hours == []
assert (appliance.load_curve == 0).all()
def test_remaining_cycle_indices_updated(self):
appliance = make_appliance(num_cycles=4)
appliance.set_completed_cycles(2)
assert appliance.remaining_cycle_indices == [2, 3]
assert appliance.num_remaining_cycles == 2
def test_clamped_to_valid_range(self):
appliance = make_appliance(num_cycles=3)
appliance.set_completed_cycles(-5)
@@ -335,97 +170,6 @@ class TestSetCompletedCycles:
assert appliance.completed_cycles == 3
# ---------------------------------------------------------------------------
# set_starting_times -- the core scheduling / repair logic
# ---------------------------------------------------------------------------
class TestSetStartingTimes:
def test_single_cycle_schedule_returns_requested_start(self):
appliance = make_appliance(prediction_hours=24, duration_h=2, num_cycles=1)
result = appliance.set_starting_times([5])
assert result == [5]
def test_two_cycles_enforce_minimum_gap(self):
appliance = make_appliance(
prediction_hours=24, duration_h=2, num_cycles=2, min_cycle_gap_h=1
)
# Requested starts overlap; cycle 1 must be pushed to start >= 0+2+1=3.
result = appliance.set_starting_times([0, 1])
assert result[0] == 0
assert result[1] >= 3
def test_three_cycles_are_all_gap_repaired(self):
appliance = make_appliance(
prediction_hours=24, duration_h=1, num_cycles=3, min_cycle_gap_h=0
)
result = appliance.set_starting_times([0, 0, 0])
# Each cycle is 1h with no gap -> expect 0, 1, 2.
assert result == [0, 1, 2]
def test_load_curve_reflects_final_start_hours(self):
appliance = make_appliance(
prediction_hours=10, duration_h=2, consumption_wh=2000, num_cycles=1
)
appliance.set_starting_times([3])
expected = np.zeros(10)
expected[3:5] = 1000 # 2000 Wh over 2h
np.testing.assert_array_equal(appliance.get_load_curve(), expected)
def test_sorting_preserves_per_cycle_window_alignment(self):
prediction_hours = 24
duration_h = 1
# Cycle 0 only allowed late (hour 20), cycle 1 only allowed early (hour 2).
steps0 = np.zeros(prediction_hours)
steps0[20] = 1.0
steps1 = np.zeros(prediction_hours)
steps1[2] = 1.0
windows = mock_cycle_windows({0: steps0, 1: steps1})
appliance = make_appliance(
prediction_hours=prediction_hours,
duration_h=duration_h,
num_cycles=2,
time_windows=windows,
)
result = appliance.set_starting_times([20, 2])
# Cycle 0 must land at 20 (its only allowed hour), cycle 1 at 2,
# regardless of chronological sorting during repair.
assert 20 in result
assert 2 in result
def test_raises_on_wrong_number_of_start_times(self):
appliance = make_appliance(prediction_hours=24, duration_h=2, num_cycles=2)
with pytest.raises(ValueError):
appliance.set_starting_times([5])
def test_no_remaining_cycles_returns_empty_list(self):
appliance = make_appliance(prediction_hours=24, duration_h=2, num_cycles=1)
appliance.completed_cycles = 1
result = appliance.set_starting_times([])
assert result == []
assert (appliance.load_curve == 0).all()
# ---------------------------------------------------------------------------
# Backwards-compatible single-cycle interface
# ---------------------------------------------------------------------------
class TestSetStartingTimeBackCompat:
def test_single_cycle_wrapper_returns_int(self):
appliance = make_appliance(prediction_hours=24, duration_h=2, num_cycles=1)
result = appliance.set_starting_time(5)
assert isinstance(result, int)
assert result == 5
def test_no_remaining_cycles_returns_input_unchanged(self):
appliance = make_appliance(prediction_hours=24, duration_h=2, num_cycles=1)
appliance.completed_cycles = 1 # nothing left to schedule
result = appliance.set_starting_time(7)
assert result == 7
assert (appliance.load_curve == 0).all()
# ---------------------------------------------------------------------------
# Load curve utilities
# ---------------------------------------------------------------------------
@@ -459,7 +203,7 @@ class TestRunInProgress:
SLOT0 = "2026-11-14T01:00:00+01:00"
def pinned(self, started: str, now: str, slot0: str = SLOT0, **overrides) -> HomeAppliance:
def pinned(self, started: str, now: str, slot0: str = SLOT0, **overrides) -> GeneticHomeAppliance:
appliance = make_appliance(
prediction_hours=overrides.pop("prediction_hours", 6),
run_started_datetime=started,
@@ -488,8 +232,8 @@ class TestRunInProgress:
load_profile_interval_seconds=900,
run_started_datetime="2026-11-14T00:00:00+01:00",
)
appliance = HomeAppliance(
parameters=params, optimization_hours=4, prediction_hours=16, slot_duration_h=0.25
appliance = GeneticHomeAppliance(
parameters=params.to_parameters(), optimization_hours=4, prediction_hours=16, slot_duration_h=0.25
)
appliance.pin_run_in_progress(
to_datetime("2026-11-14T00:15:00+01:00"), to_datetime("2026-11-14T00:20:00+01:00")
+42 -36
View File
@@ -3,13 +3,19 @@ from unittest.mock import Mock, call, patch
import numpy as np
import pytest
from akkudoktoreos.devices.genetic.battery import (
Battery,
SolarPanelBatteryParameters,
)
from akkudoktoreos.devices.genetic.inverter import Inverter, InverterParameters
from akkudoktoreos.devices.settings.invertersettings import InverterCommonSettings
from akkudoktoreos.optimization.genetic import geneticprepare
from akkudoktoreos.optimization.genetic0 import genetic0prepare
from akkudoktoreos.optimization.genetic.devices.geneticbattery import (
GeneticBattery,
)
from akkudoktoreos.optimization.genetic.devices.geneticinverter import (
GeneticInverter,
)
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticBatteryRequest,
GeneticInverterRequest,
)
@pytest.fixture
@@ -25,17 +31,17 @@ def mock_battery() -> Mock:
@pytest.fixture
def inverter(mock_battery) -> Inverter:
def inverter(mock_battery) -> GeneticInverter:
mock_self_consumption_predictor = Mock()
mock_self_consumption_predictor.calculate_expected_direct_consumption.side_effect = min
with patch(
"akkudoktoreos.devices.genetic.inverter.get_eos_load_interpolator",
"akkudoktoreos.optimization.genetic.devices.geneticinverter.get_genetic_load_interpolator",
return_value=mock_self_consumption_predictor,
):
iv = Inverter(
InverterParameters(
iv = GeneticInverter(
GeneticInverterRequest(
device_id="iv1", max_power_wh=500.0, battery_id=mock_battery.parameters.device_id
),
).to_parameters(),
battery=mock_battery,
)
return iv
@@ -43,27 +49,27 @@ def inverter(mock_battery) -> Inverter:
def test_quarter_hour_load_and_grid_export_share_discharge_power_limit():
"""Local supply plus direct export may not exceed one slot's battery budget."""
battery = Battery(
SolarPanelBatteryParameters(
battery = GeneticBattery(
GeneticBatteryRequest(
device_id="battery",
capacity_wh=10000,
charging_efficiency=1.0,
discharging_efficiency=1.0,
max_charge_power_w=7000,
initial_soc_percentage=100,
),
).to_parameters(),
prediction_hours=1,
slot_duration_h=0.25,
)
battery.set_discharge_per_hour(np.array([1]))
quarter_hour_inverter = Inverter(
InverterParameters(
quarter_hour_inverter = GeneticInverter(
GeneticInverterRequest(
device_id="inverter",
max_power_wh=10000,
battery_id="battery",
dc_to_ac_efficiency=1.0,
ac_to_dc_efficiency=1.0,
),
).to_parameters(),
battery=battery,
slot_duration_h=0.25,
)
@@ -133,11 +139,11 @@ def test_probabilistic_bypass_conserves_energy_without_battery():
predictor = Mock()
predictor.calculate_expected_direct_consumption.return_value = 150.0
with patch(
"akkudoktoreos.devices.genetic.inverter.get_eos_load_interpolator",
"akkudoktoreos.optimization.genetic.devices.geneticinverter.get_genetic_load_interpolator",
return_value=predictor,
):
inverter_without_battery = Inverter(
InverterParameters(device_id="inverter", max_power_wh=1000.0)
inverter_without_battery = GeneticInverter(
GeneticInverterRequest(device_id="inverter", max_power_wh=1000.0).to_parameters()
)
generation = 600.0
@@ -159,11 +165,11 @@ def test_probabilistic_bypass_conserves_energy_on_quarter_hour_grid():
predictor = Mock()
predictor.calculate_expected_direct_consumption.return_value = 600.0
with patch(
"akkudoktoreos.devices.genetic.inverter.get_eos_load_interpolator",
"akkudoktoreos.optimization.genetic.devices.geneticinverter.get_genetic_load_interpolator",
return_value=predictor,
):
inverter_without_battery = Inverter(
InverterParameters(device_id="inverter", max_power_wh=2000.0),
inverter_without_battery = GeneticInverter(
GeneticInverterRequest(device_id="inverter", max_power_wh=2000.0).to_parameters(),
slot_duration_h=0.25,
)
@@ -499,7 +505,7 @@ class TestInverterSettings:
convert = (
(lambda: genetic0prepare.inverter_request(settings))
if converter == "to_genetic0_param"
else getattr(settings, converter)
else (lambda: geneticprepare.inverter_request(settings))
)
with pytest.raises(ValueError, match="nominal_power_w"):
convert()
@@ -509,8 +515,8 @@ class TestInverterSettings:
def test_battery_discharge_limit_caps_load_and_grid_export():
"""The inverter's inlined discharge uses the battery's discharge power limit."""
battery = Battery(
SolarPanelBatteryParameters(
battery = GeneticBattery(
GeneticBatteryRequest(
device_id="battery",
capacity_wh=10000,
charging_efficiency=1.0,
@@ -518,19 +524,19 @@ def test_battery_discharge_limit_caps_load_and_grid_export():
max_charge_power_w=7000,
max_discharge_power_w=4000,
initial_soc_percentage=100,
),
).to_parameters(),
prediction_hours=1,
slot_duration_h=0.25,
)
battery.set_discharge_per_hour(np.array([1]))
quarter_hour_inverter = Inverter(
InverterParameters(
quarter_hour_inverter = GeneticInverter(
GeneticInverterRequest(
device_id="inverter",
max_power_wh=10000,
battery_id="battery",
dc_to_ac_efficiency=1.0,
ac_to_dc_efficiency=1.0,
),
).to_parameters(),
battery=battery,
slot_duration_h=0.25,
)
@@ -557,16 +563,16 @@ class TestFirstSlotFraction:
predictor = Mock()
predictor.calculate_expected_direct_consumption.side_effect = min
with patch(
"akkudoktoreos.devices.genetic.inverter.get_eos_load_interpolator",
"akkudoktoreos.optimization.genetic.devices.geneticinverter.get_genetic_load_interpolator",
return_value=predictor,
):
inverter = Inverter(
InverterParameters(
inverter = GeneticInverter(
GeneticInverterRequest(
device_id="inverter1",
max_power_wh=4000.0,
battery_id=battery.parameters.device_id if battery else None,
**parameters,
),
).to_parameters(),
battery=battery,
first_slot_fraction=first_slot_fraction,
)
@@ -596,15 +602,15 @@ class TestFirstSlotFraction:
assert inverter.dc_to_ac_efficiency_at(1000.0) == pytest.approx(0.97)
def test_ac_charge_in_slot_0_uses_the_remaining_part(self):
battery = Battery(
SolarPanelBatteryParameters(
battery = GeneticBattery(
GeneticBatteryRequest(
device_id="battery1",
capacity_wh=40_000,
initial_soc_percentage=0,
min_soc_percentage=0,
max_charge_power_w=8_000,
charging_efficiency=1.0,
),
).to_parameters(),
prediction_hours=2,
first_slot_fraction=0.25,
)
+635 -21
View File
@@ -1,24 +1,48 @@
import inspect
import json
import math
import re
from collections.abc import Callable
from io import BytesIO
from pathlib import Path
from typing import Any
from typing import Any, NamedTuple, Optional
from unittest.mock import AsyncMock, Mock, patch
import numpy as np
import pandas as pd
import pytest
from conftest import genetic_optimization, genetic_run_parameters
from pypdf import PdfReader
from akkudoktoreos.config.config import ConfigEOS
from akkudoktoreos.core.cache import CacheEnergyManagementStore
from akkudoktoreos.core.coreabc import get_ems
from akkudoktoreos.optimization.genetic.genetic import GeneticOptimization
from akkudoktoreos.optimization.genetic.geneticparams import (
from akkudoktoreos.core.ems import EnergyManagement
from akkudoktoreos.core.emsettings import EnergyManagementMode
from akkudoktoreos.optimization.genetic import (
geneticapi,
geneticconvert,
geneticprepare,
)
from akkudoktoreos.optimization.genetic.geneticalgorithm import (
GeneticOptimization,
)
from akkudoktoreos.optimization.genetic.geneticapi import GeneticSolution
from akkudoktoreos.optimization.genetic.geneticoptimizer import GeneticOptimizer
from akkudoktoreos.optimization.genetic.geneticparameters import (
GeneticParameters,
parameters_from_dict,
parameters_to_dict,
)
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticOptimizationParameters,
)
from akkudoktoreos.optimization.genetic.geneticsolution import GeneticSolution
from akkudoktoreos.optimization.genetic.geneticresult import GeneticResult
from akkudoktoreos.optimization.genetic.geneticvisualize import (
GeneticVisualizationReport,
genetic_prepare_visualize,
)
from akkudoktoreos.utils.datetimeutil import to_datetime
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime
ems_eos = get_ems(init=True) # init once
@@ -107,14 +131,14 @@ async def test_optimize(
# Throw away any cached results of the last energy management run.
CacheEnergyManagementStore().clear()
genetic_optimization = GeneticOptimization(fixed_seed=fixed_seed)
optimization = genetic_optimization(seed=fixed_seed)
# Activate with pytest --finalize
if ngen > 10 and not is_finalize:
pytest.skip()
# Call the optimization function
genetic_solution = genetic_optimization.optimize_ems(
genetic_solution = optimization.optimize_ems(
parameters=input_data, start_hour=fixed_start_hour, ngen=ngen
)
@@ -124,13 +148,15 @@ async def test_optimize(
# Keep the output contract, but do not demand an identical stochastic
# schedule or monetary golden from the previous direct-consumption model.
assert set(genetic_solution.model_dump()) == set(expected_result.model_dump())
assert set(geneticapi.solution_response(genetic_solution).model_dump()) == set(
expected_result.model_dump()
)
result = genetic_solution.result
expected_slots = len(input_data.ems.pv_forecast_wh) - fixed_start_hour
assert len(result.grid_consumption_wh_per_hour) == expected_slots
assert len(result.grid_feed_in_wh_per_hour) == expected_slots
prices = np.asarray(genetic_solution.parameters.ems.electricity_price_per_wh)
tariffs = np.asarray(genetic_solution.parameters.ems.feed_in_tariff_per_wh)[:expected_slots]
prices = np.asarray(genetic_solution.request.ems.electricity_price_per_wh)
tariffs = np.asarray(genetic_solution.request.ems.feed_in_tariff_per_wh)[:expected_slots]
expected_costs = np.asarray(result.grid_consumption_wh_per_hour) * prices
expected_revenues = np.asarray(result.grid_feed_in_wh_per_hour) * tariffs
np.testing.assert_allclose(result.costs_per_hour, expected_costs)
@@ -145,7 +171,7 @@ async def test_optimize(
assert all(0 <= value <= 100 for value in result.ev_soc_per_hour)
# Check the correct generic optimization solution is created
optimization_solution = await genetic_solution.optimization_solution()
optimization_solution = await geneticconvert.optimization_solution(genetic_run_parameters(genetic_solution.request), genetic_solution)
dataframe = optimization_solution.solution.to_dataframe()
assert len(dataframe) == expected_slots
assert optimization_solution.valid_from == genetic_solution.start_solution_datetime
@@ -156,7 +182,7 @@ async def test_optimize(
assert len(genetic_solution.discharge_allowed) == expected_slots
# Check the correct generic energy management plan is created
plan = genetic_solution.energy_management_plan()
plan = geneticconvert.energy_management_plan(genetic_run_parameters(genetic_solution.request), genetic_solution)
assert plan.valid_from == optimization_solution.valid_from
assert plan.valid_until is None
assert optimization_solution.valid_from is not None
@@ -167,16 +193,14 @@ async def test_optimize(
)
# Check visualization works
pdf = genetic_prepare_visualize(
solution=genetic_solution,
)
pdf = genetic_prepare_visualize(genetic_run_parameters(genetic_solution.request), genetic_solution)
assert pdf.startswith(b"%PDF-")
reader = PdfReader(BytesIO(pdf))
assert len(reader.pages) >= 6
def test_solution_inverter_parameters_come_from_the_run_or_the_profile(config_eos: ConfigEOS):
def test_solution_inverter_parameters_come_from_the_run(config_eos: ConfigEOS):
"""Inverter settings hold no efficiencies; the solution never reads them directly."""
config_eos.merge_settings_from_dict(
{
@@ -193,9 +217,599 @@ def test_solution_inverter_parameters_come_from_the_run_or_the_profile(config_eo
)
with (DIR_TESTDATA / "optimize_result_1.json").open("r") as f_in:
solution = GeneticSolution.model_validate(json.load(f_in))
stored = solution._inverter_parameters_list(solution.parameters)
stored = geneticconvert._inverter_parameters_list(solution.parameters)
assert stored == ([solution.parameters.inverter] if solution.parameters.inverter else [])
resolved = solution._inverter_parameters_list(None)
assert len(resolved) == 1
assert resolved[0].max_power_wh == pytest.approx(8000)
assert 0.0 < resolved[0].ac_to_dc_efficiency < 1.0
# Without stored parameters there is no inverter: the conversion reads no configuration.
assert geneticconvert._inverter_parameters_list(None) == []
# --- Characterization of the whole output (ADR 0008) ---------------------------------------
#
# Pins, per golden input, the raw result, the optimization solution, the energy management plan
# and the visualization of the current code, so that the migration to the optimizer architecture
# can prove that it keeps GENETIC's results. Generated once from the current code; a refactoring
# never regenerates them.
GOLDEN_TIMEZONE = "Europe/Berlin"
GOLDEN_START = "2026-09-16T10:00:00"
# The horizon crosses the switch to daylight saving time (Europe/Berlin, 2026-03-29).
DST_START = "2026-03-28T10:00:00"
GOLDEN_SEED = 42
# Report methods whose arguments are the input of the visualization; charts added directly
# through add_chart_to_group are pinned by their titles.
REPORT_METHODS = (
"create_line_chart_date",
"create_line_chart",
"create_scatter_plot",
"create_bar_chart",
"create_violin_plot",
"add_text_page",
"add_json_page",
"add_chart_to_group",
)
# Placeholder for the wall-clock time of the conversion in IDs and timestamps.
NOW = "<now>"
# Random UUIDs, e.g. in instruction IDs.
UUID_PATTERN = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
class GoldenCase(NamedTuple):
"""One golden run: input file, settings and run start."""
stem: str
input_file: str
break_even: int
start: str
interval_sec: int
observation_offset_minutes: int
tail: bool
generations: int
def golden_case(stem: str, input_file: str, break_even: int, **changes: Any) -> GoldenCase:
"""A golden case: hourly slots from GOLDEN_START, no tail, 3 generations unless changed."""
case = GoldenCase(stem, input_file, break_even, GOLDEN_START, 3600, 0, False, 3)
return case._replace(**changes)
GOLDEN_CASES = (
golden_case("1", "optimize_input_1.json", break_even=0),
golden_case("2", "optimize_input_2.json", break_even=1),
# Quarter-hour slots, the run starts within a slot.
golden_case(
"1_quarter",
"optimize_input_1.json",
break_even=0,
interval_sec=900,
observation_offset_minutes=20,
),
golden_case("2_dst", "optimize_input_2.json", break_even=1, start=DST_START),
# Tail horizon and automatic terminal value.
golden_case("2_tail", "optimize_input_2.json", break_even=1, tail=True),
golden_case("2_full", "optimize_input_2.json", break_even=1, generations=400),
)
# Runs with more generations take minutes; they run only with --finalize.
QUICK_GENERATIONS = 10
def mask_now(value: Any) -> Any:
"""Replace the wall-clock time of the conversion in ``id`` and ``generated_at``."""
if isinstance(value, dict):
masked = {key: mask_now(item) for key, item in value.items()}
if isinstance(masked.get("id"), str) and "@" in masked["id"]:
prefix, _, _ = masked["id"].partition("@")
masked["id"] = f"{prefix}@{NOW}"
if "generated_at" in masked:
masked["generated_at"] = NOW
return masked
if isinstance(value, list):
return [mask_now(item) for item in value]
return value
def to_jsonable(value: Any) -> Any:
"""Convert the output of a run into plain JSON values for golden files."""
if isinstance(value, dict):
return {str(k): to_jsonable(v) for k, v in value.items()}
if isinstance(value, (list, tuple)):
return [to_jsonable(v) for v in value]
if isinstance(value, np.ndarray):
return to_jsonable(value.tolist())
if isinstance(value, np.generic):
return to_jsonable(value.item())
if isinstance(value, float) and math.isnan(value):
return None
if isinstance(value, str):
return UUID_PATTERN.sub("<uuid>", value)
if isinstance(value, (int, float, bool)) or value is None:
return value
if callable(value):
return f"<{type(value).__name__}>"
return str(value)
def compare_jsonable(actual: Any, expected: Any, path: str = "$") -> None:
"""Compare plain JSON values; numbers approximately."""
if isinstance(expected, dict):
assert isinstance(actual, dict), path
assert set(actual) == set(expected), path
for key, value in expected.items():
compare_jsonable(actual[key], value, f"{path}.{key}")
elif isinstance(expected, list):
assert isinstance(actual, list), path
assert len(actual) == len(expected), path
for index, (a, e) in enumerate(zip(actual, expected)):
compare_jsonable(a, e, f"{path}[{index}]")
elif isinstance(expected, (int, float)) and not isinstance(expected, bool):
assert actual == pytest.approx(expected), path
else:
assert actual == expected, path
def check_golden(actual: Any, golden: str, new_prefix: str = "new_") -> None:
"""Compare ``actual`` with the golden file; write ``<new_prefix><golden>`` for review on a miss.
Tests that compare with the same golden file pass different prefixes, so that parallel
workers do not write and delete each other's review file.
"""
actual = to_jsonable(actual)
new_file = DIR_TESTDATA / f"{new_prefix}{golden}"
new_file.write_text(json.dumps(actual, indent=4) + "\n", encoding="utf-8", newline="\n")
golden_file = DIR_TESTDATA / golden
if not golden_file.exists():
pytest.fail(f"Missing golden file {golden_file}\ncp {new_file} {golden_file}\n")
compare_jsonable(actual, json.loads(golden_file.read_text(encoding="utf-8")))
new_file.unlink()
def record_report_calls() -> tuple[list[dict[str, Any]], dict[str, Any]]:
"""Spies on the report methods: the recorded calls and the patches to apply."""
calls: list[dict[str, Any]] = []
def spy(name: str, original: Callable[..., Any]) -> Callable[..., Any]:
signature = inspect.signature(original)
def method(self: Any, *args: Any, **kwargs: Any) -> Any:
# Bound by name with defaults, so the call style does not matter.
bound = signature.bind(self, *args, **kwargs)
bound.apply_defaults()
arguments = dict(bound.arguments)
arguments.pop("self")
calls.append({"method": name, "arguments": arguments})
return original(self, *args, **kwargs)
return method
patches = {
name: spy(name, getattr(GeneticVisualizationReport, name)) for name in REPORT_METHODS
}
return calls, patches
def golden_settings(case: GoldenCase, workers: Optional[int] = None) -> dict[str, Any]:
"""The configuration of a golden run."""
genetic: dict[str, Any] = {
"interval_sec": case.interval_sec,
"horizon_hours": 38,
"tail_horizon_hours": 0,
"terminal_value_mode": "FIXED",
"individuals": 300,
# The run's ngen argument (case.generations) takes precedence.
"generations": 10,
"seed": GOLDEN_SEED,
"penalties": {"ev_soc_miss": 10, "ac_charge_break_even": case.break_even},
"workers": workers,
}
if case.interval_sec == 900:
# The 48 hourly input values cover 24 hours of quarter-hour slots from a 10:15 start.
genetic["horizon_hours"] = 24
if case.tail:
genetic.update(
{"horizon_hours": 24, "tail_horizon_hours": 24, "terminal_value_mode": "AUTO"}
)
return {
"general": {"timezone": GOLDEN_TIMEZONE},
"prediction": {"hours": 48},
"optimization": {"algorithm": "GENETIC", "genetic": genetic},
"devices": {
"max_electric_vehicles": 1,
"electric_vehicles": {
"ev1": {"charge_rates": [0.0, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0]}
},
},
}
def golden_parameters(
case: GoldenCase, config_eos: ConfigEOS, workers: Optional[int] = None
) -> GeneticParameters:
"""The parameters of a golden input with its settings and run start."""
config_eos.merge_settings_from_dict(golden_settings(case, workers))
with (DIR_TESTDATA / case.input_file).open("r") as f_in:
request = GeneticOptimizationParameters(**json.load(f_in))
observation = to_datetime(case.start, in_timezone=GOLDEN_TIMEZONE).add(
minutes=case.observation_offset_minutes
)
start = ems_eos.set_start_datetime(observation, interval_seconds=case.interval_sec)
CacheEnergyManagementStore().clear()
# The golden input holds complete forecast and device parameters; the preparation adds the
# run settings.
settings = geneticprepare.run_settings(
start, observation, {"generations": case.generations, "seed": GOLDEN_SEED}
)
return GeneticParameters(request=request, start_hour=start.hour, settings=settings)
def run_golden_case(
case: GoldenCase, config_eos: ConfigEOS, workers: Optional[int] = None
) -> GeneticResult:
"""Run a golden input with its settings and run start; check its replay file."""
parameters = golden_parameters(case, config_eos, workers)
solution = GeneticOptimizer().run(parameters)
if workers is None:
check_replay(parameters, f"golden_{case.stem}", f"golden_{case.stem}_result.json")
return solution
def check_replay(parameters: GeneticParameters, stem: str, expected_result: str) -> None:
"""Compare the run's parameters with its replay file; write ``new_<replay>`` on a miss."""
replay = {"expected_result": expected_result, "parameters": parameters_to_dict(parameters)}
# Lossless: what is written reads back to the same values (compared as JSON text, so a
# NaN of a forecast gap compares equal).
written = json.dumps(replay["parameters"])
assert json.dumps(parameters_to_dict(parameters_from_dict(json.loads(written)))) == written
check_golden(replay, f"replay_{stem}.json")
@pytest.mark.asyncio
@pytest.mark.parametrize("case", GOLDEN_CASES, ids=[case.stem for case in GOLDEN_CASES])
async def test_golden_output(
case: GoldenCase, config_eos: ConfigEOS, is_finalize: bool, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A golden input gives the pinned result, solution, plan and visualization."""
if case.generations > QUICK_GENERATIONS and not is_finalize:
pytest.skip("Activate with pytest --finalize")
solution = run_golden_case(case, config_eos)
check_golden(
geneticapi.solution_response(solution).model_dump(mode="json"),
f"golden_{case.stem}_result.json",
)
optimization_solution = await geneticconvert.optimization_solution(genetic_run_parameters(solution.request), solution)
check_golden(
mask_now(optimization_solution.model_dump(mode="json")),
f"golden_{case.stem}_optimization_solution.json",
)
plan = geneticconvert.energy_management_plan(genetic_run_parameters(solution.request), solution)
check_golden(mask_now(plan.model_dump(mode="json")), f"golden_{case.stem}_plan.json")
calls, patches = record_report_calls()
with patch.multiple(GeneticVisualizationReport, **patches):
pdf = genetic_prepare_visualize(genetic_run_parameters(solution.request), solution)
pages = len(PdfReader(BytesIO(pdf)).pages)
check_golden({"pages": pages, "calls": calls}, f"golden_{case.stem}_visualize.json")
@pytest.mark.parametrize("workers", [1, 2])
def test_golden_result_does_not_depend_on_the_workers(workers: int, config_eos: ConfigEOS) -> None:
"""Serial and parallel evaluation give the pinned result (the default picks by CPU count)."""
case = next(case for case in GOLDEN_CASES if case.stem == "2")
solution = run_golden_case(case, config_eos, workers)
check_golden(
geneticapi.solution_response(solution).model_dump(mode="json"),
f"golden_{case.stem}_result.json",
new_prefix=f"new_workers{workers}_",
)
# Origin of the fake prediction series: a value depends on its time, not its index.
PREDICTION_ORIGIN = "2026-01-01T00:00:00+00:00"
PREDICTION_DAYS = 4
def fake_prediction_series(key: str, around: DateTime, gap: bool = False) -> pd.Series:
"""An hourly series per key from the day before ``around``; values follow the time (UTC).
With ``gap`` the load misses one value before the run start, which the preparation keeps.
"""
first = to_datetime(around.in_timezone("UTC").start_of("day").subtract(days=1))
index = pd.date_range(first.isoformat(), periods=24 * PREDICTION_DAYS, freq="h")
hours = (index - pd.Timestamp(PREDICTION_ORIGIN)).total_seconds().to_numpy() / 3600
day_hour = hours % 24
week_hour = hours % (24 * 7)
if key == "pvforecast_ac_power":
values = np.maximum(0.0, 4000.0 * np.sin(np.pi * (day_hour - 4.0) / 14.0))
elif key == "loadforecast_power_w":
values = 350.0 + 15.0 * day_hour + 0.5 * week_hour
elif key == "elecprice_marketprice_wh":
values = 0.00020 + 0.000008 * day_hour + 0.0000002 * week_hour
elif key == "feed_in_tariff_wh":
values = np.full(len(index), 0.00008)
else:
raise KeyError(key)
if gap and key == "loadforecast_power_w":
# 01:00 UTC of the run's day; the series starts at 00:00 UTC of the day before.
values = values.copy()
values[24 + 1] = np.nan
return pd.Series(values, index=index)
class FakeConfigMeasurement:
"""Measured states of charge shortly before the run; with ``rich`` also appliance states."""
def __init__(self, observation: DateTime, rich: bool = False) -> None:
self.records = {
"storage-soc-factor": ([observation.subtract(seconds=60)], [0.42]),
"car-soc-factor": ([observation.subtract(seconds=60)], [0.30]),
}
if rich:
# A full charge three days ago, the dishwasher runs since 30 minutes, no cycle done.
self.records["storage-soc-factor"] = (
[observation.subtract(days=3), observation.subtract(seconds=60)],
[1.0, 0.42],
)
self.records["dishwasher.run_started_at"] = (
[observation.subtract(minutes=30)],
[observation.subtract(minutes=30).timestamp()],
)
self.records["dishwasher.cycles_completed"] = ([observation.start_of("day")], [0])
async def key_to_lists(self, key: str, **kwargs: Any) -> tuple[list[Any], list[Any]]:
"""The records of ``key``.
Args:
key: Measurement key.
**kwargs: Time range and options of the real method; ignored.
Returns:
Dates and values of the key.
Raises:
KeyError: Nothing is measured for ``key``.
"""
if key not in self.records:
raise KeyError(key)
return self.records[key]
class ConfigCase(NamedTuple):
"""One golden run that prepares its parameters from the configuration."""
stem: str
start: str
interval_sec: int
observation_offset_minutes: int
tail: bool
# Appliance measurements, periodic full charge, direct marketing, a warm start and a
# forecast gap before the run start.
rich: bool = False
CONFIG_CASES = (
ConfigCase(
"config_hour", GOLDEN_START, interval_sec=3600, observation_offset_minutes=0, tail=True
),
ConfigCase(
"config_quarter", GOLDEN_START, interval_sec=900, observation_offset_minutes=20, tail=False
),
ConfigCase(
"config_dst", DST_START, interval_sec=3600, observation_offset_minutes=0, tail=False
),
ConfigCase(
"config_rich",
GOLDEN_START,
interval_sec=3600,
observation_offset_minutes=0,
tail=False,
rich=True,
),
)
def config_case_settings(case: ConfigCase) -> dict[str, Any]:
"""Configured devices and settings of a configuration-driven golden run."""
genetic: dict[str, Any] = {
"interval_sec": case.interval_sec,
"horizon_hours": 24,
"tail_horizon_hours": 24 if case.tail else 0,
"terminal_value_mode": "AUTO" if case.tail else "FIXED",
"terminal_value_euro_per_kwh": 0.23,
"individuals": 300,
"generations": 10,
"seed": GOLDEN_SEED,
}
settings: dict[str, Any] = {
"general": {"timezone": GOLDEN_TIMEZONE},
"prediction": {"hours": 48},
"optimization": {"algorithm": "GENETIC", "genetic": genetic},
"devices": {
"max_batteries": 1,
"max_electric_vehicles": 1,
"max_inverters": 1,
"max_home_appliances": 1,
"batteries": {
"storage": {
"profile_adjustment": {
"nominal_capacity_wh": 10000,
"max_charge_power_w": 5000,
},
"levelized_cost_of_storage_amt_kwh": 0.01,
"measurement_key_soc_factor": "storage-soc-factor",
}
},
"electric_vehicles": {
"car": {
"profile_adjustment": {
"nominal_capacity_wh": 40000,
"max_charge_power_w": 11000,
},
"min_soc_percentage": 60,
"charge_rates": [0.0, 0.5, 1.0],
"measurement_key_soc_factor": "car-soc-factor",
}
},
"inverters": {
"inverter": {
"battery_id": "storage",
"profile_adjustment": {"nominal_power_w": 8000},
}
},
"home_appliances": {
"dishwasher": {"consumption_wh": 2000, "duration_h": 2},
},
},
}
if case.rich:
storage = settings["devices"]["batteries"]["storage"]
storage["profile_adjustment"]["full_charge_interval_days"] = 3
storage["full_charge_allow_grid"] = True
settings["feedintariff"] = {"direct_marketing_enabled": True}
return settings
@pytest.mark.asyncio
@pytest.mark.parametrize("case", CONFIG_CASES, ids=[case.stem for case in CONFIG_CASES])
async def test_golden_output_from_configuration(
case: ConfigCase, config_eos: ConfigEOS, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A run prepared from the configuration gives the pinned parameters and output.
The prepared parameters are pinned as the preparation returns them; the result holds them
trimmed to the run start.
"""
config_eos.merge_settings_from_dict(config_case_settings(case))
observation = to_datetime(case.start, in_timezone=GOLDEN_TIMEZONE).add(
minutes=case.observation_offset_minutes
)
prediction = Mock(
update_data=AsyncMock(),
key_to_raw_series=AsyncMock(
side_effect=lambda key, **kwargs: fake_prediction_series(key, observation, case.rich)
),
)
monkeypatch.setattr(EnergyManagement, "prediction", prediction)
monkeypatch.setattr(geneticprepare, "get_prediction", Mock(return_value=prediction))
monkeypatch.setattr(EnergyManagement, "adapter", Mock(update_data=AsyncMock()))
monkeypatch.setattr(EnergyManagement, "_optimizer_runs", {})
if case.rich:
# The previous run, an hour earlier, is the warm start of the pinned one.
previous = observation.subtract(hours=1)
monkeypatch.setattr(
geneticprepare,
"get_measurement",
Mock(return_value=FakeConfigMeasurement(previous, rich=True)),
)
CacheEnergyManagementStore().clear()
warm_start = await ems_eos.run(
start_datetime=previous,
mode=EnergyManagementMode.OPTIMIZATION,
overrides={"generations": 3, "seed": GOLDEN_SEED},
)
assert warm_start is not None
monkeypatch.setattr(
geneticprepare,
"get_measurement",
Mock(return_value=FakeConfigMeasurement(observation, case.rich)),
)
prepared: list[GeneticOptimizationParameters] = []
resolve = geneticprepare.resolve_request
async def record_resolve(*args: Any) -> GeneticOptimizationParameters:
parameters = await resolve(*args)
prepared.append(parameters)
return parameters
monkeypatch.setattr(geneticprepare, "resolve_request", record_resolve)
CacheEnergyManagementStore().clear()
solution = await ems_eos.run(
start_datetime=observation,
mode=EnergyManagementMode.OPTIMIZATION,
overrides={"generations": 3, "seed": GOLDEN_SEED},
)
assert solution is not None
assert len(prepared) == 1
check_golden(prepared[0].model_dump(mode="json"), f"golden_{case.stem}_parameters.json")
run = ems_eos.optimizer_run("GENETIC")
assert run is not None
check_replay(run.parameters, f"golden_{case.stem}", f"golden_{case.stem}_result.json")
check_golden(
geneticapi.solution_response(solution).model_dump(mode="json"),
f"golden_{case.stem}_result.json",
)
optimization_solution = ems_eos.optimization_solution()
assert optimization_solution is not None
check_golden(
mask_now(optimization_solution.model_dump(mode="json")),
f"golden_{case.stem}_optimization_solution.json",
)
plan = ems_eos.plan()
assert plan is not None
check_golden(mask_now(plan.model_dump(mode="json")), f"golden_{case.stem}_plan.json")
calls, patches = record_report_calls()
with patch.multiple(GeneticVisualizationReport, **patches):
pdf = genetic_prepare_visualize(genetic_run_parameters(solution.request), solution)
pages = len(PdfReader(BytesIO(pdf)).pages)
check_golden({"pages": pages, "calls": calls}, f"golden_{case.stem}_visualize.json")
REPLAY_STEMS = [f"golden_{case.stem}" for case in GOLDEN_CASES] + [
f"golden_{case.stem}" for case in CONFIG_CASES
]
@pytest.mark.parametrize("stem", REPLAY_STEMS)
def test_replay(stem: str, config_eos: ConfigEOS, is_finalize: bool) -> None:
"""A run reproduces its golden result from the stored parameters alone (ADR 0006, 0008).
The configuration and the run start are set to different values on purpose: the run must
not read them.
"""
replay = json.loads((DIR_TESTDATA / f"replay_{stem}.json").read_text())
parameters = parameters_from_dict(replay["parameters"])
generations = parameters.settings.generations
if generations is not None and generations > QUICK_GENERATIONS and not is_finalize:
pytest.skip("Activate with pytest --finalize")
config_eos.merge_settings_from_dict(
{
"general": {"timezone_override": "America/New_York"},
"prediction": {"hours": 30},
"optimization": {
"genetic": {
"interval_sec": 3600 if parameters.settings.interval_sec == 900 else 900,
"horizon_hours": 6,
"tail_horizon_hours": 0,
"individuals": 11,
"generations": 12,
"seed": 1,
"terminal_value_mode": "FIXED",
"penalties": {"ev_soc_miss": 99, "ac_charge_break_even": 3},
}
},
"feedintariff": {"direct_marketing_enabled": False},
"devices": {"max_electric_vehicles": 0, "max_home_appliances": 0},
}
)
config_eos.merge_settings_from_dict({"optimization": {"self_consumption_interpolator": "numpy"}})
ems_eos.set_start_datetime(to_datetime("2027-01-05T03:00:00+00:00", in_timezone="UTC"))
result = GeneticOptimizer().run(parameters)
check_golden(
geneticapi.solution_response(result).model_dump(mode="json"),
replay["expected_result"],
new_prefix="new_replay_",
)
def test_replay_keeps_a_forecast_gap() -> None:
"""A gap the preparation keeps is ``null`` in the replay file and NaN in the parameters."""
replay = json.loads((DIR_TESTDATA / "replay_golden_config_rich.json").read_text())
assert replay["parameters"]["request"]["ems"]["total_load"][3] is None
parameters = parameters_from_dict(replay["parameters"])
assert math.isnan(parameters.request.ems.total_load[3])
assert parameters_to_dict(parameters)["request"]["ems"]["total_load"][3] is None
+30
View File
@@ -0,0 +1,30 @@
"""Tests of the GENETIC adapter of the optimizer interface."""
from types import SimpleNamespace
from typing import Any, cast
from unittest.mock import patch
from akkudoktoreos.optimization.genetic import geneticalgorithm
from akkudoktoreos.optimization.genetic.geneticoptimizer import GeneticOptimizer
from akkudoktoreos.utils.datetimeutil import to_datetime
class TestGeneticOptimizer:
"""The GENETIC adapter hands the run parameters to the algorithm."""
def test_run_starts_from_the_start_of_the_parameters(self) -> None:
"""The run aligns the start solution with the start of the parameters, not the request."""
start = to_datetime("2026-09-12T09:45:00+00:00", in_timezone="UTC")
parameters = SimpleNamespace(
settings=SimpleNamespace(generations=10, individuals=10),
start_hour=10,
request=SimpleNamespace(start_solution_datetime=None),
start_solution_datetime=start,
)
with patch.object(geneticalgorithm, "GeneticOptimization") as optimization:
GeneticOptimizer().run(cast(Any, parameters))
kwargs = optimization.return_value.optimize_ems.call_args.kwargs
assert kwargs["start_solution_datetime"] == start
assert kwargs["parameters"].start_solution_datetime is None
+11 -6
View File
@@ -10,16 +10,17 @@ from types import SimpleNamespace
import pytest
import uvicorn
from conftest import genetic_optimization
from akkudoktoreos.config.config import ConfigEOS
from akkudoktoreos.core.cache import CacheEnergyManagementStore
from akkudoktoreos.core.coreabc import get_ems
from akkudoktoreos.optimization.genetic import genetic as genetic_module
from akkudoktoreos.optimization.genetic.genetic import (
from akkudoktoreos.optimization.genetic import geneticalgorithm as genetic_module
from akkudoktoreos.optimization.genetic.geneticalgorithm import (
GeneticOptimization,
auto_evaluation_workers,
)
from akkudoktoreos.optimization.genetic.geneticparams import (
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticOptimizationParameters,
)
from akkudoktoreos.utils.datetimeutil import to_datetime
@@ -104,7 +105,7 @@ def _parameters(
def _run(config_eos: ConfigEOS, workers: int, cache_entries):
parameters = _parameters(config_eos, workers, cache_entries)
optimization = GeneticOptimization(fixed_seed=7)
optimization = genetic_optimization(seed=7)
used: list[int] = []
original_start = optimization._start_evaluation_pool
@@ -438,7 +439,9 @@ def test_unsupported_fork_falls_back_to_serial(config_eos: ConfigEOS, monkeypatc
def test_cgroup_cpu_limit_reads_own_and_parent_cgroups(tmp_path, monkeypatch):
from akkudoktoreos.optimization.genetic.genetic import _cgroup_cpu_limit
from akkudoktoreos.optimization.genetic.geneticalgorithm import (
_cgroup_cpu_limit,
)
service = tmp_path / "system.slice" / "eos.service"
service.mkdir(parents=True)
@@ -475,7 +478,9 @@ def test_cgroup_cpu_limit_reads_own_and_parent_cgroups(tmp_path, monkeypatch):
],
)
def test_worker_cpu_set(workers, allowed, expected):
from akkudoktoreos.optimization.genetic.genetic import worker_cpu_set
from akkudoktoreos.optimization.genetic.geneticalgorithm import (
worker_cpu_set,
)
assert worker_cpu_set(workers, allowed) == expected
+25 -23
View File
@@ -2,7 +2,8 @@
Adapted from PRs #1224 (Christin) and #1304 (Normann). Main has no direct-marketing
parameter override yet: these regressions cover its existing preparation/simulation
contract and refuse unavailable imported revenue instead of creating a demo tariff.
contract. Unavailable imported revenue falls back to the last known revenue (0 without
any) instead of creating a demo tariff.
"""
from unittest.mock import AsyncMock, Mock, patch
@@ -11,11 +12,15 @@ import numpy as np
import pandas as pd
import pytest
from akkudoktoreos.devices.genetic.inverter import Inverter, InverterParameters
from akkudoktoreos.optimization.genetic.configrequest import ConfigOptimizationRequest
from akkudoktoreos.optimization.genetic.genetic import GeneticSimulation
from akkudoktoreos.optimization.genetic.geneticparams import (
GeneticOptimizationParameters,
from akkudoktoreos.optimization.genetic import geneticprepare
from akkudoktoreos.optimization.genetic.devices.geneticinverter import (
GeneticInverter,
)
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticInverterRequest,
)
from akkudoktoreos.optimization.genetic.geneticsimulation import (
GeneticSimulation,
)
from akkudoktoreos.prediction.feedintariffabc import FeedInTariffDataRecord
from akkudoktoreos.prediction.feedintariffimport import FeedInTariffImport
@@ -64,16 +69,9 @@ def prepare_tariffs(config_eos):
prediction = Mock(
update_data=AsyncMock(), key_to_raw_series=AsyncMock(side_effect=read_series)
)
ems = Mock(
start_datetime=to_datetime("2026-08-01T00:00:00+00:00", in_timezone="UTC"),
observation_datetime=to_datetime("2026-08-01T00:00:00+00:00", in_timezone="UTC"),
)
ems.genetic_solution.return_value = None
with (
patch("akkudoktoreos.optimization.genetic.configrequest.get_ems", return_value=ems),
patch.object(ConfigOptimizationRequest, "prediction", prediction),
):
parameters = await GeneticOptimizationParameters.prepare()
start = to_datetime("2026-08-01T00:00:00+00:00", in_timezone="UTC")
with patch.object(geneticprepare, "get_prediction", return_value=prediction):
parameters = (await geneticprepare.prepare(start, start, None)).request
return parameters, prices, prediction
return prepare
@@ -107,12 +105,12 @@ async def test_provider_revenues_survive_preparation_and_simulation(
# A 1 kWh export at 0.00007 amount/Wh earns 0.07, not 70 or 0.00007.
# No battery or household load is needed to expose tariff substitution/unit bugs.
inverter = Inverter(InverterParameters(device_id="inverter1", max_power_wh=10000))
inverter = GeneticInverter(GeneticInverterRequest(device_id="inverter1", max_power_wh=10000).to_parameters())
inverter.self_consumption_predictor = Mock()
inverter.self_consumption_predictor.calculate_expected_direct_consumption.return_value = 0.0
simulation = GeneticSimulation()
simulation.prepare(
parameters.ems, optimization_hours=24, prediction_hours=24, inverter=inverter
parameters.ems.to_parameters(), optimization_hours=24, prediction_hours=24, inverter=inverter
)
result = simulation.simulate(start_hour=0)
assert result["Netzeinspeisung_Wh_pro_Stunde"] == pytest.approx([1000.0] * 24)
@@ -138,15 +136,18 @@ async def test_provider_revenues_survive_preparation_and_simulation(
[[0.00007]] * 24,
],
)
async def test_invalid_import_cancels_without_replacing_provider(
async def test_invalid_import_falls_back_without_replacing_provider(
prepare_tariffs, revenues, config_eos, caplog
):
"""Missing revenues are carried forward or 0, logged; the provider stays configured."""
parameters, _, prediction = await prepare_tariffs("FeedInTariffImport", revenues)
assert parameters is None
tariffs = parameters.ems.feed_in_tariff_per_wh
assert isinstance(tariffs, list) and len(tariffs) == 24
assert all(np.isfinite(tariffs))
assert set(tariffs) <= {0.00007, 0.0}
assert config_eos.feedintariff.provider == "FeedInTariffImport"
prediction.update_data.assert_awaited_once()
assert "canceling optimization" in caplog.text
assert "FeedInTariffImport" in caplog.text
assert "feed-in tariff missing or invalid" in caplog.text
assert "defaulting to demo" not in caplog.text
@@ -170,7 +171,8 @@ async def test_timestamped_import_records_are_read_in_order(prepare_tariffs, val
"FeedInTariffImport", [], tariff_reader=provider.key_to_raw_series
)
if values[0] is None:
assert parameters is None
# No revenue known at all: no feed-in revenue.
assert parameters.ems.feed_in_tariff_per_wh == [0.0] * 24
else:
assert parameters is not None
assert parameters.ems.feed_in_tariff_per_wh == pytest.approx(values)
+17 -18
View File
@@ -6,11 +6,13 @@ from pathlib import Path
from types import SimpleNamespace
import pytest
from conftest import genetic_result_of, genetic_run_parameters
from fastapi.testclient import TestClient
from pypdf import PdfReader
from akkudoktoreos.optimization.genetic import geneticvisualize
from akkudoktoreos.optimization.genetic.geneticsolution import GeneticSolution
from akkudoktoreos.optimization.genetic import geneticapi, geneticvisualize
from akkudoktoreos.optimization.genetic.geneticapi import GeneticSolution
from akkudoktoreos.optimization.optimizer import OptimizerRun
from akkudoktoreos.server import eos
from akkudoktoreos.utils.datetimeutil import to_datetime
@@ -20,11 +22,11 @@ def retained_result():
path = Path(__file__).parent / "testdata/genetic/optimize_result_1.json"
solution = GeneticSolution.model_validate_json(path.read_text())
solution.start_solution_datetime = to_datetime("2026-09-16T10:00:00+02:00")
return solution
return genetic_result_of(solution)
def test_missing_algorithm_report_returns_404(config_eos, monkeypatch):
monkeypatch.setattr(eos, "get_ems", lambda: SimpleNamespace(genetic_solution=lambda: None))
monkeypatch.setattr(eos, "get_ems", lambda: SimpleNamespace(optimizer_run=lambda name: None))
response = TestClient(eos.app).get("/v1/energy-management/optimization/solution/GENETIC/pdf")
assert response.status_code == 404
assert response.headers["content-type"].startswith("application/problem+json")
@@ -32,24 +34,21 @@ def test_missing_algorithm_report_returns_404(config_eos, monkeypatch):
def test_retained_algorithm_result_renders_real_pdf(config_eos, monkeypatch, retained_result):
solution = retained_result
monkeypatch.setattr(eos, "get_ems", lambda: SimpleNamespace(genetic_solution=lambda: solution))
run = OptimizerRun(parameters=genetic_run_parameters(solution.request), result=solution)
monkeypatch.setattr(eos, "get_ems", lambda: SimpleNamespace(optimizer_run={"GENETIC": run}.get))
# A later run and changed configuration must not retime the retained report.
from akkudoktoreos.core.coreabc import get_ems
from akkudoktoreos.optimization.genetic import geneticvisualize
get_ems().set_start_datetime(to_datetime("2027-01-01T00:00:00+01:00"))
config_eos.optimization.genetic.interval_sec = 900
monkeypatch.setattr(
geneticvisualize, "get_ems", lambda: pytest.fail("Report must retain its own time grid")
)
before = solution.model_dump_json()
before = geneticapi.solution_response(solution).model_dump_json()
response = TestClient(eos.app).get("/v1/energy-management/optimization/solution/GENETIC/pdf")
assert response.status_code == 200
assert response.headers["content-type"] == "application/pdf"
assert "genetic" in response.headers["content-disposition"]
assert response.content.startswith(b"%PDF-")
assert len(PdfReader(BytesIO(response.content)).pages) >= 4
assert solution.model_dump_json() == before
assert geneticapi.solution_response(solution).model_dump_json() == before
@pytest.mark.asyncio
@@ -57,21 +56,21 @@ async def test_render_is_offloaded_and_uses_an_owned_copy(config_eos, monkeypatc
solution = retained_result
caller_thread = threading.get_ident()
captured = []
monkeypatch.setattr(
eos,
"get_ems",
lambda: SimpleNamespace(genetic_solution=lambda: solution),
)
run = OptimizerRun(parameters=genetic_run_parameters(solution.request), result=solution)
monkeypatch.setattr(eos, "get_ems", lambda: SimpleNamespace(optimizer_run={"GENETIC": run}.get))
original_controls = list(solution.ac_charge)
def render(*, solution):
def render(*, parameters, result):
solution = result
captured.append((threading.get_ident(), solution))
solution.ac_charge[0] = 0.123
return b"%PDF-isolated-render"
# The PDF stack is imported on first use, so patch it at its source.
monkeypatch.setattr(geneticvisualize, "genetic_prepare_visualize", render)
response = await eos.fastapi_energy_management_optimization_solution_genetic_pdf_get()
response = await geneticapi.fastapi_energy_management_optimization_solution_genetic_pdf_get(
latest=run
)
assert response.body == b"%PDF-isolated-render"
assert captured[0][0] != caller_thread
assert captured[0][1] is not solution
+20 -39
View File
@@ -4,18 +4,19 @@ from unittest.mock import patch
import numpy as np
import pytest
from conftest import genetic_optimization
from deap import creator, tools
from akkudoktoreos.config.config import ConfigEOS
from akkudoktoreos.core.coreabc import get_ems
from akkudoktoreos.optimization.genetic.genetic import (
from akkudoktoreos.optimization.genetic.geneticalgorithm import (
GeneticOptimization,
_pack_genes,
_release_freed_memory,
_unpack_genes,
)
from akkudoktoreos.optimization.genetic.geneticparams import (
GeneticEnergyManagementParameters,
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticEnergyManagementRequest,
GeneticOptimizationParameters,
)
from akkudoktoreos.utils.datetimeutil import DateTime, compare_datetimes, to_datetime
@@ -35,7 +36,7 @@ def _configure_hourly_grid(config_eos: ConfigEOS, *, start_hour: int = 0) -> Non
def test_ev_repair_is_resimulated_before_fitness_assignment(config_eos: ConfigEOS):
_configure_hourly_grid(config_eos)
opt = GeneticOptimization(fixed_seed=42)
opt = genetic_optimization(seed=42)
opt.optimize_ev = True
opt.ev_possible_charge_values = [0.0, 1.0]
opt.setup_deap_environment({"home_appliance": 0}, start_hour=0)
@@ -115,7 +116,7 @@ def test_release_freed_memory_is_safe_to_call():
def test_fitness_cache_restores_canonical_ev_genome(config_eos: ConfigEOS):
_configure_hourly_grid(config_eos)
opt = GeneticOptimization(fixed_seed=42)
opt = genetic_optimization(seed=42)
opt.optimize_ev = True
opt.ev_possible_charge_values = [0.0, 1.0]
opt.setup_deap_environment({"home_appliance": 0}, start_hour=0)
@@ -149,7 +150,7 @@ def test_fitness_cache_restores_canonical_ev_genome(config_eos: ConfigEOS):
def test_fitness_cache_never_stores_failed_evaluations(config_eos: ConfigEOS):
_configure_hourly_grid(config_eos)
opt = GeneticOptimization(fixed_seed=42)
opt = genetic_optimization(seed=42)
opt.optimize_ev = False
opt.setup_deap_environment({"home_appliance": 0}, start_hour=0)
parameters = SimpleNamespace(
@@ -172,7 +173,7 @@ def test_fitness_cache_never_stores_failed_evaluations(config_eos: ConfigEOS):
def test_fitness_cache_includes_first_run_relative_control(config_eos: ConfigEOS):
_configure_hourly_grid(config_eos, start_hour=10)
opt = GeneticOptimization(fixed_seed=42)
opt = genetic_optimization(seed=42)
opt.optimize_ev = False
opt.setup_deap_environment({"home_appliance": 0}, start_hour=10)
parameters = SimpleNamespace(
@@ -200,7 +201,7 @@ def test_fitness_cache_includes_first_run_relative_control(config_eos: ConfigEOS
def test_mutated_warm_start_neighbors_stay_within_control_horizon(config_eos: ConfigEOS):
_configure_hourly_grid(config_eos, start_hour=10)
opt = GeneticOptimization(fixed_seed=42)
opt = genetic_optimization(seed=42)
opt.optimize_ev = False
opt.setup_deap_environment({"home_appliance": 0}, start_hour=10)
start_solution = [0.0] * opt.control_slots
@@ -218,7 +219,7 @@ def test_initial_population_uses_fixed_seed_budget_and_configured_population(
):
_configure_hourly_grid(config_eos)
config_eos.optimization.genetic.individuals = 300
opt = GeneticOptimization(fixed_seed=42)
opt = genetic_optimization(seed=42)
opt.optimize_ev = False
opt.setup_deap_environment({"home_appliance": 0}, start_hour=0)
start_solution = [5.0] * opt.control_slots
@@ -263,7 +264,7 @@ def test_initial_population_uses_fixed_seed_budget_and_configured_population(
def test_small_population_scales_warm_and_educated_seed_families(config_eos: ConfigEOS):
_configure_hourly_grid(config_eos)
config_eos.optimization.genetic.individuals = 100
opt = GeneticOptimization(fixed_seed=42)
opt = genetic_optimization(seed=42)
opt.optimize_ev = False
opt.setup_deap_environment({"home_appliance": 0}, start_hour=0)
start_solution = [5.0] * opt.control_slots
@@ -315,7 +316,7 @@ def test_small_population_scales_warm_and_educated_seed_families(config_eos: Con
def test_adaptive_evolution_soft_restarts_collapsed_population(config_eos: ConfigEOS):
_configure_hourly_grid(config_eos)
opt = GeneticOptimization(fixed_seed=42)
opt = genetic_optimization(seed=42)
opt.optimize_ev = False
opt.setup_deap_environment({"home_appliance": 0}, start_hour=0)
opt.toolbox.register("evaluate", lambda individual: (float(sum(individual)),))
@@ -347,7 +348,7 @@ def test_adaptive_evolution_soft_restarts_collapsed_population(config_eos: Confi
def test_local_search_moves_weak_export_to_later_expensive_import(config_eos: ConfigEOS):
_configure_hourly_grid(config_eos)
opt = GeneticOptimization(fixed_seed=42)
opt = genetic_optimization(seed=42)
opt.optimize_ev = False
opt.optimize_dc_charge = True
opt.optimize_battery_grid_export = True
@@ -395,7 +396,7 @@ def test_local_search_moves_weak_export_to_later_expensive_import(config_eos: Co
def test_educated_guesses_encode_high_price_direct_marketing(config_eos: ConfigEOS):
_configure_hourly_grid(config_eos)
opt = GeneticOptimization(fixed_seed=42)
opt = genetic_optimization(seed=42)
opt.optimize_ev = False
opt.optimize_dc_charge = True
opt.optimize_battery_grid_export = True
@@ -422,7 +423,7 @@ def test_educated_guesses_encode_high_price_direct_marketing(config_eos: ConfigE
def test_flat_feed_in_tariff_does_not_seed_direct_marketing(config_eos: ConfigEOS):
_configure_hourly_grid(config_eos)
opt = GeneticOptimization(fixed_seed=42)
opt = genetic_optimization(seed=42)
opt.optimize_ev = False
opt.optimize_dc_charge = True
opt.optimize_battery_grid_export = True
@@ -483,7 +484,7 @@ def _immigrant_selection_pool(opt: GeneticOptimization, protection: int):
def test_protected_immigrants_survive_the_selection(config_eos: ConfigEOS):
_configure_hourly_grid(config_eos)
opt = GeneticOptimization(fixed_seed=42)
opt = genetic_optimization(seed=42)
opt.optimize_ev = False
opt.setup_deap_environment({"home_appliance": 0}, start_hour=0)
@@ -503,7 +504,7 @@ def test_protected_immigrants_survive_the_selection(config_eos: ConfigEOS):
def test_immigrant_protection_expires_after_its_generations(config_eos: ConfigEOS):
_configure_hourly_grid(config_eos)
opt = GeneticOptimization(fixed_seed=42)
opt = genetic_optimization(seed=42)
opt.optimize_ev = False
opt.setup_deap_environment({"home_appliance": 0}, start_hour=0)
@@ -520,7 +521,7 @@ def test_immigrant_protection_expires_after_its_generations(config_eos: ConfigEO
def test_offspring_do_not_inherit_immigrant_protection(config_eos: ConfigEOS):
_configure_hourly_grid(config_eos)
opt = GeneticOptimization(fixed_seed=42)
opt = genetic_optimization(seed=42)
opt.optimize_ev = False
opt.setup_deap_environment({"home_appliance": 0}, start_hour=0)
opt.toolbox.register("evaluate", lambda individual: (float(sum(individual)),))
@@ -549,7 +550,7 @@ def _warm_start_optimizer(
}
)
slot0 = get_ems(init=True).set_start_datetime(to_datetime().set(hour=8, minute=0, second=0))
opt = GeneticOptimization(fixed_seed=42)
opt = genetic_optimization(seed=42)
opt.optimize_ev = optimize_ev
opt.appliance_layout = SimpleNamespace(n_genes=n_appliance_genes, genes=[]) # type: ignore[assignment]
opt._slot0_datetime = slot0
@@ -609,30 +610,10 @@ class TestWarmStartAlignment:
assert opt._start_solution_for_run_start(previous, slot0.add(minutes=offset_minutes)) is None
def test_start_datetime_falls_back_to_last_solution_of_this_server(self,
config_eos: ConfigEOS, monkeypatch: pytest.MonkeyPatch
):
opt, slot0 = _warm_start_optimizer(config_eos, interval=900)
last_start = slot0.subtract(minutes=15)
monkeypatch.setattr(
type(get_ems()),
"_genetic_solution",
SimpleNamespace(start_solution=[19.0, 32.0, 14.0], start_solution_datetime=last_start),
)
same = SimpleNamespace(start_solution=[19, 32, 14], start_solution_datetime=None)
other = SimpleNamespace(start_solution=[19, 32, 15], start_solution_datetime=None)
explicit_start = slot0.subtract(minutes=30)
explicit = SimpleNamespace(start_solution=[19, 32, 14], start_solution_datetime=explicit_start)
assert opt._resolve_start_solution_datetime(same) == last_start # type: ignore[arg-type]
assert opt._resolve_start_solution_datetime(other) is None # type: ignore[arg-type]
assert opt._resolve_start_solution_datetime(explicit) == explicit_start # type: ignore[arg-type]
def test_parameters_accept_iso_start_solution_datetime(self, config_eos: ConfigEOS):
parameters = GeneticOptimizationParameters.model_validate(
dict(
ems=GeneticEnergyManagementParameters.model_validate(
ems=GeneticEnergyManagementRequest.model_validate(
dict(
pv_prognose_wh=[0.0, 0.0],
strompreis_euro_pro_wh=[0.0, 0.0],
+71 -44
View File
@@ -2,24 +2,28 @@ import numpy as np
import pytest
from akkudoktoreos.config.configabc import TimeWindow, TimeWindowSequence
from akkudoktoreos.devices.genetic.battery import (
Battery,
ElectricVehicleParameters,
SolarPanelBatteryParameters,
from akkudoktoreos.optimization.genetic.devices.geneticbattery import (
GeneticBattery,
)
from akkudoktoreos.devices.genetic.homeappliance import (
HomeAppliance,
HomeApplianceParameters,
from akkudoktoreos.optimization.genetic.devices.genetichomeappliance import (
GeneticHomeAppliance,
)
from akkudoktoreos.devices.genetic.inverter import (
Inverter,
InverterParameters,
from akkudoktoreos.optimization.genetic.devices.geneticinverter import (
GeneticInverter,
)
from akkudoktoreos.optimization.genetic.genetic import (
GeneticEnergyManagementParameters,
GeneticSimulation,
from akkudoktoreos.optimization.genetic.geneticapi import (
GeneticSimulationResult,
)
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticBatteryRequest,
GeneticElectricVehicleRequest,
GeneticEnergyManagementRequest,
GeneticHomeApplianceRequest,
GeneticInverterRequest,
)
from akkudoktoreos.optimization.genetic.geneticsimulation import (
GeneticSimulation,
)
from akkudoktoreos.utils.datetimeutil import to_duration, to_time
start_hour = 1
@@ -28,8 +32,8 @@ start_hour = 1
@pytest.mark.parametrize("efficiency_curve", [None, [(0.0, 0.8), (1.0, 0.97)]])
def test_below_min_soc_requires_real_charging_energy(efficiency_curve):
"""Discharge attempts before and after partial charging must not create energy."""
battery = Battery(
SolarPanelBatteryParameters(
battery = GeneticBattery(
GeneticBatteryRequest(
device_id="battery1",
capacity_wh=26_400,
initial_soc_percentage=0,
@@ -37,12 +41,12 @@ def test_below_min_soc_requires_real_charging_energy(efficiency_curve):
max_charge_power_w=7_000,
charging_efficiency=0.95,
discharging_efficiency=0.95,
),
).to_parameters(),
prediction_hours=4,
slot_duration_h=0.25,
)
inverter = Inverter(
InverterParameters(
inverter = GeneticInverter(
GeneticInverterRequest(
device_id="inverter1",
battery_id="battery1",
max_power_wh=10_000,
@@ -50,19 +54,19 @@ def test_below_min_soc_requires_real_charging_energy(efficiency_curve):
ac_to_dc_efficiency=0.97,
dc_to_ac_efficiency=0.97,
dc_to_ac_efficiency_curve=efficiency_curve,
),
).to_parameters(),
battery=battery,
slot_duration_h=0.25,
)
simulation = GeneticSimulation()
simulation.prepare(
GeneticEnergyManagementParameters(
GeneticEnergyManagementRequest(
pv_forecast_wh=[0.0] * 4,
total_load=[280.0] * 4,
electricity_price_per_wh=[0.00037, 0.00037, 0.00050, 0.00063],
feed_in_tariff_per_wh=0.0,
price_per_wh_battery=0.0,
),
).to_parameters(),
optimization_hours=4,
prediction_hours=4,
inverter=inverter,
@@ -96,39 +100,39 @@ def genetic_simulation(config_eos) -> GeneticSimulation:
assert config_eos.optimization.genetic.horizon_hours == 24
# Initialize the battery and the inverter
akku = Battery(
SolarPanelBatteryParameters(
akku = GeneticBattery(
GeneticBatteryRequest(
device_id="battery1",
capacity_wh=5000,
initial_soc_percentage=80,
min_soc_percentage=10,
),
).to_parameters(),
prediction_hours = config_eos.prediction.hours,
)
akku.reset()
inverter = Inverter(
InverterParameters(device_id="inverter1", max_power_wh=10000, battery_id=akku.parameters.device_id),
inverter = GeneticInverter(
GeneticInverterRequest(device_id="inverter1", max_power_wh=10000, battery_id=akku.parameters.device_id).to_parameters(),
battery = akku,
)
# Household device (currently not used, set to None)
home_appliance = HomeAppliance(
HomeApplianceParameters(
home_appliance = GeneticHomeAppliance(
GeneticHomeApplianceRequest(
device_id="dishwasher1",
consumption_wh=2000,
duration_h=2,
time_windows=None,
),
).to_parameters(),
optimization_hours = config_eos.optimization.genetic.horizon_hours,
prediction_hours = config_eos.prediction.hours,
)
# Example initialization of electric car battery
eauto = Battery(
ElectricVehicleParameters(
eauto = GeneticBattery(
GeneticElectricVehicleRequest(
device_id="ev1", capacity_wh=26400, initial_soc_percentage=10, min_soc_percentage=10
),
).to_parameters(),
prediction_hours = config_eos.prediction.hours,
)
eauto.set_charge_per_hour(np.full(config_eos.prediction.hours, 1))
@@ -293,13 +297,13 @@ def genetic_simulation(config_eos) -> GeneticSimulation:
# Initialize the energy management system with the respective parameters
simulation = GeneticSimulation()
simulation.prepare(
GeneticEnergyManagementParameters.model_validate(dict(
GeneticEnergyManagementRequest.model_validate(dict(
pv_prognose_wh=pv_prognose_wh,
strompreis_euro_pro_wh=strompreis_euro_pro_wh,
einspeiseverguetung_euro_pro_wh=einspeiseverguetung_euro_pro_wh,
preis_euro_pro_wh_akku=preis_euro_pro_wh_akku,
gesamtlast=gesamtlast,
)),
)).to_parameters(),
optimization_hours = config_eos.optimization.genetic.horizon_hours,
prediction_hours = config_eos.prediction.hours,
inverter=inverter,
@@ -316,7 +320,8 @@ def genetic_simulation(config_eos) -> GeneticSimulation:
simulation.dc_charge_hours[start_hour] = 1.0
simulation.bat_discharge_hours[start_hour] = 1.0
simulation.ev_charge_hours[start_hour] = 1.0
simulation.home_appliance_start_hour = 2
assert simulation.home_appliance is not None
simulation.home_appliance.build_load_curve([2])
return simulation
@@ -435,11 +440,11 @@ def test_simulation(genetic_simulation):
def _profile_simulation(
battery_curves: dict, initial_soc_percentage: int = 50
) -> tuple[GeneticSimulation, Battery]:
) -> tuple[GeneticSimulation, GeneticBattery]:
"""48 slots with a battery that has the given profile curves, if any."""
hours = 48
battery = Battery(
SolarPanelBatteryParameters(
battery = GeneticBattery(
GeneticBatteryRequest(
device_id="battery1",
capacity_wh=8000,
initial_soc_percentage=initial_soc_percentage,
@@ -450,17 +455,17 @@ def _profile_simulation(
discharging_efficiency=0.9,
levelized_cost_of_storage_kwh=0.05,
**battery_curves,
),
).to_parameters(),
prediction_hours=hours,
)
inverter = Inverter(
InverterParameters(device_id="inverter1", max_power_wh=10000, battery_id="battery1"),
inverter = GeneticInverter(
GeneticInverterRequest(device_id="inverter1", max_power_wh=10000, battery_id="battery1").to_parameters(),
battery=battery,
)
rng = np.random.default_rng(7)
simulation = GeneticSimulation()
simulation.prepare(
GeneticEnergyManagementParameters.model_validate(
GeneticEnergyManagementRequest.model_validate(
dict(
pv_prognose_wh=(
np.clip(np.sin(np.linspace(0, 4 * np.pi, hours)), 0, None) * 6000
@@ -470,7 +475,7 @@ def _profile_simulation(
preis_euro_pro_wh_akku=0.0001,
gesamtlast=rng.uniform(300, 2500, hours).tolist(),
)
),
).to_parameters(),
optimization_hours=24,
prediction_hours=hours,
inverter=inverter,
@@ -478,7 +483,7 @@ def _profile_simulation(
return simulation, battery
def _run_plans(simulation: GeneticSimulation, battery: Battery) -> list[dict]:
def _run_plans(simulation: GeneticSimulation, battery: GeneticBattery) -> list[dict]:
rng = np.random.default_rng(11)
hours = battery.prediction_hours
results = []
@@ -546,3 +551,25 @@ def test_soc_taper_slows_charging_near_full(config_eos):
# The tapered battery takes at most 500 W x 1 h (before efficiency) per slot.
assert results["taper"][1] < results["flat"][1]
assert results["taper"][1] - results["taper"][0] <= 500.0 * 0.95 / 8000 * 100 + 1e-9
def test_without_inverter_the_grid_supplies_the_whole_load():
"""Without an inverter the load is bought from the grid; PV is neither used nor fed in."""
hours = 4
simulation = GeneticSimulation()
simulation.prepare(
GeneticEnergyManagementRequest(
pv_forecast_wh=[2000.0] * hours,
electricity_price_per_wh=[0.0003] * hours,
feed_in_tariff_per_wh=[0.0001] * hours,
price_per_wh_battery=0.0,
total_load=[1000.0] * hours,
).to_parameters(),
optimization_hours=hours,
prediction_hours=hours,
)
result = simulation.simulate(0)
assert list(result["Netzbezug_Wh_pro_Stunde"]) == [1000.0] * hours
assert list(result["Netzeinspeisung_Wh_pro_Stunde"]) == [0.0] * hours
assert result["Gesamtkosten_Euro"] == pytest.approx(hours * 1000.0 * 0.0003)
assert result["Gesamteinnahmen_Euro"] == 0.0
+32 -27
View File
@@ -2,24 +2,28 @@ import numpy as np
import pytest
from akkudoktoreos.config.configabc import TimeWindow, TimeWindowSequence
from akkudoktoreos.devices.genetic.battery import (
Battery,
ElectricVehicleParameters,
SolarPanelBatteryParameters,
from akkudoktoreos.optimization.genetic.devices.geneticbattery import (
GeneticBattery,
)
from akkudoktoreos.devices.genetic.homeappliance import (
HomeAppliance,
HomeApplianceParameters,
from akkudoktoreos.optimization.genetic.devices.genetichomeappliance import (
GeneticHomeAppliance,
)
from akkudoktoreos.devices.genetic.inverter import (
Inverter,
InverterParameters,
from akkudoktoreos.optimization.genetic.devices.geneticinverter import (
GeneticInverter,
)
from akkudoktoreos.optimization.genetic.genetic import (
GeneticEnergyManagementParameters,
GeneticSimulation,
from akkudoktoreos.optimization.genetic.geneticapi import (
GeneticSimulationResult,
)
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticBatteryRequest,
GeneticElectricVehicleRequest,
GeneticEnergyManagementRequest,
GeneticHomeApplianceRequest,
GeneticInverterRequest,
)
from akkudoktoreos.optimization.genetic.geneticsimulation import (
GeneticSimulation,
)
from akkudoktoreos.utils.datetimeutil import to_duration, to_time
start_hour = 0
@@ -37,39 +41,39 @@ def genetic_simulation_2(config_eos) -> GeneticSimulation:
assert config_eos.optimization.genetic.horizon_hours == 24
# Initialize the battery and the inverter
akku = Battery(
SolarPanelBatteryParameters(
akku = GeneticBattery(
GeneticBatteryRequest(
device_id="battery1",
capacity_wh=5000,
initial_soc_percentage=80,
min_soc_percentage=10,
),
).to_parameters(),
prediction_hours = config_eos.prediction.hours,
)
akku.reset()
inverter = Inverter(
InverterParameters(device_id="inverter1", max_power_wh=10000, battery_id=akku.parameters.device_id),
inverter = GeneticInverter(
GeneticInverterRequest(device_id="inverter1", max_power_wh=10000, battery_id=akku.parameters.device_id).to_parameters(),
battery = akku,
)
# Household device (currently not used, set to None)
home_appliance = HomeAppliance(
HomeApplianceParameters(
home_appliance = GeneticHomeAppliance(
GeneticHomeApplianceRequest(
device_id="dishwasher1",
consumption_wh=2000,
duration_h=2,
time_windows=None,
),
).to_parameters(),
optimization_hours = config_eos.optimization.genetic.horizon_hours,
prediction_hours = config_eos.prediction.hours,
)
# Example initialization of electric car battery
eauto = Battery(
ElectricVehicleParameters(
eauto = GeneticBattery(
GeneticElectricVehicleRequest(
device_id="ev1", capacity_wh=26400, initial_soc_percentage=10, min_soc_percentage=10
),
).to_parameters(),
prediction_hours = config_eos.prediction.hours,
)
@@ -140,13 +144,13 @@ def genetic_simulation_2(config_eos) -> GeneticSimulation:
# Initialize the energy management system with the respective parameters
simulation = GeneticSimulation()
simulation.prepare(
GeneticEnergyManagementParameters.model_validate(dict(
GeneticEnergyManagementRequest.model_validate(dict(
pv_prognose_wh=pv_prognose_wh,
strompreis_euro_pro_wh=strompreis_euro_pro_wh,
einspeiseverguetung_euro_pro_wh=einspeiseverguetung_euro_pro_wh,
preis_euro_pro_wh_akku=preis_euro_pro_wh_akku,
gesamtlast=gesamtlast,
)),
)).to_parameters(),
optimization_hours = config_eos.optimization.genetic.horizon_hours,
prediction_hours = config_eos.prediction.hours,
inverter=inverter,
@@ -160,7 +164,8 @@ def genetic_simulation_2(config_eos) -> GeneticSimulation:
dc = np.full(config_eos.prediction.hours, 0.0)
dc[11] = 1
simulation.dc_charge_hours = dc
simulation.home_appliance_start_hour = 2
assert simulation.home_appliance is not None
simulation.home_appliance.build_load_curve([2])
return simulation
+99
View File
@@ -0,0 +1,99 @@
"""GENETIC's own time windows give the same coverage as the shared settings windows (ADR 0004)."""
from typing import Any
import numpy as np
import pytest
from akkudoktoreos.config.configabc import CycleTimeWindowSequence
from akkudoktoreos.optimization.genetic.devices.genetichomeappliance import (
GeneticHomeAppliance,
)
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticHomeApplianceRequest,
)
from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration
WINDOWS: list[dict[str, Any]] = [
# Plain window per cycle, two windows sharing cycle 1.
{"start_time": "08:00", "duration": "3 hours", "value": 0},
{"start_time": "13:00", "duration": "2 hours", "value": 1},
{"start_time": "16:00", "duration": "1 hour", "value": 1},
# Overnight with an explicit end time, restricted to a weekday.
{"start_time": "22:00", "duration": "1 hour", "end_time": "02:30", "day_of_week": 5,
"value": 2},
# Date restriction (within the tested ranges).
{"start_time": "10:00", "duration": "2 hours", "date": "2026-09-17", "value": 4},
{"start_time": "10:00", "duration": "2 hours", "date": "2026-03-29", "value": 4},
# Month restriction and a window that belongs to no cycle.
{"start_time": "00:00", "duration": "6 hours", "month": 3, "value": 3},
{"start_time": "00:00", "duration": "24 hours"},
]
@pytest.mark.parametrize(
"start, interval_s",
[
("2026-09-16T00:00:00", 3600),
("2026-09-16T10:20:00", 900),
# Spring forward and fall back in Berlin.
("2026-03-28T00:00:00", 900),
("2026-10-24T00:00:00", 3600),
],
)
def test_window_coverage_matches_the_settings_windows(start: str, interval_s: int) -> None:
"""Per cycle, the run's window check covers the same grid steps as the settings windows.
A one-second run is allowed where a window contains its start (the end is exclusive), so the
run's check (``_windows_allow_run``) is compared with the settings' per-step coverage.
"""
settings = CycleTimeWindowSequence.model_validate({"windows": WINDOWS})
request = GeneticHomeApplianceRequest(
device_id="washer", consumption_wh=1000, duration_h=1, time_windows=settings
)
windows = request.to_parameters().time_windows
assert windows is not None
first = to_datetime(start, in_timezone="Europe/Berlin")
last = first.add(hours=72)
interval = to_duration(interval_s)
expected_cycles, expected = settings.cycles_to_matrix(first, last, interval)
# The settings floor the grid start to the interval in wall-clock time.
wall_s = first.hour * 3600 + first.minute * 60 + first.second + first.microsecond / 1_000_000
grid = [
first.subtract(seconds=wall_s % interval_s).add(seconds=step * interval_s)
for step in range(expected.shape[1])
]
one_second = to_duration(1)
cycles = sorted({int(window.value) for window in windows if window.value is not None})
matrix = np.array(
[
[
1.0
if GeneticHomeAppliance._windows_allow_run(
[w for w in windows if w.value is not None and int(w.value) == cycle],
moment,
one_second,
merge=True,
)
else 0.0
for moment in grid
]
for cycle in cycles
]
)
assert cycles == expected_cycles
np.testing.assert_array_equal(matrix, expected)
def test_window_start_and_end_match_the_settings_windows() -> None:
settings = CycleTimeWindowSequence.model_validate({"windows": WINDOWS})
request = GeneticHomeApplianceRequest(
device_id="washer", consumption_wh=1000, duration_h=1, time_windows=settings
)
windows = request.to_parameters().time_windows
assert windows is not None
for day in range(7):
anchor = to_datetime("2026-10-24T12:00:00", in_timezone="Europe/Berlin").add(days=day)
for own, shared in zip(windows, settings.windows):
assert own.start_end(anchor) == shared._window_start_end(anchor)
+20 -15
View File
@@ -1,3 +1,4 @@
from dataclasses import replace
from io import BytesIO
from pathlib import Path
from types import SimpleNamespace
@@ -7,20 +8,21 @@ import matplotlib.pyplot as plt
import numpy as np
import pendulum
import pytest
from conftest import genetic_result_of, genetic_run_parameters
from matplotlib.testing.compare import compare_images
from pypdf import PdfReader
from akkudoktoreos.optimization.genetic import geneticvisualize as visualize
from akkudoktoreos.optimization.genetic.geneticsolution import GeneticSolution
from akkudoktoreos.optimization.genetic.geneticvisualize import (
genetic_generate_example_report,
)
from akkudoktoreos.optimization.genetic.terminalvalue import (
from akkudoktoreos.optimization.genetic.geneticapi import GeneticSolution
from akkudoktoreos.optimization.genetic.geneticterminalvalue import (
TailDiagnostics,
TailPlanSlot,
TerminalValueCurve,
TerminalValueResult,
)
from akkudoktoreos.optimization.genetic.geneticvisualize import (
genetic_generate_example_report,
)
filename = "example_report.pdf"
@@ -73,7 +75,7 @@ class TestGeneticVisualizationIntervals:
home_appliance_energy_wh={"water-heater": energy},
)
return SimpleNamespace(
parameters=SimpleNamespace(
request=SimpleNamespace(
ems=SimpleNamespace(
total_load=energy,
pv_forecast_wh=energy,
@@ -131,8 +133,7 @@ class TestGeneticVisualizationIntervals:
return original(self, start_date, y_list, **kwargs)
monkeypatch.setattr(visualize.GeneticVisualizationReport, "create_line_chart_date", capture)
monkeypatch.setattr(visualize, "get_ems", lambda: pytest.fail("Snapshot must own report timing"))
pdf = visualize.genetic_prepare_visualize(report_solution)
pdf = visualize.genetic_prepare_visualize(genetic_run_parameters(report_solution.request), report_solution)
assert pdf.startswith(b"%PDF-")
assert all(row[0] == report_solution.start_solution_datetime for row in captured)
assert all(row[3] == interval_seconds for row in captured)
@@ -178,8 +179,12 @@ class TestGeneticVisualizationIntervals:
assert not solution.controls_start_at_now
assert solution.terminal_value is None
start = pendulum.datetime(2026, 9, 16, solution.start_hour, tz="UTC")
monkeypatch.setattr(visualize, "get_ems", lambda: SimpleNamespace(start_datetime=start))
pdf = visualize.genetic_prepare_visualize(solution)
# A historical solution has no start; the run start of the parameters is the fallback.
parameters = genetic_run_parameters(solution.parameters)
parameters = replace(
parameters, settings=replace(parameters.settings, start_datetime=start)
)
pdf = visualize.genetic_prepare_visualize(parameters, genetic_result_of(solution))
assert len(PdfReader(BytesIO(pdf)).pages) >= 4
def test_fixed_fallback_does_not_invent_tail_charts(self, config_eos, report_solution):
@@ -188,7 +193,7 @@ class TestGeneticVisualizationIntervals:
battery_energy_wh=500, requested_tail_hours=24,
)
report_solution.result.home_appliance_energy_wh = {}
pdf = visualize.genetic_prepare_visualize(report_solution)
pdf = visualize.genetic_prepare_visualize(genetic_run_parameters(report_solution.request), report_solution)
text = " ".join(page.extract_text() for page in PdfReader(BytesIO(pdf)).pages)
assert "No complete tail forecast" in text
assert "effective tail: 0 h" in text
@@ -219,9 +224,9 @@ class TestGeneticVisualizationIntervals:
def test_pdf_clips_forecast_tail_and_accepts_historical_diagnostics(self,
config_eos, monkeypatch, report_solution, tariff
):
report_solution.parameters.ems.total_load = [100.0] * 6
report_solution.parameters.ems.pv_forecast_wh = [200.0] * 6
report_solution.parameters.ems.feed_in_tariff_per_wh = tariff
report_solution.request.ems.total_load = [100.0] * 6
report_solution.request.ems.pv_forecast_wh = [200.0] * 6
report_solution.request.ems.feed_in_tariff_per_wh = tariff
report_solution.extra_data = {
"verluste": [1.0, 2.0, 3.0], "bilanz": [0.1, 0.2, 0.3],
"nebenbedingung": [0.0, 0.0, 0.0],
@@ -234,7 +239,7 @@ class TestGeneticVisualizationIntervals:
return original(self, start_date, y_list, **kwargs)
monkeypatch.setattr(visualize.GeneticVisualizationReport, "create_line_chart_date", capture)
pdf = visualize.genetic_prepare_visualize(report_solution)
pdf = visualize.genetic_prepare_visualize(genetic_run_parameters(report_solution.request), report_solution)
assert pdf.startswith(b"%PDF-")
tariff_plot = next(series for series, kwargs in captured if kwargs.get("title") == "Remuneration")
assert np.asarray(tariff_plot[0]).tolist() == [0.00007] * 4
+41 -31
View File
@@ -16,12 +16,18 @@ from unittest.mock import Mock, patch
import numpy as np
import pytest
from conftest import genetic_optimization
from akkudoktoreos.devices.genetic.battery import (
Battery,
SolarPanelBatteryParameters,
from akkudoktoreos.optimization.genetic.devices.geneticbattery import (
GeneticBattery,
)
from akkudoktoreos.optimization.genetic.devices.geneticinverter import (
GeneticInverter,
)
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticBatteryRequest,
GeneticInverterRequest,
)
from akkudoktoreos.devices.genetic.inverter import Inverter, InverterParameters
# ---------------------------------------------------------------------------
# Helpers / Fixtures
@@ -34,12 +40,12 @@ def _make_inverter(
max_ac_charge_power_w=None,
max_power_wh: float = 10000.0,
mock_battery=None,
) -> Inverter:
) -> GeneticInverter:
"""Create an Inverter with custom efficiency parameters and a mock battery."""
mock_self_consumption_predictor = Mock()
mock_self_consumption_predictor.calculate_expected_direct_consumption.side_effect = min
params = InverterParameters(
params = GeneticInverterRequest(
device_id="inv1",
max_power_wh=max_power_wh,
battery_id=mock_battery.parameters.device_id if mock_battery else None,
@@ -48,10 +54,10 @@ def _make_inverter(
max_ac_charge_power_w=max_ac_charge_power_w,
)
with patch(
"akkudoktoreos.devices.genetic.inverter.get_eos_load_interpolator",
"akkudoktoreos.optimization.genetic.devices.geneticinverter.get_genetic_load_interpolator",
return_value=mock_self_consumption_predictor,
):
return Inverter(params, battery=mock_battery)
return GeneticInverter(params.to_parameters(), battery=mock_battery)
@pytest.fixture
@@ -64,7 +70,7 @@ def mock_battery() -> Mock:
# ===================================================================
# 1. InverterParameters – new fields and defaults
# 1. GeneticInverterRequest – new fields and defaults
# ===================================================================
@@ -72,13 +78,13 @@ class TestInverterParametersDefaults:
"""Verify backward-compatible defaults for new parameters."""
def test_defaults(self):
params = InverterParameters(device_id="inv1", max_power_wh=5000)
params = GeneticInverterRequest(device_id="inv1", max_power_wh=5000)
assert params.dc_to_ac_efficiency == 1.0
assert params.ac_to_dc_efficiency == 1.0
assert params.max_ac_charge_power_w is None
def test_custom_values(self):
params = InverterParameters(
params = GeneticInverterRequest(
device_id="inv1",
max_power_wh=5000,
dc_to_ac_efficiency=0.95,
@@ -90,17 +96,17 @@ class TestInverterParametersDefaults:
assert params.max_ac_charge_power_w == 3000
def test_ac_to_dc_zero_disables_ac_charging(self):
params = InverterParameters(
params = GeneticInverterRequest(
device_id="inv1", max_power_wh=5000, ac_to_dc_efficiency=0.0
)
assert params.ac_to_dc_efficiency == 0.0
def test_dc_to_ac_must_be_positive(self):
with pytest.raises(Exception):
InverterParameters(device_id="inv1", max_power_wh=5000, dc_to_ac_efficiency=0.0)
GeneticInverterRequest(device_id="inv1", max_power_wh=5000, dc_to_ac_efficiency=0.0)
def test_max_ac_charge_power_zero(self):
params = InverterParameters(
params = GeneticInverterRequest(
device_id="inv1", max_power_wh=5000, max_ac_charge_power_w=0
)
assert params.max_ac_charge_power_w == 0
@@ -215,9 +221,11 @@ class TestAcChargingInSimulation:
@pytest.fixture
def simulation_setup(self, config_eos):
"""Set up a minimal GeneticSimulation with battery and inverter."""
from akkudoktoreos.optimization.genetic.genetic import GeneticSimulation
from akkudoktoreos.optimization.genetic.geneticparams import (
GeneticEnergyManagementParameters,
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticEnergyManagementRequest,
)
from akkudoktoreos.optimization.genetic.geneticsimulation import (
GeneticSimulation,
)
config_eos.merge_settings_from_dict(
@@ -236,8 +244,8 @@ class TestAcChargingInSimulation:
battery_initial_soc_pct: int = 50,
battery_max_charge_power_w: int = 5000,
):
akku = Battery(
SolarPanelBatteryParameters(
akku = GeneticBattery(
GeneticBatteryRequest(
device_id="battery1",
capacity_wh=battery_capacity_wh,
initial_soc_percentage=battery_initial_soc_pct,
@@ -246,32 +254,32 @@ class TestAcChargingInSimulation:
min_soc_percentage=0,
max_soc_percentage=100,
max_charge_power_w=battery_max_charge_power_w,
),
).to_parameters(),
prediction_hours=prediction_hours,
)
akku.reset()
inverter = Inverter(
InverterParameters(
inverter = GeneticInverter(
GeneticInverterRequest(
device_id="inverter1",
max_power_wh=10000,
battery_id="battery1",
ac_to_dc_efficiency=ac_to_dc_efficiency,
dc_to_ac_efficiency=dc_to_ac_efficiency,
max_ac_charge_power_w=max_ac_charge_power_w,
),
).to_parameters(),
battery=akku,
)
simulation = GeneticSimulation()
simulation.prepare(
GeneticEnergyManagementParameters.model_validate(dict(
GeneticEnergyManagementRequest.model_validate(dict(
pv_prognose_wh=[0.0] * prediction_hours, # No PV
strompreis_euro_pro_wh=[0.0003] * prediction_hours, # ~30ct/kWh
einspeiseverguetung_euro_pro_wh=0.00008,
preis_euro_pro_wh_akku=0.0001,
gesamtlast=[1000.0] * prediction_hours, # 1 kW constant load
)),
)).to_parameters(),
optimization_hours=config_eos.optimization.genetic.horizon_hours,
prediction_hours=prediction_hours,
inverter=inverter,
@@ -465,14 +473,14 @@ class TestResidualBatteryValue:
def test_current_energy_content_unaffected(self):
"""Battery.current_energy_content() is DC-only; inverter eff applied in optimizer."""
akku = Battery(
SolarPanelBatteryParameters(
akku = GeneticBattery(
GeneticBatteryRequest(
device_id="bat1",
capacity_wh=10000,
initial_soc_percentage=50,
discharging_efficiency=0.90,
min_soc_percentage=0,
),
).to_parameters(),
prediction_hours=24,
)
akku.reset()
@@ -551,7 +559,9 @@ def _run_evaluate_with_mocked_sim(
- self.simulation is replaced by mock_sim
Then call evaluate() and return the fitness tuple.
"""
from akkudoktoreos.optimization.genetic.genetic import GeneticOptimization
from akkudoktoreos.optimization.genetic.geneticalgorithm import (
GeneticOptimization,
)
config_eos.merge_settings_from_dict(
{
@@ -565,8 +575,8 @@ def _run_evaluate_with_mocked_sim(
}
optim = GeneticOptimization.__new__(GeneticOptimization)
# Minimal __init__ state expected by evaluate()
optim.config = config_eos
# Minimal __init__ state expected by evaluate(): the run settings of the configuration.
optim.settings = genetic_optimization().settings
optim.optimize_ev = False
optim.verbose = False
optim.opti_param = {"home_appliance": 0}
+60 -51
View File
@@ -20,19 +20,28 @@ from akkudoktoreos.devices.devicesabc import (
solve_ac_for_dc_energy,
validate_efficiency_curve,
)
from akkudoktoreos.devices.genetic.battery import Battery, SolarPanelBatteryParameters
from akkudoktoreos.devices.genetic.inverter import Inverter, InverterParameters
from akkudoktoreos.devices.settings.invertersettings import (
InverterCommonSettings,
InverterProfileAdjustment,
)
from akkudoktoreos.optimization.genetic import geneticprepare
from akkudoktoreos.optimization.genetic0 import genetic0prepare
from akkudoktoreos.optimization.genetic.genetic import GeneticSimulation
from akkudoktoreos.optimization.genetic.geneticparams import (
GeneticEnergyManagementParameters,
from akkudoktoreos.optimization.genetic.devices.geneticbattery import (
GeneticBattery,
)
from akkudoktoreos.optimization.genetic.tailvalue import build_tail_value_curve
from akkudoktoreos.optimization.genetic.terminalvalue import TerminalValueCurve
from akkudoktoreos.optimization.genetic.devices.geneticinverter import (
GeneticInverter,
)
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticBatteryRequest,
GeneticEnergyManagementRequest,
GeneticInverterRequest,
)
from akkudoktoreos.optimization.genetic.geneticsimulation import (
GeneticSimulation,
)
from akkudoktoreos.optimization.genetic.genetictailvalue import build_tail_value_curve
from akkudoktoreos.optimization.genetic.geneticterminalvalue import TerminalValueCurve
CURVE = [(0.05, 0.80), (0.20, 0.90), (0.50, 0.95), (1.0, 0.93)]
@@ -43,22 +52,22 @@ def _make_inverter(
battery=None,
dc_to_ac_efficiency: float = 1.0,
**kwargs,
) -> Inverter:
) -> GeneticInverter:
predictor = Mock()
predictor.calculate_expected_direct_consumption.side_effect = min
with patch(
"akkudoktoreos.devices.genetic.inverter.get_eos_load_interpolator",
"akkudoktoreos.optimization.genetic.devices.geneticinverter.get_genetic_load_interpolator",
return_value=predictor,
):
return Inverter(
InverterParameters(
return GeneticInverter(
GeneticInverterRequest(
device_id="inverter1",
max_power_wh=max_power_wh,
battery_id=battery.parameters.device_id if battery else None,
dc_to_ac_efficiency=dc_to_ac_efficiency,
dc_to_ac_efficiency_curve=curve,
**kwargs,
),
).to_parameters(),
battery=battery,
)
@@ -80,18 +89,18 @@ def _passthrough_battery() -> Mock:
class TestCurveValidation:
def test_none_is_allowed(self):
assert validate_efficiency_curve(None) is None
params = InverterParameters(device_id="inverter1", max_power_wh=1000)
params = GeneticInverterRequest(device_id="inverter1", max_power_wh=1000)
assert params.dc_to_ac_efficiency_curve is None
assert params.dc_to_ac_efficiency_reference_load_fraction == pytest.approx(0.06)
def test_valid_curve_is_accepted(self):
params = InverterParameters(
params = GeneticInverterRequest(
device_id="inverter1", max_power_wh=1000, dc_to_ac_efficiency_curve=CURVE
)
assert params.dc_to_ac_efficiency_curve == CURVE
def test_json_lists_are_accepted(self):
params = InverterParameters.model_validate(
params = GeneticInverterRequest.model_validate(
{
"device_id": "inverter1",
"max_power_wh": 1000,
@@ -116,14 +125,14 @@ class TestCurveValidation:
)
def test_invalid_curve_is_rejected(self, curve):
with pytest.raises(ValidationError):
InverterParameters(
GeneticInverterRequest(
device_id="inverter1", max_power_wh=1000, dc_to_ac_efficiency_curve=curve
)
@pytest.mark.parametrize("fraction", [-0.1, 1.1])
def test_reference_load_fraction_range(self, fraction):
with pytest.raises(ValidationError):
InverterParameters(
GeneticInverterRequest(
device_id="inverter1",
max_power_wh=1000,
dc_to_ac_efficiency_reference_load_fraction=fraction,
@@ -166,15 +175,15 @@ class TestInterpolation:
"""max_power_wh is scaled to the slot, so 250 Wh in 15 min is 1 kW."""
predictor = Mock()
with patch(
"akkudoktoreos.devices.genetic.inverter.get_eos_load_interpolator",
"akkudoktoreos.optimization.genetic.devices.geneticinverter.get_genetic_load_interpolator",
return_value=predictor,
):
inverter = Inverter(
InverterParameters(
inverter = GeneticInverter(
GeneticInverterRequest(
device_id="inverter1",
max_power_wh=5000.0,
dc_to_ac_efficiency_curve=CURVE,
),
).to_parameters(),
slot_duration_h=0.25,
)
# 1 kW of 5 kW -> load fraction 0.2
@@ -237,8 +246,8 @@ class TestProcessEnergyWithCurve:
def test_grid_export_uses_efficiency_at_export_level(self, config_eos):
"""A full-power export runs at the efficiency of the rated load."""
battery = Battery(
SolarPanelBatteryParameters(
battery = GeneticBattery(
GeneticBatteryRequest(
device_id="battery1",
capacity_wh=10000,
initial_soc_percentage=100,
@@ -246,7 +255,7 @@ class TestProcessEnergyWithCurve:
charging_efficiency=1.0,
discharging_efficiency=1.0,
max_charge_power_w=1000,
),
).to_parameters(),
prediction_hours=1,
)
battery.reset()
@@ -289,8 +298,8 @@ class TestReferenceEfficiency:
"""Stored energy is valued with the efficiency at the reference load."""
def tail_curve(efficiency_curve):
battery = Battery(
SolarPanelBatteryParameters(
battery = GeneticBattery(
GeneticBatteryRequest(
device_id="battery1",
capacity_wh=1000,
max_charge_power_w=1000,
@@ -298,16 +307,16 @@ class TestReferenceEfficiency:
discharging_efficiency=1.0,
initial_soc_percentage=50,
charge_rates=[0, 0.5, 1],
),
).to_parameters(),
prediction_hours=1,
)
inverter = Inverter(
InverterParameters(
inverter = GeneticInverter(
GeneticInverterRequest(
device_id="inverter1",
battery_id="battery1",
max_power_wh=5000,
dc_to_ac_efficiency_curve=efficiency_curve,
),
).to_parameters(),
battery=battery,
)
return build_tail_value_curve(
@@ -344,8 +353,8 @@ def _simulate(config_eos, efficiency_curve, dc_to_ac_efficiency=0.95):
"optimization": {"genetic": {"tail_horizon_hours": 0, "horizon_hours": hours}},
}
)
battery = Battery(
SolarPanelBatteryParameters(
battery = GeneticBattery(
GeneticBatteryRequest(
device_id="battery1",
capacity_wh=10000,
initial_soc_percentage=60,
@@ -353,25 +362,25 @@ def _simulate(config_eos, efficiency_curve, dc_to_ac_efficiency=0.95):
charging_efficiency=0.95,
discharging_efficiency=0.95,
max_charge_power_w=4000,
),
).to_parameters(),
prediction_hours=hours,
)
battery.reset()
inverter = Inverter(
InverterParameters(
inverter = GeneticInverter(
GeneticInverterRequest(
device_id="inverter1",
max_power_wh=5000,
battery_id="battery1",
dc_to_ac_efficiency=dc_to_ac_efficiency,
ac_to_dc_efficiency=0.95,
dc_to_ac_efficiency_curve=efficiency_curve,
),
).to_parameters(),
battery=battery,
)
rng = np.random.default_rng(42)
simulation = GeneticSimulation()
simulation.prepare(
GeneticEnergyManagementParameters.model_validate(
GeneticEnergyManagementRequest.model_validate(
dict(
pv_prognose_wh=list(np.maximum(rng.normal(1500, 1500, hours), 0.0)),
strompreis_euro_pro_wh=list(rng.uniform(0.0001, 0.0004, hours)),
@@ -379,7 +388,7 @@ def _simulate(config_eos, efficiency_curve, dc_to_ac_efficiency=0.95):
preis_euro_pro_wh_akku=0.0001,
gesamtlast=list(rng.uniform(100, 3000, hours)),
)
),
).to_parameters(),
optimization_hours=hours,
prediction_hours=hours,
inverter=inverter,
@@ -427,7 +436,7 @@ class TestSettings:
dc_to_ac_efficiency_reference_load_fraction=0.1,
)
profile = settings.get_inverter_profile()
params = settings.to_genetic_param()
params = geneticprepare.inverter_request(settings)
assert params.dc_to_ac_efficiency_curve is not None
# Not derated at 45 degC: the curve is the profile curve over [0, 1].
expected = list(zip(profile.dc_to_ac_efficiency.x, profile.dc_to_ac_efficiency.y))
@@ -464,9 +473,9 @@ def _real_battery(
max_power_w: float = 1000.0,
discharging_efficiency: float = 1.0,
slot_duration_h: float = 1.0,
) -> Battery:
battery = Battery(
SolarPanelBatteryParameters(
) -> GeneticBattery:
battery = GeneticBattery(
GeneticBatteryRequest(
device_id="battery1",
capacity_wh=capacity_wh,
initial_soc_percentage=soc_percentage,
@@ -474,7 +483,7 @@ def _real_battery(
charging_efficiency=1.0,
discharging_efficiency=discharging_efficiency,
max_charge_power_w=max_power_w,
),
).to_parameters(),
prediction_hours=1,
slot_duration_h=slot_duration_h,
)
@@ -483,21 +492,21 @@ def _real_battery(
return battery
def _real_inverter(battery: Battery, curve=None, slot_duration_h: float = 1.0, **kwargs) -> Inverter:
def _real_inverter(battery: GeneticBattery, curve=None, slot_duration_h: float = 1.0, **kwargs) -> GeneticInverter:
predictor = Mock()
predictor.calculate_expected_direct_consumption.side_effect = min
with patch(
"akkudoktoreos.devices.genetic.inverter.get_eos_load_interpolator",
"akkudoktoreos.optimization.genetic.devices.geneticinverter.get_genetic_load_interpolator",
return_value=predictor,
):
return Inverter(
InverterParameters(
return GeneticInverter(
GeneticInverterRequest(
device_id="inverter1",
max_power_wh=1000.0,
battery_id="battery1",
dc_to_ac_efficiency_curve=curve,
**kwargs,
),
).to_parameters(),
battery=battery,
slot_duration_h=slot_duration_h,
)
@@ -672,12 +681,12 @@ class TestSolveAcForChargeDcEnergy:
class TestChargeFromGridWithCurve:
def test_curve_is_validated(self):
with pytest.raises(ValidationError):
InverterParameters(
GeneticInverterRequest(
device_id="inverter1", max_power_wh=1000, ac_to_dc_efficiency_curve=[(0.5, 0.9)]
)
@staticmethod
def _empty_battery() -> Battery:
def _empty_battery() -> GeneticBattery:
battery = _real_battery(soc_percentage=0)
battery.charge_array = np.ones(1)
return battery
@@ -705,7 +714,7 @@ class TestChargeFromGridWithCurve:
profile_adjustment=InverterProfileAdjustment(nominal_power_w=5000),
)
profile = settings.get_inverter_profile()
params = settings.to_genetic_param()
params = geneticprepare.inverter_request(settings)
assert params.ac_to_dc_efficiency_curve is not None
assert [y for _, y in params.ac_to_dc_efficiency_curve] == pytest.approx(
list(profile.ac_to_dc_efficiency.y)
+6 -6
View File
@@ -1,16 +1,16 @@
import pytest
from akkudoktoreos.devices.genetic.heatpump import Heatpump
from akkudoktoreos.optimization.genetic.devices.geneticheatpump import GeneticHeatpump
@pytest.fixture(scope="function")
def hp_5kw_24h() -> Heatpump:
def hp_5kw_24h() -> GeneticHeatpump:
"""Heatpump with 5 kW heating power and 24 h prediction."""
return Heatpump(5000, 24)
return GeneticHeatpump(5000, 24)
class TestHeatpump:
def test_cop(self, hp_5kw_24h: Heatpump):
def test_cop(self, hp_5kw_24h: GeneticHeatpump):
"""Testing calculate COP for various outside temperatures."""
assert hp_5kw_24h.calculate_cop(-10) == 2.0
assert hp_5kw_24h.calculate_cop(0) == 3.0
@@ -23,13 +23,13 @@ class TestHeatpump:
with pytest.raises(ValueError, match=f"'{out_temp_max}' not in range"):
hp_5kw_24h.calculate_cop(out_temp_max)
def test_heating_output(self, hp_5kw_24h: Heatpump):
def test_heating_output(self, hp_5kw_24h: GeneticHeatpump):
"""Testing calculation of heating output."""
assert hp_5kw_24h.calculate_heating_output(-10.0) == 5000
assert hp_5kw_24h.calculate_heating_output(0.0) == 5000
assert hp_5kw_24h.calculate_heating_output(10.0) == pytest.approx(4939.583)
def test_heating_power(self, hp_5kw_24h: Heatpump):
def test_heating_power(self, hp_5kw_24h: GeneticHeatpump):
"""Testing calculation of heating power."""
assert hp_5kw_24h.calculate_heat_power(-10.0) == 2104
assert hp_5kw_24h.calculate_heat_power(0.0) == 1164
+7 -2
View File
@@ -104,9 +104,14 @@ def test_genetic0_inverter_keeps_its_independent_interpolator():
@pytest.mark.parametrize("load,pv", [(4000.0, 5000.0), (10000.0, 20000.0)])
def test_genetic_inverter_boundary_flows_remain_nonnegative(load, pv):
from akkudoktoreos.devices.genetic.inverter import Inverter, InverterParameters
from akkudoktoreos.optimization.genetic.devices.geneticinverter import (
GeneticInverter,
)
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticInverterRequest,
)
inverter = Inverter(InverterParameters(device_id="boundary", max_power_wh=25000))
inverter = GeneticInverter(GeneticInverterRequest(device_id="boundary", max_power_wh=25000).to_parameters())
flows = inverter.process_energy(generation=pv, consumption=load, hour=0)
assert all(np.isfinite(value) and value >= 0.0 for value in flows)
+31 -18
View File
@@ -6,17 +6,18 @@ from unittest.mock import Mock
import pytest
from akkudoktoreos.optimization.genetic import geneticprepare
from akkudoktoreos.optimization.genetic0.genetic0request import (
Genetic0EnergyManagementRequest,
)
from akkudoktoreos.optimization.genetic.geneticparams import (
GeneticEnergyManagementParameters,
from akkudoktoreos.optimization.genetic.geneticrequest import (
GeneticEnergyManagementRequest,
)
from akkudoktoreos.optimization.optimization import OptimizationAlgorithm
@pytest.mark.parametrize(
"model", [GeneticEnergyManagementParameters, Genetic0EnergyManagementRequest]
"model", [GeneticEnergyManagementRequest, Genetic0EnergyManagementRequest]
)
@pytest.mark.parametrize("tariff", [0.00008, [0.00008, -0.00002]])
def test_energy_parameter_aliases_preserve_wh_prices(model, tariff):
@@ -46,15 +47,12 @@ def test_energy_parameter_aliases_preserve_wh_prices(model, tariff):
@pytest.mark.asyncio
@pytest.mark.parametrize("algorithm", list(OptimizationAlgorithm))
async def test_algorithm_result_endpoint_keeps_solution_types_separate(monkeypatch, algorithm):
"""GENETIC is served by the generic route, GENETIC0 by its own router (ADR 0005)."""
"""Each optimizer serves its own solution from its router (ADR 0005, 0011)."""
from httpx import ASGITransport, AsyncClient
from akkudoktoreos.server import eos
fake = SimpleNamespace(
genetic_solution=Mock(return_value=None),
optimizer_run=Mock(return_value=None),
)
fake = SimpleNamespace(optimizer_run=Mock(return_value=None))
monkeypatch.setattr(eos, "get_ems", lambda: fake)
monkeypatch.setattr(
eos,
@@ -67,12 +65,27 @@ async def test_algorithm_result_endpoint_keeps_solution_types_separate(monkeypat
response = await client.get(f"/v1/energy-management/optimization/solution/{algorithm}")
assert response.status_code == 404
assert response.json()["title"] == "Algorithm specific optimization solution retrieval failed"
if algorithm == OptimizationAlgorithm.GENETIC:
fake.genetic_solution.assert_called_once_with()
fake.optimizer_run.assert_not_called()
else:
fake.optimizer_run.assert_called_once_with("GENETIC0")
fake.genetic_solution.assert_not_called()
fake.optimizer_run.assert_called_once_with(str(algorithm))
@pytest.mark.asyncio
@pytest.mark.parametrize("algorithm", ["genetic", "FOO"])
async def test_unknown_algorithm_solution_is_a_problem_response(algorithm):
"""An algorithm without its own solution endpoint gets a 404 problem response, not HTML."""
from httpx import ASGITransport, AsyncClient
from akkudoktoreos.server import eos
async with AsyncClient(
transport=ASGITransport(app=eos.app, raise_app_exceptions=False), base_url="http://test"
) as client:
response = await client.get(f"/v1/energy-management/optimization/solution/{algorithm}")
assert response.status_code == 404
assert response.headers["content-type"].startswith("application/problem+json")
problem = response.json()
assert problem["title"] == "Unknown optimization algorithm"
assert f"'{algorithm}' unknown" in problem["detail"]
assert "GENETIC0" in problem["detail"]
@pytest.mark.parametrize("algorithm", ["genetic", "genetic0"])
@@ -118,10 +131,10 @@ def test_device_maps_feed_algorithm_specific_converters(algorithm):
inverter = genetic0prepare.inverter_request(hybrid)
appliance = genetic0prepare.home_appliance_request(washer)
else:
battery = storage.to_genetic_pv_bat_param()
ev = car.to_genetic_ev_bat_param()
inverter = hybrid.to_genetic_param()
appliance = washer.to_genetic_param()
battery = geneticprepare.battery_request(storage)
ev = geneticprepare.electric_vehicle_request(car)
inverter = geneticprepare.inverter_request(hybrid)
appliance = geneticprepare.home_appliance_request(washer)
assert (battery.device_id, ev.device_id, inverter.device_id, appliance.device_id) == (
"storage",
"car",
+12 -259
View File
@@ -149,14 +149,22 @@ WORLD_NAMES: dict[str, frozenset[str]] = {
# Modules that mix the output contract or the public request schema with
# configuration or Pydantic: from them an optimizer imports only the listed
# names (ADR 0004, 0007): the solution, its DataFrame type, the operation-mode
# enums of the plan's instructions and the time windows of a request.
# enums of the plan's instructions, and the time windows and consumer schedule
# enums of a request.
CONTRACT_NAMES: dict[str, frozenset[str]] = {
"akkudoktoreos.optimization.optimization": frozenset({"OptimizationSolution"}),
"akkudoktoreos.core.pydantic": frozenset({"PydanticDateTimeDataFrame"}),
"akkudoktoreos.devices.devicesabc": frozenset(
{"ApplianceOperationMode", "BatteryOperationMode"}
{
"ApplianceOperationMode",
"BatteryOperationMode",
"ConsumerDeadlinePolicy",
"ConsumerScheduleMode",
}
),
"akkudoktoreos.config.configabc": frozenset(
{"TimeWindow", "TimeWindowSequence", "ValueTimeWindow", "CycleTimeWindowSequence"}
),
"akkudoktoreos.config.configabc": frozenset({"TimeWindow", "TimeWindowSequence"}),
}
# The roles that build the output or define the public schema, the only ones
# that may import the contract names of these modules; the parameters and the
@@ -374,261 +382,6 @@ def collect_violations() -> frozenset[Violation]:
# the existing uses revealed by a new list entry (ADR 0007).
BASELINE: frozenset[Violation] = frozenset(
{
Violation(
"internals",
"akkudoktoreos.config.configmigrate",
"akkudoktoreos.optimization.genetic.geneticsettings",
),
Violation(
"internals",
"akkudoktoreos.core.ems",
"akkudoktoreos.optimization.genetic.configrequest",
),
Violation(
"internals",
"akkudoktoreos.core.ems",
"akkudoktoreos.optimization.genetic.genetic",
),
Violation(
"internals",
"akkudoktoreos.core.ems",
"akkudoktoreos.optimization.genetic.geneticparams",
),
Violation(
"internals",
"akkudoktoreos.core.ems",
"akkudoktoreos.optimization.genetic.geneticsolution",
),
Violation(
"internals",
"akkudoktoreos.optimization.optimization",
"akkudoktoreos.optimization.genetic.geneticsettings",
),
Violation(
"internals",
"akkudoktoreos.server.eos",
"akkudoktoreos.optimization.genetic.configrequest",
),
Violation(
"internals",
"akkudoktoreos.server.eos",
"akkudoktoreos.optimization.genetic.geneticsolution",
),
Violation(
"internals",
"akkudoktoreos.server.eos",
"akkudoktoreos.optimization.genetic.geneticvisualize",
),
Violation(
"pydantic",
"akkudoktoreos.devices.genetic.battery",
"pydantic",
),
Violation(
"pydantic",
"akkudoktoreos.devices.genetic.homeappliance",
"pydantic",
),
Violation(
"pydantic",
"akkudoktoreos.devices.genetic.inverter",
"pydantic",
),
Violation(
"pydantic",
"akkudoktoreos.optimization.genetic.configrequest",
"pydantic",
),
Violation(
"pydantic",
"akkudoktoreos.optimization.genetic.genetic",
"akkudoktoreos.core.pydantic",
),
Violation(
"pydantic",
"akkudoktoreos.optimization.genetic.genetic",
"pydantic",
),
Violation(
"pydantic",
"akkudoktoreos.optimization.genetic.geneticabc",
"akkudoktoreos.core.pydantic",
),
Violation(
"pydantic",
"akkudoktoreos.optimization.genetic.geneticabc",
"pydantic",
),
Violation(
"pydantic",
"akkudoktoreos.optimization.genetic.geneticdevices",
"pydantic",
),
Violation(
"pydantic",
"akkudoktoreos.optimization.genetic.geneticparams",
"pydantic",
),
Violation(
"pydantic",
"akkudoktoreos.optimization.genetic.geneticsolution",
"akkudoktoreos.core.pydantic",
),
Violation(
"pydantic",
"akkudoktoreos.optimization.genetic.geneticsolution",
"pydantic",
),
Violation(
"pydantic",
"akkudoktoreos.optimization.genetic.tailvalue",
"pydantic",
),
Violation(
"pydantic",
"akkudoktoreos.optimization.genetic.terminalvalue",
"akkudoktoreos.core.pydantic",
),
Violation(
"pydantic",
"akkudoktoreos.optimization.genetic.terminalvalue",
"pydantic",
),
Violation(
"shared-config",
"akkudoktoreos.devices.settings.batterysettings",
"akkudoktoreos.devices.genetic.battery",
),
Violation(
"shared-config",
"akkudoktoreos.devices.settings.homeappliancesettings",
"akkudoktoreos.devices.genetic.homeappliance",
),
Violation(
"shared-config",
"akkudoktoreos.devices.settings.invertersettings",
"akkudoktoreos.devices.genetic.inverter",
),
Violation(
"world-access",
"akkudoktoreos.devices.genetic.battery",
"akkudoktoreos.devices.devicesabc",
),
Violation(
"world-access",
"akkudoktoreos.devices.genetic.battery",
"akkudoktoreos.devices.settings.batteryresolution",
),
Violation(
"world-access",
"akkudoktoreos.devices.genetic.battery",
"akkudoktoreos.devices.settings.batterysettings",
),
Violation(
"world-access",
"akkudoktoreos.devices.genetic.homeappliance",
"akkudoktoreos.config.configabc",
),
Violation(
"world-access",
"akkudoktoreos.devices.genetic.homeappliance",
"akkudoktoreos.devices.devicesabc",
),
Violation(
"world-access",
"akkudoktoreos.devices.genetic.inverter",
"akkudoktoreos.devices.devicesabc",
),
Violation(
"world-access",
"akkudoktoreos.devices.genetic.inverter",
"akkudoktoreos.prediction.interpolator",
),
Violation(
"world-access",
"akkudoktoreos.optimization.genetic.configrequest",
"akkudoktoreos.core.coreabc:ConfigMixin",
),
Violation(
"world-access",
"akkudoktoreos.optimization.genetic.configrequest",
"akkudoktoreos.core.coreabc:MeasurementMixin",
),
Violation(
"world-access",
"akkudoktoreos.optimization.genetic.configrequest",
"akkudoktoreos.core.coreabc:PredictionMixin",
),
Violation(
"world-access",
"akkudoktoreos.optimization.genetic.configrequest",
"akkudoktoreos.core.coreabc:get_ems",
),
Violation(
"world-access",
"akkudoktoreos.optimization.genetic.configrequest",
"akkudoktoreos.devices.settings.batteryresolution",
),
Violation(
"world-access",
"akkudoktoreos.optimization.genetic.configrequest",
"akkudoktoreos.devices.settings.batterysettings",
),
Violation(
"world-access",
"akkudoktoreos.optimization.genetic.genetic",
"akkudoktoreos.devices.devicesabc",
),
Violation(
"world-access",
"akkudoktoreos.optimization.genetic.genetic",
"akkudoktoreos.optimization.optimizationabc:OptimizationBase",
),
Violation(
"world-access",
"akkudoktoreos.optimization.genetic.geneticparams",
"akkudoktoreos.core.coreabc:ConfigMixin",
),
Violation(
"world-access",
"akkudoktoreos.optimization.genetic.geneticparams",
"akkudoktoreos.core.coreabc:MeasurementMixin",
),
Violation(
"world-access",
"akkudoktoreos.optimization.genetic.geneticparams",
"akkudoktoreos.core.coreabc:PredictionMixin",
),
Violation(
"world-access",
"akkudoktoreos.optimization.genetic.geneticsolution",
"akkudoktoreos.core.coreabc:ConfigMixin",
),
Violation(
"world-access",
"akkudoktoreos.optimization.genetic.geneticsolution",
"akkudoktoreos.core.coreabc:get_ems",
),
Violation(
"world-access",
"akkudoktoreos.optimization.genetic.geneticsolution",
"akkudoktoreos.core.coreabc:get_prediction",
),
Violation(
"world-access",
"akkudoktoreos.optimization.genetic.geneticsolution",
"akkudoktoreos.devices.devicesabc",
),
Violation(
"world-access",
"akkudoktoreos.optimization.genetic.geneticvisualize",
"akkudoktoreos.core.coreabc:ConfigMixin",
),
Violation(
"world-access",
"akkudoktoreos.optimization.genetic.geneticvisualize",
"akkudoktoreos.core.coreabc:get_ems",
),
}
)
@@ -1030,7 +783,7 @@ class TestOptimizerArchitecture:
),
(
"from akkudoktoreos.devices.devicesabc import BatteryOperationMode, "
"ConsumerScheduleMode\n",
"validate_efficiency_curve\n",
Violation(
"world-access",
"akkudoktoreos.optimization.alpha.alphaconvert",
+33 -3
View File
@@ -2,14 +2,19 @@
import pytest
from akkudoktoreos.config.config import ConfigEOS
from akkudoktoreos.optimization.optimization import OptimizationAlgorithm
from akkudoktoreos.optimization.optimizerregistry import get_optimizer
from akkudoktoreos.optimization.optimizer import RunClock
from akkudoktoreos.optimization.optimizerregistry import get_optimizer, optimizer_names
class TestOptimizerRegistry:
"""Finding optimizers by name."""
@pytest.mark.parametrize("name", ["GENETIC0"])
def test_every_algorithm_is_registered(self) -> None:
assert sorted(optimizer_names()) == sorted(OptimizationAlgorithm)
@pytest.mark.parametrize("name", ["GENETIC", "GENETIC0"])
def test_registered_optimizer_carries_its_name(self, name: str) -> None:
optimizer = get_optimizer(name)
assert optimizer is not None
@@ -20,6 +25,31 @@ class TestOptimizerRegistry:
def test_algorithm_enum_finds_the_same_optimizer(self) -> None:
assert get_optimizer(OptimizationAlgorithm.GENETIC0) is get_optimizer("GENETIC0")
@pytest.mark.parametrize("name", ["UNKNOWN", "", "genetic0"])
@pytest.mark.parametrize("name", ["UNKNOWN", "", "genetic", "genetic0"])
def test_unregistered_name_gives_none(self, name: str) -> None:
assert get_optimizer(name) is None
class TestRunClock:
"""The slot length and time zone the energy management starts a run in (ADR 0006)."""
@pytest.mark.parametrize("interval", [900, 3600])
def test_genetic_follows_its_slot_setting_and_the_site_time_zone(
self, config_eos: ConfigEOS, interval: int
) -> None:
config_eos.merge_settings_from_dict(
{
"general": {"timezone_override": "America/New_York"},
"optimization": {"genetic": {"interval_sec": interval}},
}
)
optimizer = get_optimizer("GENETIC")
assert optimizer is not None
assert optimizer.run_clock() == RunClock(
slot_seconds=interval, timezone="America/New_York"
)
def test_genetic0_runs_hourly_in_server_time(self) -> None:
optimizer = get_optimizer("GENETIC0")
assert optimizer is not None
assert optimizer.run_clock() == RunClock(slot_seconds=3600, timezone=None)
+1 -1
View File
@@ -6,7 +6,7 @@ import pendulum
import pytest
import requests
from akkudoktoreos.optimization.genetic.forecast import bounded_forecast_array
from akkudoktoreos.optimization.genetic.geneticforecast import bounded_forecast_array
from akkudoktoreos.prediction.pvforecastforecastsolar import PVForecastForecastSolar
from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration
+1 -1
View File
@@ -5,7 +5,7 @@ from typing import Any
import numpy as np
import pytest
from akkudoktoreos.optimization.genetic.terminalvalue import (
from akkudoktoreos.optimization.genetic.geneticterminalvalue import (
build_terminal_value_curve,
trailing_window,
)
File diff suppressed because it is too large Load Diff
+99
View File
@@ -0,0 +1,99 @@
{
"id": "plan-genetic@<now>",
"generated_at": "<now>",
"valid_from": "2026-09-16T10:00:00+02:00",
"valid_until": null,
"instructions": [
{
"id": "battery1@<now>",
"execution_time": "2026-09-16T10:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-16T10:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-16T13:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-17T06:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-17T07:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-17T09:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-17T17:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-17T19:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-17T22:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
}
],
"comment": "Energy management plan derived from GeneticSolution."
}
File diff suppressed because it is too large Load Diff
+99
View File
@@ -0,0 +1,99 @@
{
"id": "plan-genetic@<now>",
"generated_at": "<now>",
"valid_from": "2026-09-16T10:15:00+02:00",
"valid_until": null,
"instructions": [
{
"id": "battery1@<now>",
"execution_time": "2026-09-16T10:15:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-16T10:15:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-16T12:45:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-16T13:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-16T15:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-16T19:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-16T21:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-17T00:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-17T09:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
}
],
"comment": "Energy management plan derived from GeneticSolution."
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+299
View File
@@ -0,0 +1,299 @@
{
"id": "plan-genetic@<now>",
"generated_at": "<now>",
"valid_from": "2026-03-28T10:00:00+01:00",
"valid_until": null,
"instructions": [
{
"id": "battery1@<now>",
"execution_time": "2026-03-28T10:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-03-28T10:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "ev1"
},
{
"id": "dishwasher1@<now>",
"execution_time": "2026-03-28T10:00:00+01:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "dishwasher1",
"operation_mode_id": "OFF",
"operation_mode_factor": 1.0,
"resource_id": "dishwasher1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-03-28T11:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-03-28T11:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.375,
"resource_id": "ev1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-03-28T12:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-03-28T12:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "dishwasher1@<now>",
"execution_time": "2026-03-28T12:00:00+01:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "dishwasher1",
"operation_mode_id": "RUN",
"operation_mode_factor": 1.0,
"resource_id": "dishwasher1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-03-28T13:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.625,
"resource_id": "ev1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-03-28T14:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.875,
"resource_id": "ev1"
},
{
"id": "dishwasher1@<now>",
"execution_time": "2026-03-28T14:00:00+01:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "dishwasher1",
"operation_mode_id": "OFF",
"operation_mode_factor": 1.0,
"resource_id": "dishwasher1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-03-28T15:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "ev1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-03-28T16:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-03-28T17:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.625,
"resource_id": "ev1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-03-28T18:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-03-28T18:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.375,
"resource_id": "ev1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-03-28T19:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.625,
"resource_id": "ev1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-03-28T20:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.375,
"resource_id": "ev1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-03-28T21:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-03-28T21:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-03-28T22:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.875,
"resource_id": "ev1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-03-28T23:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-03-29T01:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-03-29T04:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-03-29T05:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-03-29T06:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-03-29T20:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-03-29T22:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-03-30T00:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
}
],
"comment": "Energy management plan derived from GeneticSolution."
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+259
View File
@@ -0,0 +1,259 @@
{
"id": "plan-genetic@<now>",
"generated_at": "<now>",
"valid_from": "2026-09-16T10:00:00+02:00",
"valid_until": null,
"instructions": [
{
"id": "battery1@<now>",
"execution_time": "2026-09-16T10:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-16T10:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "dishwasher1@<now>",
"execution_time": "2026-09-16T10:00:00+02:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "dishwasher1",
"operation_mode_id": "OFF",
"operation_mode_factor": 1.0,
"resource_id": "dishwasher1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-16T11:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-16T12:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-16T12:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "ev1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-16T13:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-16T13:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.625,
"resource_id": "ev1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-16T14:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.375,
"resource_id": "ev1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-16T15:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.875,
"resource_id": "ev1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-16T16:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-16T17:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-16T17:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "ev1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-16T18:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.375,
"resource_id": "ev1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-16T19:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-17T10:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-17T12:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.375,
"resource_id": "ev1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-17T13:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-17T14:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.375,
"resource_id": "ev1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-17T15:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "dishwasher1@<now>",
"execution_time": "2026-09-17T16:00:00+02:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "dishwasher1",
"operation_mode_id": "RUN",
"operation_mode_factor": 1.0,
"resource_id": "dishwasher1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-17T18:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "dishwasher1@<now>",
"execution_time": "2026-09-17T18:00:00+02:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "dishwasher1",
"operation_mode_id": "OFF",
"operation_mode_factor": 1.0,
"resource_id": "dishwasher1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-17T21:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.375,
"resource_id": "ev1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-17T22:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
}
],
"comment": "Energy management plan derived from GeneticSolution."
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+299
View File
@@ -0,0 +1,299 @@
{
"id": "plan-genetic@<now>",
"generated_at": "<now>",
"valid_from": "2026-09-16T10:00:00+02:00",
"valid_until": null,
"instructions": [
{
"id": "battery1@<now>",
"execution_time": "2026-09-16T10:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-16T10:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "ev1"
},
{
"id": "dishwasher1@<now>",
"execution_time": "2026-09-16T10:00:00+02:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "dishwasher1",
"operation_mode_id": "OFF",
"operation_mode_factor": 1.0,
"resource_id": "dishwasher1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-16T11:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-16T11:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.375,
"resource_id": "ev1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-16T12:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-16T12:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "dishwasher1@<now>",
"execution_time": "2026-09-16T12:00:00+02:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "dishwasher1",
"operation_mode_id": "RUN",
"operation_mode_factor": 1.0,
"resource_id": "dishwasher1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-16T13:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.625,
"resource_id": "ev1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-16T14:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.875,
"resource_id": "ev1"
},
{
"id": "dishwasher1@<now>",
"execution_time": "2026-09-16T14:00:00+02:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "dishwasher1",
"operation_mode_id": "OFF",
"operation_mode_factor": 1.0,
"resource_id": "dishwasher1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-16T15:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "ev1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-16T16:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-16T17:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.625,
"resource_id": "ev1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-16T18:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-16T18:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.375,
"resource_id": "ev1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-16T19:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.625,
"resource_id": "ev1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-16T20:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.375,
"resource_id": "ev1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-16T21:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-16T21:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-16T22:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.875,
"resource_id": "ev1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-16T23:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-17T01:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-17T03:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-17T04:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-17T05:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-17T19:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-17T21:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-17T23:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
}
],
"comment": "Energy management plan derived from GeneticSolution."
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+239
View File
@@ -0,0 +1,239 @@
{
"id": "plan-genetic@<now>",
"generated_at": "<now>",
"valid_from": "2026-09-16T10:00:00+02:00",
"valid_until": null,
"instructions": [
{
"id": "battery1@<now>",
"execution_time": "2026-09-16T10:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-16T10:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.75,
"resource_id": "ev1"
},
{
"id": "dishwasher1@<now>",
"execution_time": "2026-09-16T10:00:00+02:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "dishwasher1",
"operation_mode_id": "OFF",
"operation_mode_factor": 1.0,
"resource_id": "dishwasher1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-16T11:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-16T12:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "FORCED_CHARGE",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-16T13:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-16T13:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.375,
"resource_id": "ev1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-16T14:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-16T15:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "FORCED_CHARGE",
"operation_mode_factor": 0.36480744397939074,
"resource_id": "battery1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-16T15:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.375,
"resource_id": "ev1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-16T16:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-16T16:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-16T17:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-16T17:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.875,
"resource_id": "ev1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-16T18:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<now>",
"execution_time": "2026-09-16T18:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-16T19:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "dishwasher1@<now>",
"execution_time": "2026-09-17T03:00:00+02:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "dishwasher1",
"operation_mode_id": "RUN",
"operation_mode_factor": 1.0,
"resource_id": "dishwasher1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-17T05:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "dishwasher1@<now>",
"execution_time": "2026-09-17T05:00:00+02:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "dishwasher1",
"operation_mode_id": "OFF",
"operation_mode_factor": 1.0,
"resource_id": "dishwasher1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-17T06:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-17T08:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<now>",
"execution_time": "2026-09-17T09:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
}
],
"comment": "Energy management plan derived from GeneticSolution."
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+169
View File
@@ -0,0 +1,169 @@
{
"id": "plan-genetic@<now>",
"generated_at": "<now>",
"valid_from": "2026-03-28T10:00:00+01:00",
"valid_until": null,
"instructions": [
{
"id": "storage@<now>",
"execution_time": "2026-03-28T10:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "storage"
},
{
"id": "car@<now>",
"execution_time": "2026-03-28T10:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "car",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "car"
},
{
"id": "dishwasher@<now>",
"execution_time": "2026-03-28T10:00:00+01:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "dishwasher",
"operation_mode_id": "OFF",
"operation_mode_factor": 1.0,
"resource_id": "dishwasher"
},
{
"id": "storage@<now>",
"execution_time": "2026-03-28T11:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "storage"
},
{
"id": "storage@<now>",
"execution_time": "2026-03-28T12:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "storage"
},
{
"id": "car@<now>",
"execution_time": "2026-03-28T12:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "car",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "car"
},
{
"id": "storage@<now>",
"execution_time": "2026-03-28T13:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "FORCED_CHARGE",
"operation_mode_factor": 0.3000168834799237,
"resource_id": "storage"
},
{
"id": "car@<now>",
"execution_time": "2026-03-28T13:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "car",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "car"
},
{
"id": "storage@<now>",
"execution_time": "2026-03-28T14:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "storage"
},
{
"id": "car@<now>",
"execution_time": "2026-03-28T16:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "car",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 1.0,
"resource_id": "car"
},
{
"id": "dishwasher@<now>",
"execution_time": "2026-03-28T16:00:00+01:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "dishwasher",
"operation_mode_id": "RUN",
"operation_mode_factor": 1.0,
"resource_id": "dishwasher"
},
{
"id": "car@<now>",
"execution_time": "2026-03-28T17:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "car",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "car"
},
{
"id": "dishwasher@<now>",
"execution_time": "2026-03-28T18:00:00+01:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "dishwasher",
"operation_mode_id": "OFF",
"operation_mode_factor": 1.0,
"resource_id": "dishwasher"
},
{
"id": "storage@<now>",
"execution_time": "2026-03-29T04:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "storage"
},
{
"id": "storage@<now>",
"execution_time": "2026-03-29T08:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "storage"
},
{
"id": "storage@<now>",
"execution_time": "2026-03-29T09:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "storage"
}
],
"comment": "Energy management plan derived from GeneticSolution."
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+179
View File
@@ -0,0 +1,179 @@
{
"id": "plan-genetic@<now>",
"generated_at": "<now>",
"valid_from": "2026-09-16T10:00:00+02:00",
"valid_until": null,
"instructions": [
{
"id": "storage@<now>",
"execution_time": "2026-09-16T10:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "storage"
},
{
"id": "car@<now>",
"execution_time": "2026-09-16T10:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "car",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "car"
},
{
"id": "dishwasher@<now>",
"execution_time": "2026-09-16T10:00:00+02:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "dishwasher",
"operation_mode_id": "OFF",
"operation_mode_factor": 1.0,
"resource_id": "dishwasher"
},
{
"id": "storage@<now>",
"execution_time": "2026-09-16T11:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "storage"
},
{
"id": "storage@<now>",
"execution_time": "2026-09-16T12:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "storage"
},
{
"id": "car@<now>",
"execution_time": "2026-09-16T13:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "car",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "car"
},
{
"id": "car@<now>",
"execution_time": "2026-09-16T14:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "car",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 1.0,
"resource_id": "car"
},
{
"id": "storage@<now>",
"execution_time": "2026-09-16T15:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "storage"
},
{
"id": "car@<now>",
"execution_time": "2026-09-16T15:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "car",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "car"
},
{
"id": "storage@<now>",
"execution_time": "2026-09-16T18:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "storage"
},
{
"id": "dishwasher@<now>",
"execution_time": "2026-09-16T18:00:00+02:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "dishwasher",
"operation_mode_id": "RUN",
"operation_mode_factor": 1.0,
"resource_id": "dishwasher"
},
{
"id": "dishwasher@<now>",
"execution_time": "2026-09-16T20:00:00+02:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "dishwasher",
"operation_mode_id": "OFF",
"operation_mode_factor": 1.0,
"resource_id": "dishwasher"
},
{
"id": "storage@<now>",
"execution_time": "2026-09-16T22:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "storage"
},
{
"id": "storage@<now>",
"execution_time": "2026-09-16T23:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "storage"
},
{
"id": "storage@<now>",
"execution_time": "2026-09-17T01:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "storage"
},
{
"id": "storage@<now>",
"execution_time": "2026-09-17T02:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "storage"
},
{
"id": "storage@<now>",
"execution_time": "2026-09-17T09:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "storage"
}
],
"comment": "Energy management plan derived from GeneticSolution."
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+299
View File
@@ -0,0 +1,299 @@
{
"id": "plan-genetic@<now>",
"generated_at": "<now>",
"valid_from": "2026-09-16T10:15:00+02:00",
"valid_until": null,
"instructions": [
{
"id": "storage@<now>",
"execution_time": "2026-09-16T10:15:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "storage"
},
{
"id": "car@<now>",
"execution_time": "2026-09-16T10:15:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "car",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "car"
},
{
"id": "dishwasher@<now>",
"execution_time": "2026-09-16T10:15:00+02:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "dishwasher",
"operation_mode_id": "OFF",
"operation_mode_factor": 1.0,
"resource_id": "dishwasher"
},
{
"id": "car@<now>",
"execution_time": "2026-09-16T11:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "car",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 1.0,
"resource_id": "car"
},
{
"id": "car@<now>",
"execution_time": "2026-09-16T11:15:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "car",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "car"
},
{
"id": "car@<now>",
"execution_time": "2026-09-16T11:45:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "car",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "car"
},
{
"id": "storage@<now>",
"execution_time": "2026-09-16T12:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "storage"
},
{
"id": "storage@<now>",
"execution_time": "2026-09-16T12:15:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "storage"
},
{
"id": "car@<now>",
"execution_time": "2026-09-16T12:15:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "car",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 1.0,
"resource_id": "car"
},
{
"id": "car@<now>",
"execution_time": "2026-09-16T12:45:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "car",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "car"
},
{
"id": "storage@<now>",
"execution_time": "2026-09-16T13:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "FORCED_CHARGE",
"operation_mode_factor": 1.0,
"resource_id": "storage"
},
{
"id": "car@<now>",
"execution_time": "2026-09-16T13:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "car",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "car"
},
{
"id": "storage@<now>",
"execution_time": "2026-09-16T13:15:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "storage"
},
{
"id": "car@<now>",
"execution_time": "2026-09-16T13:30:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "car",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "car"
},
{
"id": "storage@<now>",
"execution_time": "2026-09-16T13:45:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "storage"
},
{
"id": "car@<now>",
"execution_time": "2026-09-16T13:45:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "car",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "car"
},
{
"id": "car@<now>",
"execution_time": "2026-09-16T14:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "car",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "car"
},
{
"id": "car@<now>",
"execution_time": "2026-09-16T14:15:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "car",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 1.0,
"resource_id": "car"
},
{
"id": "car@<now>",
"execution_time": "2026-09-16T14:45:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "car",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "car"
},
{
"id": "car@<now>",
"execution_time": "2026-09-16T15:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "car",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "car"
},
{
"id": "storage@<now>",
"execution_time": "2026-09-16T16:30:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "storage"
},
{
"id": "storage@<now>",
"execution_time": "2026-09-16T19:15:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "storage"
},
{
"id": "storage@<now>",
"execution_time": "2026-09-16T19:30:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "storage"
},
{
"id": "dishwasher@<now>",
"execution_time": "2026-09-16T19:30:00+02:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "dishwasher",
"operation_mode_id": "RUN",
"operation_mode_factor": 1.0,
"resource_id": "dishwasher"
},
{
"id": "storage@<now>",
"execution_time": "2026-09-16T20:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "storage"
},
{
"id": "storage@<now>",
"execution_time": "2026-09-16T20:30:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "storage"
},
{
"id": "storage@<now>",
"execution_time": "2026-09-16T20:45:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "storage"
},
{
"id": "dishwasher@<now>",
"execution_time": "2026-09-16T21:30:00+02:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "dishwasher",
"operation_mode_id": "OFF",
"operation_mode_factor": 1.0,
"resource_id": "dishwasher"
},
{
"id": "storage@<now>",
"execution_time": "2026-09-17T02:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "storage"
}
],
"comment": "Energy management plan derived from GeneticSolution."
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+159
View File
@@ -0,0 +1,159 @@
{
"id": "plan-genetic@<now>",
"generated_at": "<now>",
"valid_from": "2026-09-16T10:00:00+02:00",
"valid_until": null,
"instructions": [
{
"id": "storage@<now>",
"execution_time": "2026-09-16T10:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "storage"
},
{
"id": "car@<now>",
"execution_time": "2026-09-16T10:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "car",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "car"
},
{
"id": "dishwasher@<now>",
"execution_time": "2026-09-16T10:00:00+02:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "dishwasher",
"operation_mode_id": "RUN",
"operation_mode_factor": 1.0,
"resource_id": "dishwasher"
},
{
"id": "storage@<now>",
"execution_time": "2026-09-16T11:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "storage"
},
{
"id": "car@<now>",
"execution_time": "2026-09-16T12:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "car",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "car"
},
{
"id": "dishwasher@<now>",
"execution_time": "2026-09-16T12:00:00+02:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "dishwasher",
"operation_mode_id": "OFF",
"operation_mode_factor": 1.0,
"resource_id": "dishwasher"
},
{
"id": "car@<now>",
"execution_time": "2026-09-16T13:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "car",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "car"
},
{
"id": "car@<now>",
"execution_time": "2026-09-16T18:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "car",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "car"
},
{
"id": "car@<now>",
"execution_time": "2026-09-16T19:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "car",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "car"
},
{
"id": "storage@<now>",
"execution_time": "2026-09-17T02:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "storage"
},
{
"id": "car@<now>",
"execution_time": "2026-09-17T04:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "car",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "car"
},
{
"id": "car@<now>",
"execution_time": "2026-09-17T05:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "car",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "car"
},
{
"id": "storage@<now>",
"execution_time": "2026-09-17T07:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "storage"
},
{
"id": "storage@<now>",
"execution_time": "2026-09-17T08:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "storage"
},
{
"id": "storage@<now>",
"execution_time": "2026-09-17T09:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "storage",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "storage"
}
],
"comment": "Energy management plan derived from GeneticSolution."
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+705
View File
@@ -0,0 +1,705 @@
{
"expected_result": "golden_1_result.json",
"parameters": {
"request": {
"ems": {
"pv_forecast_wh": [
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
8.05,
352.91,
728.51,
930.28,
1043.25,
1106.74,
1161.69,
6018.82,
5519.07,
3969.88,
3017.96,
1943.07,
1007.17,
319.67,
7.88,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
5.04,
335.59,
705.32,
1121.12,
1604.79,
2157.38,
1433.25,
5718.49,
4553.96,
3027.55,
2574.46,
1720.4,
963.4,
383.3,
0.0,
0.0,
0.0
],
"electricity_price_per_wh": [
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278,
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278
],
"feed_in_tariff_per_wh": [
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05
],
"price_per_wh_battery": 0.0001,
"total_load": [
676.71,
876.19,
527.13,
468.88,
531.38,
517.95,
483.15,
472.28,
1011.68,
995.0,
1053.07,
1063.91,
1320.56,
1132.03,
1163.67,
1176.82,
1216.22,
1103.78,
1129.12,
1178.71,
1050.98,
988.56,
912.38,
704.61,
516.37,
868.05,
694.34,
608.79,
556.31,
488.89,
506.91,
804.89,
1141.98,
1056.97,
992.46,
1155.99,
827.01,
1257.98,
1232.67,
871.26,
860.88,
1158.03,
1222.72,
1221.04,
949.99,
987.01,
733.99,
592.97
],
"pv_prognose_wh": [
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
8.05,
352.91,
728.51,
930.28,
1043.25,
1106.74,
1161.69,
6018.82,
5519.07,
3969.88,
3017.96,
1943.07,
1007.17,
319.67,
7.88,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
5.04,
335.59,
705.32,
1121.12,
1604.79,
2157.38,
1433.25,
5718.49,
4553.96,
3027.55,
2574.46,
1720.4,
963.4,
383.3,
0.0,
0.0,
0.0
],
"strompreis_euro_pro_wh": [
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278,
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278
],
"einspeiseverguetung_euro_pro_wh": [
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05
],
"preis_euro_pro_wh_akku": 0.0001,
"gesamtlast": [
676.71,
876.19,
527.13,
468.88,
531.38,
517.95,
483.15,
472.28,
1011.68,
995.0,
1053.07,
1063.91,
1320.56,
1132.03,
1163.67,
1176.82,
1216.22,
1103.78,
1129.12,
1178.71,
1050.98,
988.56,
912.38,
704.61,
516.37,
868.05,
694.34,
608.79,
556.31,
488.89,
506.91,
804.89,
1141.98,
1056.97,
992.46,
1155.99,
827.01,
1257.98,
1232.67,
871.26,
860.88,
1158.03,
1222.72,
1221.04,
949.99,
987.01,
733.99,
592.97
]
},
"pv_battery": {
"device_id": "battery1",
"hours": null,
"capacity_wh": 26400,
"charging_efficiency": 0.88,
"discharging_efficiency": 0.88,
"max_charge_power_w": 5000.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 80,
"min_soc_percentage": 15,
"max_soc_percentage": 100,
"charge_rates": null,
"grid_export_rates": null,
"charge_power_limit_w_by_soc": null,
"discharge_power_limit_w_by_soc": null,
"charging_efficiency_curve": null,
"discharging_efficiency_curve": null,
"levelized_cost_of_storage_kwh": 0.0,
"full_charge_soc_percentage": null,
"full_charge_deadline_datetime": null
},
"inverter": {
"device_id": "inverter1",
"hours": null,
"max_power_wh": 10000.0,
"battery_id": "battery1",
"ac_to_dc_efficiency": 1.0,
"dc_to_ac_efficiency": 1.0,
"dc_to_ac_efficiency_curve": null,
"dc_to_ac_efficiency_reference_load_fraction": 0.06,
"ac_to_dc_efficiency_curve": null,
"max_ac_charge_power_w": null,
"ac_charge_limits_total_charge": false
},
"ev": {
"device_id": "ev1",
"hours": null,
"capacity_wh": 60000,
"charging_efficiency": 0.95,
"discharging_efficiency": 1.0,
"max_charge_power_w": 11040.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 54,
"min_soc_percentage": 0,
"max_soc_percentage": 100,
"charge_rates": null,
"grid_export_rates": null,
"charge_power_limit_w_by_soc": null,
"discharge_power_limit_w_by_soc": null,
"charging_efficiency_curve": null,
"discharging_efficiency_curve": null,
"min_soc_deadline_datetime": null,
"min_soc_max_duration_h": null
},
"dishwasher": null,
"temperature_forecast": [
18.3,
17.8,
16.9,
16.2,
15.6,
15.1,
14.6,
14.2,
14.3,
14.8,
15.7,
16.7,
17.4,
18.0,
18.6,
19.2,
19.1,
18.7,
18.5,
17.7,
16.2,
14.6,
13.6,
13.0,
12.6,
12.2,
11.7,
11.6,
11.3,
11.0,
10.7,
10.2,
11.4,
14.4,
16.4,
18.3,
19.5,
20.7,
21.9,
22.7,
23.1,
23.1,
22.8,
21.8,
20.2,
19.1,
18.0,
17.4
],
"start_solution": [
1.0,
1.0,
1.0,
1.0,
0.0,
1.0,
0.0,
0.0,
1.0,
1.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
0.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0
],
"forecast_interval_seconds": null,
"home_appliances": null,
"start_solution_datetime": null,
"pv_akku": {
"device_id": "battery1",
"hours": null,
"capacity_wh": 26400,
"charging_efficiency": 0.88,
"discharging_efficiency": 0.88,
"max_charge_power_w": 5000.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 80,
"min_soc_percentage": 15,
"max_soc_percentage": 100,
"charge_rates": null,
"grid_export_rates": null,
"charge_power_limit_w_by_soc": null,
"discharge_power_limit_w_by_soc": null,
"charging_efficiency_curve": null,
"discharging_efficiency_curve": null,
"levelized_cost_of_storage_kwh": 0.0,
"full_charge_soc_percentage": null,
"full_charge_deadline_datetime": null
},
"eauto": {
"device_id": "ev1",
"hours": null,
"capacity_wh": 60000,
"charging_efficiency": 0.95,
"discharging_efficiency": 1.0,
"max_charge_power_w": 11040.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 54,
"min_soc_percentage": 0,
"max_soc_percentage": 100,
"charge_rates": null,
"grid_export_rates": null,
"charge_power_limit_w_by_soc": null,
"discharge_power_limit_w_by_soc": null,
"charging_efficiency_curve": null,
"discharging_efficiency_curve": null,
"min_soc_deadline_datetime": null,
"min_soc_max_duration_h": null
}
},
"start_hour": 10,
"settings": {
"interval_sec": 3600,
"horizon_hours": 38,
"tail_horizon_hours": 0,
"prediction_hours": 48,
"individuals": 300,
"generations": 3,
"seed": 42,
"penalties": {
"ev_soc_miss": 10,
"ac_charge_break_even": 0
},
"workers": null,
"pin_workers": true,
"fitness_cache_max_entries": null,
"terminal_value_mode": "FIXED",
"terminal_value_window_hours": 24,
"direct_marketing_enabled": false,
"battery_charge_rates": null,
"battery_grid_export_rates": null,
"ev_charge_rates": [
0.0,
0.375,
0.5,
0.625,
0.75,
0.875,
1.0
],
"start_datetime": {
"datetime": "2026-09-16T10:00:00+02:00",
"timezone": "Europe/Berlin"
},
"observation_datetime": {
"datetime": "2026-09-16T10:00:00+02:00",
"timezone": "Europe/Berlin"
},
"timezone": "Europe/Berlin",
"self_consumption_interpolator": "scipy",
"verbose": false
},
"start_solution_datetime": null
}
}
+705
View File
@@ -0,0 +1,705 @@
{
"expected_result": "golden_1_quarter_result.json",
"parameters": {
"request": {
"ems": {
"pv_forecast_wh": [
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
8.05,
352.91,
728.51,
930.28,
1043.25,
1106.74,
1161.69,
6018.82,
5519.07,
3969.88,
3017.96,
1943.07,
1007.17,
319.67,
7.88,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
5.04,
335.59,
705.32,
1121.12,
1604.79,
2157.38,
1433.25,
5718.49,
4553.96,
3027.55,
2574.46,
1720.4,
963.4,
383.3,
0.0,
0.0,
0.0
],
"electricity_price_per_wh": [
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278,
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278
],
"feed_in_tariff_per_wh": [
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05
],
"price_per_wh_battery": 0.0001,
"total_load": [
676.71,
876.19,
527.13,
468.88,
531.38,
517.95,
483.15,
472.28,
1011.68,
995.0,
1053.07,
1063.91,
1320.56,
1132.03,
1163.67,
1176.82,
1216.22,
1103.78,
1129.12,
1178.71,
1050.98,
988.56,
912.38,
704.61,
516.37,
868.05,
694.34,
608.79,
556.31,
488.89,
506.91,
804.89,
1141.98,
1056.97,
992.46,
1155.99,
827.01,
1257.98,
1232.67,
871.26,
860.88,
1158.03,
1222.72,
1221.04,
949.99,
987.01,
733.99,
592.97
],
"pv_prognose_wh": [
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
8.05,
352.91,
728.51,
930.28,
1043.25,
1106.74,
1161.69,
6018.82,
5519.07,
3969.88,
3017.96,
1943.07,
1007.17,
319.67,
7.88,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
5.04,
335.59,
705.32,
1121.12,
1604.79,
2157.38,
1433.25,
5718.49,
4553.96,
3027.55,
2574.46,
1720.4,
963.4,
383.3,
0.0,
0.0,
0.0
],
"strompreis_euro_pro_wh": [
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278,
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278
],
"einspeiseverguetung_euro_pro_wh": [
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05
],
"preis_euro_pro_wh_akku": 0.0001,
"gesamtlast": [
676.71,
876.19,
527.13,
468.88,
531.38,
517.95,
483.15,
472.28,
1011.68,
995.0,
1053.07,
1063.91,
1320.56,
1132.03,
1163.67,
1176.82,
1216.22,
1103.78,
1129.12,
1178.71,
1050.98,
988.56,
912.38,
704.61,
516.37,
868.05,
694.34,
608.79,
556.31,
488.89,
506.91,
804.89,
1141.98,
1056.97,
992.46,
1155.99,
827.01,
1257.98,
1232.67,
871.26,
860.88,
1158.03,
1222.72,
1221.04,
949.99,
987.01,
733.99,
592.97
]
},
"pv_battery": {
"device_id": "battery1",
"hours": null,
"capacity_wh": 26400,
"charging_efficiency": 0.88,
"discharging_efficiency": 0.88,
"max_charge_power_w": 5000.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 80,
"min_soc_percentage": 15,
"max_soc_percentage": 100,
"charge_rates": null,
"grid_export_rates": null,
"charge_power_limit_w_by_soc": null,
"discharge_power_limit_w_by_soc": null,
"charging_efficiency_curve": null,
"discharging_efficiency_curve": null,
"levelized_cost_of_storage_kwh": 0.0,
"full_charge_soc_percentage": null,
"full_charge_deadline_datetime": null
},
"inverter": {
"device_id": "inverter1",
"hours": null,
"max_power_wh": 10000.0,
"battery_id": "battery1",
"ac_to_dc_efficiency": 1.0,
"dc_to_ac_efficiency": 1.0,
"dc_to_ac_efficiency_curve": null,
"dc_to_ac_efficiency_reference_load_fraction": 0.06,
"ac_to_dc_efficiency_curve": null,
"max_ac_charge_power_w": null,
"ac_charge_limits_total_charge": false
},
"ev": {
"device_id": "ev1",
"hours": null,
"capacity_wh": 60000,
"charging_efficiency": 0.95,
"discharging_efficiency": 1.0,
"max_charge_power_w": 11040.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 54,
"min_soc_percentage": 0,
"max_soc_percentage": 100,
"charge_rates": null,
"grid_export_rates": null,
"charge_power_limit_w_by_soc": null,
"discharge_power_limit_w_by_soc": null,
"charging_efficiency_curve": null,
"discharging_efficiency_curve": null,
"min_soc_deadline_datetime": null,
"min_soc_max_duration_h": null
},
"dishwasher": null,
"temperature_forecast": [
18.3,
17.8,
16.9,
16.2,
15.6,
15.1,
14.6,
14.2,
14.3,
14.8,
15.7,
16.7,
17.4,
18.0,
18.6,
19.2,
19.1,
18.7,
18.5,
17.7,
16.2,
14.6,
13.6,
13.0,
12.6,
12.2,
11.7,
11.6,
11.3,
11.0,
10.7,
10.2,
11.4,
14.4,
16.4,
18.3,
19.5,
20.7,
21.9,
22.7,
23.1,
23.1,
22.8,
21.8,
20.2,
19.1,
18.0,
17.4
],
"start_solution": [
1.0,
1.0,
1.0,
1.0,
0.0,
1.0,
0.0,
0.0,
1.0,
1.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
0.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0
],
"forecast_interval_seconds": null,
"home_appliances": null,
"start_solution_datetime": null,
"pv_akku": {
"device_id": "battery1",
"hours": null,
"capacity_wh": 26400,
"charging_efficiency": 0.88,
"discharging_efficiency": 0.88,
"max_charge_power_w": 5000.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 80,
"min_soc_percentage": 15,
"max_soc_percentage": 100,
"charge_rates": null,
"grid_export_rates": null,
"charge_power_limit_w_by_soc": null,
"discharge_power_limit_w_by_soc": null,
"charging_efficiency_curve": null,
"discharging_efficiency_curve": null,
"levelized_cost_of_storage_kwh": 0.0,
"full_charge_soc_percentage": null,
"full_charge_deadline_datetime": null
},
"eauto": {
"device_id": "ev1",
"hours": null,
"capacity_wh": 60000,
"charging_efficiency": 0.95,
"discharging_efficiency": 1.0,
"max_charge_power_w": 11040.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 54,
"min_soc_percentage": 0,
"max_soc_percentage": 100,
"charge_rates": null,
"grid_export_rates": null,
"charge_power_limit_w_by_soc": null,
"discharge_power_limit_w_by_soc": null,
"charging_efficiency_curve": null,
"discharging_efficiency_curve": null,
"min_soc_deadline_datetime": null,
"min_soc_max_duration_h": null
}
},
"start_hour": 10,
"settings": {
"interval_sec": 900,
"horizon_hours": 24,
"tail_horizon_hours": 0,
"prediction_hours": 48,
"individuals": 300,
"generations": 3,
"seed": 42,
"penalties": {
"ev_soc_miss": 10,
"ac_charge_break_even": 0
},
"workers": null,
"pin_workers": true,
"fitness_cache_max_entries": null,
"terminal_value_mode": "FIXED",
"terminal_value_window_hours": 24,
"direct_marketing_enabled": false,
"battery_charge_rates": null,
"battery_grid_export_rates": null,
"ev_charge_rates": [
0.0,
0.375,
0.5,
0.625,
0.75,
0.875,
1.0
],
"start_datetime": {
"datetime": "2026-09-16T10:15:00+02:00",
"timezone": "Europe/Berlin"
},
"observation_datetime": {
"datetime": "2026-09-16T10:20:00+02:00",
"timezone": "Europe/Berlin"
},
"timezone": "Europe/Berlin",
"self_consumption_interpolator": "scipy",
"verbose": false
},
"start_solution_datetime": null
}
}
+523
View File
@@ -0,0 +1,523 @@
{
"expected_result": "golden_2_result.json",
"parameters": {
"request": {
"ems": {
"pv_forecast_wh": [
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
8.05,
352.91,
728.51,
930.28,
1043.25,
1106.74,
1161.69,
6018.82,
5519.07,
3969.88,
3017.96,
1943.07,
1007.17,
319.67,
7.88,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
5.04,
335.59,
705.32,
1121.12,
1604.79,
2157.38,
1433.25,
5718.49,
4553.96,
3027.55,
2574.46,
1720.4,
963.4,
383.3,
0.0,
0.0,
0.0
],
"electricity_price_per_wh": [
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278,
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278
],
"feed_in_tariff_per_wh": 7e-05,
"price_per_wh_battery": 0.0,
"total_load": [
676.71,
876.19,
527.13,
468.88,
531.38,
517.95,
483.15,
472.28,
1011.68,
995.0,
1053.07,
1063.91,
1320.56,
1132.03,
1163.67,
1176.82,
1216.22,
1103.78,
1129.12,
1178.71,
1050.98,
988.56,
912.38,
704.61,
516.37,
868.05,
694.34,
608.79,
556.31,
488.89,
506.91,
804.89,
1141.98,
1056.97,
992.46,
1155.99,
827.01,
1257.98,
1232.67,
871.26,
860.88,
1158.03,
1222.72,
1221.04,
949.99,
987.01,
733.99,
592.97
],
"pv_prognose_wh": [
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
8.05,
352.91,
728.51,
930.28,
1043.25,
1106.74,
1161.69,
6018.82,
5519.07,
3969.88,
3017.96,
1943.07,
1007.17,
319.67,
7.88,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
5.04,
335.59,
705.32,
1121.12,
1604.79,
2157.38,
1433.25,
5718.49,
4553.96,
3027.55,
2574.46,
1720.4,
963.4,
383.3,
0.0,
0.0,
0.0
],
"strompreis_euro_pro_wh": [
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278,
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278
],
"einspeiseverguetung_euro_pro_wh": 7e-05,
"preis_euro_pro_wh_akku": 0.0,
"gesamtlast": [
676.71,
876.19,
527.13,
468.88,
531.38,
517.95,
483.15,
472.28,
1011.68,
995.0,
1053.07,
1063.91,
1320.56,
1132.03,
1163.67,
1176.82,
1216.22,
1103.78,
1129.12,
1178.71,
1050.98,
988.56,
912.38,
704.61,
516.37,
868.05,
694.34,
608.79,
556.31,
488.89,
506.91,
804.89,
1141.98,
1056.97,
992.46,
1155.99,
827.01,
1257.98,
1232.67,
871.26,
860.88,
1158.03,
1222.72,
1221.04,
949.99,
987.01,
733.99,
592.97
]
},
"pv_battery": {
"device_id": "battery1",
"hours": null,
"capacity_wh": 26400,
"charging_efficiency": 0.88,
"discharging_efficiency": 0.88,
"max_charge_power_w": 5000.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 80,
"min_soc_percentage": 0,
"max_soc_percentage": 100,
"charge_rates": null,
"grid_export_rates": null,
"charge_power_limit_w_by_soc": null,
"discharge_power_limit_w_by_soc": null,
"charging_efficiency_curve": null,
"discharging_efficiency_curve": null,
"levelized_cost_of_storage_kwh": 0.0,
"full_charge_soc_percentage": null,
"full_charge_deadline_datetime": null
},
"inverter": {
"device_id": "inverter1",
"hours": null,
"max_power_wh": 10000.0,
"battery_id": "battery1",
"ac_to_dc_efficiency": 1.0,
"dc_to_ac_efficiency": 1.0,
"dc_to_ac_efficiency_curve": null,
"dc_to_ac_efficiency_reference_load_fraction": 0.06,
"ac_to_dc_efficiency_curve": null,
"max_ac_charge_power_w": null,
"ac_charge_limits_total_charge": false
},
"ev": {
"device_id": "ev1",
"hours": null,
"capacity_wh": 60000,
"charging_efficiency": 0.95,
"discharging_efficiency": 1.0,
"max_charge_power_w": 11040.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 5,
"min_soc_percentage": 80,
"max_soc_percentage": 100,
"charge_rates": null,
"grid_export_rates": null,
"charge_power_limit_w_by_soc": null,
"discharge_power_limit_w_by_soc": null,
"charging_efficiency_curve": null,
"discharging_efficiency_curve": null,
"min_soc_deadline_datetime": null,
"min_soc_max_duration_h": null
},
"dishwasher": {
"device_id": "dishwasher1",
"hours": null,
"consumption_wh": 5000,
"duration_h": 2,
"num_cycles": 1,
"completed_cycles": 0,
"run_started_datetime": null,
"min_cycle_gap_h": 0,
"time_windows": null,
"shared_time_windows": null,
"load_profile_power_w": null,
"load_profile_interval_seconds": null,
"schedule_mode": "ONCE",
"earliest_start_datetime": null,
"deadline_datetime": null,
"deadline_policy": "BEST_EFFORT"
},
"temperature_forecast": [
18.3,
17.8,
16.9,
16.2,
15.6,
15.1,
14.6,
14.2,
14.3,
14.8,
15.7,
16.7,
17.4,
18.0,
18.6,
19.2,
19.1,
18.7,
18.5,
17.7,
16.2,
14.6,
13.6,
13.0,
12.6,
12.2,
11.7,
11.6,
11.3,
11.0,
10.7,
10.2,
11.4,
14.4,
16.4,
18.3,
19.5,
20.7,
21.9,
22.7,
23.1,
23.1,
22.8,
21.8,
20.2,
19.1,
18.0,
17.4
],
"start_solution": null,
"forecast_interval_seconds": null,
"home_appliances": null,
"start_solution_datetime": null,
"pv_akku": {
"device_id": "battery1",
"hours": null,
"capacity_wh": 26400,
"charging_efficiency": 0.88,
"discharging_efficiency": 0.88,
"max_charge_power_w": 5000.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 80,
"min_soc_percentage": 0,
"max_soc_percentage": 100,
"charge_rates": null,
"grid_export_rates": null,
"charge_power_limit_w_by_soc": null,
"discharge_power_limit_w_by_soc": null,
"charging_efficiency_curve": null,
"discharging_efficiency_curve": null,
"levelized_cost_of_storage_kwh": 0.0,
"full_charge_soc_percentage": null,
"full_charge_deadline_datetime": null
},
"eauto": {
"device_id": "ev1",
"hours": null,
"capacity_wh": 60000,
"charging_efficiency": 0.95,
"discharging_efficiency": 1.0,
"max_charge_power_w": 11040.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 5,
"min_soc_percentage": 80,
"max_soc_percentage": 100,
"charge_rates": null,
"grid_export_rates": null,
"charge_power_limit_w_by_soc": null,
"discharge_power_limit_w_by_soc": null,
"charging_efficiency_curve": null,
"discharging_efficiency_curve": null,
"min_soc_deadline_datetime": null,
"min_soc_max_duration_h": null
}
},
"start_hour": 10,
"settings": {
"interval_sec": 3600,
"horizon_hours": 38,
"tail_horizon_hours": 0,
"prediction_hours": 48,
"individuals": 300,
"generations": 3,
"seed": 42,
"penalties": {
"ev_soc_miss": 10,
"ac_charge_break_even": 1
},
"workers": null,
"pin_workers": true,
"fitness_cache_max_entries": null,
"terminal_value_mode": "FIXED",
"terminal_value_window_hours": 24,
"direct_marketing_enabled": false,
"battery_charge_rates": null,
"battery_grid_export_rates": null,
"ev_charge_rates": [
0.0,
0.375,
0.5,
0.625,
0.75,
0.875,
1.0
],
"start_datetime": {
"datetime": "2026-09-16T10:00:00+02:00",
"timezone": "Europe/Berlin"
},
"observation_datetime": {
"datetime": "2026-09-16T10:00:00+02:00",
"timezone": "Europe/Berlin"
},
"timezone": "Europe/Berlin",
"self_consumption_interpolator": "scipy",
"verbose": false
},
"start_solution_datetime": null
}
}
+523
View File
@@ -0,0 +1,523 @@
{
"expected_result": "golden_2_dst_result.json",
"parameters": {
"request": {
"ems": {
"pv_forecast_wh": [
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
8.05,
352.91,
728.51,
930.28,
1043.25,
1106.74,
1161.69,
6018.82,
5519.07,
3969.88,
3017.96,
1943.07,
1007.17,
319.67,
7.88,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
5.04,
335.59,
705.32,
1121.12,
1604.79,
2157.38,
1433.25,
5718.49,
4553.96,
3027.55,
2574.46,
1720.4,
963.4,
383.3,
0.0,
0.0,
0.0
],
"electricity_price_per_wh": [
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278,
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278
],
"feed_in_tariff_per_wh": 7e-05,
"price_per_wh_battery": 0.0,
"total_load": [
676.71,
876.19,
527.13,
468.88,
531.38,
517.95,
483.15,
472.28,
1011.68,
995.0,
1053.07,
1063.91,
1320.56,
1132.03,
1163.67,
1176.82,
1216.22,
1103.78,
1129.12,
1178.71,
1050.98,
988.56,
912.38,
704.61,
516.37,
868.05,
694.34,
608.79,
556.31,
488.89,
506.91,
804.89,
1141.98,
1056.97,
992.46,
1155.99,
827.01,
1257.98,
1232.67,
871.26,
860.88,
1158.03,
1222.72,
1221.04,
949.99,
987.01,
733.99,
592.97
],
"pv_prognose_wh": [
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
8.05,
352.91,
728.51,
930.28,
1043.25,
1106.74,
1161.69,
6018.82,
5519.07,
3969.88,
3017.96,
1943.07,
1007.17,
319.67,
7.88,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
5.04,
335.59,
705.32,
1121.12,
1604.79,
2157.38,
1433.25,
5718.49,
4553.96,
3027.55,
2574.46,
1720.4,
963.4,
383.3,
0.0,
0.0,
0.0
],
"strompreis_euro_pro_wh": [
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278,
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278
],
"einspeiseverguetung_euro_pro_wh": 7e-05,
"preis_euro_pro_wh_akku": 0.0,
"gesamtlast": [
676.71,
876.19,
527.13,
468.88,
531.38,
517.95,
483.15,
472.28,
1011.68,
995.0,
1053.07,
1063.91,
1320.56,
1132.03,
1163.67,
1176.82,
1216.22,
1103.78,
1129.12,
1178.71,
1050.98,
988.56,
912.38,
704.61,
516.37,
868.05,
694.34,
608.79,
556.31,
488.89,
506.91,
804.89,
1141.98,
1056.97,
992.46,
1155.99,
827.01,
1257.98,
1232.67,
871.26,
860.88,
1158.03,
1222.72,
1221.04,
949.99,
987.01,
733.99,
592.97
]
},
"pv_battery": {
"device_id": "battery1",
"hours": null,
"capacity_wh": 26400,
"charging_efficiency": 0.88,
"discharging_efficiency": 0.88,
"max_charge_power_w": 5000.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 80,
"min_soc_percentage": 0,
"max_soc_percentage": 100,
"charge_rates": null,
"grid_export_rates": null,
"charge_power_limit_w_by_soc": null,
"discharge_power_limit_w_by_soc": null,
"charging_efficiency_curve": null,
"discharging_efficiency_curve": null,
"levelized_cost_of_storage_kwh": 0.0,
"full_charge_soc_percentage": null,
"full_charge_deadline_datetime": null
},
"inverter": {
"device_id": "inverter1",
"hours": null,
"max_power_wh": 10000.0,
"battery_id": "battery1",
"ac_to_dc_efficiency": 1.0,
"dc_to_ac_efficiency": 1.0,
"dc_to_ac_efficiency_curve": null,
"dc_to_ac_efficiency_reference_load_fraction": 0.06,
"ac_to_dc_efficiency_curve": null,
"max_ac_charge_power_w": null,
"ac_charge_limits_total_charge": false
},
"ev": {
"device_id": "ev1",
"hours": null,
"capacity_wh": 60000,
"charging_efficiency": 0.95,
"discharging_efficiency": 1.0,
"max_charge_power_w": 11040.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 5,
"min_soc_percentage": 80,
"max_soc_percentage": 100,
"charge_rates": null,
"grid_export_rates": null,
"charge_power_limit_w_by_soc": null,
"discharge_power_limit_w_by_soc": null,
"charging_efficiency_curve": null,
"discharging_efficiency_curve": null,
"min_soc_deadline_datetime": null,
"min_soc_max_duration_h": null
},
"dishwasher": {
"device_id": "dishwasher1",
"hours": null,
"consumption_wh": 5000,
"duration_h": 2,
"num_cycles": 1,
"completed_cycles": 0,
"run_started_datetime": null,
"min_cycle_gap_h": 0,
"time_windows": null,
"shared_time_windows": null,
"load_profile_power_w": null,
"load_profile_interval_seconds": null,
"schedule_mode": "ONCE",
"earliest_start_datetime": null,
"deadline_datetime": null,
"deadline_policy": "BEST_EFFORT"
},
"temperature_forecast": [
18.3,
17.8,
16.9,
16.2,
15.6,
15.1,
14.6,
14.2,
14.3,
14.8,
15.7,
16.7,
17.4,
18.0,
18.6,
19.2,
19.1,
18.7,
18.5,
17.7,
16.2,
14.6,
13.6,
13.0,
12.6,
12.2,
11.7,
11.6,
11.3,
11.0,
10.7,
10.2,
11.4,
14.4,
16.4,
18.3,
19.5,
20.7,
21.9,
22.7,
23.1,
23.1,
22.8,
21.8,
20.2,
19.1,
18.0,
17.4
],
"start_solution": null,
"forecast_interval_seconds": null,
"home_appliances": null,
"start_solution_datetime": null,
"pv_akku": {
"device_id": "battery1",
"hours": null,
"capacity_wh": 26400,
"charging_efficiency": 0.88,
"discharging_efficiency": 0.88,
"max_charge_power_w": 5000.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 80,
"min_soc_percentage": 0,
"max_soc_percentage": 100,
"charge_rates": null,
"grid_export_rates": null,
"charge_power_limit_w_by_soc": null,
"discharge_power_limit_w_by_soc": null,
"charging_efficiency_curve": null,
"discharging_efficiency_curve": null,
"levelized_cost_of_storage_kwh": 0.0,
"full_charge_soc_percentage": null,
"full_charge_deadline_datetime": null
},
"eauto": {
"device_id": "ev1",
"hours": null,
"capacity_wh": 60000,
"charging_efficiency": 0.95,
"discharging_efficiency": 1.0,
"max_charge_power_w": 11040.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 5,
"min_soc_percentage": 80,
"max_soc_percentage": 100,
"charge_rates": null,
"grid_export_rates": null,
"charge_power_limit_w_by_soc": null,
"discharge_power_limit_w_by_soc": null,
"charging_efficiency_curve": null,
"discharging_efficiency_curve": null,
"min_soc_deadline_datetime": null,
"min_soc_max_duration_h": null
}
},
"start_hour": 10,
"settings": {
"interval_sec": 3600,
"horizon_hours": 38,
"tail_horizon_hours": 0,
"prediction_hours": 48,
"individuals": 300,
"generations": 3,
"seed": 42,
"penalties": {
"ev_soc_miss": 10,
"ac_charge_break_even": 1
},
"workers": null,
"pin_workers": true,
"fitness_cache_max_entries": null,
"terminal_value_mode": "FIXED",
"terminal_value_window_hours": 24,
"direct_marketing_enabled": false,
"battery_charge_rates": null,
"battery_grid_export_rates": null,
"ev_charge_rates": [
0.0,
0.375,
0.5,
0.625,
0.75,
0.875,
1.0
],
"start_datetime": {
"datetime": "2026-03-28T10:00:00+01:00",
"timezone": "Europe/Berlin"
},
"observation_datetime": {
"datetime": "2026-03-28T10:00:00+01:00",
"timezone": "Europe/Berlin"
},
"timezone": "Europe/Berlin",
"self_consumption_interpolator": "scipy",
"verbose": false
},
"start_solution_datetime": null
}
}
+523
View File
@@ -0,0 +1,523 @@
{
"expected_result": "golden_2_full_result.json",
"parameters": {
"request": {
"ems": {
"pv_forecast_wh": [
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
8.05,
352.91,
728.51,
930.28,
1043.25,
1106.74,
1161.69,
6018.82,
5519.07,
3969.88,
3017.96,
1943.07,
1007.17,
319.67,
7.88,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
5.04,
335.59,
705.32,
1121.12,
1604.79,
2157.38,
1433.25,
5718.49,
4553.96,
3027.55,
2574.46,
1720.4,
963.4,
383.3,
0.0,
0.0,
0.0
],
"electricity_price_per_wh": [
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278,
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278
],
"feed_in_tariff_per_wh": 7e-05,
"price_per_wh_battery": 0.0,
"total_load": [
676.71,
876.19,
527.13,
468.88,
531.38,
517.95,
483.15,
472.28,
1011.68,
995.0,
1053.07,
1063.91,
1320.56,
1132.03,
1163.67,
1176.82,
1216.22,
1103.78,
1129.12,
1178.71,
1050.98,
988.56,
912.38,
704.61,
516.37,
868.05,
694.34,
608.79,
556.31,
488.89,
506.91,
804.89,
1141.98,
1056.97,
992.46,
1155.99,
827.01,
1257.98,
1232.67,
871.26,
860.88,
1158.03,
1222.72,
1221.04,
949.99,
987.01,
733.99,
592.97
],
"pv_prognose_wh": [
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
8.05,
352.91,
728.51,
930.28,
1043.25,
1106.74,
1161.69,
6018.82,
5519.07,
3969.88,
3017.96,
1943.07,
1007.17,
319.67,
7.88,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
5.04,
335.59,
705.32,
1121.12,
1604.79,
2157.38,
1433.25,
5718.49,
4553.96,
3027.55,
2574.46,
1720.4,
963.4,
383.3,
0.0,
0.0,
0.0
],
"strompreis_euro_pro_wh": [
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278,
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278
],
"einspeiseverguetung_euro_pro_wh": 7e-05,
"preis_euro_pro_wh_akku": 0.0,
"gesamtlast": [
676.71,
876.19,
527.13,
468.88,
531.38,
517.95,
483.15,
472.28,
1011.68,
995.0,
1053.07,
1063.91,
1320.56,
1132.03,
1163.67,
1176.82,
1216.22,
1103.78,
1129.12,
1178.71,
1050.98,
988.56,
912.38,
704.61,
516.37,
868.05,
694.34,
608.79,
556.31,
488.89,
506.91,
804.89,
1141.98,
1056.97,
992.46,
1155.99,
827.01,
1257.98,
1232.67,
871.26,
860.88,
1158.03,
1222.72,
1221.04,
949.99,
987.01,
733.99,
592.97
]
},
"pv_battery": {
"device_id": "battery1",
"hours": null,
"capacity_wh": 26400,
"charging_efficiency": 0.88,
"discharging_efficiency": 0.88,
"max_charge_power_w": 5000.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 80,
"min_soc_percentage": 0,
"max_soc_percentage": 100,
"charge_rates": null,
"grid_export_rates": null,
"charge_power_limit_w_by_soc": null,
"discharge_power_limit_w_by_soc": null,
"charging_efficiency_curve": null,
"discharging_efficiency_curve": null,
"levelized_cost_of_storage_kwh": 0.0,
"full_charge_soc_percentage": null,
"full_charge_deadline_datetime": null
},
"inverter": {
"device_id": "inverter1",
"hours": null,
"max_power_wh": 10000.0,
"battery_id": "battery1",
"ac_to_dc_efficiency": 1.0,
"dc_to_ac_efficiency": 1.0,
"dc_to_ac_efficiency_curve": null,
"dc_to_ac_efficiency_reference_load_fraction": 0.06,
"ac_to_dc_efficiency_curve": null,
"max_ac_charge_power_w": null,
"ac_charge_limits_total_charge": false
},
"ev": {
"device_id": "ev1",
"hours": null,
"capacity_wh": 60000,
"charging_efficiency": 0.95,
"discharging_efficiency": 1.0,
"max_charge_power_w": 11040.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 5,
"min_soc_percentage": 80,
"max_soc_percentage": 100,
"charge_rates": null,
"grid_export_rates": null,
"charge_power_limit_w_by_soc": null,
"discharge_power_limit_w_by_soc": null,
"charging_efficiency_curve": null,
"discharging_efficiency_curve": null,
"min_soc_deadline_datetime": null,
"min_soc_max_duration_h": null
},
"dishwasher": {
"device_id": "dishwasher1",
"hours": null,
"consumption_wh": 5000,
"duration_h": 2,
"num_cycles": 1,
"completed_cycles": 0,
"run_started_datetime": null,
"min_cycle_gap_h": 0,
"time_windows": null,
"shared_time_windows": null,
"load_profile_power_w": null,
"load_profile_interval_seconds": null,
"schedule_mode": "ONCE",
"earliest_start_datetime": null,
"deadline_datetime": null,
"deadline_policy": "BEST_EFFORT"
},
"temperature_forecast": [
18.3,
17.8,
16.9,
16.2,
15.6,
15.1,
14.6,
14.2,
14.3,
14.8,
15.7,
16.7,
17.4,
18.0,
18.6,
19.2,
19.1,
18.7,
18.5,
17.7,
16.2,
14.6,
13.6,
13.0,
12.6,
12.2,
11.7,
11.6,
11.3,
11.0,
10.7,
10.2,
11.4,
14.4,
16.4,
18.3,
19.5,
20.7,
21.9,
22.7,
23.1,
23.1,
22.8,
21.8,
20.2,
19.1,
18.0,
17.4
],
"start_solution": null,
"forecast_interval_seconds": null,
"home_appliances": null,
"start_solution_datetime": null,
"pv_akku": {
"device_id": "battery1",
"hours": null,
"capacity_wh": 26400,
"charging_efficiency": 0.88,
"discharging_efficiency": 0.88,
"max_charge_power_w": 5000.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 80,
"min_soc_percentage": 0,
"max_soc_percentage": 100,
"charge_rates": null,
"grid_export_rates": null,
"charge_power_limit_w_by_soc": null,
"discharge_power_limit_w_by_soc": null,
"charging_efficiency_curve": null,
"discharging_efficiency_curve": null,
"levelized_cost_of_storage_kwh": 0.0,
"full_charge_soc_percentage": null,
"full_charge_deadline_datetime": null
},
"eauto": {
"device_id": "ev1",
"hours": null,
"capacity_wh": 60000,
"charging_efficiency": 0.95,
"discharging_efficiency": 1.0,
"max_charge_power_w": 11040.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 5,
"min_soc_percentage": 80,
"max_soc_percentage": 100,
"charge_rates": null,
"grid_export_rates": null,
"charge_power_limit_w_by_soc": null,
"discharge_power_limit_w_by_soc": null,
"charging_efficiency_curve": null,
"discharging_efficiency_curve": null,
"min_soc_deadline_datetime": null,
"min_soc_max_duration_h": null
}
},
"start_hour": 10,
"settings": {
"interval_sec": 3600,
"horizon_hours": 38,
"tail_horizon_hours": 0,
"prediction_hours": 48,
"individuals": 300,
"generations": 400,
"seed": 42,
"penalties": {
"ev_soc_miss": 10,
"ac_charge_break_even": 1
},
"workers": null,
"pin_workers": true,
"fitness_cache_max_entries": null,
"terminal_value_mode": "FIXED",
"terminal_value_window_hours": 24,
"direct_marketing_enabled": false,
"battery_charge_rates": null,
"battery_grid_export_rates": null,
"ev_charge_rates": [
0.0,
0.375,
0.5,
0.625,
0.75,
0.875,
1.0
],
"start_datetime": {
"datetime": "2026-09-16T10:00:00+02:00",
"timezone": "Europe/Berlin"
},
"observation_datetime": {
"datetime": "2026-09-16T10:00:00+02:00",
"timezone": "Europe/Berlin"
},
"timezone": "Europe/Berlin",
"self_consumption_interpolator": "scipy",
"verbose": false
},
"start_solution_datetime": null
}
}
+523
View File
@@ -0,0 +1,523 @@
{
"expected_result": "golden_2_tail_result.json",
"parameters": {
"request": {
"ems": {
"pv_forecast_wh": [
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
8.05,
352.91,
728.51,
930.28,
1043.25,
1106.74,
1161.69,
6018.82,
5519.07,
3969.88,
3017.96,
1943.07,
1007.17,
319.67,
7.88,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
5.04,
335.59,
705.32,
1121.12,
1604.79,
2157.38,
1433.25,
5718.49,
4553.96,
3027.55,
2574.46,
1720.4,
963.4,
383.3,
0.0,
0.0,
0.0
],
"electricity_price_per_wh": [
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278,
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278
],
"feed_in_tariff_per_wh": 7e-05,
"price_per_wh_battery": 0.0,
"total_load": [
676.71,
876.19,
527.13,
468.88,
531.38,
517.95,
483.15,
472.28,
1011.68,
995.0,
1053.07,
1063.91,
1320.56,
1132.03,
1163.67,
1176.82,
1216.22,
1103.78,
1129.12,
1178.71,
1050.98,
988.56,
912.38,
704.61,
516.37,
868.05,
694.34,
608.79,
556.31,
488.89,
506.91,
804.89,
1141.98,
1056.97,
992.46,
1155.99,
827.01,
1257.98,
1232.67,
871.26,
860.88,
1158.03,
1222.72,
1221.04,
949.99,
987.01,
733.99,
592.97
],
"pv_prognose_wh": [
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
8.05,
352.91,
728.51,
930.28,
1043.25,
1106.74,
1161.69,
6018.82,
5519.07,
3969.88,
3017.96,
1943.07,
1007.17,
319.67,
7.88,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
5.04,
335.59,
705.32,
1121.12,
1604.79,
2157.38,
1433.25,
5718.49,
4553.96,
3027.55,
2574.46,
1720.4,
963.4,
383.3,
0.0,
0.0,
0.0
],
"strompreis_euro_pro_wh": [
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278,
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278
],
"einspeiseverguetung_euro_pro_wh": 7e-05,
"preis_euro_pro_wh_akku": 0.0,
"gesamtlast": [
676.71,
876.19,
527.13,
468.88,
531.38,
517.95,
483.15,
472.28,
1011.68,
995.0,
1053.07,
1063.91,
1320.56,
1132.03,
1163.67,
1176.82,
1216.22,
1103.78,
1129.12,
1178.71,
1050.98,
988.56,
912.38,
704.61,
516.37,
868.05,
694.34,
608.79,
556.31,
488.89,
506.91,
804.89,
1141.98,
1056.97,
992.46,
1155.99,
827.01,
1257.98,
1232.67,
871.26,
860.88,
1158.03,
1222.72,
1221.04,
949.99,
987.01,
733.99,
592.97
]
},
"pv_battery": {
"device_id": "battery1",
"hours": null,
"capacity_wh": 26400,
"charging_efficiency": 0.88,
"discharging_efficiency": 0.88,
"max_charge_power_w": 5000.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 80,
"min_soc_percentage": 0,
"max_soc_percentage": 100,
"charge_rates": null,
"grid_export_rates": null,
"charge_power_limit_w_by_soc": null,
"discharge_power_limit_w_by_soc": null,
"charging_efficiency_curve": null,
"discharging_efficiency_curve": null,
"levelized_cost_of_storage_kwh": 0.0,
"full_charge_soc_percentage": null,
"full_charge_deadline_datetime": null
},
"inverter": {
"device_id": "inverter1",
"hours": null,
"max_power_wh": 10000.0,
"battery_id": "battery1",
"ac_to_dc_efficiency": 1.0,
"dc_to_ac_efficiency": 1.0,
"dc_to_ac_efficiency_curve": null,
"dc_to_ac_efficiency_reference_load_fraction": 0.06,
"ac_to_dc_efficiency_curve": null,
"max_ac_charge_power_w": null,
"ac_charge_limits_total_charge": false
},
"ev": {
"device_id": "ev1",
"hours": null,
"capacity_wh": 60000,
"charging_efficiency": 0.95,
"discharging_efficiency": 1.0,
"max_charge_power_w": 11040.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 5,
"min_soc_percentage": 80,
"max_soc_percentage": 100,
"charge_rates": null,
"grid_export_rates": null,
"charge_power_limit_w_by_soc": null,
"discharge_power_limit_w_by_soc": null,
"charging_efficiency_curve": null,
"discharging_efficiency_curve": null,
"min_soc_deadline_datetime": null,
"min_soc_max_duration_h": null
},
"dishwasher": {
"device_id": "dishwasher1",
"hours": null,
"consumption_wh": 5000,
"duration_h": 2,
"num_cycles": 1,
"completed_cycles": 0,
"run_started_datetime": null,
"min_cycle_gap_h": 0,
"time_windows": null,
"shared_time_windows": null,
"load_profile_power_w": null,
"load_profile_interval_seconds": null,
"schedule_mode": "ONCE",
"earliest_start_datetime": null,
"deadline_datetime": null,
"deadline_policy": "BEST_EFFORT"
},
"temperature_forecast": [
18.3,
17.8,
16.9,
16.2,
15.6,
15.1,
14.6,
14.2,
14.3,
14.8,
15.7,
16.7,
17.4,
18.0,
18.6,
19.2,
19.1,
18.7,
18.5,
17.7,
16.2,
14.6,
13.6,
13.0,
12.6,
12.2,
11.7,
11.6,
11.3,
11.0,
10.7,
10.2,
11.4,
14.4,
16.4,
18.3,
19.5,
20.7,
21.9,
22.7,
23.1,
23.1,
22.8,
21.8,
20.2,
19.1,
18.0,
17.4
],
"start_solution": null,
"forecast_interval_seconds": null,
"home_appliances": null,
"start_solution_datetime": null,
"pv_akku": {
"device_id": "battery1",
"hours": null,
"capacity_wh": 26400,
"charging_efficiency": 0.88,
"discharging_efficiency": 0.88,
"max_charge_power_w": 5000.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 80,
"min_soc_percentage": 0,
"max_soc_percentage": 100,
"charge_rates": null,
"grid_export_rates": null,
"charge_power_limit_w_by_soc": null,
"discharge_power_limit_w_by_soc": null,
"charging_efficiency_curve": null,
"discharging_efficiency_curve": null,
"levelized_cost_of_storage_kwh": 0.0,
"full_charge_soc_percentage": null,
"full_charge_deadline_datetime": null
},
"eauto": {
"device_id": "ev1",
"hours": null,
"capacity_wh": 60000,
"charging_efficiency": 0.95,
"discharging_efficiency": 1.0,
"max_charge_power_w": 11040.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 5,
"min_soc_percentage": 80,
"max_soc_percentage": 100,
"charge_rates": null,
"grid_export_rates": null,
"charge_power_limit_w_by_soc": null,
"discharge_power_limit_w_by_soc": null,
"charging_efficiency_curve": null,
"discharging_efficiency_curve": null,
"min_soc_deadline_datetime": null,
"min_soc_max_duration_h": null
}
},
"start_hour": 10,
"settings": {
"interval_sec": 3600,
"horizon_hours": 24,
"tail_horizon_hours": 24,
"prediction_hours": 48,
"individuals": 300,
"generations": 3,
"seed": 42,
"penalties": {
"ev_soc_miss": 10,
"ac_charge_break_even": 1
},
"workers": null,
"pin_workers": true,
"fitness_cache_max_entries": null,
"terminal_value_mode": "AUTO",
"terminal_value_window_hours": 24,
"direct_marketing_enabled": false,
"battery_charge_rates": null,
"battery_grid_export_rates": null,
"ev_charge_rates": [
0.0,
0.375,
0.5,
0.625,
0.75,
0.875,
1.0
],
"start_datetime": {
"datetime": "2026-09-16T10:00:00+02:00",
"timezone": "Europe/Berlin"
},
"observation_datetime": {
"datetime": "2026-09-16T10:00:00+02:00",
"timezone": "Europe/Berlin"
},
"timezone": "Europe/Berlin",
"self_consumption_interpolator": "scipy",
"verbose": false
},
"start_solution_datetime": null
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff