From cc875f798cc2935423d09669c9bada0f9cc91e35 Mon Sep 17 00:00:00 2001 From: Bobby Noelte Date: Sun, 15 Nov 2026 11:43:11 +0000 Subject: [PATCH] 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 Assisted-by: Claude Code (claude-opus-5-5) --- .env | 2 +- CHANGELOG.md | 5 +++ config.yaml | 2 +- docs/_generated/configexample.md | 3 +- docs/_generated/configmeasurement.md | 5 ++- docs/_generated/openapi.md | 2 +- docs/akkudoktoreos/measurement.md | 45 ++++++++++++++++++-- docs/akkudoktoreos/prediction.md | 6 ++- openapi.json | 38 ++++++++++++++++- src/akkudoktoreos/core/_version_date.py | 2 +- src/akkudoktoreos/measurement/measurement.py | 27 ++++++++++-- tests/test_loadakkudoktor.py | 23 +++++----- tests/test_measurement.py | 44 +++++++++++++++++++ 13 files changed, 179 insertions(+), 25 deletions(-) diff --git a/.env b/.env index f351acd6..47bb2e17 100644 --- a/.env +++ b/.env @@ -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 # ----------------------------------------------------------------------------- diff --git a/CHANGELOG.md b/CHANGELOG.md index c95dbadf..526cf27f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/config.yaml b/config.yaml index d8d535d1..a04b7339 100644 --- a/config.yaml +++ b/config.yaml @@ -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" diff --git a/docs/_generated/configexample.md b/docs/_generated/configexample.md index 91b1845e..7255122e 100644 --- a/docs/_generated/configexample.md +++ b/docs/_generated/configexample.md @@ -277,7 +277,8 @@ ], "pv_production_emr_keys": [ "pv1_emr" - ] + ], + "emr_max_gap_seconds": 10800 }, "optimization": { "algorithm": "GENETIC", diff --git a/docs/_generated/configmeasurement.md b/docs/_generated/configmeasurement.md index c0d58f09..ee380313 100644 --- a/docs/_generated/configmeasurement.md +++ b/docs/_generated/configmeasurement.md @@ -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", diff --git a/docs/_generated/openapi.md b/docs/_generated/openapi.md index a23bd20d..b941e9f7 100644 --- a/docs/_generated/openapi.md +++ b/docs/_generated/openapi.md @@ -1,6 +1,6 @@ # Akkudoktor-EOS -**Version**: `v0.3.0.dev2611122196862169` +**Version**: `v0.3.0.dev2611151515912129` **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. diff --git a/docs/akkudoktoreos/measurement.md b/docs/akkudoktoreos/measurement.md index 5b75c8ab..ea4154e2 100644 --- a/docs/akkudoktoreos/measurement.md +++ b/docs/akkudoktoreos/measurement.md @@ -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 diff --git a/docs/akkudoktoreos/prediction.md b/docs/akkudoktoreos/prediction.md index 1121753a..52576327 100644 --- a/docs/akkudoktoreos/prediction.md +++ b/docs/akkudoktoreos/prediction.md @@ -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. diff --git a/openapi.json b/openapi.json index 84c4e6bb..981de9bc 100644 --- a/openapi.json +++ b/openapi.json @@ -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" diff --git a/src/akkudoktoreos/core/_version_date.py b/src/akkudoktoreos/core/_version_date.py index 6060a3ab..e9a0f7bf 100644 --- a/src/akkudoktoreos/core/_version_date.py +++ b/src/akkudoktoreos/core/_version_date.py @@ -1 +1 @@ -VERSION_DATE = "2026-11-12T21:01:05Z" +VERSION_DATE = "2026-11-15T15:34:31Z" diff --git a/src/akkudoktoreos/measurement/measurement.py b/src/akkudoktoreos/measurement/measurement.py index 1c1b286e..978abbc6 100644 --- a/src/akkudoktoreos/measurement/measurement.py +++ b/src/akkudoktoreos/measurement/measurement.py @@ -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) diff --git a/tests/test_loadakkudoktor.py b/tests/test_loadakkudoktor.py index 025dcf2d..7c16ffd9 100644 --- a/tests/test_loadakkudoktor.py +++ b/tests/test_loadakkudoktor.py @@ -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)) diff --git a/tests/test_measurement.py b/tests/test_measurement.py index efee7ef9..7a819374 100644 --- a/tests/test_measurement.py +++ b/tests/test_measurement.py @@ -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):