Files
EOS/tests/test_geneticparamsfeedin.py
Bobby NoelteandClaude Opus 5.5 b3d5334d3e 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)
2026-11-27 13:55:41 +01:00

181 lines
7.2 KiB
Python

"""Keep imported sale revenues separate from purchase prices in main's async GENETIC path.
Adapted from PRs #1224 (Christin) and #1304 (Normann). Main has no direct-marketing
parameter override yet: these regressions cover its existing preparation/simulation
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
import numpy as np
import pandas as pd
import pytest
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
from akkudoktoreos.utils.datetimeutil import to_datetime
@pytest.fixture
def prepare_tariffs(config_eos):
"""Run real async preparation with deterministic forecasts and no device fallback."""
async def prepare(provider, revenues, tariff_reader=None):
config_eos.merge_settings_from_dict(
{
"prediction": {"hours": 24},
"optimization": {"genetic": {"horizon_hours": 24, "interval_sec": 3600}},
"feedintariff": {"provider": provider},
"elecfee": {"provider": None},
"devices": {
"max_batteries": 0,
"max_electric_vehicles": 0,
"max_inverters": 1,
"inverters": {"inverter1": {"profile_adjustment": {"nominal_power_w": 10000}}},
"max_home_appliances": 0,
},
}
)
prices = np.array([0.000269, -0.00002] * 12)
arrays = {
"weather_temp_air": np.full(24, 20.0),
"pvforecast_ac_power": np.full(24, 1000.0),
"loadforecast_power_w": np.zeros(24),
"elecprice_marketprice_wh": prices,
"feed_in_tariff_wh": revenues,
}
async def read_series(key, **kwargs):
if key == "feed_in_tariff_wh" and tariff_reader is not None:
return await tariff_reader(key=key, **kwargs)
value = arrays[key]
if isinstance(value, Exception):
raise value
return pd.Series(
value, index=pd.date_range("2026-08-01T00:00:00Z", periods=len(value), freq="h")
)
prediction = Mock(
update_data=AsyncMock(), key_to_raw_series=AsyncMock(side_effect=read_series)
)
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
@pytest.mark.asyncio
@pytest.mark.parametrize(
"provider",
[
"FeedInTariffImport",
"FeedInTariffAkkudoktor",
"FeedInTariffEnergyCharts",
"FeedInTariffTibber",
"FeedInTariffFixed",
"FeedInTariffSMARD",
"FeedInTariffDvhubOnline",
],
)
@pytest.mark.parametrize("revenues", [[0.00007], [0.0], [-0.00005], [0.000184, -0.00005]])
async def test_provider_revenues_survive_preparation_and_simulation(
prepare_tariffs, provider, revenues, config_eos
):
expected = (revenues * 24)[:24]
parameters, prices, prediction = await prepare_tariffs(provider, expected)
assert parameters is not None
assert parameters.ems.feed_in_tariff_per_wh == expected
assert parameters.ems.einspeiseverguetung_euro_pro_wh == expected
assert parameters.ems.electricity_price_per_wh == prices.tolist()
assert config_eos.feedintariff.provider == provider
prediction.update_data.assert_awaited_once()
# 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 = 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.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)
assert result["Einnahmen_Euro_pro_Stunde"] == pytest.approx(np.array(expected) * 1000)
assert result["Gesamteinnahmen_Euro"] == pytest.approx(sum(expected) * 1000)
assert result["Gesamtbilanz_Euro"] == pytest.approx(-sum(expected) * 1000)
assert parameters.ems.feed_in_tariff_per_wh == expected
@pytest.mark.asyncio
@pytest.mark.parametrize(
"revenues",
[
KeyError("feed_in_tariff_wh"),
RuntimeError("import unavailable"),
[],
[0.00007] * 23,
[np.nan] * 24,
[0.00007] * 23 + [np.nan],
[np.inf] * 24,
[-np.inf] * 24,
[None] * 24,
[[0.00007]] * 24,
],
)
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)
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 "feed-in tariff missing or invalid" in caplog.text
assert "defaulting to demo" not in caplog.text
def test_prediction_record_prices_are_already_per_wh():
record = FeedInTariffDataRecord(feed_in_tariff_wh=0.00007)
assert record.feed_in_tariff_kwh == pytest.approx(0.07)
@pytest.mark.asyncio
@pytest.mark.parametrize("values", [[0.000184, -0.00005] * 12, [0.0] * 24, [None] * 24])
async def test_timestamped_import_records_are_read_in_order(prepare_tariffs, values):
provider = FeedInTariffImport()
provider._db_reset_state()
start = to_datetime("2026-08-01T00:00:00+00:00", in_timezone="UTC").set(hour=0)
try:
await provider.key_from_series(
"feed_in_tariff_wh",
pd.Series(values, index=pd.date_range(start=start, periods=24, freq="h")),
)
parameters, _, _ = await prepare_tariffs(
"FeedInTariffImport", [], tariff_reader=provider.key_to_raw_series
)
if values[0] 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)
finally:
provider._db_reset_state()