mirror of
https://github.com/Akkudoktor-EOS/EOS.git
synced 2026-10-09 07:56:40 +00:00
feat(devices): add bounded slot physics for GENETIC (#1327)
* 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(devices): preserve charge-rate typing and public import compatibility
* ruff format fix
* feat(devices): port slot-aware battery export and direct-use physics
Port scoped device changes from d2e2d58237. 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>
* 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(devices): regenerate slot-physics configuration and OpenAPI schemas
* fix(config): satisfy typed device conversion and migration contracts
* docs(config): refresh validated configuration prerequisite schemas
* test(devices): align physics regressions with strict type checking
* docs(devices): refresh API version after prerequisite merge
* docs(interpolator): use portable reStructuredText markup
* docs(devices): refresh API version after docstring compatibility fix
---------
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: Christin <info@bikinibottom.capital>
This commit is contained in:
co-authored by
Andreas
Christin
Bobby Noelte
r0b2g1t
parent
1a18935667
commit
3c862543a1
@@ -1,6 +1,8 @@
|
||||
import numpy as np
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from akkudoktoreos.devices.devices import BatteriesCommonSettings
|
||||
from akkudoktoreos.devices.genetic.battery import Battery, SolarPanelBatteryParameters
|
||||
|
||||
|
||||
@@ -294,3 +296,105 @@ def test_car_and_pv_battery_discharge_and_max_charge_power(setup_pv_battery, set
|
||||
assert car_battery.parameters.max_charge_power_w == 7000, (
|
||||
"Car battery max charge power should remain as defined"
|
||||
)
|
||||
|
||||
|
||||
def test_quarter_hour_charge_calls_share_one_power_budget():
|
||||
params = SolarPanelBatteryParameters(
|
||||
device_id="battery1",
|
||||
capacity_wh=10_000,
|
||||
initial_soc_percentage=0,
|
||||
min_soc_percentage=0,
|
||||
max_soc_percentage=100,
|
||||
max_charge_power_w=1_000,
|
||||
charging_efficiency=1.0,
|
||||
discharging_efficiency=1.0,
|
||||
)
|
||||
battery = Battery(params, prediction_hours=4, slot_duration_h=0.25)
|
||||
battery.set_charge_per_hour(np.ones(4))
|
||||
|
||||
first_stored, _ = battery.charge_energy(200.0, 0)
|
||||
second_stored, _ = battery.charge_energy(200.0, 0)
|
||||
|
||||
assert first_stored == pytest.approx(200.0)
|
||||
assert second_stored == pytest.approx(50.0)
|
||||
assert battery.soc_wh == pytest.approx(250.0)
|
||||
|
||||
|
||||
def test_quarter_hour_discharge_calls_share_one_power_budget():
|
||||
params = SolarPanelBatteryParameters(
|
||||
device_id="battery1",
|
||||
capacity_wh=10_000,
|
||||
initial_soc_percentage=100,
|
||||
min_soc_percentage=0,
|
||||
max_soc_percentage=100,
|
||||
max_charge_power_w=1_000,
|
||||
charging_efficiency=1.0,
|
||||
discharging_efficiency=1.0,
|
||||
)
|
||||
battery = Battery(params, prediction_hours=4, slot_duration_h=0.25)
|
||||
battery.set_discharge_per_hour(np.ones(4))
|
||||
|
||||
first_delivered, _ = battery.discharge_energy(200.0, 0)
|
||||
second_delivered, _ = battery.discharge_energy(200.0, 0)
|
||||
|
||||
assert first_delivered == pytest.approx(200.0)
|
||||
assert second_delivered == pytest.approx(50.0)
|
||||
assert battery.discharged_energy_wh(0) == pytest.approx(250.0)
|
||||
assert battery.soc_wh == pytest.approx(9_750.0)
|
||||
|
||||
battery.reset()
|
||||
|
||||
assert battery.discharged_energy_wh(0) == 0.0
|
||||
|
||||
|
||||
def test_grid_export_rates_are_sorted_and_deduplicated():
|
||||
"""Export rates are normalized like the charge rates."""
|
||||
settings = BatteriesCommonSettings(
|
||||
device_id="battery1", grid_export_rates=[1.0, 0.5, 0.5, 0.25]
|
||||
)
|
||||
assert settings.grid_export_rates == [0.25, 0.5, 1.0]
|
||||
|
||||
|
||||
def test_grid_export_rates_default_and_override():
|
||||
"""None falls back to the defaults; [1.0] restores all-or-nothing export."""
|
||||
assert BatteriesCommonSettings(device_id="battery1").grid_export_rates == [
|
||||
0.25,
|
||||
0.5,
|
||||
0.75,
|
||||
1.0,
|
||||
]
|
||||
fallback = BatteriesCommonSettings(device_id="battery1", grid_export_rates=None)
|
||||
assert fallback.grid_export_rates == [0.25, 0.5, 0.75, 1.0]
|
||||
full_export = BatteriesCommonSettings(device_id="battery1", grid_export_rates=[1.0])
|
||||
assert full_export.grid_export_rates == [1.0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rates", [[0.0, 0.5], [1.5], [-0.25], [], [np.nan], [np.inf], [[0.5]], 0.5])
|
||||
def test_grid_export_rates_reject_invalid_values(rates):
|
||||
"""0.0 is not an export level, and rates above the rated power are rejected."""
|
||||
with pytest.raises(ValidationError):
|
||||
BatteriesCommonSettings(device_id="battery1", grid_export_rates=rates)
|
||||
|
||||
|
||||
def test_rated_discharge_energy_scales_with_slot_duration(setup_pv_battery):
|
||||
"""The rate reference is the rated discharge energy of one slot."""
|
||||
battery = setup_pv_battery
|
||||
expected = battery.max_charge_power_w * battery.slot_duration_h * battery.discharging_efficiency
|
||||
assert battery.rated_discharge_energy_wh() == pytest.approx(expected)
|
||||
|
||||
|
||||
def test_pv_converter_preserves_id_lcos_charge_and_export_rates():
|
||||
settings = BatteriesCommonSettings(
|
||||
device_id="house",
|
||||
charge_rates=[0.0, 0.5, 1.0],
|
||||
grid_export_rates=[1.0, 0.25],
|
||||
levelized_cost_of_storage_amt_kwh=0.123,
|
||||
)
|
||||
assert isinstance(BatteriesCommonSettings.validate_and_sort_charge_rates(None), np.ndarray)
|
||||
parameters = settings.to_genetic_pv_bat_param()
|
||||
assert parameters.device_id == "house"
|
||||
assert parameters.charge_rates == [0.0, 0.5, 1.0]
|
||||
assert parameters.grid_export_rates == [0.25, 1.0]
|
||||
assert parameters.levelized_cost_of_storage_kwh == pytest.approx(0.123)
|
||||
battery = Battery(parameters, prediction_hours=4, slot_duration_h=0.25)
|
||||
assert battery.levelized_cost_of_storage_kwh == pytest.approx(0.123)
|
||||
|
||||
@@ -88,6 +88,55 @@ class TestCacheUntilUpdateDecorators:
|
||||
assert CacheEnergyManagementStore.hit_count == 1
|
||||
assert result1 == result2
|
||||
|
||||
@pytest.mark.parametrize("reverse", [False, True])
|
||||
@pytest.mark.parametrize("use_kwargs", [False, True])
|
||||
def test_methods_with_identical_arguments_keep_separate_results(
|
||||
self, cache_energy_management_store, reverse, use_kwargs
|
||||
):
|
||||
calls = []
|
||||
|
||||
class Model:
|
||||
@cache_energy_management
|
||||
def fraction(self, value):
|
||||
calls.append("fraction")
|
||||
return value / 1000
|
||||
|
||||
@cache_energy_management
|
||||
def energy(self, value):
|
||||
calls.append("energy")
|
||||
return value * 1000
|
||||
|
||||
model = Model()
|
||||
cases = [(model.fraction, 0.005), (model.energy, 5000)]
|
||||
if reverse:
|
||||
cases.reverse()
|
||||
for _ in range(2):
|
||||
for method, expected in cases:
|
||||
result = method(value=5) if use_kwargs else method(5)
|
||||
assert result == expected
|
||||
assert sorted(calls) == ["energy", "fraction"]
|
||||
assert CacheEnergyManagementStore.miss_count == 2
|
||||
assert CacheEnergyManagementStore.hit_count == 2
|
||||
|
||||
def test_distinct_closures_with_same_name_do_not_share_results(
|
||||
self, cache_energy_management_store
|
||||
):
|
||||
def make_function(factor):
|
||||
@cache_energy_management
|
||||
def compute(value):
|
||||
return value * factor
|
||||
return compute
|
||||
|
||||
double = make_function(2)
|
||||
triple = make_function(3)
|
||||
assert double.__qualname__ == triple.__qualname__
|
||||
assert double(4) == 8
|
||||
assert triple(4) == 12
|
||||
assert double(4) == 8
|
||||
assert triple(4) == 12
|
||||
assert CacheEnergyManagementStore.miss_count == 2
|
||||
assert CacheEnergyManagementStore.hit_count == 2
|
||||
|
||||
def test_cache_energy_management(self, cache_energy_management_store):
|
||||
"""Test that cache_energy_management caches function results."""
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ from pathlib import Path
|
||||
from typing import Any
|
||||
from unittest.mock import patch
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
from pypdf import PdfReader
|
||||
@@ -140,14 +141,29 @@ async def test_optimize(
|
||||
f"cp {TESTDATA_FILE} {solution_file}\n"
|
||||
)
|
||||
|
||||
assert genetic_solution.result.Gesamtbilanz_Euro == pytest.approx(
|
||||
expected_result.result.Gesamtbilanz_Euro
|
||||
)
|
||||
|
||||
# Assert that the output contains all expected entries.
|
||||
# This does not assert that the optimization always gives the same result!
|
||||
# Reproducibility and mathematical accuracy should be tested on the level of individual components.
|
||||
compare_dict(genetic_solution.model_dump(), expected_result.model_dump())
|
||||
# Keep the output contract, but do not demand an identical stochastic
|
||||
# schedule or monetary golden from the previous direct-consumption model.
|
||||
assert set(genetic_solution.model_dump()) == set(expected_result.model_dump())
|
||||
result = genetic_solution.result
|
||||
expected_slots = len(input_data.ems.pv_forecast_wh) - fixed_start_hour
|
||||
assert len(result.grid_consumption_wh_per_hour) == expected_slots
|
||||
assert len(result.grid_feed_in_wh_per_hour) == expected_slots
|
||||
prices = np.asarray(genetic_solution.parameters.ems.electricity_price_per_wh)[fixed_start_hour:]
|
||||
tariffs = np.asarray(genetic_solution.parameters.ems.feed_in_tariff_per_wh)
|
||||
if tariffs.ndim > 0:
|
||||
tariffs = tariffs[fixed_start_hour:]
|
||||
expected_costs = np.asarray(result.grid_consumption_wh_per_hour) * prices
|
||||
expected_revenues = np.asarray(result.grid_feed_in_wh_per_hour) * tariffs
|
||||
np.testing.assert_allclose(result.costs_per_hour, expected_costs)
|
||||
np.testing.assert_allclose(result.revenue_per_hour, expected_revenues)
|
||||
assert result.total_costs == pytest.approx(sum(expected_costs))
|
||||
assert result.total_revenue == pytest.approx(sum(expected_revenues))
|
||||
assert result.total_balance == pytest.approx(sum(expected_costs) - sum(expected_revenues))
|
||||
assert result.total_losses == pytest.approx(sum(result.losses_per_hour))
|
||||
assert all(value >= 0 for value in result.grid_consumption_wh_per_hour)
|
||||
assert all(value >= 0 for value in result.grid_feed_in_wh_per_hour)
|
||||
assert all(0 <= value <= 100 for value in result.battery_soc_per_hour)
|
||||
assert all(0 <= value <= 100 for value in result.ev_soc_per_hour)
|
||||
|
||||
# Check the correct generic optimization solution is created
|
||||
optimization_solution = await genetic_solution.optimization_solution()
|
||||
|
||||
@@ -334,18 +334,13 @@ def test_simulation(genetic_simulation):
|
||||
"The value at index 1 of 'Netzbezug_Wh_pro_Stunde' should be 1527.13."
|
||||
)
|
||||
|
||||
# Verify the total balance
|
||||
assert abs(result["Gesamtbilanz_Euro"] - 6.612835813556755) < 1e-5, (
|
||||
"Total balance should be 6.612835813556755."
|
||||
)
|
||||
|
||||
# Check total revenue and total costs
|
||||
assert abs(result["Gesamteinnahmen_Euro"] - 1.964301131937134) < 1e-5, (
|
||||
"Total revenue should be 1.964301131937134."
|
||||
)
|
||||
assert abs(result["Gesamtkosten_Euro"] - 8.577136945493889) < 1e-5, (
|
||||
"Total costs should be 8.577136945493889 ."
|
||||
)
|
||||
# Reprice the physical grid flows independently. The new direct-use
|
||||
# probability model changes the old aggregate monetary golden values.
|
||||
costs = np.dot(result["Netzbezug_Wh_pro_Stunde"], simulation.elect_price_hourly[start_hour:])
|
||||
revenues = np.dot(result["Netzeinspeisung_Wh_pro_Stunde"], simulation.elect_revenue_per_hour_arr[start_hour:])
|
||||
assert result["Gesamtkosten_Euro"] == pytest.approx(costs)
|
||||
assert result["Gesamteinnahmen_Euro"] == pytest.approx(revenues)
|
||||
assert result["Gesamtbilanz_Euro"] == pytest.approx(costs - revenues)
|
||||
|
||||
# Check the losses
|
||||
assert abs(result["Gesamt_Verluste"] - 1620.0) < 1e-5, (
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from akkudoktoreos.prediction.interpolator import get_eos_load_interpolator
|
||||
|
||||
|
||||
def test_quarter_hour_energy_is_converted_back_to_same_mean_power():
|
||||
"""Splitting hourly energy must not change the minute-load probability lookup."""
|
||||
interpolator = get_eos_load_interpolator()
|
||||
hourly_load_wh = 800.0
|
||||
hourly_pv_wh = 1200.0
|
||||
slot_duration_h = 0.25
|
||||
|
||||
hourly = interpolator.calculate_expected_direct_consumption(hourly_load_wh, hourly_pv_wh)
|
||||
quarter_hour = interpolator.calculate_expected_direct_consumption(
|
||||
(hourly_load_wh / 4) / slot_duration_h,
|
||||
(hourly_pv_wh / 4) / slot_duration_h,
|
||||
)
|
||||
|
||||
assert quarter_hour == pytest.approx(hourly)
|
||||
|
||||
|
||||
def test_load_above_probability_grid_uses_highest_supported_distribution():
|
||||
"""Out-of-range household load must not make self-consumption jump to zero."""
|
||||
interpolator = get_eos_load_interpolator()
|
||||
|
||||
at_boundary = interpolator.calculate_self_consumption(3450.0, 5000.0)
|
||||
above_boundary = interpolator.calculate_self_consumption(4000.0, 5000.0)
|
||||
|
||||
assert above_boundary == pytest.approx(at_boundary)
|
||||
assert above_boundary > 0.99
|
||||
|
||||
|
||||
def test_expected_direct_consumption_accounts_for_subhourly_load_variation():
|
||||
"""Expected overlap must be below the optimistic overlap of interval means."""
|
||||
interpolator = get_eos_load_interpolator()
|
||||
|
||||
direct_power_w = interpolator.calculate_expected_direct_consumption(800.0, 1200.0)
|
||||
|
||||
assert direct_power_w == pytest.approx(621.0, abs=2.0)
|
||||
assert 0.0 < direct_power_w < 800.0
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("mean_load_power_w", "pv_power_w"),
|
||||
[(800.0, 1200.0), (1000.0, 500.0), (1500.0, 1500.0)],
|
||||
)
|
||||
def test_expected_direct_consumption_produces_conservative_energy_balance(
|
||||
mean_load_power_w, pv_power_w
|
||||
):
|
||||
"""Direct use, residual load and surplus must conserve both mean powers."""
|
||||
interpolator = get_eos_load_interpolator()
|
||||
|
||||
direct_power_w = interpolator.calculate_expected_direct_consumption(
|
||||
mean_load_power_w, pv_power_w
|
||||
)
|
||||
residual_load_w = mean_load_power_w - direct_power_w
|
||||
pv_surplus_w = pv_power_w - direct_power_w
|
||||
|
||||
assert 0.0 <= direct_power_w <= min(mean_load_power_w, pv_power_w)
|
||||
assert direct_power_w + residual_load_w == pytest.approx(mean_load_power_w)
|
||||
assert direct_power_w + pv_surplus_w == pytest.approx(pv_power_w)
|
||||
|
||||
|
||||
def test_expected_direct_consumption_preserves_forecast_mean_at_high_pv():
|
||||
"""A PV level above every normalized load bin covers the complete mean load."""
|
||||
interpolator = get_eos_load_interpolator()
|
||||
|
||||
direct_power_w = interpolator.calculate_expected_direct_consumption(3000.0, 10000.0)
|
||||
|
||||
assert direct_power_w == pytest.approx(3000.0)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("load,pv", [(4000.0, 5000.0), (10000.0, 20000.0), (0.0, 0.0)])
|
||||
def test_genetic_interpolator_boundaries_are_finite_and_physical(load, pv):
|
||||
interpolator = get_eos_load_interpolator()
|
||||
fraction = interpolator.calculate_self_consumption(load, pv)
|
||||
direct = interpolator.calculate_expected_direct_consumption(load, pv)
|
||||
assert np.isfinite(fraction)
|
||||
assert 0.0 <= fraction <= 1.0
|
||||
assert np.isfinite(direct)
|
||||
assert 0.0 <= direct <= min(load, pv)
|
||||
|
||||
|
||||
def test_genetic0_inverter_keeps_its_independent_interpolator():
|
||||
from akkudoktoreos.devices.genetic0.genetic0inverter import (
|
||||
Genetic0Inverter,
|
||||
Genetic0InverterParameters,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic0.genetic0loadinterpolator import (
|
||||
get_genetic0_load_interpolator,
|
||||
)
|
||||
|
||||
inverter = Genetic0Inverter(Genetic0InverterParameters(device_id="legacy", max_power_wh=10000))
|
||||
assert inverter.self_consumption_predictor is get_genetic0_load_interpolator()
|
||||
assert inverter.self_consumption_predictor is not get_eos_load_interpolator()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("load,pv", [(4000.0, 5000.0), (10000.0, 20000.0)])
|
||||
def test_genetic_inverter_boundary_flows_remain_nonnegative(load, pv):
|
||||
from akkudoktoreos.devices.genetic.inverter import Inverter, InverterParameters
|
||||
|
||||
inverter = Inverter(InverterParameters(device_id="boundary", max_power_wh=25000))
|
||||
flows = inverter.process_energy(generation=pv, consumption=load, hour=0)
|
||||
assert all(np.isfinite(value) and value >= 0.0 for value in flows)
|
||||
+177
-28
@@ -1,7 +1,12 @@
|
||||
from unittest.mock import Mock, patch
|
||||
from unittest.mock import Mock, call, patch
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from akkudoktoreos.devices.genetic.battery import (
|
||||
Battery,
|
||||
SolarPanelBatteryParameters,
|
||||
)
|
||||
from akkudoktoreos.devices.genetic.inverter import Inverter, InverterParameters
|
||||
|
||||
|
||||
@@ -10,6 +15,9 @@ def mock_battery() -> Mock:
|
||||
mock_battery = Mock()
|
||||
mock_battery.charge_energy = Mock(return_value=(0.0, 0.0))
|
||||
mock_battery.discharge_energy = Mock(return_value=(0.0, 0.0))
|
||||
# Rated discharge energy of one slot - the reference a grid-export rate is
|
||||
# applied to. Large enough to never bind at the default factor of 1.0.
|
||||
mock_battery.rated_discharge_energy_wh = Mock(return_value=1e9)
|
||||
mock_battery.parameters.device_id = "battery1"
|
||||
return mock_battery
|
||||
|
||||
@@ -17,7 +25,7 @@ def mock_battery() -> Mock:
|
||||
@pytest.fixture
|
||||
def inverter(mock_battery) -> Inverter:
|
||||
mock_self_consumption_predictor = Mock()
|
||||
mock_self_consumption_predictor.calculate_self_consumption.return_value = 1.0
|
||||
mock_self_consumption_predictor.calculate_expected_direct_consumption.side_effect = min
|
||||
with patch(
|
||||
"akkudoktoreos.devices.genetic.inverter.get_eos_load_interpolator",
|
||||
return_value=mock_self_consumption_predictor,
|
||||
@@ -26,11 +34,51 @@ def inverter(mock_battery) -> Inverter:
|
||||
InverterParameters(
|
||||
device_id="iv1", max_power_wh=500.0, battery_id=mock_battery.parameters.device_id
|
||||
),
|
||||
battery = mock_battery
|
||||
battery=mock_battery,
|
||||
)
|
||||
return iv
|
||||
|
||||
|
||||
def test_quarter_hour_load_and_grid_export_share_discharge_power_limit():
|
||||
"""Local supply plus direct export may not exceed one slot's battery budget."""
|
||||
battery = Battery(
|
||||
SolarPanelBatteryParameters(
|
||||
device_id="battery",
|
||||
capacity_wh=10000,
|
||||
charging_efficiency=1.0,
|
||||
discharging_efficiency=1.0,
|
||||
max_charge_power_w=7000,
|
||||
initial_soc_percentage=100,
|
||||
),
|
||||
prediction_hours=1,
|
||||
slot_duration_h=0.25,
|
||||
)
|
||||
battery.set_discharge_per_hour(np.array([1]))
|
||||
quarter_hour_inverter = Inverter(
|
||||
InverterParameters(
|
||||
device_id="inverter",
|
||||
max_power_wh=10000,
|
||||
battery_id="battery",
|
||||
dc_to_ac_efficiency=1.0,
|
||||
ac_to_dc_efficiency=1.0,
|
||||
),
|
||||
battery=battery,
|
||||
slot_duration_h=0.25,
|
||||
)
|
||||
initial_soc_wh = battery.soc_wh
|
||||
|
||||
grid_export, grid_import, _, _ = quarter_hour_inverter.process_energy(
|
||||
generation=0.0,
|
||||
consumption=1000.0,
|
||||
hour=0,
|
||||
allow_battery_grid_export=True,
|
||||
)
|
||||
|
||||
assert grid_import == 0.0
|
||||
assert grid_export == pytest.approx(750.0)
|
||||
assert initial_soc_wh - battery.soc_wh == pytest.approx(1750.0)
|
||||
|
||||
|
||||
def test_process_energy_excess_generation(inverter, mock_battery):
|
||||
# Battery charges 100 Wh with 10 Wh loss
|
||||
mock_battery.charge_energy.return_value = (100.0, 10.0)
|
||||
@@ -48,7 +96,7 @@ def test_process_energy_excess_generation(inverter, mock_battery):
|
||||
assert self_consumption == 200.0 # All consumption is met
|
||||
mock_battery.charge_energy.assert_called_once_with(400.0, hour)
|
||||
mock_battery.discharge_energy.assert_not_called()
|
||||
inverter.self_consumption_predictor.calculate_self_consumption.assert_called_once_with(
|
||||
inverter.self_consumption_predictor.calculate_expected_direct_consumption.assert_called_once_with(
|
||||
consumption, generation
|
||||
)
|
||||
|
||||
@@ -57,7 +105,8 @@ def test_process_energy_excess_generation_interpolator(inverter, mock_battery):
|
||||
# Battery charges 100 Wh with 10 Wh loss
|
||||
mock_battery.charge_energy.return_value = (100.0, 10.0)
|
||||
mock_battery.discharge_energy.return_value = (20.0, 2.0)
|
||||
inverter.self_consumption_predictor.calculate_self_consumption.return_value = 0.95
|
||||
inverter.self_consumption_predictor.calculate_expected_direct_consumption.side_effect = None
|
||||
inverter.self_consumption_predictor.calculate_expected_direct_consumption.return_value = 180.0
|
||||
|
||||
generation = 600.0
|
||||
consumption = 200.0
|
||||
@@ -67,19 +116,71 @@ def test_process_energy_excess_generation_interpolator(inverter, mock_battery):
|
||||
generation, consumption, hour
|
||||
)
|
||||
|
||||
assert grid_export == pytest.approx(
|
||||
270.0, rel=1e-2
|
||||
) # 290 Wh feed-in - 5% of generation-consumption self consumption after battery charges
|
||||
assert grid_export == pytest.approx(300.0, rel=1e-2)
|
||||
assert grid_import == pytest.approx(0.0, rel=1e-2) # No grid draw
|
||||
assert losses == 12.0 # Battery charging losses
|
||||
assert self_consumption == 220.0 # All consumption is met
|
||||
mock_battery.charge_energy.assert_called_once_with(pytest.approx(380.0, rel=1e-2), hour)
|
||||
assert losses == 22.0 # Battery/inverter losses plus curtailed PV
|
||||
assert self_consumption == 200.0 # 180 Wh direct PV + 20 Wh battery
|
||||
mock_battery.charge_energy.assert_called_once_with(pytest.approx(420.0, rel=1e-2), hour)
|
||||
mock_battery.discharge_energy.assert_called_once_with(pytest.approx(20.0, rel=1e-2), hour)
|
||||
inverter.self_consumption_predictor.calculate_self_consumption.assert_called_once_with(
|
||||
inverter.self_consumption_predictor.calculate_expected_direct_consumption.assert_called_once_with(
|
||||
consumption, generation
|
||||
)
|
||||
|
||||
|
||||
def test_probabilistic_bypass_conserves_energy_without_battery():
|
||||
predictor = Mock()
|
||||
predictor.calculate_expected_direct_consumption.return_value = 150.0
|
||||
with patch(
|
||||
"akkudoktoreos.devices.genetic.inverter.get_eos_load_interpolator",
|
||||
return_value=predictor,
|
||||
):
|
||||
inverter_without_battery = Inverter(
|
||||
InverterParameters(device_id="inverter", max_power_wh=1000.0)
|
||||
)
|
||||
|
||||
generation = 600.0
|
||||
consumption = 200.0
|
||||
grid_export, grid_import, losses, self_consumption = (
|
||||
inverter_without_battery.process_energy(generation, consumption, hour=0)
|
||||
)
|
||||
|
||||
assert self_consumption == pytest.approx(150.0)
|
||||
assert grid_import == pytest.approx(50.0)
|
||||
assert grid_export == pytest.approx(450.0)
|
||||
assert losses == 0.0
|
||||
assert generation + grid_import == pytest.approx(
|
||||
consumption + grid_export + losses
|
||||
)
|
||||
|
||||
|
||||
def test_probabilistic_bypass_conserves_energy_on_quarter_hour_grid():
|
||||
predictor = Mock()
|
||||
predictor.calculate_expected_direct_consumption.return_value = 600.0
|
||||
with patch(
|
||||
"akkudoktoreos.devices.genetic.inverter.get_eos_load_interpolator",
|
||||
return_value=predictor,
|
||||
):
|
||||
inverter_without_battery = Inverter(
|
||||
InverterParameters(device_id="inverter", max_power_wh=2000.0),
|
||||
slot_duration_h=0.25,
|
||||
)
|
||||
|
||||
generation = 300.0 # 1200 W over 15 minutes
|
||||
consumption = 200.0 # 800 W over 15 minutes
|
||||
grid_export, grid_import, losses, self_consumption = (
|
||||
inverter_without_battery.process_energy(generation, consumption, hour=0)
|
||||
)
|
||||
|
||||
predictor.calculate_expected_direct_consumption.assert_called_once_with(800.0, 1200.0)
|
||||
assert self_consumption == pytest.approx(150.0)
|
||||
assert grid_import == pytest.approx(50.0)
|
||||
assert grid_export == pytest.approx(150.0)
|
||||
assert losses == 0.0
|
||||
assert generation + grid_import == pytest.approx(
|
||||
consumption + grid_export + losses
|
||||
)
|
||||
|
||||
|
||||
def test_process_energy_generation_equals_consumption(inverter, mock_battery):
|
||||
generation = 300.0
|
||||
consumption = 300.0
|
||||
@@ -96,7 +197,7 @@ def test_process_energy_generation_equals_consumption(inverter, mock_battery):
|
||||
|
||||
mock_battery.charge_energy.assert_not_called()
|
||||
mock_battery.discharge_energy.assert_not_called()
|
||||
inverter.self_consumption_predictor.calculate_self_consumption.assert_called_once_with(
|
||||
inverter.self_consumption_predictor.calculate_expected_direct_consumption.assert_called_once_with(
|
||||
consumption, generation
|
||||
)
|
||||
|
||||
@@ -120,7 +221,49 @@ def test_process_energy_battery_discharges(inverter, mock_battery):
|
||||
assert self_consumption == 200.0 # Generation + battery discharge
|
||||
mock_battery.charge_energy.assert_not_called()
|
||||
mock_battery.discharge_energy.assert_called_once_with(150.0, hour)
|
||||
inverter.self_consumption_predictor.calculate_self_consumption.assert_not_called()
|
||||
inverter.self_consumption_predictor.calculate_expected_direct_consumption.assert_called_once_with(
|
||||
consumption, generation
|
||||
)
|
||||
|
||||
|
||||
def test_process_energy_allows_battery_grid_export(inverter, mock_battery):
|
||||
mock_battery.max_charge_power_w = 300.0
|
||||
mock_battery.remaining_discharge_energy_wh.return_value = 200.0
|
||||
mock_battery.discharge_energy.side_effect = [(100.0, 0.0), (200.0, 0.0)]
|
||||
|
||||
grid_export, grid_import, losses, self_consumption = inverter.process_energy(
|
||||
generation=0.0,
|
||||
consumption=100.0,
|
||||
hour=12,
|
||||
allow_battery_grid_export=True,
|
||||
)
|
||||
|
||||
assert grid_export == pytest.approx(200.0, rel=1e-2)
|
||||
assert grid_import == 0.0
|
||||
assert losses == 0.0
|
||||
assert self_consumption == 100.0
|
||||
mock_battery.discharge_energy.assert_has_calls([call(100.0, 12), call(200.0, 12)])
|
||||
inverter.self_consumption_predictor.calculate_expected_direct_consumption.assert_not_called()
|
||||
|
||||
|
||||
def test_process_energy_grid_export_rate_limits_export(inverter, mock_battery):
|
||||
"""An export rate caps the export at that share of the rated discharge power."""
|
||||
mock_battery.max_charge_power_w = 300.0
|
||||
mock_battery.remaining_discharge_energy_wh.return_value = 200.0
|
||||
mock_battery.rated_discharge_energy_wh.return_value = 300.0
|
||||
mock_battery.discharge_energy.side_effect = [(100.0, 0.0), (150.0, 0.0)]
|
||||
|
||||
grid_export, grid_import, losses, self_consumption = inverter.process_energy(
|
||||
generation=0.0,
|
||||
consumption=100.0,
|
||||
hour=12,
|
||||
allow_battery_grid_export=True,
|
||||
battery_grid_export_factor=0.5,
|
||||
)
|
||||
|
||||
# 0.5 * 300 Wh rated = 150 Wh, below the 200 Wh the battery could still give.
|
||||
assert grid_export == pytest.approx(150.0)
|
||||
mock_battery.discharge_energy.assert_has_calls([call(100.0, 12), call(150.0, 12)])
|
||||
|
||||
|
||||
def test_process_energy_battery_empty(inverter, mock_battery):
|
||||
@@ -140,7 +283,9 @@ def test_process_energy_battery_empty(inverter, mock_battery):
|
||||
assert self_consumption == 100.0 # Only generation is consumed
|
||||
mock_battery.charge_energy.assert_not_called()
|
||||
mock_battery.discharge_energy.assert_called_once_with(200.0, hour)
|
||||
inverter.self_consumption_predictor.calculate_self_consumption.assert_not_called()
|
||||
inverter.self_consumption_predictor.calculate_expected_direct_consumption.assert_called_once_with(
|
||||
consumption, generation
|
||||
)
|
||||
|
||||
|
||||
def test_process_energy_battery_full_at_start(inverter, mock_battery):
|
||||
@@ -162,7 +307,7 @@ def test_process_energy_battery_full_at_start(inverter, mock_battery):
|
||||
assert self_consumption == 200.0 # Only consumption is met
|
||||
mock_battery.charge_energy.assert_called_once_with(300.0, hour)
|
||||
mock_battery.discharge_energy.assert_not_called()
|
||||
inverter.self_consumption_predictor.calculate_self_consumption.assert_called_once_with(
|
||||
inverter.self_consumption_predictor.calculate_expected_direct_consumption.assert_called_once_with(
|
||||
consumption, generation
|
||||
)
|
||||
|
||||
@@ -184,7 +329,9 @@ def test_process_energy_insufficient_generation_no_battery(inverter, mock_batter
|
||||
assert self_consumption == 100.0 # Only generation is consumed
|
||||
mock_battery.charge_energy.assert_not_called()
|
||||
mock_battery.discharge_energy.assert_called_once_with(400.0, hour)
|
||||
inverter.self_consumption_predictor.calculate_self_consumption.assert_not_called()
|
||||
inverter.self_consumption_predictor.calculate_expected_direct_consumption.assert_called_once_with(
|
||||
consumption, generation
|
||||
)
|
||||
|
||||
|
||||
def test_process_energy_insufficient_generation_battery_assists(inverter, mock_battery):
|
||||
@@ -209,7 +356,9 @@ def test_process_energy_insufficient_generation_battery_assists(inverter, mock_b
|
||||
assert self_consumption == 250.0 # Generation + battery discharge
|
||||
mock_battery.charge_energy.assert_not_called()
|
||||
mock_battery.discharge_energy.assert_called_once_with(200.0, hour)
|
||||
inverter.self_consumption_predictor.calculate_self_consumption.assert_not_called()
|
||||
inverter.self_consumption_predictor.calculate_expected_direct_consumption.assert_called_once_with(
|
||||
consumption, generation
|
||||
)
|
||||
|
||||
|
||||
def test_process_energy_zero_generation(inverter, mock_battery):
|
||||
@@ -232,7 +381,7 @@ def test_process_energy_zero_generation(inverter, mock_battery):
|
||||
assert self_consumption == 100.0 # Only battery discharge is consumed
|
||||
mock_battery.charge_energy.assert_not_called()
|
||||
mock_battery.discharge_energy.assert_called_once_with(300.0, hour)
|
||||
inverter.self_consumption_predictor.calculate_self_consumption.assert_not_called()
|
||||
inverter.self_consumption_predictor.calculate_expected_direct_consumption.assert_not_called()
|
||||
|
||||
|
||||
def test_process_energy_zero_consumption(inverter, mock_battery):
|
||||
@@ -252,9 +401,7 @@ def test_process_energy_zero_consumption(inverter, mock_battery):
|
||||
assert self_consumption == 0.0 # Zero consumption
|
||||
mock_battery.charge_energy.assert_called_once_with(500.0, hour)
|
||||
mock_battery.discharge_energy.assert_not_called()
|
||||
inverter.self_consumption_predictor.calculate_self_consumption.assert_called_once_with(
|
||||
consumption, generation
|
||||
)
|
||||
inverter.self_consumption_predictor.calculate_expected_direct_consumption.assert_not_called()
|
||||
|
||||
|
||||
def test_process_energy_zero_generation_zero_consumption(inverter, mock_battery):
|
||||
@@ -272,9 +419,7 @@ def test_process_energy_zero_generation_zero_consumption(inverter, mock_battery)
|
||||
assert self_consumption == 0.0 # No consumption
|
||||
mock_battery.charge_energy.assert_not_called()
|
||||
mock_battery.discharge_energy.assert_not_called()
|
||||
inverter.self_consumption_predictor.calculate_self_consumption.assert_called_once_with(
|
||||
consumption, generation
|
||||
)
|
||||
inverter.self_consumption_predictor.calculate_expected_direct_consumption.assert_not_called()
|
||||
|
||||
|
||||
def test_process_energy_partial_battery_discharge(inverter, mock_battery):
|
||||
@@ -295,7 +440,9 @@ def test_process_energy_partial_battery_discharge(inverter, mock_battery):
|
||||
assert self_consumption == 250.0 # Generation + battery discharge
|
||||
mock_battery.charge_energy.assert_not_called()
|
||||
mock_battery.discharge_energy.assert_called_once_with(200.0, 12)
|
||||
inverter.self_consumption_predictor.calculate_self_consumption.assert_not_called()
|
||||
inverter.self_consumption_predictor.calculate_expected_direct_consumption.assert_called_once_with(
|
||||
consumption, generation
|
||||
)
|
||||
|
||||
|
||||
def test_process_energy_consumption_exceeds_max_no_battery(inverter, mock_battery):
|
||||
@@ -315,7 +462,9 @@ def test_process_energy_consumption_exceeds_max_no_battery(inverter, mock_batter
|
||||
assert self_consumption == 100.0 # Only the generation is consumed, maxing out the inverter
|
||||
mock_battery.charge_energy.assert_not_called()
|
||||
mock_battery.discharge_energy.assert_called_once_with(400.0, hour)
|
||||
inverter.self_consumption_predictor.calculate_self_consumption.assert_not_called()
|
||||
inverter.self_consumption_predictor.calculate_expected_direct_consumption.assert_called_once_with(
|
||||
consumption, generation
|
||||
)
|
||||
|
||||
|
||||
def test_process_energy_zero_generation_full_battery_high_consumption(inverter, mock_battery):
|
||||
@@ -337,4 +486,4 @@ def test_process_energy_zero_generation_full_battery_high_consumption(inverter,
|
||||
assert self_consumption == 500.0 # Battery fully discharges to meet consumption
|
||||
mock_battery.charge_energy.assert_not_called()
|
||||
mock_battery.discharge_energy.assert_called_once_with(500.0, hour)
|
||||
inverter.self_consumption_predictor.calculate_self_consumption.assert_not_called()
|
||||
inverter.self_consumption_predictor.calculate_expected_direct_consumption.assert_not_called()
|
||||
|
||||
@@ -21,10 +21,7 @@ from akkudoktoreos.devices.genetic.battery import (
|
||||
Battery,
|
||||
SolarPanelBatteryParameters,
|
||||
)
|
||||
from akkudoktoreos.devices.genetic.inverter import (
|
||||
Inverter,
|
||||
InverterParameters,
|
||||
)
|
||||
from akkudoktoreos.devices.genetic.inverter import Inverter, InverterParameters
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers / Fixtures
|
||||
@@ -40,7 +37,7 @@ def _make_inverter(
|
||||
) -> Inverter:
|
||||
"""Create an Inverter with custom efficiency parameters and a mock battery."""
|
||||
mock_self_consumption_predictor = Mock()
|
||||
mock_self_consumption_predictor.calculate_self_consumption.return_value = 1.0
|
||||
mock_self_consumption_predictor.calculate_expected_direct_consumption.side_effect = min
|
||||
|
||||
params = InverterParameters(
|
||||
device_id="inv1",
|
||||
@@ -167,12 +164,14 @@ class TestDcToAcEfficiency:
|
||||
assert losses == pytest.approx(10.0, rel=1e-5) # Only battery losses
|
||||
|
||||
def test_discharge_surplus_path_with_efficiency(self, mock_battery):
|
||||
"""When generation > consumption but SCR < 1, discharge goes through inverter."""
|
||||
mock_battery.discharge_energy.return_value = (50.0, 5.0)
|
||||
"""A probabilistic load gap discharges through the inverter."""
|
||||
mock_battery.discharge_energy.return_value = (30.0 / 0.90, 5.0)
|
||||
mock_battery.charge_energy.return_value = (100.0, 10.0)
|
||||
|
||||
inv = _make_inverter(dc_to_ac_efficiency=0.90, mock_battery=mock_battery)
|
||||
cast(Mock, inv.self_consumption_predictor).calculate_self_consumption.return_value = 0.90
|
||||
predictor = cast(Mock, inv.self_consumption_predictor)
|
||||
predictor.calculate_expected_direct_consumption.side_effect = None
|
||||
predictor.calculate_expected_direct_consumption.return_value = 170.0
|
||||
|
||||
generation = 500.0
|
||||
consumption = 200.0
|
||||
@@ -182,18 +181,23 @@ class TestDcToAcEfficiency:
|
||||
generation, consumption, hour
|
||||
)
|
||||
|
||||
# surplus = 300, remaining_power = 300*0.9 = 270, remaining_load_evq = 300*0.1 = 30
|
||||
# DC request for discharge = 30 / 0.90 = 33.333
|
||||
# Expected direct PV is 170 Wh, leaving 30 Wh of load gap and
|
||||
# 330 Wh of PV surplus within different sub-periods of the slot.
|
||||
# DC request for discharge = 30 / 0.90 = 33.333 Wh.
|
||||
expected_dc_request = 30.0 / 0.90
|
||||
mock_battery.discharge_energy.assert_called_once_with(
|
||||
pytest.approx(expected_dc_request, rel=1e-3), hour
|
||||
)
|
||||
|
||||
# Battery delivers 50 Wh DC → 45 Wh AC
|
||||
from_battery_ac = 50.0 * 0.90 # 45 Wh
|
||||
inverter_discharge_loss = 50.0 - from_battery_ac # 5 Wh
|
||||
# Battery delivers 33.333 Wh DC -> 30 Wh AC.
|
||||
from_battery_dc = 30.0 / 0.90
|
||||
from_battery_ac = from_battery_dc * 0.90
|
||||
inverter_discharge_loss = from_battery_dc - from_battery_ac
|
||||
|
||||
assert self_consumption == pytest.approx(consumption + from_battery_ac, rel=1e-5)
|
||||
assert self_consumption == pytest.approx(170.0 + from_battery_ac, rel=1e-5)
|
||||
assert grid_import == pytest.approx(0.0)
|
||||
assert grid_export == pytest.approx(220.0)
|
||||
assert losses == pytest.approx(5.0 + inverter_discharge_loss + 10.0)
|
||||
|
||||
|
||||
# ===================================================================
|
||||
|
||||
Reference in New Issue
Block a user