mirror of
https://github.com/Akkudoktor-EOS/EOS.git
synced 2026-10-09 07:56:40 +00:00
* feat: adapt configuration for multi optimization algorithms Decouple configuration from optimization algorithm parameters. Add to_[algorithm]_param() methods to the configuration that derive optimization algorithm specific parameters from the configuration. Add x-scope tags to the configuration options that describe for which specific algorithms the configuration option is for. The whole device settings are restructured. There are now general settings for the device classes with the afore mentioned to_[algorithm]_param() methods. The general device settings got their own directory `devices/settings`. By this the parameter class also does not have to be a pydantic model which can be used for future optimization/ simulations speed up. Also the parameter class for a device is now part of the device module. This better decouples and also is the natural place for parameters of a device. Besides this feature there are also fixes and improvements: * feat: extend home appliance time window settings and simulation Home appliance can now be configured for multiple runs with per-cycle allowed time windows. The number of remaining cycles to plan is determined at runtime by reading the ``cycles_completed_measurement_key`` from the measurement store. * feat: specialiced CycleTimeWindowSequence for time window sequences Sequence of time windows associated to cycles. This model specializes ``ValueTimeWindowSequence`` so that the ``value`` field of each ``ValueTimeWindow`` encodes the **cycle index** (0-based integer) the window belongs to. Typical use: an appliance that must run ``n`` times per day, each run constrained to a distinct time window. Assign ``value=0`` to windows for the first cycle, ``value=1`` for the second, and so on. Multiple windows may share the same cycle index (their allowed regions are unioned). Windows with ``value=None`` are silently ignored by all cycle-aware methods. * fix: Make test_configmigrate also regard the _ANY_SENTENIEL in key values * chore: Make devices configurations a map instead of a list This makes config paths stable regardless of declaration order and lets each device settings class build its own config path from ``self.device_id`` without needing an external index. Tests are adapted likewise. Devices configurations are automatically migrated from lists to maps. * chore: rename levelized_cost_of_storage_kwh to levelized_cost_of_storage_amt kwh This better fits in the naming scheme and also makes clear the costs are money. Signed-off-by: Bobby Noelte <b0661n0e17e@gmail.com> * fix: runtime config update ignored by config file Runtime settings were handed back to pydantic-settings as init settings, which rank below the config file and the environment. Any key already present in EOS.config.json or in the environment silently discarded the update, so a bulk PUT /v1/config returned 200 without applying anything, while the granular PUT /v1/config/{path} endpoint kept working. Add a dedicated runtime settings source ranked directly below the command line arguments and record granular updates there as well, so both endpoints share one store that survives re-evaluation of the settings sources. Environment variables keep precedence over the config file for all keys that were not set at runtime. Also repairs revert_settings() and update(), which passed their data through the same init settings. Closes #1303 * fix: env vars ignored on first config build ConfigEOS.__init__ passed self as first positional argument to _setup, which forwards it to pydantic_settings.BaseSettings.__init__. Its first positional parameter is _case_sensitive, so the environment source matched the upper case variable names against the lower case field names and returned nothing. Environment settings only took effect after the next configuration setup. * docs: changelog for config priority fixes * fix(config): preserve device identities and storage costs during migration * fix(measurement): restore JSON records into the existing singleton * fix(devices): preserve charge-rate typing and public import compatibility * feat(measurement): integrate typed energy quality and capacity APIs Port the locally backed-up measurement extensions to main async storage and PR #1256 device maps. Preserve runtime capacity estimates across #1305 bulk updates. Confirm JSON singleton restore defect on unchanged main and add regression. No production configuration or measurements included. Co-authored-by: Andreas <drbacke@gmx.de> * docs(measurement): describe household settings and consolidate regression coverage * docs(measurement): regenerate configuration and API contracts * test(measurement): isolate capacity database state between tests * ruff format fix * fix(measurement): restore JSON records into the existing singleton * test(measurement): assert restored timestamps before timezone conversion * test(measurement): assert restored timestamps before timezone conversion * fix: preserve imported feed-in revenue during parameter preparation Cancel GENETIC preparation when imported revenue cannot be read or contains invalid values, preserving the chosen provider instead of replacing it with demo tariffs. Keep valid positive, zero and negative amount/Wh series unchanged. Adapt the revenue-preservation regressions from PRs #1224 and #1304 to the async main API, including real timestamped imports and simulation repricing. The feature-only direct-marketing override remains outside this main fix. Co-authored-by: Christin <info@bikinibottom.capital> Co-authored-by: Normann <github@koldrack.com> * feat(devices): port slot-aware battery export and direct-use physics Port scoped device changes fromd2e2d58237. Keep PR #1256 parameter conversion structure and separate GENETIC0 devices. Validate physical flows and reprice changed simulation results. Co-authored-by: Andreas <drbacke@gmx.de> Co-authored-by: Christin <info@bikinibottom.capital> * docs(measurement): align API version with refreshed prerequisites * fix: return only completed optimization results per run * feat(pvforecast): add calibrated local Akkudoktor backend Port local PV modeling and outage calibration from feature commitsf976335,6dc58c3andfaed0fdby Andreas. Keep PVForecastAkkudoktor identity and remote default, adapt to async storage, and migrate legacy provider settings. * fix(cache): distinguish callables in the shared EMS cache Include the function object in cache keys so methods of one interpolator cannot reuse a probability as a power value. Cover both call orders, keyword arguments, cache hits and separate closures with identical qualified names. * fix(devices): constrain the physics port and validate export levels Defer inactive EV deadline fields to the optimizer port, reject nonfinite export rates, and document the hourly Optimize boundary. Verify converter IDs, rates and LCOS, separate GENETIC0 interpolation, physical boundary flows and independent GENETIC repricing. * docs(pvforecast): regenerate local backend configuration schema * docs(devices): regenerate slot-physics configuration and OpenAPI schemas * test: type dynamic Optimize regression arguments * style: wrap imported tariff test parameter import * style(pvforecast): apply CI import formatting * docs(pvforecast): refresh API version after CI formatting * fix(config): satisfy typed device conversion and migration contracts * docs(config): refresh validated configuration prerequisite schemas * fix(measurement): enforce typed capacity and sample validation * test(devices): align physics regressions with strict type checking * style(measurement): normalize imports for CI * docs(measurement): refresh typed measurement API schemas * docs(devices): refresh API version after prerequisite merge * test: make optimization dispatch timezones explicit * docs(interpolator): use portable reStructuredText markup * docs(devices): refresh API version after docstring compatibility fix * feat: complete configuration-driven GENETIC optimization and reports (#1329) * feat(devices): port slot-aware battery export and direct-use physics Port scoped device changes fromd2e2d58237. Keep PR #1256 parameter conversion structure and separate GENETIC0 devices. Validate physical flows and reprice changed simulation results. Co-authored-by: Andreas <drbacke@gmx.de> Co-authored-by: Christin <info@bikinibottom.capital> * feat(optimization): port tested terminal and tail value primitives Sourced2e2d58237. 22 primitive tests pass; integration with the optimizer, forecast horizon and API is still pending. Co-authored-by: Andreas <drbacke@gmx.de> Co-authored-by: Christin <info@bikinibottom.capital> * fix(devices): preserve charge-rate typing and public import compatibility * feat(measurement): integrate typed energy quality and capacity APIs Port the locally backed-up measurement extensions to main async storage and PR #1256 device maps. Preserve runtime capacity estimates across #1305 bulk updates. Confirm JSON singleton restore defect on unchanged main and add regression. No production configuration or measurements included. Co-authored-by: Andreas <drbacke@gmx.de> * test(integration): validate optimizer economics and document measurement settings * docs(integration): record tested checkpoint and remaining consolidation work * docs(development): define isolated PR packages and remaining porting gates * docs(integration): refresh API version after measurement reconciliation * docs(integration): record PR readiness verification results * docs(development): record publication and verification of PR 1322 * test(measurement): assert restored timestamps before timezone conversion * docs(development): record corrected PR head and CI progress * docs(integration): refresh API version after prerequisite alignment * docs(integration): define parallel packages and Optimize compatibility gates * fix: preserve imported feed-in revenue during parameter preparation Cancel GENETIC preparation when imported revenue cannot be read or contains invalid values, preserving the chosen provider instead of replacing it with demo tariffs. Keep valid positive, zero and negative amount/Wh series unchanged. Adapt the revenue-preservation regressions from PRs #1224 and #1304 to the async main API, including real timestamped imports and simulation repricing. The feature-only direct-marketing override remains outside this main fix. Co-authored-by: Christin <info@bikinibottom.capital> Co-authored-by: Normann <github@koldrack.com> * test(integration): verify tariff protection with mapped device physics * fix: return only completed optimization results per run * test(integration): verify algorithm aliases and mapped-device contracts * fix(cache): distinguish callables in the shared EMS cache Include the function object in cache keys so methods of one interpolator cannot reuse a probability as a power value. Cover both call orders, keyword arguments, cache hits and separate closures with identical qualified names. * fix(devices): constrain the physics port and validate export levels Defer inactive EV deadline fields to the optimizer port, reject nonfinite export rates, and document the hourly Optimize boundary. Verify converter IDs, rates and LCOS, separate GENETIC0 interpolation, physical boundary flows and independent GENETIC repricing. * feat(pvforecast): add calibrated local Akkudoktor backend Port local PV modeling and outage calibration from feature commitsf976335,6dc58c3andfaed0fdby Andreas. Keep PVForecastAkkudoktor identity and remote default, adapt to async storage, and migrate legacy provider settings. * docs(integration): record combined compatibility checks and green JSON PR CI * test: type dynamic Optimize regression arguments * docs(integration): record Optimize fix PR publication * docs(integration): record imported tariff protection PR * style(pvforecast): apply CI import formatting * style(integration): align combined regression imports * test: make optimization dispatch timezones explicit * docs(interpolator): use portable reStructuredText markup * chore: validate combined integration with locked mypy * docs: hand off six validated pull requests for manual review * feat: report genetic interval and terminal value diagnostics * feat(devices): reconcile flexible profiles and EV deadlines with cycle scheduling Adapt the flexible consumer primitives fromd2e2d582while retaining the keyed settings and per-cycle scheduling introduced by #1256. Preserve slot battery physics and GENETIC0 flat-load conversion. Cover energy conservation, deadlines, window intersections, DST, completed cycles and EV converters. * test: satisfy typed genetic PDF chart contracts * feat(optimization): resolve quarter-hour GENETIC requests from configuration * test(genetic): verify real device scheduling, measurement and export contracts Register appliance completed-cycle measurement keys so the real store accepts both default and custom counters. Exercise complete low-budget optimizer runs, persisted measurements, generic solution output and instructions, including zero-power phases, EV departure boundaries, per-cycle windows and LCOS. * fix: bound genetic report forecasts to executable horizon * feat: complete native genetic scheduling and retained result contracts * fix: retain missing raw samples when dropna is disabled * fix: align local optimization slots and measurement instants * docs: explain complete genetic rollout and PR dependencies * feat: expose retained GENETIC report through the versioned API * docs: regenerate complete genetic configuration and API schema * docs: format consolidation and review handoff markdown * test: align isolated EMS fixture with native genetic run options * test(genetic): clean up singleton measurements after device integration tests * test: freeze the clock without replacing timestamp conversion * fix: preserve explicit warmstart timezones in runtime requests * test(genetic): validate device schedules in UTC and Berlin Use explicit Berlin origins for Berlin wall-clock windows, compare absolute deadline instants correctly, and run all real device optimizer scenarios under both UTC and Europe/Berlin. Compare exported starts in the run timezone instead of assuming the output timezone matches the host. * fix: start automatic genetic runs in the site timezone * Preserve aware GENETIC snapshot times across host timezones * docs: specify site clock and rehearsed merge resolutions * test: isolate invalid measurement records and refresh API version * fix: render single-slot genetic tail diagnostics * docs: refresh schema version after report fix * fix: preserve configuration-only Optimize API contract * docs: refresh configuration request schema --------- Co-authored-by: Christin <info@bikinibottom.capital> Co-authored-by: Normann <github@koldrack.com> --------- Signed-off-by: Bobby Noelte <b0661n0e17e@gmail.com> Co-authored-by: Bobby Noelte <b0661n0e17e@gmail.com> Co-authored-by: r0b2g1t <r0b2g1t@users.noreply.github.com> Co-authored-by: Normann <github@koldrack.com> Co-authored-by: Christin <info@bikinibottom.capital>
361 lines
15 KiB
Python
361 lines
15 KiB
Python
"""Offline regression tests for per-run optimization results and atomic publication."""
|
|
|
|
from asyncio import Lock
|
|
from types import SimpleNamespace
|
|
from typing import Any
|
|
from unittest.mock import AsyncMock, Mock
|
|
|
|
import pytest
|
|
|
|
from akkudoktoreos.core import ems as ems_module
|
|
from akkudoktoreos.core.emsettings import EnergyManagementMode
|
|
from akkudoktoreos.optimization.genetic0.genetic0params import (
|
|
Genetic0OptimizationParameters,
|
|
)
|
|
from akkudoktoreos.optimization.optimization import OptimizationAlgorithm
|
|
from akkudoktoreos.utils.datetimeutil import to_datetime
|
|
|
|
|
|
@pytest.fixture
|
|
def offline_ems(monkeypatch):
|
|
"""Run the actual EMS orchestration with no real adapters or prediction IO."""
|
|
cls = ems_module.EnergyManagement
|
|
for name in (
|
|
"_start_datetime",
|
|
"_observation_datetime",
|
|
"_last_run_datetime",
|
|
"_plan",
|
|
"_optimization_solution",
|
|
"_genetic_solution",
|
|
"_genetic0_solution",
|
|
):
|
|
monkeypatch.setattr(cls, name, None)
|
|
monkeypatch.setattr(cls, "_stage", ems_module.EnergyManagementStage.IDLE)
|
|
monkeypatch.setattr(cls, "_run_lock", Lock())
|
|
monkeypatch.setattr(ems_module, "CacheEnergyManagementStore", Mock())
|
|
return SimpleNamespace(
|
|
config=SimpleNamespace(
|
|
general=SimpleNamespace(timezone="Europe/Berlin"),
|
|
ems=SimpleNamespace(mode=EnergyManagementMode.OPTIMIZATION),
|
|
optimization=SimpleNamespace(
|
|
algorithm=OptimizationAlgorithm.GENETIC,
|
|
genetic=SimpleNamespace(generations=3, seed=17, interval_sec=3600, individuals=31),
|
|
genetic0=SimpleNamespace(generations=5, seed=29),
|
|
),
|
|
server=SimpleNamespace(verbose=False),
|
|
),
|
|
prediction=SimpleNamespace(update_data=AsyncMock()),
|
|
adapter=SimpleNamespace(update_data=AsyncMock()),
|
|
set_start_datetime=cls.set_start_datetime,
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("algorithm", list(OptimizationAlgorithm))
|
|
@pytest.mark.parametrize("explicit_start", [False, True])
|
|
async def test_implicit_genetic_start_uses_site_timezone(
|
|
offline_ems, monkeypatch, set_other_timezone, algorithm, explicit_start
|
|
):
|
|
set_other_timezone("UTC")
|
|
now = to_datetime("2026-09-16T22:47:23Z", in_timezone="UTC")
|
|
|
|
def frozen_datetime(value=None, **kwargs):
|
|
return to_datetime(now if value is None else value, **kwargs)
|
|
|
|
monkeypatch.setattr(ems_module, "to_datetime", frozen_datetime)
|
|
offline_ems.config.optimization.genetic.interval_sec = 900
|
|
await ems_module.EnergyManagement.run(
|
|
offline_ems,
|
|
mode=EnergyManagementMode.PREDICTION,
|
|
algorithm=algorithm,
|
|
start_datetime=now if explicit_start else None,
|
|
)
|
|
start = ems_module.EnergyManagement._start_datetime
|
|
observed = ems_module.EnergyManagement._observation_datetime
|
|
assert start is not None and observed is not None
|
|
assert observed.timestamp() == now.timestamp()
|
|
if algorithm == OptimizationAlgorithm.GENETIC:
|
|
assert start.minute == 45
|
|
assert start.hour == (22 if explicit_start else 0)
|
|
assert start.day == (16 if explicit_start else 17)
|
|
assert start.timezone_name == ("UTC" if explicit_start else "Europe/Berlin")
|
|
else:
|
|
assert start.minute == 0
|
|
assert start.hour == 22
|
|
assert start.day == 16
|
|
assert start.timezone_name == "UTC"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("algorithm", list(OptimizationAlgorithm))
|
|
@pytest.mark.parametrize("selection", ["configured", "explicit"])
|
|
@pytest.mark.parametrize("supplied", [False, True])
|
|
@pytest.mark.parametrize("timezone, expected_hour", [("UTC", 8), ("Europe/Berlin", 10)])
|
|
async def test_optimization_routes_only_selected_algorithm(
|
|
monkeypatch, offline_ems, algorithm, selection, supplied, timezone, expected_hour
|
|
):
|
|
"""Configuration selection and explicit overrides retain isolated async paths."""
|
|
selected_name = "Genetic" if algorithm == OptimizationAlgorithm.GENETIC else "Genetic0"
|
|
suffix = "genetic" if algorithm == OptimizationAlgorithm.GENETIC else "genetic0"
|
|
other_suffix = "genetic0" if suffix == "genetic" else "genetic"
|
|
sentinel_parameters = object()
|
|
sentinel_result, sentinel_plan = object(), object()
|
|
solution = SimpleNamespace(
|
|
optimization_solution=AsyncMock(return_value=sentinel_result),
|
|
energy_management_plan=Mock(return_value=sentinel_plan),
|
|
)
|
|
constructors = {}
|
|
preparers = {}
|
|
for prefix in ("Genetic", "Genetic0"):
|
|
constructor = Mock()
|
|
constructor.return_value.optimize_ems.return_value = solution
|
|
constructors[prefix] = constructor
|
|
monkeypatch.setattr(ems_module, prefix + "Optimization", constructor)
|
|
prepare = AsyncMock(return_value=sentinel_parameters)
|
|
preparers[prefix] = prepare
|
|
monkeypatch.setattr(
|
|
getattr(ems_module, prefix + "OptimizationParameters"), "prepare", prepare
|
|
)
|
|
kwargs: dict[str, Any] = {
|
|
"start_datetime": to_datetime("2026-09-16T10:00:00+02:00", in_timezone=timezone)
|
|
}
|
|
if selection == "configured":
|
|
offline_ems.config.optimization.algorithm = algorithm
|
|
else:
|
|
offline_ems.config.optimization.algorithm = OptimizationAlgorithm(other_suffix.upper())
|
|
kwargs["algorithm"] = algorithm
|
|
if supplied:
|
|
kwargs[suffix + "_parameters"] = sentinel_parameters
|
|
kwargs[suffix + "_generations"] = 7
|
|
kwargs[suffix + "_seed"] = 43
|
|
if algorithm == OptimizationAlgorithm.GENETIC:
|
|
kwargs["genetic_individuals"] = 11
|
|
run_result = await ems_module.EnergyManagement.run(offline_ems, **kwargs)
|
|
assert run_result is solution
|
|
selected = constructors[selected_name]
|
|
expected_config = getattr(offline_ems.config.optimization, suffix)
|
|
selected.assert_called_once_with(
|
|
verbose=False, fixed_seed=43 if supplied else expected_config.seed
|
|
)
|
|
expected_arguments: dict[str, Any] = {
|
|
"start_hour": expected_hour,
|
|
"parameters": sentinel_parameters,
|
|
"ngen": 7 if supplied else expected_config.generations,
|
|
}
|
|
if algorithm == OptimizationAlgorithm.GENETIC:
|
|
expected_arguments["individuals"] = 11 if supplied else None
|
|
selected.return_value.optimize_ems.assert_called_once_with(**expected_arguments)
|
|
other_name = "Genetic0" if selected_name == "Genetic" else "Genetic"
|
|
constructors[other_name].assert_not_called()
|
|
preparers[other_name].assert_not_awaited()
|
|
if supplied:
|
|
preparers[selected_name].assert_not_awaited()
|
|
else:
|
|
preparers[selected_name].assert_awaited_once_with()
|
|
solution.optimization_solution.assert_awaited_once_with()
|
|
solution.energy_management_plan.assert_called_once_with()
|
|
cls = ems_module.EnergyManagement
|
|
assert getattr(cls, "_" + suffix + "_solution") is solution
|
|
assert getattr(cls, "_" + other_suffix + "_solution") is None
|
|
assert cls.optimization_solution() is sentinel_result
|
|
assert cls.plan() is sentinel_plan
|
|
assert cls.stage() == ems_module.EnergyManagementStage.IDLE
|
|
offline_ems.prediction.update_data.assert_awaited_once_with(
|
|
force_enable=False, force_update=False
|
|
)
|
|
assert offline_ems.adapter.update_data.await_count == 2
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("mode", [EnergyManagementMode.DISABLED, EnergyManagementMode.PREDICTION])
|
|
async def test_non_optimization_modes_never_optimize(monkeypatch, offline_ems, mode):
|
|
constructors = [Mock(), Mock()]
|
|
monkeypatch.setattr(ems_module, "GeneticOptimization", constructors[0])
|
|
monkeypatch.setattr(ems_module, "Genetic0Optimization", constructors[1])
|
|
offline_ems.config.ems.mode = mode
|
|
await ems_module.EnergyManagement.run(offline_ems)
|
|
for constructor in constructors:
|
|
constructor.assert_not_called()
|
|
assert offline_ems.prediction.update_data.await_count == (
|
|
mode == EnergyManagementMode.PREDICTION
|
|
)
|
|
assert offline_ems.adapter.update_data.await_count == (mode == EnergyManagementMode.PREDICTION)
|
|
assert ems_module.EnergyManagement.plan() is None
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("prefix", ["Genetic", "Genetic0"])
|
|
async def test_missing_preparation_does_not_dispatch_controls(monkeypatch, offline_ems, prefix):
|
|
constructor = Mock()
|
|
monkeypatch.setattr(ems_module, prefix + "Optimization", constructor)
|
|
prepare = AsyncMock(return_value=None)
|
|
monkeypatch.setattr(getattr(ems_module, prefix + "OptimizationParameters"), "prepare", prepare)
|
|
await ems_module.EnergyManagement.run(
|
|
offline_ems, algorithm=OptimizationAlgorithm(prefix.upper())
|
|
)
|
|
prepare.assert_awaited_once_with()
|
|
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):
|
|
"""Even with GENETIC configured, /optimize must never become the new optimizer."""
|
|
from akkudoktoreos.server import eos
|
|
from akkudoktoreos.server.rest.error import EOSProblem
|
|
|
|
fake = SimpleNamespace(
|
|
run=AsyncMock(return_value=None), genetic0_solution=Mock(return_value=None)
|
|
)
|
|
monkeypatch.setattr(eos, "get_ems", lambda: fake)
|
|
parameters = Genetic0OptimizationParameters.model_validate(
|
|
{
|
|
"ems": {
|
|
"pv_prognose_wh": [0.0, 100.0],
|
|
"gesamtlast": [100.0, 100.0],
|
|
"strompreis_euro_pro_wh": [0.0003, 0.0003],
|
|
"einspeiseverguetung_euro_pro_wh": 0.00008,
|
|
"preis_euro_pro_wh_akku": 0.0,
|
|
},
|
|
"pv_akku": None,
|
|
"eauto": None,
|
|
"inverter": None,
|
|
}
|
|
)
|
|
with pytest.raises(EOSProblem):
|
|
await eos.fastapi_optimize(parameters=parameters, start_hour=start_hour, ngen=2)
|
|
kwargs = fake.run.await_args.kwargs
|
|
assert kwargs["mode"] == EnergyManagementMode.OPTIMIZATION
|
|
assert kwargs["algorithm"] == OptimizationAlgorithm.GENETIC0
|
|
assert kwargs["genetic0_parameters"] is parameters
|
|
assert kwargs["genetic0_generations"] == 2
|
|
assert "genetic_parameters" not in kwargs
|
|
assert (
|
|
kwargs["start_datetime"] is None
|
|
if start_hour is None
|
|
else kwargs["start_datetime"].hour == 11
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("phase", ["optimizer", "conversion", "plan"])
|
|
async def test_failed_legacy_http_run_never_reports_previous_solution(
|
|
monkeypatch, offline_ems, phase
|
|
):
|
|
import json
|
|
from pathlib import Path
|
|
from types import MethodType
|
|
|
|
from httpx import ASGITransport, AsyncClient
|
|
|
|
from akkudoktoreos.optimization.genetic0.genetic0solution import Genetic0Solution
|
|
from akkudoktoreos.server import eos
|
|
|
|
cls = ems_module.EnergyManagement
|
|
data = json.loads(
|
|
(Path(__file__).parent / "testdata/genetic0/optimize_result_1.json").read_text()
|
|
)
|
|
previous = Genetic0Solution.model_validate(data)
|
|
monkeypatch.setattr(cls, "_genetic0_solution", previous)
|
|
constructor = Mock()
|
|
error = RuntimeError("synthetic " + phase + " failure")
|
|
native = SimpleNamespace(
|
|
optimization_solution=AsyncMock(return_value=object()),
|
|
energy_management_plan=Mock(return_value=object()),
|
|
)
|
|
constructor.return_value.optimize_ems.return_value = native
|
|
if phase == "optimizer":
|
|
constructor.return_value.optimize_ems.side_effect = error
|
|
elif phase == "conversion":
|
|
native.optimization_solution.side_effect = error
|
|
else:
|
|
native.energy_management_plan.side_effect = error
|
|
monkeypatch.setattr(ems_module, "Genetic0Optimization", constructor)
|
|
offline_ems.run = MethodType(cls.run, offline_ems)
|
|
offline_ems.genetic0_solution = cls.genetic0_solution
|
|
monkeypatch.setattr(eos, "get_ems", lambda: offline_ems)
|
|
async with AsyncClient(
|
|
transport=ASGITransport(app=eos.app, raise_app_exceptions=False), base_url="http://test"
|
|
) as client:
|
|
response = await client.post("/optimize?ngen=1", json=data["parameters"])
|
|
constructor.return_value.optimize_ems.assert_called_once()
|
|
# This diagnostic proves a failure is the stale-success bug, not invalid input.
|
|
if response.status_code == 200:
|
|
assert response.json()["start_solution"] == previous.start_solution
|
|
assert response.json()["result"]["total_balance"] == previous.result.total_balance
|
|
assert response.status_code >= 400, (
|
|
"The failing optimizer returned HTTP 200 with the previous solution"
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("prefix", ["Genetic", "Genetic0"])
|
|
@pytest.mark.parametrize("phase", ["conversion", "plan"])
|
|
async def test_conversion_failure_preserves_consistent_previous_results(
|
|
monkeypatch, offline_ems, prefix, phase
|
|
):
|
|
cls = ems_module.EnergyManagement
|
|
previous_specific, previous_generic, previous_plan = object(), object(), object()
|
|
suffix = prefix.lower()
|
|
monkeypatch.setattr(cls, "_" + suffix + "_solution", previous_specific)
|
|
monkeypatch.setattr(cls, "_optimization_solution", previous_generic)
|
|
monkeypatch.setattr(cls, "_plan", previous_plan)
|
|
conversion = AsyncMock(return_value=object())
|
|
solution = SimpleNamespace(optimization_solution=conversion, energy_management_plan=Mock())
|
|
if phase == "conversion":
|
|
conversion.side_effect = RuntimeError("synthetic conversion failure")
|
|
else:
|
|
solution.energy_management_plan.side_effect = RuntimeError("synthetic plan failure")
|
|
constructor = Mock()
|
|
constructor.return_value.optimize_ems.return_value = solution
|
|
monkeypatch.setattr(ems_module, prefix + "Optimization", constructor)
|
|
supplied_parameters: dict[str, Any] = {suffix + "_parameters": object()}
|
|
result = await cls.run(
|
|
offline_ems,
|
|
algorithm=OptimizationAlgorithm(prefix.upper()),
|
|
**supplied_parameters,
|
|
)
|
|
assert result is None
|
|
conversion.assert_awaited_once_with()
|
|
assert solution.energy_management_plan.call_count == (phase == "plan")
|
|
assert offline_ems.adapter.update_data.await_count == 1
|
|
assert (
|
|
getattr(cls, "_" + suffix + "_solution"),
|
|
cls.optimization_solution(),
|
|
cls.plan(),
|
|
cls.stage(),
|
|
) == (
|
|
previous_specific,
|
|
previous_generic,
|
|
previous_plan,
|
|
ems_module.EnergyManagementStage.IDLE,
|
|
), (
|
|
"Failed conversion published a new algorithm result beside the old plan and left EMS in OPTIMIZATION"
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_legacy_endpoint_uses_run_return_value_not_last_cached_solution(monkeypatch):
|
|
import json
|
|
from pathlib import Path
|
|
|
|
from akkudoktoreos.optimization.genetic0.genetic0solution import Genetic0Solution
|
|
from akkudoktoreos.server import eos
|
|
|
|
data = json.loads(
|
|
(Path(__file__).parent / "testdata/genetic0/optimize_result_1.json").read_text()
|
|
)
|
|
produced = Genetic0Solution.model_validate(data)
|
|
fake = SimpleNamespace(
|
|
run=AsyncMock(return_value=produced),
|
|
genetic0_solution=Mock(side_effect=AssertionError("must use this run's result")),
|
|
)
|
|
monkeypatch.setattr(eos, "get_ems", lambda: fake)
|
|
result = await eos.fastapi_optimize(parameters=produced.parameters, ngen=1)
|
|
assert result.start_solution == produced.start_solution
|
|
assert result.result.total_balance == produced.result.total_balance
|
|
fake.genetic0_solution.assert_not_called()
|