mirror of
https://github.com/Akkudoktor-EOS/EOS.git
synced 2026-11-13 09:13:30 +01:00
An inverter profile describes the technical data of an inverter model: its nominal AC power, the DC→AC and AC→DC efficiency curves over the load fraction (AC power relative to the nominal power), the AC charge power limit of the model, whether that limit also limits PV charging, and an optional power derating over the ambient temperature. Curves are read linearly and clamped at their ends, so every lookup yields a value. The packaged profile generic-hybrid has typical hybrid inverter efficiencies, no nominal power (the inverter device has to provide it) and full power up to 45 degC. Inverter settings name their profile (inverter_profile, default generic-hybrid) and hold the differences of the unit in profile_adjustment: nominal_power_w (replaces the profile value, required for a generic profile), max_power_w and max_ac_charge_power_w (installation limits that can only lower; an AC charge limit of 0 disables AC charging). The effective parameters are resolved at the ambient temperature of the inverter, given by the new measurement key <device_id>-temperature-degc (45 degC without a fresh value); the power derating lowers the maximum power and the AC charge limit. Optimization parameters are always valid: the GENETIC and GENETIC0 parameter preparation resolve the inverter with resolve_current_operating_parameters_or_defaults, which never raises. An unusable profile gives the generic-hybrid profile, a missing nominal power the fallback of 10000 W, an inverter derated to zero power the parameters at 45 degC, and no usable profile at all the profile adjustment with constant efficiency; each is logged as error. The GENETIC inverter takes the AC→DC efficiency curve of the profile, solved exactly on each linear piece of the curve (about 2 % longer runs); GENETIC0 keeps constant efficiencies and no longer replaces the configured inverters with the demo inverter; a battery, electric vehicle or inverter that cannot be prepared is left out of the GENETIC0 run, never replaced by a demo device. Configurations migrate: max_power_w becomes profile_adjustment.nominal_power_w, max_ac_charge_power_w moves into the adjustment, an ac_to_dc_efficiency of 0 keeps AC charging disabled, and the efficiency fields are dropped with an error log, as for batteries, so the profile efficiencies apply. Home Assistant config paths follow. Additional changes - Move the curve algorithms of the battery profile into profilecurve, so battery and inverter profiles share them; the battery profile keeps its document format and classes. - Move ProfileBaseModel, the strict base of profile documents, into profilestore. - Serve inverter profiles through the profile REST API. Refuse to delete a profile that a configured device uses and that has no packaged profile to revert to (409). - Share the measurement access of the device settings in devicemeasurement. - Rename check_battery_profiles to check_device_profiles; the device profile check at configuration setup covers inverters, too. - Document inverter profiles, their configuration, defaults and sharing; regenerate the configuration and OpenAPI documentation. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Assisted-by: Claude Code (claude-opus-5-5)
179 lines
7.1 KiB
Python
179 lines
7.1 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 and refuse unavailable imported revenue 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.devices.genetic.inverter import Inverter, InverterParameters
|
|
from akkudoktoreos.optimization.genetic.configrequest import ConfigOptimizationRequest
|
|
from akkudoktoreos.optimization.genetic.genetic import GeneticSimulation
|
|
from akkudoktoreos.optimization.genetic.geneticparams import (
|
|
GeneticOptimizationParameters,
|
|
)
|
|
from akkudoktoreos.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)
|
|
)
|
|
ems = Mock(
|
|
start_datetime=to_datetime("2026-08-01T00:00:00+00:00", in_timezone="UTC"),
|
|
observation_datetime=to_datetime("2026-08-01T00:00:00+00:00", in_timezone="UTC"),
|
|
)
|
|
ems.genetic_solution.return_value = None
|
|
with (
|
|
patch("akkudoktoreos.optimization.genetic.configrequest.get_ems", return_value=ems),
|
|
patch.object(ConfigOptimizationRequest, "prediction", prediction),
|
|
):
|
|
parameters = await GeneticOptimizationParameters.prepare()
|
|
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 = Inverter(InverterParameters(device_id="inverter1", max_power_wh=10000))
|
|
inverter.self_consumption_predictor = Mock()
|
|
inverter.self_consumption_predictor.calculate_expected_direct_consumption.return_value = 0.0
|
|
simulation = GeneticSimulation()
|
|
simulation.prepare(
|
|
parameters.ems, optimization_hours=24, prediction_hours=24, inverter=inverter
|
|
)
|
|
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_cancels_without_replacing_provider(
|
|
prepare_tariffs, revenues, config_eos, caplog
|
|
):
|
|
parameters, _, prediction = await prepare_tariffs("FeedInTariffImport", revenues)
|
|
assert parameters is None
|
|
assert config_eos.feedintariff.provider == "FeedInTariffImport"
|
|
prediction.update_data.assert_awaited_once()
|
|
assert "canceling optimization" in caplog.text
|
|
assert "FeedInTariffImport" 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:
|
|
assert parameters is None
|
|
else:
|
|
assert parameters is not None
|
|
assert parameters.ems.feed_in_tariff_per_wh == pytest.approx(values)
|
|
finally:
|
|
provider._db_reset_state()
|