mirror of
https://github.com/Akkudoktor-EOS/EOS.git
synced 2026-10-08 23:46:38 +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>
386 lines
15 KiB
Python
386 lines
15 KiB
Python
from pathlib import Path
|
|
from typing import Optional
|
|
from unittest.mock import MagicMock
|
|
|
|
import pytest
|
|
|
|
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 (
|
|
GeneticOptimizationParameters,
|
|
)
|
|
from akkudoktoreos.optimization.genetic.geneticsolution import GeneticSolution
|
|
from akkudoktoreos.utils.datetimeutil import to_datetime
|
|
|
|
ems_eos = get_ems(init=True) # init once
|
|
|
|
DIR_TESTDATA = Path(__file__).parent / "testdata"
|
|
|
|
|
|
def test_direct_marketing_preserves_constant_supplied_feed_in_tariff(config_eos: ConfigEOS):
|
|
config_eos.merge_settings_from_dict({"feedintariff": {"direct_marketing_enabled": True}})
|
|
parameters = GeneticOptimizationParameters.model_validate(
|
|
dict(
|
|
ems={
|
|
"pv_prognose_wh": [0.0, 0.0],
|
|
"strompreis_euro_pro_wh": [0.0002, -0.0001],
|
|
"einspeiseverguetung_euro_pro_wh": [0.00007, 0.00007],
|
|
"preis_euro_pro_wh_akku": 0.0,
|
|
"gesamtlast": [0.0, 0.0],
|
|
},
|
|
pv_battery=None,
|
|
# Without an inverter the simulation books no grid energy at all, so the
|
|
# price signal would never reach the fitness.
|
|
inverter={"device_id": "inverter1", "max_power_wh": 20000},
|
|
ev=None,
|
|
)
|
|
)
|
|
|
|
adjusted = GeneticOptimization()._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]
|
|
|
|
|
|
def test_direct_marketing_keeps_variable_feed_in_tariff(config_eos: ConfigEOS):
|
|
config_eos.merge_settings_from_dict({"feedintariff": {"direct_marketing_enabled": True}})
|
|
parameters = GeneticOptimizationParameters.model_validate(
|
|
dict(
|
|
ems={
|
|
"pv_prognose_wh": [0.0, 0.0],
|
|
"strompreis_euro_pro_wh": [0.0002, 0.0003],
|
|
"einspeiseverguetung_euro_pro_wh": [0.0001, -0.00005],
|
|
"preis_euro_pro_wh_akku": 0.0,
|
|
"gesamtlast": [0.0, 0.0],
|
|
},
|
|
pv_battery=None,
|
|
inverter=None,
|
|
ev=None,
|
|
)
|
|
)
|
|
|
|
adjusted = GeneticOptimization()._parameters_for_config(parameters)
|
|
|
|
assert adjusted.ems.einspeiseverguetung_euro_pro_wh == [0.0001, -0.00005]
|
|
|
|
|
|
def test_grid_export_rates_reach_the_solution(config_eos: ConfigEOS):
|
|
"""Configured export rates end up as per-slot export levels in the solution."""
|
|
config_eos.merge_settings_from_dict(
|
|
{
|
|
"prediction": {"hours": 24},
|
|
"optimization": {
|
|
"genetic": {
|
|
"individuals": 40,
|
|
"generations": 10,
|
|
"tail_horizon_hours": 0,
|
|
"horizon_hours": 24,
|
|
"interval_sec": 3600,
|
|
}
|
|
},
|
|
"feedintariff": {"direct_marketing_enabled": True},
|
|
"devices": {
|
|
"max_batteries": 1,
|
|
"batteries": {
|
|
"battery1": {"device_id": "battery1", "grid_export_rates": [0.5, 1.0]}
|
|
},
|
|
},
|
|
}
|
|
)
|
|
ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0))
|
|
CacheEnergyManagementStore().clear()
|
|
|
|
hours = 24
|
|
parameters = GeneticOptimizationParameters.model_validate(
|
|
dict(
|
|
ems={
|
|
"pv_prognose_wh": [0.0] * hours,
|
|
"strompreis_euro_pro_wh": [0.0003] * hours,
|
|
# A pronounced tariff peak makes exporting worthwhile at all.
|
|
"einspeiseverguetung_euro_pro_wh": [0.0001] * 12 + [0.0009] * 12,
|
|
"preis_euro_pro_wh_akku": 0.0,
|
|
"gesamtlast": [200.0] * hours,
|
|
},
|
|
pv_battery={
|
|
"device_id": "battery1",
|
|
"capacity_wh": 10000,
|
|
"initial_soc_percentage": 100,
|
|
"min_soc_percentage": 0,
|
|
"max_charge_power_w": 5000,
|
|
},
|
|
inverter={
|
|
"device_id": "inverter1",
|
|
"max_power_wh": 10000,
|
|
"battery_id": "battery1",
|
|
},
|
|
ev=None,
|
|
)
|
|
)
|
|
|
|
optimization = GeneticOptimization(fixed_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.
|
|
assert optimization.bat_possible_grid_export_values == [1.0, 0.5]
|
|
assert len(solution.battery_grid_export_factor) == len(solution.battery_grid_export_allowed)
|
|
assert set(solution.battery_grid_export_factor) <= {0.0, 0.5, 1.0}
|
|
assert [
|
|
1 if factor > 0.0 else 0 for factor in solution.battery_grid_export_factor
|
|
] == solution.battery_grid_export_allowed
|
|
|
|
# @TODO
|
|
|
|
|
|
def _ev_deadline_parameters(hours: int, **ev_extra) -> GeneticOptimizationParameters:
|
|
"""Optimization parameters with an EV that has to be charged."""
|
|
return GeneticOptimizationParameters.model_validate(
|
|
dict(
|
|
ems={
|
|
"pv_prognose_wh": [0.0] * hours,
|
|
# Expensive for the first six hours, dirt cheap afterwards: without a
|
|
# deadline the optimizer would always wait for the cheap slots.
|
|
"strompreis_euro_pro_wh": [0.0009] * 6 + [0.00001] * (hours - 6),
|
|
"einspeiseverguetung_euro_pro_wh": [0.00007] * hours,
|
|
"preis_euro_pro_wh_akku": 0.0,
|
|
"gesamtlast": [300.0] * hours,
|
|
},
|
|
pv_battery=None,
|
|
inverter=None,
|
|
ev={
|
|
"device_id": "ev1",
|
|
"capacity_wh": 60000,
|
|
"charging_efficiency": 0.95,
|
|
"max_charge_power_w": 11040,
|
|
"initial_soc_percentage": 20,
|
|
"min_soc_percentage": 60,
|
|
**ev_extra,
|
|
},
|
|
)
|
|
)
|
|
|
|
|
|
def test_ev_deadline_slot_resolution(config_eos: ConfigEOS):
|
|
"""Datetime and maximum duration resolve to a slot; the earlier one wins."""
|
|
config_eos.merge_settings_from_dict(
|
|
{
|
|
"prediction": {"hours": 48},
|
|
"optimization": {
|
|
"genetic": {"tail_horizon_hours": 0, "horizon_hours": 48, "interval_sec": 3600}
|
|
},
|
|
}
|
|
)
|
|
ems_eos.set_start_datetime(to_datetime().set(hour=10, minute=0))
|
|
optimization = GeneticOptimization(fixed_seed=1)
|
|
optimization._slot0_datetime = optimization.ems.start_datetime
|
|
slot0 = optimization._slot0_datetime
|
|
|
|
# Duration only: 6 h after the start hour 10.
|
|
parameters = _ev_deadline_parameters(48, min_soc_max_duration_h=6)
|
|
assert optimization._ev_deadline_slot(parameters) == 6
|
|
|
|
# Datetime only.
|
|
parameters = _ev_deadline_parameters(48, min_soc_deadline_datetime=slot0.add(hours=14))
|
|
assert optimization._ev_deadline_slot(parameters) == 14
|
|
|
|
# Both: the earlier one wins.
|
|
parameters = _ev_deadline_parameters(
|
|
48, min_soc_deadline_datetime=slot0.add(hours=20), min_soc_max_duration_h=6
|
|
)
|
|
assert optimization._ev_deadline_slot(parameters) == 6
|
|
|
|
# Beyond the horizon: no deadline, the end-of-horizon target already covers it.
|
|
parameters = _ev_deadline_parameters(48, min_soc_deadline_datetime=slot0.add(hours=100))
|
|
assert optimization._ev_deadline_slot(parameters) is None
|
|
|
|
# In the past: due right now.
|
|
parameters = _ev_deadline_parameters(48, min_soc_deadline_datetime=slot0.subtract(hours=2))
|
|
assert optimization._ev_deadline_slot(parameters) == 0
|
|
|
|
# No deadline at all.
|
|
assert optimization._ev_deadline_slot(_ev_deadline_parameters(48)) is None
|
|
|
|
|
|
def test_ev_soc_penalty_reads_the_deadline_slot(config_eos: ConfigEOS):
|
|
"""With a deadline the penalty checks the SoC at that slot, not at the end."""
|
|
config_eos.merge_settings_from_dict(
|
|
{
|
|
"prediction": {"hours": 48},
|
|
"optimization": {
|
|
"genetic": {"tail_horizon_hours": 0, "horizon_hours": 48, "interval_sec": 3600}
|
|
},
|
|
}
|
|
)
|
|
ems_eos.set_start_datetime(to_datetime().set(hour=10, minute=0))
|
|
optimization = GeneticOptimization(fixed_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.current_soc_percentage.return_value = 80.0
|
|
|
|
# Without a deadline the final SoC counts.
|
|
optimization._ev_soc_deadline_slot = None
|
|
assert optimization._ev_soc_at_deadline(simulation_result, 10) == 80.0
|
|
|
|
# With one, the SoC at the beginning of the deadline slot counts.
|
|
optimization._ev_soc_deadline_slot = 12
|
|
assert optimization._ev_soc_at_deadline(simulation_result, 10) == 50.0
|
|
|
|
# A deadline beyond the reported slots falls back to the final SoC.
|
|
optimization._ev_soc_deadline_slot = 99
|
|
assert optimization._ev_soc_at_deadline(simulation_result, 10) == 80.0
|
|
|
|
|
|
def test_ev_deadline_charges_before_departure(config_eos: ConfigEOS):
|
|
"""The EV reaches its target before the deadline even when energy is cheaper later."""
|
|
hours = 24
|
|
config_eos.merge_settings_from_dict(
|
|
{
|
|
"prediction": {"hours": hours},
|
|
"optimization": {
|
|
"genetic": {
|
|
"individuals": 100,
|
|
"generations": 40,
|
|
"tail_horizon_hours": 0,
|
|
"horizon_hours": hours,
|
|
"interval_sec": 3600,
|
|
}
|
|
},
|
|
}
|
|
)
|
|
ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0))
|
|
CacheEnergyManagementStore().clear()
|
|
|
|
parameters = _ev_deadline_parameters(hours, min_soc_max_duration_h=6)
|
|
solution = GeneticOptimization(fixed_seed=42).optimize_ems(
|
|
parameters=parameters, start_hour=0, ngen=40
|
|
)
|
|
|
|
soc_per_hour = solution.result.ev_soc_per_hour
|
|
# Slot 6 is the first slot at or after the deadline, so its start-of-slot SoC
|
|
# is what the target is checked against.
|
|
assert soc_per_hour[6] >= 60.0
|
|
|
|
|
|
def _terminal_value_run(
|
|
config_eos: ConfigEOS, mode: str, prices: Optional[list[float]] = None
|
|
) -> GeneticSolution:
|
|
"""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
|
|
value beyond the horizon.
|
|
"""
|
|
hours = 48
|
|
config_eos.merge_settings_from_dict(
|
|
{
|
|
"prediction": {"hours": hours},
|
|
"optimization": {
|
|
"genetic": {
|
|
"individuals": 80,
|
|
"generations": 20,
|
|
"tail_horizon_hours": 0,
|
|
"horizon_hours": hours,
|
|
"interval_sec": 3600,
|
|
"terminal_value_mode": mode,
|
|
"terminal_value_euro_per_kwh": 0.0,
|
|
}
|
|
},
|
|
}
|
|
)
|
|
ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0))
|
|
CacheEnergyManagementStore().clear()
|
|
|
|
if prices is None:
|
|
prices = [0.0004] * (hours - 2) + [0.00002] * 2
|
|
parameters = GeneticOptimizationParameters.model_validate(
|
|
dict(
|
|
ems={
|
|
"pv_prognose_wh": [0.0] * hours,
|
|
"strompreis_euro_pro_wh": prices,
|
|
"einspeiseverguetung_euro_pro_wh": [0.00007] * hours,
|
|
"preis_euro_pro_wh_akku": 0.0,
|
|
"gesamtlast": [200.0] * hours,
|
|
},
|
|
pv_battery={
|
|
"device_id": "battery1",
|
|
"capacity_wh": 10000,
|
|
"initial_soc_percentage": 20,
|
|
"min_soc_percentage": 0,
|
|
"max_soc_percentage": 100,
|
|
"charging_efficiency": 1.0,
|
|
"discharging_efficiency": 1.0,
|
|
"max_charge_power_w": 5000,
|
|
},
|
|
inverter={
|
|
"device_id": "inverter1",
|
|
"max_power_wh": 10000,
|
|
"battery_id": "battery1",
|
|
"ac_to_dc_efficiency": 1.0,
|
|
"dc_to_ac_efficiency": 1.0,
|
|
"max_ac_charge_power_w": 5000,
|
|
},
|
|
ev=None,
|
|
)
|
|
)
|
|
return GeneticOptimization(fixed_seed=7).optimize_ems(
|
|
parameters=parameters, start_hour=0, ngen=20
|
|
)
|
|
|
|
|
|
def test_terminal_value_auto_keeps_energy_that_fixed_zero_throws_away(config_eos: ConfigEOS):
|
|
"""AUTO values the energy left in the battery, a fixed zero does not."""
|
|
auto = _terminal_value_run(config_eos, "AUTO")
|
|
fixed = _terminal_value_run(config_eos, "FIXED")
|
|
|
|
assert auto.terminal_value is not None
|
|
assert auto.terminal_value.mode == "AUTO"
|
|
assert auto.terminal_value.curve is not None
|
|
assert auto.terminal_value.credited_euro > 0.0
|
|
|
|
assert fixed.terminal_value is not None
|
|
assert fixed.terminal_value.mode == "FIXED"
|
|
assert fixed.terminal_value.credited_euro == 0.0
|
|
|
|
# The cheap slots at the end are only worth using with a terminal value.
|
|
assert auto.result.battery_soc_per_hour[-1] > fixed.result.battery_soc_per_hour[-1]
|
|
|
|
|
|
def test_terminal_value_curve_is_concave_and_reported(config_eos: ConfigEOS):
|
|
"""The reported curve is what the credit was read from."""
|
|
solution = _terminal_value_run(config_eos, "AUTO")
|
|
assert solution.terminal_value is not None
|
|
curve = solution.terminal_value.curve
|
|
assert curve is not None
|
|
|
|
assert curve.window_slots == 24
|
|
assert len(curve.energy_wh) == len(curve.value_euro)
|
|
assert len(curve.marginal_euro_per_kwh) == len(curve.energy_wh) - 1
|
|
marginals = curve.marginal_euro_per_kwh
|
|
assert all(a >= b for a, b in zip(marginals, marginals[1:]))
|
|
|
|
# The credit is the curve evaluated at the energy left in the battery.
|
|
expected = curve.value(solution.terminal_value.battery_energy_wh)
|
|
assert solution.terminal_value.credited_euro == pytest.approx(expected)
|
|
|
|
|
|
def test_terminal_value_reports_why_it_fell_back_to_fixed(config_eos: ConfigEOS):
|
|
"""AUTO without any prices cannot build a curve - and has to say so.
|
|
|
|
A request whose price forecast is all zeros used to be indistinguishable
|
|
from a run configured for FIXED.
|
|
"""
|
|
hours = 48
|
|
solution = _terminal_value_run(config_eos, "AUTO", prices=[0.0] * hours)
|
|
|
|
assert solution.terminal_value is not None
|
|
assert solution.terminal_value.mode == "FIXED"
|
|
assert solution.terminal_value.curve is None
|
|
assert solution.terminal_value.reason is not None
|
|
assert "no priced residual load" in solution.terminal_value.reason
|
|
|
|
configured = _terminal_value_run(config_eos, "FIXED")
|
|
assert configured.terminal_value is not None
|
|
assert configured.terminal_value.reason == "terminal_value_mode is FIXED"
|