mirror of
https://github.com/Akkudoktor-EOS/EOS.git
synced 2026-11-25 15:06:20 +01:00
fix(measurement): use quality-aware meter energy for load and PV
Additional fixes Measurement.meter_energy_kwh converts meter energy over the whole period in one read; the 31-day and 10000-interval limits apply to the public energy queries only. Load intervals a meter does not fully cover are NaN and the load adjustment skips them; load_total_kwh returns an empty array for an empty store and keeps full last intervals. The load adjustment compares over the period the load meters report, skips a stale load meter period and says when no load meter is configured. PV calibration, snow feedback and the load adjustment fall back without measurements when a conversion fails, logged as error once per failure streak and consumer. Measurement.keys_first_datetime and keys_last_datetime find each meter's first and last valid reading in bounded scans, keep each meter's newest reading and return stamps in the configured zone. Measurement.keys_common_period derives the common meter period for PV calibration and the load adjustment and names the meter that ends it, also when meters share no period. PV calibration warns once per stale period when a stopped PV meter holds it on old data; snow feedback warns once about a stale feedback meter. Lasting meter conditions (silent, reset, gap, replaced meter, no shared period) are warned once per condition and consumer through one helper and warned again when they recur. A replaced meter whose readings touch the new one is reported; a single reading is not; a meter group waiting for its second reading is an info once. The PV meter resolution is detected from valid readings only (pre-existing), using one shared valid-reading rule in energy.py. Stale meter stamps are compared with compare_datetimes; new meter tests create durations with datetimeutil. The unused legacy Measurement._energy_from_meter_readings is removed; its test scenarios cover meter_energy_kwh. The converter's range error no longer mentions the API's 31-day limit, and its duplicate interval check is gone. Measurement and prediction docs describe the meter coverage rule, even gap spreading and when the load forecast stays unadjusted. Tests reset the warn-once state of the shared measurement store and restore the EMS start they change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Assisted-by: Claude Code (claude-opus-5-5)
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
2bfb6eafab
commit
f441759dfa
@@ -49,7 +49,12 @@ def loadakkudoktoradjusted(config_eos):
|
||||
config_eos.merge_settings_from_dict(settings)
|
||||
assert config_eos.load.provider == "LoadAkkudoktorAdjusted"
|
||||
assert config_eos.load.loadakkudoktor.loadakkudoktor_year_energy_kwh == 1000
|
||||
return LoadAkkudoktorAdjusted()
|
||||
# The adjustment ignores stale meter periods; run the tests next to their data.
|
||||
ems_class = type(get_ems())
|
||||
previous_start = ems_class._start_datetime
|
||||
get_ems().set_start_datetime(to_datetime("2024-01-02T00:00:00"))
|
||||
yield LoadAkkudoktorAdjusted()
|
||||
ems_class._start_datetime = previous_start
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def measurement_eos():
|
||||
@@ -264,6 +269,8 @@ async def empty_measurement(config_eos):
|
||||
"""Own, empty measurement store (the singleton is shared between tests)."""
|
||||
measurement = get_measurement()
|
||||
await measurement.delete_by_datetime(None, None)
|
||||
# Warn-once state lives on the shared singleton; start each test fresh.
|
||||
measurement._reported_warnings.clear()
|
||||
config_eos.merge_settings_from_dict(
|
||||
{"devices": {"max_batteries": 1, "batteries": {"storage": {"profile_adjustment": {"nominal_capacity_wh": 2000}}}}}
|
||||
)
|
||||
@@ -290,6 +297,7 @@ async def _adjustment_window(adjusted, measurement):
|
||||
@pytest.mark.asyncio
|
||||
async def test_adjustment_buckets_stay_on_full_hours(loadakkudoktoradjusted, empty_measurement):
|
||||
"""A newer off-hour record (e.g. a device SoC) must not shift the hourly buckets (#1447)."""
|
||||
loadakkudoktoradjusted.config.measurement.load_emr_keys = ["load0_mr"]
|
||||
dt = to_datetime("2024-01-01T00:00:00")
|
||||
for hour in range(25):
|
||||
await empty_measurement.update_value(dt.add(hours=hour), "load0_mr", 500.0 + hour)
|
||||
@@ -319,3 +327,175 @@ async def test_adjustment_within_first_hour_returns_zero(
|
||||
(weekday, weekend), calls = await _adjustment_window(loadakkudoktoradjusted, empty_measurement)
|
||||
assert calls == []
|
||||
assert not weekday.any() and not weekend.any()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_adjustment_skips_hours_without_load_meter_coverage(
|
||||
loadakkudoktoradjusted, empty_measurement
|
||||
):
|
||||
"""Hours the load meters do not cover are unknown and must not adjust the profile."""
|
||||
# A Monday, in the zone whose local hours the adjustment buckets.
|
||||
timezone = loadakkudoktoradjusted.config.general.timezone
|
||||
dt = to_datetime("2024-01-01T00:00:00", in_timezone=timezone)
|
||||
for hour in range(13):
|
||||
await empty_measurement.update_value(dt.add(hours=hour), "load0_mr", 500.0 + hour)
|
||||
await empty_measurement.update_value(dt.add(hours=hour), "load1_mr", 500.0 + hour)
|
||||
# Another channel keeps the store going until midnight.
|
||||
await empty_measurement.update_value(dt.add(hours=24), "storage-soc-factor", 0.42)
|
||||
|
||||
(weekday, weekend), calls = await _adjustment_window(loadakkudoktoradjusted, empty_measurement)
|
||||
|
||||
assert calls
|
||||
assert np.isfinite(weekday).all() and np.isfinite(weekend).all()
|
||||
assert (weekday[:12] != 0.0).all()
|
||||
assert (weekday[12:] == 0.0).all()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_adjustment_falls_back_when_the_meter_conversion_fails(
|
||||
loadakkudoktoradjusted, empty_measurement, caplog
|
||||
):
|
||||
"""A broken meter history disables the adjustment instead of the load prediction.
|
||||
|
||||
The failure is an error once per streak, not on every prediction run.
|
||||
"""
|
||||
loadakkudoktoradjusted.config.measurement.load_emr_keys = ["load0_mr"]
|
||||
dt = to_datetime("2024-01-01T00:00:00")
|
||||
for hour in range(25):
|
||||
await empty_measurement.update_value(dt.add(hours=hour), "load0_mr", 500.0 + hour)
|
||||
|
||||
def failure_levels() -> set[str]:
|
||||
levels = {r.levelname for r in caplog.records if "conversion failed" in r.getMessage()}
|
||||
caplog.clear()
|
||||
return levels
|
||||
|
||||
with caplog.at_level("DEBUG"):
|
||||
with patch.object(
|
||||
type(empty_measurement),
|
||||
"load_total_kwh",
|
||||
side_effect=ValueError("Overlapping source energy intervals."),
|
||||
):
|
||||
weekday, weekend = await loadakkudoktoradjusted._calculate_adjustment(
|
||||
np.random.rand(365, 2, 24)
|
||||
)
|
||||
assert failure_levels() == {"ERROR"}
|
||||
await loadakkudoktoradjusted._calculate_adjustment(np.random.rand(365, 2, 24))
|
||||
assert failure_levels() == {"DEBUG"}
|
||||
# A successful conversion ends the streak.
|
||||
await loadakkudoktoradjusted._calculate_adjustment(np.random.rand(365, 2, 24))
|
||||
with patch.object(
|
||||
type(empty_measurement),
|
||||
"load_total_kwh",
|
||||
side_effect=ValueError("Overlapping source energy intervals."),
|
||||
):
|
||||
await loadakkudoktoradjusted._calculate_adjustment(np.random.rand(365, 2, 24))
|
||||
assert failure_levels() == {"ERROR"}
|
||||
|
||||
assert (weekday == 0.0).all() and (weekend == 0.0).all()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_adjustment_without_load_meters_is_zero(loadakkudoktoradjusted, empty_measurement):
|
||||
"""Without configured load meters there is nothing to adjust from."""
|
||||
loadakkudoktoradjusted.config.measurement.load_emr_keys = None
|
||||
for day in (1, 2):
|
||||
await empty_measurement.update_value(
|
||||
to_datetime(f"2024-01-0{day}T00:00:00"), "storage-soc-factor", 0.5
|
||||
)
|
||||
|
||||
(weekday, weekend), calls = await _adjustment_window(loadakkudoktoradjusted, empty_measurement)
|
||||
|
||||
assert calls == []
|
||||
assert (weekday == 0.0).all() and (weekend == 0.0).all()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_adjustment_window_follows_the_load_meters(
|
||||
loadakkudoktoradjusted, empty_measurement
|
||||
):
|
||||
"""A load meter lagging behind other channels still gives its last 7 days."""
|
||||
loadakkudoktoradjusted.config.measurement.load_emr_keys = ["load0_mr"]
|
||||
dt = to_datetime("2024-01-01T00:00:00")
|
||||
for hour in range(10 * 24 + 1):
|
||||
await empty_measurement.update_value(dt.add(hours=hour), "load0_mr", 500.0 + hour)
|
||||
# SoC keeps reporting three days after the load meter stopped.
|
||||
await empty_measurement.update_value(dt.add(days=13), "storage-soc-factor", 0.42)
|
||||
|
||||
_, calls = await _adjustment_window(loadakkudoktoradjusted, empty_measurement)
|
||||
|
||||
assert calls
|
||||
assert compare_datetimes(calls[0]["end_datetime"], dt.add(days=10)).equal
|
||||
assert compare_datetimes(calls[0]["start_datetime"], dt.add(days=3)).equal
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_adjustment_ignores_a_stale_load_meter_period(
|
||||
loadakkudoktoradjusted, empty_measurement, caplog
|
||||
):
|
||||
"""A load meter that stopped long ago must not adjust today's profile with old weeks."""
|
||||
loadakkudoktoradjusted.config.measurement.load_emr_keys = ["load0_mr"]
|
||||
dt = to_datetime("2024-01-01T00:00:00")
|
||||
for hour in range(3 * 24 + 1):
|
||||
await empty_measurement.update_value(dt.add(hours=hour), "load0_mr", 500.0 + hour)
|
||||
get_ems().set_start_datetime(dt.add(days=30))
|
||||
|
||||
def stale_warnings() -> int:
|
||||
return sum(
|
||||
record.levelname == "WARNING"
|
||||
and "load meter 'load0_mr' last reported at" in record.getMessage()
|
||||
for record in caplog.records
|
||||
)
|
||||
|
||||
with caplog.at_level("WARNING"):
|
||||
(weekday, weekend), calls = await _adjustment_window(
|
||||
loadakkudoktoradjusted, empty_measurement
|
||||
)
|
||||
first_run = stale_warnings()
|
||||
await _adjustment_window(loadakkudoktoradjusted, empty_measurement)
|
||||
|
||||
assert calls == []
|
||||
assert (weekday == 0.0).all() and (weekend == 0.0).all()
|
||||
assert first_run > 0
|
||||
assert stale_warnings() == first_run
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_adjustment_names_a_load_meter_without_readings(
|
||||
loadakkudoktoradjusted, empty_measurement, caplog
|
||||
):
|
||||
"""A configured load meter key without readings (e.g. a typo) is named in a warning."""
|
||||
loadakkudoktoradjusted.config.measurement.load_emr_keys = ["load0_mr", "load0_mr_typo"]
|
||||
dt = to_datetime("2024-01-01T00:00:00")
|
||||
for hour in range(25):
|
||||
await empty_measurement.update_value(dt.add(hours=hour), "load0_mr", 500.0 + hour)
|
||||
|
||||
with caplog.at_level("WARNING"):
|
||||
(weekday, weekend), calls = await _adjustment_window(
|
||||
loadakkudoktoradjusted, empty_measurement
|
||||
)
|
||||
|
||||
assert calls == []
|
||||
assert (weekday == 0.0).all() and (weekend == 0.0).all()
|
||||
assert "['load0_mr_typo'] have no valid readings" in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_adjustment_names_a_replaced_load_meter(
|
||||
loadakkudoktoradjusted, empty_measurement, caplog
|
||||
):
|
||||
"""Meters that share no period (a replaced meter still configured) are named."""
|
||||
loadakkudoktoradjusted.config.measurement.load_emr_keys = ["load0_mr", "load1_mr"]
|
||||
dt = to_datetime("2024-01-01T00:00:00")
|
||||
for hour in range(25):
|
||||
await empty_measurement.update_value(dt.add(hours=hour), "load0_mr", 500.0 + hour)
|
||||
await empty_measurement.update_value(dt.add(days=2, hours=hour), "load1_mr", 900.0 + hour)
|
||||
|
||||
with caplog.at_level("WARNING"):
|
||||
(weekday, weekend), calls = await _adjustment_window(
|
||||
loadakkudoktoradjusted, empty_measurement
|
||||
)
|
||||
|
||||
assert calls == []
|
||||
assert (weekday == 0.0).all() and (weekend == 0.0).all()
|
||||
assert "meter 'load0_mr' last reported at" in caplog.text
|
||||
assert "the meters share no period" in caplog.text
|
||||
|
||||
+273
-86
@@ -9,14 +9,17 @@ from pydantic import ValidationError
|
||||
|
||||
from akkudoktoreos.core.coreabc import get_measurement
|
||||
from akkudoktoreos.core.dataabc import DataSequence
|
||||
from akkudoktoreos.core.databaseabc import DatabaseTimestamp
|
||||
from akkudoktoreos.measurement.measurement import (
|
||||
MeasurementChannelSettings,
|
||||
MeasurementCommonSettings,
|
||||
MeasurementDataRecord,
|
||||
)
|
||||
from akkudoktoreos.measurement.quality import SampleQuality
|
||||
from akkudoktoreos.utils.datetimeutil import (
|
||||
compare_datetimes,
|
||||
to_datetime,
|
||||
to_duration,
|
||||
)
|
||||
|
||||
|
||||
@@ -187,6 +190,8 @@ class TestMeasurement:
|
||||
config_eos.measurement.load_emr_keys = ["load0_mr", "load1_mr", "load2_mr", "load3_mr"]
|
||||
measurement = get_measurement()
|
||||
await measurement.delete_by_datetime(None, None)
|
||||
# Warn-once state lives on the shared singleton; start each test fresh.
|
||||
measurement._reported_warnings.clear()
|
||||
record0 = MeasurementDataRecord(
|
||||
date_time=datetime(2023, 1, 1, hour=0),
|
||||
load0_mr=100,
|
||||
@@ -255,109 +260,176 @@ class TestMeasurement:
|
||||
with pytest.raises(ValueError, match="interval must be positive"):
|
||||
measurement_eos._interval_count(start, end, duration(hours=0))
|
||||
|
||||
async def test_energy_from_meter_readings_valid_input(self, measurement_eos):
|
||||
"""Test _energy_from_meter_readings with valid inputs and proper alignment of load data."""
|
||||
key = "load0_mr"
|
||||
start_datetime = to_datetime("2023-01-01T00:00:00")
|
||||
end_datetime = to_datetime("2023-01-01T05:00:00")
|
||||
interval = duration(hours=1)
|
||||
|
||||
load_array = await measurement_eos._energy_from_meter_readings(
|
||||
key, start_datetime, end_datetime, interval
|
||||
async def test_meter_energy_kwh_valid_input(self, measurement_eos):
|
||||
"""Energy per interval is the difference of the readings at its boundaries."""
|
||||
result = await measurement_eos.meter_energy_kwh(
|
||||
["load0_mr", "load1_mr"],
|
||||
to_datetime("2023-01-01T00:00:00"),
|
||||
to_datetime("2023-01-01T05:00:00"),
|
||||
to_duration("1 hour"),
|
||||
)
|
||||
|
||||
expected_load_array = np.array([50, 50, 50, 50, 50]) # Differences between consecutive readings
|
||||
np.testing.assert_array_equal(load_array, expected_load_array)
|
||||
np.testing.assert_array_equal(result["load0_mr"], [50, 50, 50, 50, 50])
|
||||
np.testing.assert_array_equal(result["load1_mr"], [50, 50, 50, 50, 50])
|
||||
|
||||
async def test_energy_from_meter_readings_empty_array(self, measurement_eos):
|
||||
"""Test _energy_from_meter_readings with no data (empty array)."""
|
||||
key = "load0_mr"
|
||||
async def test_meter_energy_kwh_interpolates_a_missing_reading(self, measurement_eos):
|
||||
"""A reading missing at an interval boundary is interpolated from its neighbours."""
|
||||
start_datetime = to_datetime("2023-01-01T00:00:00")
|
||||
end_datetime = to_datetime("2023-01-01T05:00:00")
|
||||
interval = duration(hours=1)
|
||||
|
||||
# Use empyt records array
|
||||
await measurement_eos.delete_by_datetime(start_datetime, end_datetime)
|
||||
|
||||
load_array = await measurement_eos._energy_from_meter_readings(
|
||||
key, start_datetime, end_datetime, interval
|
||||
)
|
||||
|
||||
# Expected: an array of zeros with one less than the number of intervals
|
||||
expected_size = (
|
||||
measurement_eos._interval_count(start_datetime, end_datetime + interval, interval) - 1
|
||||
)
|
||||
expected_load_array = np.zeros(expected_size)
|
||||
np.testing.assert_array_equal(load_array, expected_load_array)
|
||||
|
||||
async def test_energy_from_meter_readings_misaligned_array(self, measurement_eos):
|
||||
"""Test _energy_from_meter_readings with misaligned array size."""
|
||||
key = "load1_mr"
|
||||
interval = duration(hours=1)
|
||||
start_datetime = to_datetime("2023-01-01T00:00:00")
|
||||
end_datetime = to_datetime("2023-01-01T05:00:00")
|
||||
|
||||
# Use misaligned array, latest interval set to 2 hours (instead of 1 hour)
|
||||
latest_record_datetime = to_datetime("2023-01-01T05:00:00")
|
||||
new_record_datetime = to_datetime("2023-01-01T06:00:00")
|
||||
record = await measurement_eos.get_by_datetime(latest_record_datetime)
|
||||
record = await measurement_eos.get_by_datetime(to_datetime("2023-01-01T05:00:00"))
|
||||
assert record is not None
|
||||
await measurement_eos.delete_by_datetime(start_datetime = latest_record_datetime,
|
||||
end_datetime = new_record_datetime)
|
||||
record.date_time = new_record_datetime
|
||||
await measurement_eos.delete_by_datetime(
|
||||
start_datetime=to_datetime("2023-01-01T05:00:00"),
|
||||
end_datetime=to_datetime("2023-01-01T06:00:00"),
|
||||
)
|
||||
record.date_time = to_datetime("2023-01-01T06:00:00")
|
||||
record.load1_mr = 500
|
||||
await measurement_eos.insert_by_datetime(record)
|
||||
|
||||
# Check test setup
|
||||
dates, values = await measurement_eos.key_to_lists(key, start_datetime, None)
|
||||
assert dates == [
|
||||
to_datetime("2023-01-01T00:00:00"),
|
||||
to_datetime("2023-01-01T01:00:00"),
|
||||
to_datetime("2023-01-01T02:00:00"),
|
||||
to_datetime("2023-01-01T03:00:00"),
|
||||
to_datetime("2023-01-01T04:00:00"),
|
||||
to_datetime("2023-01-01T06:00:00"),
|
||||
]
|
||||
assert values == [200, 250, 300, 350, 400, 450]
|
||||
array = await measurement_eos.key_to_array(key, start_datetime, end_datetime + interval, interval=interval)
|
||||
np.testing.assert_array_equal(array, [200, 250, 300, 350, 400, 425])
|
||||
|
||||
load_array = await measurement_eos._energy_from_meter_readings(
|
||||
key, start_datetime, end_datetime, interval
|
||||
result = await measurement_eos.meter_energy_kwh(
|
||||
["load1_mr"], start_datetime, to_datetime("2023-01-01T06:00:00"), to_duration("1 hour")
|
||||
)
|
||||
|
||||
expected_load_array = np.array([50., 50., 50., 50., 25.]) # Differences between consecutive readings
|
||||
np.testing.assert_array_equal(load_array, expected_load_array)
|
||||
np.testing.assert_array_equal(result["load1_mr"], [50.0, 50.0, 50.0, 50.0, 50.0, 50.0])
|
||||
|
||||
async def test_energy_from_meter_readings_partial_data(self, measurement_eos, caplog):
|
||||
"""Test _energy_from_meter_readings with partial data (misaligned but empty array)."""
|
||||
key = "load2_mr"
|
||||
start_datetime = to_datetime("2023-01-01T00:00:00")
|
||||
end_datetime = to_datetime("2023-01-01T05:00:00")
|
||||
interval = duration(hours=1)
|
||||
async def test_meter_energy_kwh_is_nan_outside_the_readings(self, measurement_eos):
|
||||
"""Intervals before the first or after the last reading are unknown."""
|
||||
result = await measurement_eos.meter_energy_kwh(
|
||||
["load0_mr", "load2_mr"],
|
||||
to_datetime("2022-12-31T23:00:00"),
|
||||
to_datetime("2023-01-01T07:00:00"),
|
||||
to_duration("1 hour"),
|
||||
)
|
||||
|
||||
with caplog.at_level("DEBUG"):
|
||||
load_array = await measurement_eos._energy_from_meter_readings(
|
||||
key, start_datetime, end_datetime, interval
|
||||
np.testing.assert_array_equal(
|
||||
result["load0_mr"], [np.nan, 50, 50, 50, 50, 50, np.nan, np.nan]
|
||||
)
|
||||
assert np.isnan(result["load2_mr"]).all()
|
||||
|
||||
async def test_meter_energy_kwh_extends_a_partial_last_interval(self, measurement_eos):
|
||||
"""A period that ends inside an interval still yields that full interval."""
|
||||
result = await measurement_eos.meter_energy_kwh(
|
||||
["load0_mr"],
|
||||
to_datetime("2023-01-01T00:00:00"),
|
||||
to_datetime("2023-01-01T02:20:00"),
|
||||
to_duration("1 hour"),
|
||||
)
|
||||
|
||||
np.testing.assert_array_equal(result["load0_mr"], [50, 50, 50])
|
||||
|
||||
async def test_meter_energy_kwh_negative_interval(self, measurement_eos):
|
||||
"""A non-positive interval is rejected."""
|
||||
with pytest.raises(ValueError, match="positive whole number of seconds"):
|
||||
await measurement_eos.meter_energy_kwh(
|
||||
["load0_mr"],
|
||||
to_datetime("2023-01-01T00:00:00"),
|
||||
to_datetime("2023-01-01T05:00:00"),
|
||||
to_duration(-3600),
|
||||
)
|
||||
|
||||
expected_size = (
|
||||
measurement_eos._interval_count(start_datetime, end_datetime + interval, interval) - 1
|
||||
async def test_keys_first_and_last_datetime(self, measurement_eos):
|
||||
"""First and last valid reading per key, each key on its own.
|
||||
|
||||
load1_mr reports two days longer than load0_mr, so the backward scan finds the
|
||||
two last readings in different windows; a trailing non-finite value of
|
||||
load0_mr is no reading.
|
||||
"""
|
||||
for hour in range(6, 54):
|
||||
await measurement_eos.update_value(
|
||||
to_datetime("2023-01-01T00:00:00").add(hours=hour), "load1_mr", 450 + hour
|
||||
)
|
||||
await measurement_eos.update_value(
|
||||
to_datetime("2023-01-03T12:00:00"), "load0_mr", float("nan")
|
||||
)
|
||||
expected_load_array = np.zeros(expected_size)
|
||||
np.testing.assert_array_equal(load_array, expected_load_array)
|
||||
keys = ["load0_mr", "load1_mr", "load1_mr", "load2_mr"]
|
||||
|
||||
async def test_energy_from_meter_readings_negative_interval(self, measurement_eos):
|
||||
"""Test _energy_from_meter_readings with a negative interval."""
|
||||
key = "load3_mr"
|
||||
start_datetime = to_datetime("2023-01-01T00:00:00")
|
||||
end_datetime = to_datetime("2023-01-01T05:00:00")
|
||||
interval = duration(hours=-1)
|
||||
firsts = await measurement_eos.keys_first_datetime(keys)
|
||||
lasts = await measurement_eos.keys_last_datetime(keys)
|
||||
|
||||
with pytest.raises(ValueError, match="interval must be positive"):
|
||||
await measurement_eos._energy_from_meter_readings(key, start_datetime, end_datetime, interval)
|
||||
assert firsts == {
|
||||
"load0_mr": to_datetime("2023-01-01T00:00:00"),
|
||||
"load1_mr": to_datetime("2023-01-01T00:00:00"),
|
||||
}
|
||||
assert lasts == {
|
||||
"load0_mr": to_datetime("2023-01-01T05:00:00"),
|
||||
"load1_mr": to_datetime("2023-01-03T05:00:00"),
|
||||
}
|
||||
timezone = measurement_eos.config.general.timezone
|
||||
assert all(stamp.timezone_name == timezone for stamp in [*firsts.values(), *lasts.values()])
|
||||
|
||||
async def test_conversion_failure_is_logged_once_per_streak(self, measurement_eos, caplog):
|
||||
"""Error on the first failure, debug while it persists, error again after a success."""
|
||||
|
||||
def levels() -> set[str]:
|
||||
levels = {r.levelname for r in caplog.records if "conversion failed" in r.getMessage()}
|
||||
caplog.clear()
|
||||
return levels
|
||||
|
||||
with caplog.at_level("DEBUG"):
|
||||
measurement_eos.report_conversion_failure("consumer", "consumer: conversion failed")
|
||||
assert levels() == {"ERROR"}
|
||||
measurement_eos.report_conversion_failure("consumer", "consumer: conversion failed")
|
||||
assert levels() == {"DEBUG"}
|
||||
# Each consumer has its own streak.
|
||||
measurement_eos.report_conversion_failure("other", "other: conversion failed")
|
||||
assert levels() == {"ERROR"}
|
||||
measurement_eos.clear_conversion_failure("consumer")
|
||||
measurement_eos.report_conversion_failure("consumer", "consumer: conversion failed")
|
||||
assert levels() == {"ERROR"}
|
||||
|
||||
async def test_keys_valid_datetimes(self, measurement_eos):
|
||||
"""Stamps of valid readings in [start, end): invalid quality does not count."""
|
||||
stamp = to_datetime("2023-01-01T02:00:00")
|
||||
record = await measurement_eos.db_get_record(DatabaseTimestamp.from_datetime(stamp))
|
||||
record.sample_quality["load0_mr"] = SampleQuality(status="invalid")
|
||||
await measurement_eos.db_mark_dirty_record(record)
|
||||
|
||||
stamps = await measurement_eos.keys_valid_datetimes(
|
||||
["load0_mr", "load_silent_mr"],
|
||||
to_datetime("2023-01-01T01:00:00"),
|
||||
to_datetime("2023-01-01T04:00:00"),
|
||||
)
|
||||
|
||||
assert stamps == {
|
||||
"load0_mr": [to_datetime("2023-01-01T01:00:00"), to_datetime("2023-01-01T03:00:00")],
|
||||
"load_silent_mr": [],
|
||||
}
|
||||
|
||||
async def test_load_total_kwh_warns_once_about_a_silent_meter(self, measurement_eos, caplog):
|
||||
"""A configured meter that never reports is a warning once, not on every run."""
|
||||
measurement_eos.config.measurement.load_emr_keys = ["load0_mr", "load_silent_mr"]
|
||||
period = {
|
||||
"start_datetime": to_datetime("2023-01-01T00:00:00"),
|
||||
"end_datetime": to_datetime("2023-01-01T03:00:00"),
|
||||
"interval": to_duration("1 hour"),
|
||||
}
|
||||
|
||||
def silent_meter_warnings() -> int:
|
||||
return sum(
|
||||
record.levelname == "WARNING"
|
||||
and "'load_silent_mr' gives no usable energy" in record.getMessage()
|
||||
for record in caplog.records
|
||||
)
|
||||
|
||||
with caplog.at_level("WARNING"):
|
||||
await measurement_eos.load_total_kwh(**period)
|
||||
first_run = silent_meter_warnings()
|
||||
await measurement_eos.load_total_kwh(**period)
|
||||
|
||||
assert first_run > 0
|
||||
assert silent_meter_warnings() == first_run
|
||||
|
||||
async def test_load_total_kwh_empty_store_without_period(self, measurement_eos):
|
||||
"""No data and no period yields an empty result, not an error."""
|
||||
await measurement_eos.delete_by_datetime(None, None)
|
||||
|
||||
result = await measurement_eos.load_total_kwh()
|
||||
|
||||
assert result.shape == (0,)
|
||||
|
||||
async def test_load_total_kwh(self, measurement_eos):
|
||||
"""Test total load calculation."""
|
||||
# Only these meters report; a silent configured meter makes the total unknown.
|
||||
measurement_eos.config.measurement.load_emr_keys = ["load0_mr", "load1_mr"]
|
||||
start_datetime = to_datetime("2023-01-01T03:00:00")
|
||||
end_datetime = to_datetime("2023-01-01T05:00:00")
|
||||
interval = duration(hours=1)
|
||||
@@ -376,11 +448,13 @@ class TestMeasurement:
|
||||
interval = duration(hours=1)
|
||||
|
||||
result = await measurement_eos.load_total_kwh(start_datetime=start_datetime, end_datetime=end_datetime, interval=interval)
|
||||
expected = np.zeros(3) # No data, so all intervals are zero
|
||||
np.testing.assert_array_equal(result, expected)
|
||||
# No data: the load of every interval is unknown, not zero.
|
||||
assert result.shape == (3,)
|
||||
assert np.isnan(result).all()
|
||||
|
||||
async def test_load_total_kwh_partial_intervals(self, measurement_eos):
|
||||
"""Test total load calculation with partial intervals."""
|
||||
measurement_eos.config.measurement.load_emr_keys = ["load0_mr", "load1_mr"]
|
||||
start_datetime = to_datetime("2023-01-01T00:30:00") # Start in the middle of an interval
|
||||
end_datetime = to_datetime("2023-01-01T01:30:00") # End in the middle of another interval
|
||||
interval = duration(hours=1)
|
||||
@@ -390,6 +464,60 @@ class TestMeasurement:
|
||||
np.testing.assert_array_equal(result, expected)
|
||||
|
||||
|
||||
async def test_load_total_kwh_follows_a_jittered_meter(self, measurement_eos):
|
||||
"""Hourly load energy is exact for a meter reporting at arbitrary stamps.
|
||||
|
||||
The meter reports every ~5 minutes off the hour. Load is 1 kW until noon and
|
||||
3 kW afterwards; each hour must get exactly its own energy, also around the step.
|
||||
"""
|
||||
measurement_eos.config.measurement.load_emr_keys = ["load_jitter_mr"]
|
||||
start = to_datetime("2023-02-01T00:00:00Z")
|
||||
jitter = [0, 21, 47, 13, 34]
|
||||
stamp = to_datetime("2023-01-31T23:57:10Z")
|
||||
energy_kwh = 0.0
|
||||
step = 0
|
||||
while compare_datetimes(stamp, to_datetime("2023-02-02T00:15:00Z")).lt:
|
||||
await measurement_eos.update_value(stamp, "load_jitter_mr", round(energy_kwh, 6))
|
||||
following = stamp.add(minutes=5, seconds=jitter[step % len(jitter)])
|
||||
noon = to_datetime("2023-02-01T12:00:00Z")
|
||||
seconds_before_noon = max(0.0, min(following.timestamp(), noon.timestamp()) - stamp.timestamp())
|
||||
seconds_after_noon = (following.timestamp() - stamp.timestamp()) - seconds_before_noon
|
||||
energy_kwh += (1.0 * seconds_before_noon + 3.0 * seconds_after_noon) / 3600.0
|
||||
stamp = following
|
||||
step += 1
|
||||
|
||||
result = await measurement_eos.load_total_kwh(
|
||||
start_datetime=start, end_datetime=start.add(days=1), interval=to_duration("1 hour")
|
||||
)
|
||||
|
||||
# Away from the step every hour is exact. The step lies inside one ~5-minute
|
||||
# reading interval, which a meter cannot resolve: hours 11 and 12 share it, but
|
||||
# keep their sum (a bucket-mean conversion moves about half an hour across).
|
||||
np.testing.assert_allclose(result[:11], 1.0, atol=1e-5)
|
||||
np.testing.assert_allclose(result[13:], 3.0, atol=1e-5)
|
||||
assert result[11] == pytest.approx(1.0, abs=0.05)
|
||||
assert result[12] == pytest.approx(3.0, abs=0.05)
|
||||
assert result[11] + result[12] == pytest.approx(4.0, abs=1e-5)
|
||||
|
||||
async def test_load_total_kwh_is_nan_without_full_coverage(self, measurement_eos):
|
||||
"""An hour a load meter does not fully cover is unknown, not zero load."""
|
||||
result = await measurement_eos.load_total_kwh(
|
||||
start_datetime=to_datetime("2023-01-01T03:00:00"),
|
||||
end_datetime=to_datetime("2023-01-01T07:00:00"),
|
||||
interval=to_duration("1 hour"),
|
||||
)
|
||||
|
||||
# load2_mr and load3_mr are configured but never report.
|
||||
assert np.isnan(result).all()
|
||||
measurement_eos.config.measurement.load_emr_keys = ["load0_mr", "load1_mr"]
|
||||
result = await measurement_eos.load_total_kwh(
|
||||
start_datetime=to_datetime("2023-01-01T03:00:00"),
|
||||
end_datetime=to_datetime("2023-01-01T07:00:00"),
|
||||
interval=to_duration("1 hour"),
|
||||
)
|
||||
np.testing.assert_array_equal(result, [100.0, 100.0, np.nan, np.nan])
|
||||
|
||||
|
||||
class TestMeasurementFileRestore:
|
||||
@pytest.fixture
|
||||
def file_measurements(self, config_eos, tmp_path, monkeypatch):
|
||||
@@ -546,3 +674,62 @@ class TestMeasurementChannels:
|
||||
measurement.records = previous_records
|
||||
config_eos.measurement = previous_settings
|
||||
config_eos.general.data_folder_path = previous_folder
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestMeasurementCommonPeriod:
|
||||
"""Common period of a meter group and its warnings."""
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def measurement(self, config_eos):
|
||||
# Configured meter keys are writable record keys of the store.
|
||||
config_eos.measurement.load_emr_keys = ["meter_a_mr", "meter_b_mr"]
|
||||
measurement = get_measurement()
|
||||
await measurement.delete_by_datetime(None, None)
|
||||
measurement._reported_warnings.clear()
|
||||
yield measurement
|
||||
await measurement.delete_by_datetime(None, None)
|
||||
measurement._reported_warnings.clear()
|
||||
|
||||
@staticmethod
|
||||
def warnings(caplog, text: str) -> int:
|
||||
return sum(
|
||||
record.levelname == "WARNING" and text in record.getMessage()
|
||||
for record in caplog.records
|
||||
)
|
||||
|
||||
async def test_silent_group_is_warned_again_after_it_reported(self, measurement, caplog):
|
||||
keys = ["meter_a_mr", "meter_b_mr"]
|
||||
start = to_datetime("2024-01-01T00:00:00Z")
|
||||
with caplog.at_level("WARNING"):
|
||||
assert await measurement.keys_common_period(keys, "test") is None
|
||||
first = self.warnings(caplog, "have no valid readings")
|
||||
for hour in range(3):
|
||||
for key in keys:
|
||||
await measurement.update_value(start.add(hours=hour), key, 10.0 + hour)
|
||||
assert await measurement.keys_common_period(keys, "test") is not None
|
||||
await measurement.delete_by_datetime(None, None)
|
||||
assert await measurement.keys_common_period(keys, "test") is None
|
||||
|
||||
assert first > 0
|
||||
assert self.warnings(caplog, "have no valid readings") > first
|
||||
|
||||
async def test_single_reading_is_no_replaced_meter(self, measurement, caplog):
|
||||
await measurement.update_value(to_datetime("2024-01-01T00:00:00Z"), "meter_a_mr", 10.0)
|
||||
|
||||
with caplog.at_level("WARNING"):
|
||||
assert await measurement.keys_common_period(["meter_a_mr"], "test") is None
|
||||
|
||||
assert self.warnings(caplog, "share no period") == 0
|
||||
|
||||
async def test_touching_replacement_is_a_replaced_meter(self, measurement, caplog):
|
||||
"""A swap where the new meter starts at the old meter's last stamp is named."""
|
||||
start = to_datetime("2024-01-01T00:00:00Z")
|
||||
for hour in range(4):
|
||||
await measurement.update_value(start.add(hours=hour), "meter_a_mr", 10.0 + hour)
|
||||
await measurement.update_value(start.add(hours=3 + hour), "meter_b_mr", 50.0 + hour)
|
||||
|
||||
with caplog.at_level("WARNING"):
|
||||
assert await measurement.keys_common_period(["meter_a_mr", "meter_b_mr"], "test") is None
|
||||
|
||||
assert self.warnings(caplog, "meter 'meter_a_mr' last reported at") > 0
|
||||
|
||||
@@ -8,8 +8,9 @@ from zoneinfo import ZoneInfo
|
||||
|
||||
import pytest
|
||||
|
||||
from akkudoktoreos.measurement.energy import energy_intervals
|
||||
from akkudoktoreos.measurement.energy import energy_intervals, valid_reading
|
||||
from akkudoktoreos.measurement.measurement import MeasurementChannelSettings
|
||||
from akkudoktoreos.measurement.quality import SampleQuality
|
||||
from akkudoktoreos.utils.datetimeutil import to_datetime
|
||||
|
||||
START = datetime(2026, 9, 10, tzinfo=timezone.utc)
|
||||
@@ -133,3 +134,22 @@ async def test_measurement_wrapper_preserves_asynchronous_channels(config_eos):
|
||||
measurement._db_reset_state()
|
||||
measurement.records = records
|
||||
config_eos.measurement = previous
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("value", "quality", "expected"),
|
||||
[
|
||||
(1, None, 1.0),
|
||||
(2.5, SampleQuality(status="estimated"), 2.5),
|
||||
(2.5, SampleQuality(status="invalid"), None),
|
||||
(2.5, SampleQuality(status="unavailable"), None),
|
||||
(True, None, None),
|
||||
(float("nan"), None, None),
|
||||
(float("inf"), None, None),
|
||||
(None, None, None),
|
||||
("1.0", None, None),
|
||||
],
|
||||
)
|
||||
def test_valid_reading(value: Any, quality: SampleQuality | None, expected: float | None) -> None:
|
||||
"""One rule decides which raw readings count, shared by conversion and scans."""
|
||||
assert valid_reading(value, quality) == expected
|
||||
|
||||
@@ -12,6 +12,7 @@ import pytest_asyncio
|
||||
import requests
|
||||
|
||||
from akkudoktoreos.core.coreabc import get_ems, get_measurement, get_prediction
|
||||
from akkudoktoreos.measurement.quality import MeasurementSample, SampleQuality
|
||||
from akkudoktoreos.prediction.pvforecastakkudoktor import PVForecastAkkudoktor
|
||||
from akkudoktoreos.prediction.pvforecastakkudoktorlocal import (
|
||||
PVForecastAkkudoktorLocal,
|
||||
@@ -103,6 +104,8 @@ async def pvforecast_instance(config_eos):
|
||||
get_ems().set_start_datetime(START)
|
||||
await provider.delete_by_datetime()
|
||||
await get_measurement().delete_by_datetime()
|
||||
# Warn-once state lives on the shared singleton; start each test fresh.
|
||||
get_measurement()._reported_warnings.clear()
|
||||
yield provider
|
||||
await provider.delete_by_datetime()
|
||||
await get_measurement().delete_by_datetime()
|
||||
@@ -404,6 +407,30 @@ async def test_calibration_uses_real_quarter_hour_measurements(pvforecast_instan
|
||||
assert "15-minute measurement resolution" in caplog.text or "15-minute intervals" in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_meter_resolution_counts_valid_readings_only(pvforecast_instance):
|
||||
"""Invalid intrahour readings must not make an hourly meter look quarter-hourly.
|
||||
|
||||
Fitting native slots on such a meter would interpolate within each hour and
|
||||
invent a flat intrahour profile.
|
||||
"""
|
||||
key = "pv_hourly_valid_emr"
|
||||
pvforecast_instance.config.measurement.pv_production_emr_keys = [key]
|
||||
start = START.subtract(days=3)
|
||||
samples = []
|
||||
for slot in range(3 * 24 * 4):
|
||||
stamp = start.add(minutes=15 * slot)
|
||||
quality = (
|
||||
SampleQuality(status="measured") if slot % 4 == 0 else SampleQuality(status="invalid")
|
||||
)
|
||||
samples.append(
|
||||
MeasurementSample(date_time=stamp, key=key, value=float(slot), quality=quality)
|
||||
)
|
||||
await get_measurement().import_samples(samples)
|
||||
|
||||
assert await pvforecast_instance._calibration_interval_minutes(start, START) == 60
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_calibration_factor_is_clamped(pvforecast_instance):
|
||||
"""A wildly wrong meter must not be allowed to swing the forecast."""
|
||||
@@ -1059,3 +1086,76 @@ async def test_snow_feedback_window_is_on_the_slot_grid(pvforecast_instance, rec
|
||||
assert end.timestamp() % 900 == 0
|
||||
assert compare_datetimes(end, pv_window.last).le
|
||||
assert compare_datetimes(end.add(minutes=15), pv_window.last).gt
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_calibration_falls_back_when_the_meter_conversion_fails(
|
||||
pvforecast_instance, monkeypatch, caplog
|
||||
):
|
||||
"""A broken PV meter history disables calibration instead of the forecast."""
|
||||
pvforecast_instance.config.pvforecast.akkudoktor = _calibration_settings(snow_enabled=True)
|
||||
frame = await pvforecast_instance._forecast_frame(synthetic_openmeteo(), calibrate=False)
|
||||
meter = _unaligned_meter_series(frame, 0.8, to_datetime("2025-06-09T00:04:50Z"), START, 5)
|
||||
await _feed_meters(pvforecast_instance, {"pv_broken_emr": meter})
|
||||
|
||||
async def failing_production_total_kwh(self, start_datetime, end_datetime, interval):
|
||||
raise ValueError("Overlapping source energy intervals.")
|
||||
|
||||
monkeypatch.setattr(
|
||||
PVForecastAkkudoktorLocal, "_pv_production_total_kwh", failing_production_total_kwh
|
||||
)
|
||||
|
||||
with caplog.at_level("ERROR"):
|
||||
forecast = await pvforecast_instance._forecast_frame(synthetic_openmeteo())
|
||||
calibration = await _fit(pvforecast_instance, frame)
|
||||
|
||||
assert calibration is None
|
||||
np.testing.assert_allclose(forecast["ac_power"], frame["ac_power"])
|
||||
assert "calibration: PV meter energy conversion failed" in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_calibration_warns_about_a_stale_common_meter_period(pvforecast_instance, caplog):
|
||||
"""A PV meter that stopped reporting holds the fit on old data - say so."""
|
||||
pvforecast_instance.config.pvforecast.akkudoktor = _calibration_settings()
|
||||
frame = await pvforecast_instance._forecast_frame(synthetic_openmeteo(), calibrate=False)
|
||||
meter = _unaligned_meter_series(frame, 0.8, to_datetime("2025-06-09T00:04:50Z"), START, 5)
|
||||
await _feed_meters(pvforecast_instance, {"pv_stale_emr": meter})
|
||||
|
||||
def stale_warnings() -> int:
|
||||
return sum(
|
||||
record.levelname == "WARNING"
|
||||
and "meter 'pv_stale_emr' last reported at" in record.getMessage()
|
||||
for record in caplog.records
|
||||
)
|
||||
|
||||
with caplog.at_level("WARNING"):
|
||||
get_ems().set_start_datetime(START.add(hours=12))
|
||||
await _fit(pvforecast_instance, frame)
|
||||
fresh = stale_warnings()
|
||||
get_ems().set_start_datetime(START.add(days=3))
|
||||
calibration = await _fit(pvforecast_instance, frame)
|
||||
first_stale_run = stale_warnings()
|
||||
await _fit(pvforecast_instance, frame)
|
||||
|
||||
_assert_fitted_bias(calibration, 0.8)
|
||||
assert fresh == 0
|
||||
assert first_stale_run > 0
|
||||
# Once per stale period, not on every run.
|
||||
assert stale_warnings() == first_stale_run
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pv_meter_window_skips_readings_that_vanish_between_scans(
|
||||
pvforecast_instance, monkeypatch
|
||||
):
|
||||
"""Readings removed between the first and last scan give no window, not an error."""
|
||||
pvforecast_instance.config.pvforecast.akkudoktor = _calibration_settings()
|
||||
frame = await pvforecast_instance._forecast_frame(synthetic_openmeteo(), calibrate=False)
|
||||
meter = _unaligned_meter_series(frame, 0.8, to_datetime("2025-06-09T00:04:50Z"), START, 5)
|
||||
await _feed_meters(pvforecast_instance, {"pv_vanishing_emr": meter})
|
||||
monkeypatch.setattr(
|
||||
type(get_measurement()), "keys_last_datetime", AsyncMock(return_value={})
|
||||
)
|
||||
|
||||
assert await pvforecast_instance._pv_measurement_window() is None
|
||||
|
||||
@@ -390,9 +390,39 @@ async def test_stale_meter_readings_are_reported(snow_instance, caplog):
|
||||
await feed_meter("stale", fixture, local("2026-02-20 09:00"))
|
||||
get_ems().set_start_datetime(local("2026-02-20 15:00"))
|
||||
|
||||
await snow_instance._forecast_frame(fixture["openmeteo"])
|
||||
def stale_levels() -> set[str]:
|
||||
return {
|
||||
record.levelname for record in caplog.records if "older than 3 h" in record.getMessage()
|
||||
}
|
||||
|
||||
assert "older than 3 h" in caplog.text
|
||||
with caplog.at_level("DEBUG"):
|
||||
await snow_instance._forecast_frame(fixture["openmeteo"])
|
||||
assert stale_levels() == {"WARNING"}
|
||||
caplog.clear()
|
||||
# Reported once per stale reading, not on every forecast run.
|
||||
await snow_instance._forecast_frame(fixture["openmeteo"])
|
||||
assert stale_levels() == {"DEBUG"}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_missing_meter_period_is_warned_once(snow_instance, caplog):
|
||||
"""Without a PV meter period only the meter lookup warns, once, not snow feedback."""
|
||||
fixture = load_fixture()
|
||||
get_measurement()._reported_warnings.clear()
|
||||
snow_instance.config.measurement.pv_production_emr_keys = ["silent"]
|
||||
get_ems().set_start_datetime(local("2026-02-20 15:00"))
|
||||
|
||||
def warnings() -> set[str]:
|
||||
return {r.getMessage() for r in caplog.records if r.levelname == "WARNING"}
|
||||
|
||||
with caplog.at_level("DEBUG"):
|
||||
await snow_instance._forecast_frame(fixture["openmeteo"])
|
||||
(message,) = warnings()
|
||||
assert "'silent'" in message and "no valid readings" in message
|
||||
caplog.clear()
|
||||
# The lasting condition is not warned about again on the next forecast run.
|
||||
await snow_instance._forecast_frame(fixture["openmeteo"])
|
||||
assert warnings() == set()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- calibration
|
||||
|
||||
Reference in New Issue
Block a user