feat(measurement): treat long *_emr_keys meter gaps as unknown

Additional fixes:
Add timezone to loadakkudoktoradapted tests datetime generation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Assisted-by: Claude Code (claude-opus-5-5)
This commit is contained in:
Bobby Noelte
2026-11-15 18:30:00 +01:00
co-authored by Claude Opus 5.5
parent f441759dfa
commit cc875f798c
13 changed files with 179 additions and 25 deletions
+1 -1
View File
@@ -11,7 +11,7 @@ DOCKER_COMPOSE_DATA_DIR=${HOME}/.local/share/net.akkudoktor.eos
# -----------------------------------------------------------------------------
# Image / build
# -----------------------------------------------------------------------------
VERSION=0.3.0.dev2611122196862169
VERSION=0.3.0.dev2611151515912129
PYTHON_VERSION=3.13.15
# -----------------------------------------------------------------------------
+5
View File
@@ -186,6 +186,11 @@ test procedure. These changes are not yet a tagged release.
final solution only, offspring are created without `deepcopy`, and identical genomes of a
generation are evaluated once also when the fitness cache is off.
- Data management (predictions, measurements, database) runs asynchronously.
- A gap longer than `measurement.emr_max_gap_seconds` (default 3 hours) between two readings of
a `*_emr_keys` meter has no energy value instead of being spread evenly over the gap: PV
calibration, the PV snow feedback and the load adjustment skip it, and `/v1/measurement/energy`
and `/v1/measurement/household` report it as missing. Set it to `null` for the former behaviour, e.g.
for a feeder that only sends a reading when the meter value changes.
### Fixed
+1 -1
View File
@@ -6,7 +6,7 @@
# the root directory (no add-on folder as usual).
name: "Akkudoktor-EOS"
version: "0.3.0.dev2611122196862169"
version: "0.3.0.dev2611151515912129"
slug: "eos"
description: "Akkudoktor-EOS add-on"
url: "https://github.com/Akkudoktor-EOS/EOS"
+2 -1
View File
@@ -277,7 +277,8 @@
],
"pv_production_emr_keys": [
"pv1_emr"
]
],
"emr_max_gap_seconds": 10800
},
"optimization": {
"algorithm": "GENETIC",
+4 -1
View File
@@ -8,6 +8,7 @@
| Name | Environment Variable | Type | Read-Only | Default | Description |
| ---- | -------------------- | ---- | --------- | ------- | ----------- |
| channels | `EOS_MEASUREMENT__CHANNELS` | `dict[str, akkudoktoreos.measurement.measurement.MeasurementChannelSettings]` | `rw` | `required` | Typed raw measurement channels keyed by measurement key. |
| emr_max_gap_seconds | `EOS_MEASUREMENT__EMR_MAX_GAP_SECONDS` | `Optional[int]` | `rw` | `10800` | Longest gap between two readings of a `*_emr_keys` meter [s] whose energy is spread evenly over the gap. A longer gap has no energy value (unknown) instead. A meter with its own `channels` entry uses that entry's `max_gap_seconds`. None spreads every gap evenly. |
| energy_context_seconds | `EOS_MEASUREMENT__ENERGY_CONTEXT_SECONDS` | `int` | `rw` | `86400` | None |
| grid_export_emr_keys | `EOS_MEASUREMENT__GRID_EXPORT_EMR_KEYS` | `Optional[list[str]]` | `rw` | `None` | The keys of the measurements that are energy meter readings of energy export to grid [kWh]. |
| grid_import_emr_keys | `EOS_MEASUREMENT__GRID_IMPORT_EMR_KEYS` | `Optional[list[str]]` | `rw` | `None` | The keys of the measurements that are energy meter readings of energy import from grid [kWh]. |
@@ -42,7 +43,8 @@
],
"pv_production_emr_keys": [
"pv1_emr"
]
],
"emr_max_gap_seconds": 10800
}
}
```
@@ -72,6 +74,7 @@
"pv_production_emr_keys": [
"pv1_emr"
],
"emr_max_gap_seconds": 10800,
"keys": [
"grid_export_emr",
"grid_import_emr",
+1 -1
View File
@@ -1,6 +1,6 @@
# Akkudoktor-EOS
**Version**: `v0.3.0.dev2611122196862169`
**Version**: `v0.3.0.dev2611151515912129`
<!-- pyml disable line-length -->
**Description**: This project provides a comprehensive solution for simulating and optimizing an energy system based on renewable energy sources. With a focus on photovoltaic (PV) systems, battery storage (batteries), load management (consumer requirements), heat pumps, electric vehicles, and consideration of electricity price data, this system enables forecasting and optimization of energy flow and costs over a specified period.
+42 -3
View File
@@ -80,9 +80,48 @@ linearly approximated. Storing values between optimization intervals is generall
The EOS measurement store automatically sums all given loads to create a total load value series
for specified intervals, usually one hour. This aggregated data can be used for load predictions.
An interval that the meters do not fully cover (before the first or after the last reading, a meter
reset, or a gap longer than the channel's `max_gap_seconds`) has no value instead of zero load; with
several load meters, all of them must cover it. Without `max_gap_seconds` a gap between two readings
is spread evenly over it. The `LoadAkkudoktorAdjusted` provider skips hours without a value.
reset, or a gap longer than the meter's gap limit) has no value instead of zero load; with
several load meters, all of them must cover it. The `LoadAkkudoktorAdjusted` provider skips hours
without a value.
### Meter gaps
The energy between two readings of a `*_emr_keys` meter (load, grid import/export, PV production)
is spread evenly over the time between them. A gap longer than `measurement.emr_max_gap_seconds`
(default 10800 s, 3 hours) has no energy value instead: an outage of EOS or of the meter does not
turn into invented, even consumption or production, nights included.
```json
{
"measurement": {
"emr_max_gap_seconds": 10800
}
}
```
Set it to `null` to spread every gap evenly (the behaviour before the limit). A feeder that only
sends a reading when the meter value changes (e.g. a PV or export meter that stands still at night)
needs `null` or a value longer than its longest still period; the Home Assistant adapter reads
the meters on every energy management run and needs no change.
A single meter can get its own limit with a `channels` entry, which takes precedence:
```json
{
"measurement": {
"pv_production_emr_keys": ["pv1_emr"],
"channels": {
"pv1_emr": {
"quantity": "cumulative_energy",
"unit": "kWh",
"max_gap_seconds": 43200
}
}
}
}
```
The entry of a `*_emr_keys` meter must stay `cumulative_energy` in `kWh`.
:::{admonition} Warning
:class: warning
+4 -2
View File
@@ -907,10 +907,12 @@ keys in `measurement.pv_production_emr_keys` to fit the model against measuremen
Calibration preserves daily energy while optionally correcting the intraday
azimuth shape, clamps correction factors and respects inverter capacity.
Hourly meters are fitted hourly; native quarter-hour meters retain their cadence.
Readings marked invalid or unavailable do not count for the meter cadence.
Meters may report at any time stamps: each interval gets the energy interpolated at its
boundaries. With several PV meters only the period all of them report is fitted, and
intervals a meter does not fully cover (a reset, or a gap longer than the channel's
`max_gap_seconds`) are skipped.
intervals a meter does not fully cover (a reset, or a gap longer than
`measurement.emr_max_gap_seconds` or the channel's `max_gap_seconds`, see the meter gaps
in the measurement documentation) are skipped.
Probable outage or curtailment days are excluded by default. Without sufficient
usable measurements the uncalibrated physical model is used.
+37 -1
View File
@@ -8,7 +8,7 @@
"name": "Apache 2.0",
"url": "https://www.apache.org/licenses/LICENSE-2.0.html"
},
"version": "v0.3.0.dev2611122196862169"
"version": "v0.3.0.dev2611151515912129"
},
"paths": {
"/v1/measurement/battery-capacity/{battery_id}": {
@@ -14086,6 +14086,24 @@
"pv1_emr"
]
]
},
"emr_max_gap_seconds": {
"anyOf": [
{
"type": "integer",
"exclusiveMinimum": 0.0
},
{
"type": "null"
}
],
"title": "Emr Max Gap Seconds",
"description": "Longest gap between two readings of a `*_emr_keys` meter [s] whose energy is spread evenly over the gap. A longer gap has no energy value (unknown) instead. A meter with its own `channels` entry uses that entry's `max_gap_seconds`. None spreads every gap evenly.",
"default": 10800,
"examples": [
10800,
null
]
}
},
"type": "object",
@@ -14220,6 +14238,24 @@
]
]
},
"emr_max_gap_seconds": {
"anyOf": [
{
"type": "integer",
"exclusiveMinimum": 0.0
},
{
"type": "null"
}
],
"title": "Emr Max Gap Seconds",
"description": "Longest gap between two readings of a `*_emr_keys` meter [s] whose energy is spread evenly over the gap. A longer gap has no energy value (unknown) instead. A meter with its own `channels` entry uses that entry's `max_gap_seconds`. None spreads every gap evenly.",
"default": 10800,
"examples": [
10800,
null
]
},
"keys": {
"items": {
"type": "string"
+1 -1
View File
@@ -1 +1 @@
VERSION_DATE = "2026-11-12T21:01:05Z"
VERSION_DATE = "2026-11-15T15:34:31Z"
+24 -3
View File
@@ -179,6 +179,21 @@ class MeasurementCommonSettings(SettingsBaseModel):
},
)
emr_max_gap_seconds: Optional[int] = Field(
default=10800,
gt=0,
strict=True,
json_schema_extra={
"description": (
"Longest gap between two readings of a `*_emr_keys` meter [s] whose energy "
"is spread evenly over the gap. A longer gap has no energy value (unknown) "
"instead. A meter with its own `channels` entry uses that entry's "
"`max_gap_seconds`. None spreads every gap evenly."
),
"examples": [10800, None],
},
)
## Computed fields
@computed_field # type: ignore[prop-decorator]
@property
@@ -353,7 +368,11 @@ class Measurement(SingletonMixin, DataImportMixin, DataSequence[MeasurementDataR
return channel
for name in type(self.config.measurement).model_fields:
if name.endswith("_emr_keys") and key in (getattr(self.config.measurement, name) or []):
return MeasurementChannelSettings(quantity="cumulative_energy", unit="kWh")
return MeasurementChannelSettings(
quantity="cumulative_energy",
unit="kWh",
max_gap_seconds=self.config.measurement.emr_max_gap_seconds,
)
raise ValueError(f"No energy channel definition for {key!r}.")
async def _energy_converter(
@@ -502,7 +521,8 @@ class Measurement(SingletonMixin, DataImportMixin, DataSequence[MeasurementDataR
Returns:
Energy in kWh per interval for each key, NaN where the channel does not
fully cover the interval (before its first or after its last reading, a
reset, or a gap longer than the channel's ``max_gap_seconds``).
reset, or a gap longer than the channel's ``max_gap_seconds``; for a
``*_emr_keys`` meter without own channel ``emr_max_gap_seconds``).
Raises:
ValueError: If the period or interval is invalid or a key has no energy
@@ -811,7 +831,8 @@ class Measurement(SingletonMixin, DataImportMixin, DataSequence[MeasurementDataR
if np.isnan(meter_kwh).all():
message = (
f"Load meter '{key}' gives no usable energy for {start_datetime} .. "
f"{end_datetime} (no readings, resets or gaps longer than its "
f"{end_datetime} (no readings, resets or gaps longer than its gap "
"limit, measurement.emr_max_gap_seconds or its channel's "
"max_gap_seconds): the total load of this period is unknown."
)
self._warn_once(f"meter-unusable:{key}", message)
+13 -10
View File
@@ -298,17 +298,18 @@ async def _adjustment_window(adjusted, measurement):
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")
start_dt = to_datetime("2024-01-01T00:00:00", in_timezone=loadakkudoktoradjusted.config.general.timezone)
end_dt = to_datetime("2024-01-02T00:00:00", in_timezone=loadakkudoktoradjusted.config.general.timezone)
for hour in range(25):
await empty_measurement.update_value(dt.add(hours=hour), "load0_mr", 500.0 + hour)
await empty_measurement.update_value(start_dt.add(hours=hour), "load0_mr", 500.0 + hour)
await empty_measurement.update_value(
to_datetime("2024-01-02T00:11:00"), "storage-soc-factor", 0.42
to_datetime("2024-01-02T00:11:00", in_timezone=loadakkudoktoradjusted.config.general.timezone),
"storage-soc-factor", 0.42
)
_, calls = await _adjustment_window(loadakkudoktoradjusted, empty_measurement)
assert calls
assert calls[0]["start_datetime"] == to_datetime("2024-01-01T00:00:00")
assert calls[0]["end_datetime"] == to_datetime("2024-01-02T00:00:00")
assert calls[0]["start_datetime"] == start_dt
assert calls[0]["end_datetime"] == end_dt
@pytest.mark.asyncio
@pytest.mark.parametrize(
@@ -322,8 +323,10 @@ async def test_adjustment_within_first_hour_returns_zero(
loadakkudoktoradjusted, empty_measurement, records
):
"""Less than one full hour of data yields no adjustment instead of an error."""
timezone = loadakkudoktoradjusted.config.general.timezone
for time, key, value in records:
await empty_measurement.update_value(to_datetime(f"2026-08-01T{time}:00"), key, value)
time_dt = to_datetime(f"2026-08-01T{time}:00", in_timezone=timezone)
await empty_measurement.update_value(time_dt, key, value)
(weekday, weekend), calls = await _adjustment_window(loadakkudoktoradjusted, empty_measurement)
assert calls == []
assert not weekday.any() and not weekend.any()
@@ -360,7 +363,7 @@ async def test_adjustment_falls_back_when_the_meter_conversion_fails(
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")
dt = to_datetime("2024-01-01T00:00:00", in_timezone=loadakkudoktoradjusted.config.general.timezone)
for hour in range(25):
await empty_measurement.update_value(dt.add(hours=hour), "load0_mr", 500.0 + hour)
@@ -415,7 +418,7 @@ async def test_adjustment_window_follows_the_load_meters(
):
"""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")
dt = to_datetime("2024-01-01T00:00:00", in_timezone=loadakkudoktoradjusted.config.general.timezone)
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.
@@ -434,7 +437,7 @@ async def test_adjustment_ignores_a_stale_load_meter_period(
):
"""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")
dt = to_datetime("2024-01-01T00:00:00", in_timezone=loadakkudoktoradjusted.config.general.timezone)
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))
+44
View File
@@ -356,6 +356,43 @@ class TestMeasurement:
timezone = measurement_eos.config.general.timezone
assert all(stamp.timezone_name == timezone for stamp in [*firsts.values(), *lasts.values()])
@pytest.mark.parametrize(
("emr_max_gap_seconds", "channel_max_gap_seconds", "expected_kwh"),
[
# Default limit (3 h): a 6 h gap has no energy value.
("default", None, [np.nan] * 6),
# No limit: the gap's energy is spread evenly, as before the limit.
(None, None, [1.0] * 6),
# An own channels entry overrides the limit for its meter.
("default", 86400, [1.0] * 6),
],
)
async def test_emr_meter_gap_limit(
self, measurement_eos, emr_max_gap_seconds, channel_max_gap_seconds, expected_kwh
):
"""A *_emr_keys meter gap longer than emr_max_gap_seconds is unknown energy."""
settings = measurement_eos.config.measurement
settings.load_emr_keys = ["load_gap_mr"]
if emr_max_gap_seconds != "default":
settings.emr_max_gap_seconds = emr_max_gap_seconds
if channel_max_gap_seconds is not None:
settings.channels = {
"load_gap_mr": MeasurementChannelSettings(
quantity="cumulative_energy",
unit="kWh",
max_gap_seconds=channel_max_gap_seconds,
)
}
start = to_datetime("2023-01-02T00:00:00")
await measurement_eos.update_value(start, "load_gap_mr", 10.0)
await measurement_eos.update_value(start.add(hours=6), "load_gap_mr", 16.0)
energy = await measurement_eos.meter_energy_kwh(
["load_gap_mr"], start, start.add(hours=6), to_duration("1 hour")
)
np.testing.assert_allclose(energy["load_gap_mr"], expected_kwh)
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."""
@@ -633,6 +670,13 @@ class TestMeasurementChannels:
**{legacy_field: ["legacy"]}, channels={"legacy": CHANNELS["house_power"]}
))
def test_emr_max_gap_seconds_default(self):
"""Three hours tolerate hourly meters with jitter; None turns the limit off."""
assert MeasurementCommonSettings().emr_max_gap_seconds == 10800
assert MeasurementCommonSettings(emr_max_gap_seconds=None).emr_max_gap_seconds is None
with pytest.raises(ValidationError):
MeasurementCommonSettings(emr_max_gap_seconds=0)
@pytest.mark.parametrize("key", ["", " x", "date_time", "configured_data", "keys", "_private"])
def test_reject_reserved_key(self, key):
with pytest.raises(ValidationError):