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>
439 lines
17 KiB
Python
439 lines
17 KiB
Python
"""Economic tail scenarios and hard control/forecast boundaries."""
|
|
|
|
from unittest.mock import patch
|
|
|
|
import numpy as np
|
|
import pandas as pd
|
|
import pytest
|
|
|
|
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.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 (
|
|
GeneticOptimizationParameters,
|
|
)
|
|
from akkudoktoreos.optimization.genetic.tailvalue import build_tail_value_curve
|
|
from akkudoktoreos.optimization.genetic.terminalvalue 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,
|
|
)
|
|
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,
|
|
)
|
|
return bat, inv
|
|
|
|
|
|
def curve(
|
|
prices=(-0.1, 0.3),
|
|
tariffs=(0, 0.3),
|
|
direct=True,
|
|
continuation=None,
|
|
load=None,
|
|
pv=None,
|
|
**kwargs,
|
|
):
|
|
bat, inv = devices(**kwargs)
|
|
return build_tail_value_curve(
|
|
battery=bat,
|
|
inverter=inv,
|
|
prices_euro_per_wh=np.array(prices) / 1000,
|
|
feed_in_euro_per_wh=np.array(tariffs) / 1000,
|
|
load_wh=np.zeros(len(prices)) if load is None else np.array(load),
|
|
pv_wh=np.zeros(len(prices)) if pv is None else np.array(pv),
|
|
continuation=continuation or TerminalValueCurve(),
|
|
charge_rates=[0.5, 1],
|
|
export_rates=[1],
|
|
direct_marketing=direct,
|
|
)
|
|
|
|
|
|
def test_headroom_has_value_and_empty_state_can_earn():
|
|
c = curve()
|
|
assert c.value(0) == pytest.approx(0.4)
|
|
tail, continuation = c.component_values(0)
|
|
assert tail == pytest.approx(0.4)
|
|
assert continuation == pytest.approx(0.0)
|
|
assert c.value(0) == pytest.approx(tail + continuation)
|
|
assert c.value(500) > c.value(1000)
|
|
assert any(v < 0 for v in c.marginal_euro_per_kwh)
|
|
|
|
|
|
def test_chronology_changes_arbitrage():
|
|
forward = curve()
|
|
reverse = curve(prices=(0.3, -0.1), tariffs=(0.3, 0))
|
|
assert forward.value(0) > reverse.value(0)
|
|
|
|
|
|
def test_discharge_and_ac_power_limits():
|
|
limited = curve(prices=(1,), tariffs=(1,), power=100)
|
|
assert limited.value(1000) == pytest.approx(0.1)
|
|
limited_ac = curve(ac_limit=100)
|
|
assert limited_ac.value(0) == pytest.approx(0.04)
|
|
limited_inverter = curve(prices=(1,), tariffs=(1,), export_power=50)
|
|
assert limited_inverter.value(1000) == pytest.approx(0.05)
|
|
|
|
|
|
def test_losses_and_lcos_reduce_arbitrage():
|
|
ideal = curve(prices=(0.1, 0.3))
|
|
lossy = curve(prices=(0.1, 0.3), efficiency=0.8)
|
|
assert 0 < lossy.value(0) < ideal.value(0)
|
|
assert curve(prices=(0.1, 0.3), lcos=0.25).value(0) == pytest.approx(0)
|
|
|
|
|
|
def test_no_battery_export_without_permission():
|
|
assert curve(prices=(0.1, 0.3), direct=False).value(0) == pytest.approx(0)
|
|
|
|
|
|
def test_pv_surplus_can_be_stored_for_local_load():
|
|
c = curve(prices=(0.2, 0.3), tariffs=(0, 0), pv=[1000, 0], load=[0, 1000], direct=False)
|
|
assert c.value(0) == pytest.approx(0)
|
|
# Without PV the same empty battery must buy energy to serve the load.
|
|
assert curve(prices=(0.2, 0.3), tariffs=(0, 0), load=[0, 1000], direct=False).value(
|
|
0
|
|
) < c.value(0)
|
|
|
|
|
|
def test_continuation_survives_tail_end():
|
|
continuation = TerminalValueCurve(energy_wh=[0, 1000], value_euro=[0, 0.2])
|
|
c = curve(prices=(0.5,), tariffs=(0,), continuation=continuation)
|
|
assert c.value(1000) == pytest.approx(0.2)
|
|
tail, continuation_credit = c.component_values(1000)
|
|
assert tail == pytest.approx(0.0)
|
|
assert continuation_credit == pytest.approx(0.2)
|
|
|
|
|
|
def test_tail_diagnostic_plan_explains_the_selected_path():
|
|
c = curve()
|
|
plan = c.diagnostic_plan(0, control_horizon_hours=24)
|
|
assert len(plan) == 2
|
|
assert plan[0].hour_from_start == 24
|
|
assert plan[0].action == "GRID_CHARGE"
|
|
assert plan[0].soc_end_percentage > plan[0].soc_start_percentage
|
|
assert plan[0].grid_import_wh > 0
|
|
assert plan[1].action == "BATTERY_EXPORT"
|
|
assert plan[1].soc_end_percentage < plan[1].soc_start_percentage
|
|
assert plan[1].grid_export_wh > 0
|
|
assert sum(slot.slot_value_euro for slot in plan) == pytest.approx(c.value(0))
|
|
|
|
|
|
def test_central_config_invariant():
|
|
# Only the control horizon is mandatory. A prediction horizon that cannot
|
|
# cover the requested tail shortens the tail instead of failing the run,
|
|
# so existing configurations keep starting after an upgrade.
|
|
short = SettingsEOSDefaults.model_validate(
|
|
dict(
|
|
prediction={"hours": 48},
|
|
optimization={"genetic": {"horizon_hours": 24, "tail_horizon_hours": 48}},
|
|
)
|
|
)
|
|
assert short.prediction.hours == 48
|
|
assert short.optimization.genetic.tail_horizon_hours == 48
|
|
|
|
# A control horizon the forecast cannot serve is not rejected here either -
|
|
# prediction.hours also serves callers that never optimize. The optimizer
|
|
# rejects the run itself, naming the series that ran out.
|
|
undersized = SettingsEOSDefaults.model_validate(
|
|
dict(
|
|
prediction={"hours": 48},
|
|
optimization={"genetic": {"horizon_hours": 72, "tail_horizon_hours": 0}},
|
|
)
|
|
)
|
|
assert undersized.optimization.genetic.horizon_hours == 72
|
|
|
|
settings = SettingsEOSDefaults()
|
|
assert settings.prediction.hours == 48
|
|
assert settings.optimization.genetic.tail_horizon_hours == 48
|
|
|
|
|
|
def setup_run(config, interval=3600, start_hour=0, hours=72, prediction_hours=72):
|
|
config.merge_settings_from_dict(
|
|
{
|
|
"prediction": {"hours": prediction_hours},
|
|
"optimization": {
|
|
"genetic": {"horizon_hours": 24, "tail_horizon_hours": 48, "interval_sec": interval}
|
|
},
|
|
"feedintariff": {"direct_marketing_enabled": True},
|
|
}
|
|
)
|
|
ems = get_ems(init=True)
|
|
ems.set_start_datetime(to_datetime("2026-09-05T00:00:00").set(hour=start_hour))
|
|
bat, inv = devices()
|
|
params = GeneticOptimizationParameters.model_validate(
|
|
dict(
|
|
ems={
|
|
"pv_prognose_wh": [0.0] * hours,
|
|
"gesamtlast": [0.0] * hours,
|
|
"strompreis_euro_pro_wh": [0.0002] * hours,
|
|
"einspeiseverguetung_euro_pro_wh": [0.0001] * hours,
|
|
"preis_euro_pro_wh_akku": 0,
|
|
},
|
|
pv_battery=bat.parameters,
|
|
inverter=inv.parameters,
|
|
ev=None,
|
|
)
|
|
)
|
|
return GeneticOptimization(fixed_seed=42), params
|
|
|
|
|
|
@pytest.mark.parametrize("interval", [3600, 900])
|
|
@pytest.mark.parametrize("start_hour", [0, 10])
|
|
@pytest.mark.asyncio
|
|
async def test_genome_output_and_final_control_state(config_eos, interval, start_hour):
|
|
opt, params = setup_run(config_eos, interval, start_hour, hours=72 + start_hour)
|
|
|
|
def choose(*args, **kwargs):
|
|
# Discharge only in the last control slot. Its POST-slot SOC is credited.
|
|
genome = opt.create_individual()
|
|
genome[:] = [0] * opt.control_end_slot
|
|
genome[-1] = opt._battery_state_layout().grid_export_state
|
|
assert len(genome) == 24 * (3600 // interval)
|
|
return genome, {}
|
|
|
|
with (
|
|
patch.object(opt, "optimize", side_effect=choose),
|
|
patch(
|
|
"akkudoktoreos.optimization.genetic.genetic.build_tail_value_curve",
|
|
wraps=build_tail_value_curve,
|
|
) as builder,
|
|
):
|
|
result = opt.optimize_ems(params)
|
|
assert builder.call_count == 1
|
|
assert len(result.ac_charge) == opt.control_slots
|
|
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 result.terminal_value.mode == "TAIL"
|
|
assert result.terminal_value.battery_energy_wh == pytest.approx(
|
|
max(500 - 1000 * opt.slot_duration_h, 0)
|
|
)
|
|
assert result.terminal_value.effective_tail_hours == 48
|
|
assert result.terminal_value.credited_euro == pytest.approx(
|
|
result.terminal_value.tail_operating_euro + result.terminal_value.continuation_value_euro
|
|
)
|
|
assert result.terminal_value.continuation_curve is not None
|
|
assert result.terminal_value.tail_diagnostics is not None
|
|
assert result.terminal_value.tail_diagnostics.slots == 48 * (3600 // interval)
|
|
assert result.terminal_value.tail_diagnostics.soc_grid_points == 101
|
|
assert len(result.terminal_value.tail_plan) == result.terminal_value.tail_diagnostics.slots
|
|
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
|
|
|
|
|
|
def test_short_tail_is_reported(config_eos, caplog):
|
|
opt, params = setup_run(config_eos, hours=52)
|
|
with patch.object(
|
|
opt, "optimize", side_effect=lambda *a, **k: ([0] * opt.control_end_slot, {})
|
|
):
|
|
result = opt.optimize_ems(params)
|
|
assert result.terminal_value.effective_tail_hours == 28
|
|
assert "Tail forecast shortened" in caplog.text
|
|
assert result.terminal_value.reason
|
|
|
|
|
|
def test_missing_control_is_rejected(config_eos):
|
|
opt, params = setup_run(config_eos, hours=23)
|
|
with pytest.raises(ValueError, match="Incomplete control forecast"):
|
|
opt.optimize_ems(params)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_provider_values_are_not_extrapolated():
|
|
from types import SimpleNamespace
|
|
|
|
start = to_datetime("2026-09-05T00:00:00Z")
|
|
series = pd.Series([1.0, 2.0], index=pd.date_range(start=start, periods=2, freq="h"))
|
|
from unittest.mock import AsyncMock
|
|
|
|
provider = SimpleNamespace(key_to_raw_series=AsyncMock(return_value=series))
|
|
result = await bounded_forecast_array(
|
|
provider,
|
|
key="price",
|
|
start_datetime=start,
|
|
end_datetime=start.add(hours=3),
|
|
interval=to_duration("15 minutes"),
|
|
)
|
|
assert result[:8].tolist() == [1.0] * 4 + [2.0] * 4
|
|
assert np.isnan(result[8:]).all()
|
|
|
|
|
|
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)
|
|
config_eos.merge_settings_from_dict(
|
|
{"optimization": {"genetic": {"horizon_hours": 1, "tail_horizon_hours": 2}}}
|
|
)
|
|
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)
|
|
final_energy.append(result.terminal_value.battery_energy_wh)
|
|
assert final_energy[0] > final_energy[1]
|
|
|
|
|
|
@pytest.mark.parametrize("control", [24, 48])
|
|
def test_continuation_prevents_emptying_at_moved_boundary(config_eos, control):
|
|
opt, params = setup_run(config_eos, hours=96)
|
|
config_eos.merge_settings_from_dict(
|
|
{"prediction": {"hours": 96}, "optimization": {"genetic": {"horizon_hours": control}}}
|
|
)
|
|
# Zero control load, with the same future local demand visible to both tails.
|
|
params.ems.gesamtlast[60] = 1000
|
|
params.ems.feed_in_tariff_per_wh = [0.0] * 96
|
|
config_eos.feedintariff.direct_marketing_enabled = False
|
|
|
|
def choose(*a, **kw):
|
|
from deap import creator
|
|
|
|
idle = creator.Individual([0] * control)
|
|
discharge = creator.Individual([len(opt.bat_possible_charge_values)] * control)
|
|
assert opt.toolbox.evaluate(idle)[0] <= opt.toolbox.evaluate(discharge)[0]
|
|
return idle, {}
|
|
|
|
with patch.object(opt, "optimize", side_effect=choose):
|
|
result = opt.optimize_ems(params)
|
|
assert result.terminal_value.battery_energy_wh == pytest.approx(500)
|
|
assert result.terminal_value.continuation_mode == "AUTO"
|
|
|
|
|
|
def test_missing_price_inside_tail_stops_at_first_gap(config_eos):
|
|
opt, params = setup_run(config_eos)
|
|
params.ems.electricity_price_per_wh[30] = float("nan")
|
|
with patch.object(opt, "optimize", side_effect=lambda *a, **k: ([0] * opt.control_slots, {})):
|
|
result = opt.optimize_ems(params)
|
|
assert result.terminal_value.effective_tail_hours == 6
|
|
|
|
|
|
def test_ev_genome_and_output_are_control_only(config_eos):
|
|
from akkudoktoreos.devices.genetic.battery import ElectricVehicleParameters
|
|
|
|
opt, params = setup_run(config_eos, interval=900, start_hour=10, hours=82)
|
|
params.ev = ElectricVehicleParameters(
|
|
device_id="ev1",
|
|
capacity_wh=5000,
|
|
initial_soc_percentage=0,
|
|
min_soc_percentage=50,
|
|
charge_rates=[0, 0.5, 1],
|
|
)
|
|
|
|
def choose(*a, **kw):
|
|
genome = opt.create_individual()
|
|
assert len(genome) == 2 * 96
|
|
return genome, {}
|
|
|
|
with patch.object(opt, "optimize", side_effect=choose):
|
|
result = opt.optimize_ems(params)
|
|
assert len(result.ev_charge_hours_float) == 96
|
|
|
|
|
|
def test_rejected_config_update_is_atomic(config_eos):
|
|
# The candidate is validated before the singleton is reinitialized, so a
|
|
# rejected update must leave the running configuration untouched rather
|
|
# than half-applied. `hours` is constrained to be non-negative.
|
|
before = config_eos.prediction.hours
|
|
with pytest.raises(ValueError):
|
|
config_eos.merge_settings_from_dict({"prediction": {"hours": -1}})
|
|
assert config_eos.prediction.hours == before
|
|
|
|
|
|
def test_disabled_ac_conversion_cannot_earn_negative_price_revenue():
|
|
bat, inv = devices()
|
|
inv.parameters.ac_to_dc_efficiency = 0
|
|
c = build_tail_value_curve(
|
|
battery=bat,
|
|
inverter=inv,
|
|
prices_euro_per_wh=np.array([-0.001, 0.001]),
|
|
feed_in_euro_per_wh=np.array([0.0, 0.001]),
|
|
load_wh=np.zeros(2),
|
|
pv_wh=np.zeros(2),
|
|
continuation=TerminalValueCurve(),
|
|
charge_rates=[1],
|
|
export_rates=[1],
|
|
direct_marketing=True,
|
|
)
|
|
assert c.value(0) == pytest.approx(0)
|
|
assert bat.soc_wh == 500 # Building the tail never mutates the real battery.
|
|
|
|
|
|
def test_short_native_forecast_declares_its_resolution(config_eos):
|
|
opt, params = setup_run(config_eos, interval=900, hours=52 * 4)
|
|
params.forecast_interval_seconds = 900
|
|
with patch.object(opt, "optimize", side_effect=lambda *a, **k: ([0] * opt.control_slots, {})):
|
|
result = opt.optimize_ems(params)
|
|
assert result.terminal_value.effective_tail_hours == 28
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"field,reason",
|
|
[
|
|
("electricity_price_per_wh", "import price"),
|
|
("feed_in_tariff_per_wh", "feed-in tariff"),
|
|
],
|
|
)
|
|
def test_differing_provider_lengths_use_the_common_tail(config_eos, field, reason):
|
|
opt, params = setup_run(config_eos)
|
|
setattr(params.ems, field, getattr(params.ems, field)[:52])
|
|
with patch.object(opt, "optimize", side_effect=lambda *a, **k: ([0] * opt.control_slots, {})):
|
|
result = opt.optimize_ems(params)
|
|
assert result.terminal_value.effective_tail_hours == 28
|
|
assert reason in result.terminal_value.reason
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_missing_provider_key_stays_missing():
|
|
from types import SimpleNamespace
|
|
|
|
async def unavailable(*a, **kw):
|
|
raise KeyError("price unavailable")
|
|
|
|
start = to_datetime("2026-09-05T00:00:00Z")
|
|
result = await bounded_forecast_array(
|
|
SimpleNamespace(key_to_raw_series=unavailable),
|
|
key="price",
|
|
start_datetime=start,
|
|
end_datetime=start.add(hours=2),
|
|
interval=to_duration("1 hour"),
|
|
)
|
|
assert np.isnan(result).all()
|
|
assert len(result) == 2
|
|
|
|
|
|
def test_short_prediction_horizon_shortens_the_tail(config_eos):
|
|
# The forecast budget cannot serve the full 48 h tail. The run keeps going
|
|
# with the 12 h that are left after the control horizon instead of failing.
|
|
opt, params = setup_run(config_eos, hours=36, prediction_hours=36)
|
|
assert opt.control_slots == 24
|
|
assert opt.tail_slots == 12
|
|
|
|
result = opt.optimize_ems(params, ngen=2)
|
|
assert result.terminal_value.mode == "TAIL"
|
|
assert result.terminal_value.requested_tail_hours == 48
|
|
assert result.terminal_value.effective_tail_hours == 12
|