diff --git a/docs/akkudoktoreos/measurement.md b/docs/akkudoktoreos/measurement.md index 1035b852..5b75c8ab 100644 --- a/docs/akkudoktoreos/measurement.md +++ b/docs/akkudoktoreos/measurement.md @@ -79,6 +79,10 @@ 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. :::{admonition} Warning :class: warning diff --git a/docs/akkudoktoreos/prediction.md b/docs/akkudoktoreos/prediction.md index a7bb6116..1121753a 100644 --- a/docs/akkudoktoreos/prediction.md +++ b/docs/akkudoktoreos/prediction.md @@ -579,7 +579,9 @@ The `LoadAkkudoktorAdjusted` provider retrieves generic load data from the local it to match the annual energy consumption specified in the `LoadAkkudoktor.loadakkudoktor_year_energy` configuration option. In addition, the provider refines the forecast by incorporating available measured load data, ensuring a more realistic and -site-specific consumption profile. +site-specific consumption profile. It compares the last 7 days that every configured load meter +reports; if a load meter has no readings or stopped reporting more than 7 days ago, the forecast +stays unadjusted and a warning names the meter. Prediction keys: @@ -905,6 +907,10 @@ 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. +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. Probable outage or curtailment days are excluded by default. Without sufficient usable measurements the uncalibrated physical model is used. diff --git a/src/akkudoktoreos/measurement/energy.py b/src/akkudoktoreos/measurement/energy.py index df610a19..0dd3aca4 100644 --- a/src/akkudoktoreos/measurement/energy.py +++ b/src/akkudoktoreos/measurement/energy.py @@ -40,6 +40,27 @@ def _date(value: float) -> datetime: return datetime.fromtimestamp(value, timezone.utc) +def valid_reading(value: object, quality: SampleQuality | None = None) -> float | None: + """Value of a raw reading that counts as a valid observation. + + A reading counts when it is a finite number (not a bool) whose sample quality is + neither invalid nor unavailable. The energy conversion, the meter period scans + and the meter resolution detection share this rule. + + Args: + value: Raw stored reading. + quality: Sample quality of the reading, None for the default (measured). + + Returns: + The reading as float, or None when it does not count. + """ + if isinstance(value, bool) or not isinstance(value, (int, float)) or not isfinite(value): + return None + if quality is not None and quality.status in ("invalid", "unavailable"): + return None + return float(value) + + def energy_intervals( samples: Iterable[tuple[datetime, float | None]], channel: "MeasurementChannelSettings", @@ -66,10 +87,9 @@ def energy_intervals( def sample_quality(time: float) -> SampleQuality: return quality.get(time, SampleQuality()) - def number(value: float | None) -> float | None: - if isinstance(value, bool) or not isinstance(value, (int, float)) or not isfinite(value): - return None - return float(value) * scale + def number(value: float | None, sample: SampleQuality) -> float | None: + reading = valid_reading(value, sample) + return None if reading is None else reading * scale # Segment: start, end, start/end power in W, method, error flag. segments = [] @@ -84,21 +104,15 @@ def energy_intervals( if previous_end is not None and a < previous_end: raise ValueError("Overlapping source energy intervals.") previous_end = b - value = number(raw) - if sample_quality(time).status in ("invalid", "unavailable"): - value = None + value = number(raw, sample_quality(time)) power = value * 3600 / duration if value is not None else None segments.append( (a, b, power, power, "interval_energy", "invalid_sample" if power is None else None) ) else: for (a, raw_a), (b, raw_b) in zip(points, points[1:]): - va, vb = number(raw_a), number(raw_b) qa, qb = sample_quality(a), sample_quality(b) - if qa.status in ("invalid", "unavailable"): - va = None - if qb.status in ("invalid", "unavailable"): - vb = None + va, vb = number(raw_a, qa), number(raw_b, qb) flag = None if channel.max_gap_seconds is not None and b - a > channel.max_gap_seconds: flag = "gap_too_large" diff --git a/src/akkudoktoreos/measurement/measurement.py b/src/akkudoktoreos/measurement/measurement.py index 4ca0235c..1c1b286e 100644 --- a/src/akkudoktoreos/measurement/measurement.py +++ b/src/akkudoktoreos/measurement/measurement.py @@ -8,6 +8,8 @@ The measurements can be added programmatically or imported from a file or JSON s import json from bisect import bisect_left, bisect_right +from collections.abc import Iterable +from dataclasses import dataclass from datetime import datetime, timedelta from pathlib import Path from typing import Any, Callable, Literal, Optional @@ -26,16 +28,36 @@ from akkudoktoreos.measurement.batterycapacity import ( BatteryCapacityRequest, estimate_capacity, ) -from akkudoktoreos.measurement.energy import EnergyInterval +from akkudoktoreos.measurement.energy import EnergyInterval, valid_reading from akkudoktoreos.measurement.household import HouseholdSettings, household_intervals from akkudoktoreos.measurement.quality import MeasurementSample, SampleQuality from akkudoktoreos.utils.datetimeutil import ( DateTime, Duration, + compare_datetimes, to_datetime, to_duration, ) +# Limits of one quality-aware energy query (`Measurement.energy_intervals`). +ENERGY_QUERY_MAX_SECONDS = 31 * 86400 +ENERGY_QUERY_MAX_INTERVALS = 10000 + + +@dataclass(frozen=True) +class MeterPeriod: + """Period that every meter of a group reports. + + Attributes: + first: Latest first valid reading across the meters. + last: Earliest last valid reading across the meters. + last_key: Meter whose last reading ends the period. + """ + + first: DateTime + last: DateTime + last_key: str + class MeasurementChannelSettings(SettingsBaseModel): """Meaning of a raw measurement channel; no conversion is performed on storage.""" @@ -209,6 +231,55 @@ class Measurement(SingletonMixin, DataImportMixin, DataSequence[MeasurementDataR return super().__init__(*args, **kwargs) + @property + def _reported_warnings(self) -> set[str]: + """Topics of conditions already warned about; see `_warn_once`. + + Created lazily and cached on the instance, like the record locks. + """ + try: + return object.__getattribute__(self, "_reported_warnings_instance") + except AttributeError: + reported: set[str] = set() + object.__setattr__(self, "_reported_warnings_instance", reported) + return reported + + def _warn_once(self, topics: str | Iterable[str], message: str, level: str = "WARNING") -> None: + """Log a lasting condition once at ``level``, then as debug until it clears. + + Args: + topics: Identity of the condition, e.g. ``"meter-silent::"``; + several topics log at ``level`` when any of them is new. + message: Log message. + level: Log level of the first message. + """ + topic_set = {topics} if isinstance(topics, str) else set(topics) + if topic_set <= self._reported_warnings: + logger.debug(message) + else: + self._reported_warnings.update(topic_set) + logger.log(level, message) + + def _clear_warning(self, topic: str) -> None: + """Forget a condition, so it is warned about again when it comes back.""" + self._reported_warnings.discard(topic) + + def report_conversion_failure(self, consumer: str, message: str) -> None: + """Log a failed meter energy conversion of ``consumer`` once per failure streak. + + The first failure logs as error, repeated failures as debug until + `clear_conversion_failure` reports a successful conversion. + + Args: + consumer: Conversion path, e.g. ``"LoadAkkudoktorAdjusted"``. + message: Log message, including the conversion error. + """ + self._warn_once(f"conversion-failed:{consumer}", message, level="ERROR") + + def clear_conversion_failure(self, consumer: str) -> None: + """End the failure streak of ``consumer`` after a successful conversion.""" + self._clear_warning(f"conversion-failed:{consumer}") + def _measurement_file_path(self) -> Optional[Path]: """Path to measurements file (may be used optional to database).""" try: @@ -291,14 +362,25 @@ class Measurement(SingletonMixin, DataImportMixin, DataSequence[MeasurementDataR start: datetime, end: datetime, ) -> Callable[[str, datetime, datetime, int], list[EnergyInterval]]: - """Load a bounded window once, including configured boundary context.""" + """Load a window once, including configured boundary context. + + The query limits that protect the API are checked by the public wrappers + (`_check_energy_query`), not here. + + Args: + keys: Energy channels to convert. + start: Start of the window. + end: End of the window. + + Returns: + Converter from a channel and a sub-window to energy intervals. + """ from akkudoktoreos.measurement.energy import energy_intervals if any(dt.tzinfo is None or dt.utcoffset() is None for dt in (start, end)): raise ValueError("Explicit timezone required.") - seconds = end.timestamp() - start.timestamp() - if not 0 < seconds <= 31 * 86400: - raise ValueError("Energy queries require a positive range of at most 31 days.") + if compare_datetimes(to_datetime(end), to_datetime(start)).le: + raise ValueError("Energy queries require a positive range.") channels = {key: self._energy_channel(key) for key in keys} context = self.config.measurement.energy_context_seconds records = [ @@ -339,10 +421,6 @@ class Measurement(SingletonMixin, DataImportMixin, DataSequence[MeasurementDataR def convert( key: str, left: datetime, right: datetime, interval_seconds: int ) -> list[EnergyInterval]: - if type(interval_seconds) is not int or interval_seconds <= 0: - raise ValueError("Positive integer interval_seconds required.") - if (right.timestamp() - left.timestamp()) / interval_seconds > 10000: - raise ValueError("At most 10000 output intervals per query.") lo = max(0, bisect_left(timestamps[key], left.timestamp()) - 1) hi = bisect_right(timestamps[key], right.timestamp()) + 1 return energy_intervals( @@ -351,6 +429,21 @@ class Measurement(SingletonMixin, DataImportMixin, DataSequence[MeasurementDataR return convert + @staticmethod + def _check_energy_query(start: datetime, end: datetime, interval_seconds: int) -> None: + """Enforce the limits of one public energy query (31 days, 10000 intervals). + + Raises: + ValueError: If the query exceeds a limit. + """ + seconds = to_datetime(start).diff(to_datetime(end), False).total_seconds() + if not 0 < seconds <= ENERGY_QUERY_MAX_SECONDS: + raise ValueError("Energy queries require a positive range of at most 31 days.") + if type(interval_seconds) is not int or interval_seconds <= 0: + raise ValueError("Positive integer interval_seconds required.") + if seconds / interval_seconds > ENERGY_QUERY_MAX_INTERVALS: + raise ValueError("At most 10000 output intervals per query.") + async def household_intervals( self, start_datetime: datetime, end_datetime: datetime, interval_seconds: int = 900 ) -> dict[str, list[EnergyInterval]]: @@ -360,6 +453,7 @@ class Measurement(SingletonMixin, DataImportMixin, DataSequence[MeasurementDataR raise ValueError("No household balance configured.") # Revalidate references even after an in-place configuration mutation. settings = HouseholdSettings.model_validate(settings.model_dump()) + self._check_energy_query(start_datetime, end_datetime, interval_seconds) convert = await self._energy_converter( [item.key for item in settings.inputs], start_datetime, end_datetime ) @@ -374,14 +468,243 @@ class Measurement(SingletonMixin, DataImportMixin, DataSequence[MeasurementDataR end_datetime: datetime, interval_seconds: int = 900, ) -> list[EnergyInterval]: - """Convert a typed channel without changing the legacy kWh calculation. + """Convert a typed channel; load and PV energy use the same conversion. Read only explicitly stored values for this key: another channel's timestamp must not introduce a synthetic outage. Explicit null values remain barriers. """ + self._check_energy_query(start_datetime, end_datetime, interval_seconds) convert = await self._energy_converter([key], start_datetime, end_datetime) return convert(key, start_datetime, end_datetime, interval_seconds) + async def meter_energy_kwh( + self, + keys: list[str], + start_datetime: DateTime, + end_datetime: DateTime, + interval: Duration, + ) -> dict[str, NDArray[Shape["*"], float]]: + """Energy per interval of energy channels, read from the store once. + + Uses the quality-aware conversion (`energy_intervals`): a cumulative meter is + interpolated at the interval boundaries, so a meter reporting at arbitrary + stamps yields exactly the energy of each interval. The records of the whole + period are loaded once for all channels, so a gap converts the same way + wherever it lies in the period. + + Args: + keys: Energy channels, e.g. configured meter reading keys. + start_datetime: Start of the first interval; intervals start here. + end_datetime: End of the period. A last partial interval is extended to a + full interval. + interval: Interval length, a positive whole number of seconds. + + 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``). + + Raises: + ValueError: If the period or interval is invalid or a key has no energy + channel definition. + """ + interval_seconds = int(interval.total_seconds()) + if interval_seconds <= 0 or interval_seconds != interval.total_seconds(): + raise ValueError("Interval must be a positive whole number of seconds.") + size = self._interval_count(start_datetime, end_datetime, interval) + if size == 0: + return {key: np.zeros(0) for key in keys} + period_end = start_datetime.add(seconds=size * interval_seconds) + convert = await self._energy_converter(keys, start_datetime, period_end) + return { + key: np.asarray( + [ + np.nan if slot.energy_wh is None else slot.energy_wh / 1000.0 + for slot in convert(key, start_datetime, period_end, interval_seconds) + ], + dtype=float, + ) + for key in keys + } + + def _valid_reading_keys(self, record: MeasurementDataRecord, keys: Iterable[str]) -> list[str]: + """Keys of ``record`` that carry a valid reading. + + Uses the reading rule of the energy conversion (`valid_reading`). + """ + if record.date_time is None: + return [] + return [ + key + for key in keys + if valid_reading(record.configured_data.get(key), record.sample_quality.get(key)) + is not None + ] + + async def keys_valid_datetimes( + self, keys: list[str], start_datetime: DateTime, end_datetime: DateTime + ) -> dict[str, list[DateTime]]: + """Stamps of the valid readings per key in a period, read in one pass. + + Unlike `key_to_lists`, readings whose sample quality is invalid or unavailable + do not count (`valid_reading`), as for the energy conversion. + + Args: + keys: Record keys, e.g. meter reading keys. + start_datetime: Start of the period (inclusive). + end_datetime: End of the period (exclusive). + + Returns: + Ascending stamps per key, empty for a key without valid readings. + """ + stamps: dict[str, list[DateTime]] = {key: [] for key in keys} + async for record in self.db_iterate_records( + DatabaseTimestamp.from_datetime(start_datetime), + DatabaseTimestamp.from_datetime(end_datetime), + ): + for key in self._valid_reading_keys(record, keys): + stamps[key].append(to_datetime(record.date_time)) + return stamps + + async def keys_first_datetime(self, keys: list[str]) -> dict[str, DateTime]: + """First stamp with a valid reading per key, in one forward pass. + + Scans forward from the oldest record in windows that double in size and stops + once every key is found, instead of reading the keys' whole history. + + Args: + keys: Record keys, e.g. meter reading keys. + + Returns: + First stamp per key, in the configured timezone like `min_datetime`; keys + without a valid reading are missing. + """ + timezone = self.config.general.timezone + wanted = set(keys) + firsts: dict[str, DateTime] = {} + oldest = await self.min_datetime() + newest = await self.max_datetime() + if not wanted or oldest is None or newest is None: + return firsts + end_of_store = newest.add(seconds=1) + step_seconds = 86400 + window_start = oldest + while len(firsts) < len(wanted) and compare_datetimes(window_start, end_of_store).lt: + window_end = window_start.add(seconds=step_seconds) + async for record in self.db_iterate_records( + DatabaseTimestamp.from_datetime(window_start), + DatabaseTimestamp.from_datetime(window_end), + ): + for key in self._valid_reading_keys(record, wanted - firsts.keys()): + firsts[key] = to_datetime(record.date_time, in_timezone=timezone) + window_start = window_end + step_seconds *= 2 + return firsts + + async def keys_last_datetime(self, keys: list[str]) -> dict[str, DateTime]: + """Last stamp with a valid reading per key, in one backward pass. + + Scans backward from the newest record in windows that double in size and + stops once every key is found. + + Args: + keys: Record keys, e.g. meter reading keys. + + Returns: + Last stamp per key, in the configured timezone like `max_datetime`; keys + without a valid reading are missing. + """ + timezone = self.config.general.timezone + wanted = set(keys) + lasts: dict[str, DateTime] = {} + oldest = await self.min_datetime() + newest = await self.max_datetime() + if not wanted or oldest is None or newest is None: + return lasts + step_seconds = 86400 + window_end = newest.add(seconds=1) + while len(lasts) < len(wanted) and compare_datetimes(window_end, oldest).gt: + window_start = window_end.subtract(seconds=step_seconds) + # Newest valid reading per key in this window; keys found in a newer + # window keep their stamp. + window_lasts: dict[str, DateTime] = {} + async for record in self.db_iterate_records( + DatabaseTimestamp.from_datetime(window_start), + DatabaseTimestamp.from_datetime(window_end), + ): + for key in self._valid_reading_keys(record, wanted - lasts.keys()): + window_lasts[key] = to_datetime(record.date_time, in_timezone=timezone) + lasts.update(window_lasts) + window_end = window_start + step_seconds *= 2 + return lasts + + async def keys_common_period(self, keys: list[str], consumer: str) -> Optional[MeterPeriod]: + """Period that every meter in ``keys`` covers with valid readings. + + Outside this period a sum over the meters is not the total they measure. + Logs why there is none, once per condition until it clears: a meter without + valid readings (e.g. a mistyped key) and meters that share no period (e.g. a + replaced meter still configured) are warnings; a single reading so far is an + info. + + Args: + keys: Meter reading keys of one group, e.g. the PV production meters. + consumer: Name used in the log messages and warning topics. + + Returns: + The common period, or None when a meter has no valid reading or the meters + share no period. + """ + keys = list(dict.fromkeys(keys)) + if not keys: + return None + firsts = await self.keys_first_datetime(keys) + silent = [key for key in keys if key not in firsts] + for key in firsts: + self._clear_warning(f"meter-silent:{consumer}:{key}") + if silent: + self._warn_once( + [f"meter-silent:{consumer}:{key}" for key in silent], + f"{consumer}: meter(s) {silent} have no valid readings (check the keys) - " + "waiting for them.", + ) + return None + lasts = await self.keys_last_datetime(keys) + if any(key not in lasts for key in keys): + logger.info(f"{consumer}: meter readings changed while reading them - skipping.") + return None + first_key = keys[0] + last_key = keys[0] + for key in keys[1:]: + if compare_datetimes(firsts[key], firsts[first_key]).gt: + first_key = key + if compare_datetimes(lasts[key], lasts[last_key]).lt: + last_key = key + first, last = firsts[first_key], lasts[last_key] + overlapping = compare_datetimes(first, last).lt + no_period_topic = f"meter-no-period:{consumer}" + if not overlapping and first_key != last_key: + # Two meters that do not report together, e.g. a replaced meter. + self._warn_once( + f"{no_period_topic}:{last_key}", + f"{consumer}: meter '{last_key}' last reported at {last}, before meter " + f"'{first_key}' started at {first} - the meters share no period.", + ) + return None + for key in keys: + self._clear_warning(f"{no_period_topic}:{key}") + if not overlapping: + # One meter with a single reading so far (or readings that changed). + self._warn_once( + f"meter-waiting:{consumer}", + f"{consumer}: the meters {keys} have no period yet ({first}) - waiting.", + level="INFO", + ) + return None + self._clear_warning(f"meter-waiting:{consumer}") + return MeterPeriod(first=first, last=last, last_key=last_key) + async def estimate_battery_capacity( self, battery_id: str, request: BatteryCapacityRequest ) -> BatteryCapacityEstimate: @@ -436,90 +759,37 @@ class Measurement(SingletonMixin, DataImportMixin, DataSequence[MeasurementDataR discharging_efficiency=parameters.discharging_efficiency, ) - async def _energy_from_meter_readings( - self, - key: str, - start_datetime: DateTime, - end_datetime: DateTime, - interval: Duration, - ) -> NDArray[Shape["*"], Any]: - """Calculate an energy values array indexed by fixed time intervals from energy metering data within an optional date range. - - Args: - key: Key for energy meter readings. - start_datetime (datetime): The start date for filtering the energy data (inclusive). - end_datetime (datetime): The end date for filtering the energy data (exclusive). - interval (duration): The fixed time interval. - - Returns: - np.ndarray: A NumPy Array of the energy [kWh] per interval values calculated from - the meter readings. - """ - if start_datetime is None or end_datetime is None: - raise ValueError("Start and end datetimes are required for energy calculation") - size = self._interval_count(start_datetime, end_datetime, interval) - - energy_mr_array = await self.key_to_array( - key=key, - start_datetime=start_datetime, - end_datetime=end_datetime + interval, - interval=interval, - fill_method="time", - boundary="context", - ) - if energy_mr_array.size != size + 1: - logging_msg = ( - f"'{key}' meter reading array size: {energy_mr_array.size}" - f" does not fit to expected size: {size + 1}, {energy_mr_array}" - ) - if energy_mr_array.size != 0: - logger.error(logging_msg) - raise ValueError(logging_msg) - logger.debug(logging_msg) - energy_array = np.zeros(size) - elif np.any(energy_mr_array == None): - # 'key_to_array()' creates None values array if no data records are available. - # Array contains None value -> ignore - debug_msg = f"'{key}' meter reading None: {energy_mr_array}" - logger.debug(debug_msg) - energy_array = np.zeros(size) - else: - # Calculate load per interval - debug_msg = f"'{key}' meter reading: {energy_mr_array}" - logger.debug(debug_msg) - energy_array = np.diff(energy_mr_array) - debug_msg = f"'{key}' energy calculation: {energy_array}" - logger.debug(debug_msg) - return energy_array - async def load_total_kwh( self, start_datetime: Optional[DateTime] = None, end_datetime: Optional[DateTime] = None, interval: Optional[Duration] = None, - ) -> NDArray[Shape["*"], Any]: - """Calculate a total load energy values array indexed by fixed time intervals from load metering data within an optional date range. + ) -> NDArray[Shape["*"], float]: + """Total load energy per interval from the configured load meters. + + Each meter is converted with `meter_energy_kwh`: the cumulative reading is + interpolated at the interval boundaries, and an interval a meter does not + fully cover is unknown (NaN), never zero load. Args: - start_datetime (datetime, optional): The start date for filtering the load data (inclusive). - end_datetime (datetime, optional): The end date for filtering the load data (exclusive). + start_datetime (datetime, optional): Start of the first interval. Defaults + to the first measurement. + end_datetime (datetime, optional): End of the period (exclusive). Defaults to + just after the last measurement. interval (duration, optional): The fixed time interval. Defaults to 1 hour. Returns: - np.ndarray: A NumPy Array of the total load energy [kWh] per interval values calculated from - the load meter readings. + np.ndarray: Total load energy [kWh] per interval; NaN where any load meter + lacks full coverage or no load meter is configured. + + Raises: + ValueError: If the period cannot be determined or is invalid. """ if interval is None: interval = to_duration("1 hour") - - if len(self) < 1: - # No data available - if start_datetime is None or end_datetime is None: - size = 0 - else: - size = self._interval_count(start_datetime, end_datetime, interval) - return np.zeros(size) - + if len(self) < 1 and (start_datetime is None or end_datetime is None): + # No data and no period: nothing to report. + return np.zeros(0) if start_datetime is None: start_datetime = await self.min_datetime() if end_datetime is None: @@ -529,23 +799,26 @@ class Measurement(SingletonMixin, DataImportMixin, DataSequence[MeasurementDataR if start_datetime is None or end_datetime is None: raise ValueError("Start and end datetimes are required for energy calculation") size = self._interval_count(start_datetime, end_datetime, interval) + if size == 0: + return np.zeros(0) + load_keys = self.config.measurement.load_emr_keys or [] + if not load_keys: + return np.full(size, np.nan) + load_total_kwh_array = np.zeros(size) - - # Loop through all loads - if isinstance(self.config.measurement.load_emr_keys, list): - for key in self.config.measurement.load_emr_keys: - # Calculate load per interval - load_array = await self._energy_from_meter_readings( - key=key, - start_datetime=start_datetime, - end_datetime=end_datetime, - interval=interval, + meters_kwh = await self.meter_energy_kwh(load_keys, start_datetime, end_datetime, interval) + for key, meter_kwh in meters_kwh.items(): + 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 " + "max_gap_seconds): the total load of this period is unknown." ) - # Add calculated load to total load - load_total_kwh_array += load_array - debug_msg = f"Total load '{key}' calculation: {load_total_kwh_array}" - logger.debug(debug_msg) - + self._warn_once(f"meter-unusable:{key}", message) + else: + self._clear_warning(f"meter-unusable:{key}") + load_total_kwh_array += meter_kwh + logger.debug(f"Total load calculation: {load_total_kwh_array}") return load_total_kwh_array # ----------------------- Measurement Database Protocol --------------------- diff --git a/src/akkudoktoreos/prediction/loadakkudoktor.py b/src/akkudoktoreos/prediction/loadakkudoktor.py index a4ffd5ae..c123c47b 100644 --- a/src/akkudoktoreos/prediction/loadakkudoktor.py +++ b/src/akkudoktoreos/prediction/loadakkudoktor.py @@ -4,11 +4,19 @@ from typing import Optional import numpy as np from loguru import logger -from pydantic import Field +from pydantic import Field, PrivateAttr from akkudoktoreos.config.configabc import SettingsBaseModel from akkudoktoreos.prediction.loadabc import LoadDataRecord, LoadProvider -from akkudoktoreos.utils.datetimeutil import compare_datetimes, to_datetime, to_duration +from akkudoktoreos.utils.datetimeutil import ( + DateTime, + compare_datetimes, + to_datetime, + to_duration, +) + +# The load adjustment ignores meters whose common period ended longer ago than this. +LOAD_ADJUSTMENT_STALE_DAYS = 7 class LoadAkkudoktorCommonSettings(SettingsBaseModel): @@ -93,6 +101,9 @@ class LoadAkkudoktor(LoadProvider[LoadAkkudoktorDataRecord]): class LoadAkkudoktorAdjusted(LoadAkkudoktor): """Fetch Load forecast data from Akkudoktor load profiles with adjustment by measurements.""" + # End of the load meter period last warned about as stale (warned once). + _stale_adjustment_reported_end: Optional[DateTime] = PrivateAttr(default=None) + @classmethod def provider_id(cls) -> str: """Return the unique identifier for the LoadAkkudoktor provider.""" @@ -112,16 +123,42 @@ class LoadAkkudoktorAdjusted(LoadAkkudoktor): weekend_adjust = np.zeros(24) weekend_adjust_weight = np.zeros(24) - max_dt = await self.measurement.max_datetime() - if max_dt is None: - # No measurements - return 0 adjustment - return (weekday_adjust, weekday_adjust) + if not self.config.measurement.load_emr_keys: + logger.info( + "LoadAkkudoktorAdjusted: measurement.load_emr_keys is not configured - " + "no load adjustment." + ) + return (weekday_adjust, weekend_adjust) - min_dt = await self.measurement.min_datetime() + # Compare against the period every load meter reports, not the whole store: + # other channels (PV, SoC) often reach further than the load meters. + period = await self.measurement.keys_common_period( + self.config.measurement.load_emr_keys, "LoadAkkudoktorAdjusted" + ) + if period is None: + return (weekday_adjust, weekend_adjust) + min_dt, max_dt = period.first, period.last + if compare_datetimes( + max_dt.add(days=LOAD_ADJUSTMENT_STALE_DAYS), self.ems_start_datetime + ).lt: + # A week that old says nothing about the current load profile. + message = ( + f"LoadAkkudoktorAdjusted: load meter '{period.last_key}' last reported at " + f"{max_dt}, more than {LOAD_ADJUSTMENT_STALE_DAYS} days ago - no load " + "adjustment." + ) + if ( + self._stale_adjustment_reported_end is not None + and compare_datetimes(self._stale_adjustment_reported_end, max_dt).equal + ): + logger.debug(message) + else: + self._stale_adjustment_reported_end = max_dt + logger.warning(message) + return (weekday_adjust, weekend_adjust) # compare predictions with real measurement - try to use last 7 days - # Keep the hourly buckets on full hours: the newest record may be an off-hour - # device state (e.g. SoC stamped with the run time, #1447). + # Keep the hourly buckets on full hours (#1447). compare_end = max_dt.start_of("hour") compare_start = compare_end - to_duration("7 days") if compare_datetimes(compare_start, min_dt).lt: @@ -134,13 +171,31 @@ class LoadAkkudoktorAdjusted(LoadAkkudoktor): return (weekday_adjust, weekend_adjust) compare_interval = to_duration("1 hour") - load_total_kwh_array = await self.measurement.load_total_kwh( - start_datetime=compare_start, - end_datetime=compare_end, - interval=compare_interval, - ) + try: + load_total_kwh_array = await self.measurement.load_total_kwh( + start_datetime=compare_start, + end_datetime=compare_end, + interval=compare_interval, + ) + except ValueError as exc: + self.measurement.report_conversion_failure( + "LoadAkkudoktorAdjusted", + f"Load adjustment: load meter energy conversion failed - no adjustment: {exc}", + ) + return (weekday_adjust, weekend_adjust) + self.measurement.clear_conversion_failure("LoadAkkudoktorAdjusted") + missing_hours = int(np.isnan(load_total_kwh_array).sum()) + if missing_hours: + logger.debug( + f"Load adjustment: {missing_hours} of {len(load_total_kwh_array)} hours lack " + "full load meter coverage and are skipped." + ) compare_dt = compare_start for i in range(len(load_total_kwh_array)): + if np.isnan(load_total_kwh_array[i]): + # Unknown load (meter gap): no information about this hour. + compare_dt += compare_interval + continue load_total_wh = load_total_kwh_array[i] * 1000 hour = compare_dt.hour diff --git a/src/akkudoktoreos/prediction/pvforecastakkudoktorlocal.py b/src/akkudoktoreos/prediction/pvforecastakkudoktorlocal.py index 7ce63e74..cb86112d 100644 --- a/src/akkudoktoreos/prediction/pvforecastakkudoktorlocal.py +++ b/src/akkudoktoreos/prediction/pvforecastakkudoktorlocal.py @@ -41,10 +41,11 @@ import pandas as pd import pendulum import requests from loguru import logger -from pydantic import Field, field_validator, model_validator +from pydantic import Field, PrivateAttr, field_validator, model_validator from akkudoktoreos.config.configabc import SettingsBaseModel from akkudoktoreos.core.cache import cache_in_file +from akkudoktoreos.measurement.measurement import MeterPeriod from akkudoktoreos.prediction.pvforecastabc import ( PVForecastDataRecordT, PVForecastProvider, @@ -77,15 +78,15 @@ OPENMETEO_SNOW_VARIABLES = ("snowfall", "snow_depth") # Snow feedback warns when the newest PV meter reading is older than this. SNOW_FEEDBACK_STALE_HOURS = 3 +# Calibration warns when the common PV meter period ended longer ago than this. +CALIBRATION_STALE_HOURS = 24 + # Open-Meteo hard limits for a single forecast request. MAX_FORECAST_DAYS = 16 MAX_PAST_DAYS = 92 TRANSPOSITION_MODELS = ("isotropic", "klucher", "haydavies", "reindl", "king", "perez") -# The measurement store converts energy for at most 31 days per query. -ENERGY_QUERY_MAX_DAYS = 30 - # pvlib SAPM cell temperature parameter set per EOS `mountingplace`. MOUNTING_TEMPERATURE_MODEL = { "free": "open_rack_glass_glass", @@ -93,19 +94,6 @@ MOUNTING_TEMPERATURE_MODEL = { } -@dataclass(frozen=True) -class PVMeterWindow: - """Period every configured PV production meter reports. - - Attributes: - first: Latest first reading across the PV meters. - last: Earliest last reading across the PV meters. - """ - - first: DateTime - last: DateTime - - def _utc_timestamp(moment: DateTime | pd.Timestamp) -> pd.Timestamp: """Convert a moment to a UTC pandas timestamp. @@ -589,6 +577,11 @@ class PVForecastAkkudoktorLocalCommonSettings(SettingsBaseModel): class PVForecastAkkudoktorLocal(PVForecastProvider[PVForecastDataRecordT]): """Compute the PV forecast locally from Open-Meteo irradiance using pvlib.""" + # End of the common PV meter period last warned about as stale (warned once). + _stale_calibration_reported_end: Optional[DateTime] = PrivateAttr(default=None) + # Last PV reading the snow feedback last warned about as stale (warned once). + _stale_snow_reported_end: Optional[DateTime] = PrivateAttr(default=None) + @classmethod def provider_id(cls) -> str: """Return the unique identifier for the PV-Forecast-Provider.""" @@ -1055,7 +1048,7 @@ class PVForecastAkkudoktorLocal(PVForecastProvider[PVForecastDataRecordT]): raw_ac = frame["ac_power"].to_numpy(dtype=float).copy() # Calibration and snow feedback share one scan of the PV meter readings. - pv_window: Optional[PVMeterWindow] = None + pv_window: Optional[MeterPeriod] = None if ( calibrate and self.config.measurement.pv_production_emr_keys @@ -1133,7 +1126,7 @@ class PVForecastAkkudoktorLocal(PVForecastProvider[PVForecastDataRecordT]): row_start = row_start - pd.Timedelta(minutes=self._settings.resolution_minutes) return row_start - async def _pv_measurement_window(self) -> Optional[PVMeterWindow]: + async def _pv_measurement_window(self) -> Optional[MeterPeriod]: """Period that every configured PV production meter covers with readings. The measurement store holds every meter, not just the PV ones. Load meters @@ -1147,48 +1140,25 @@ class PVForecastAkkudoktorLocal(PVForecastProvider[PVForecastDataRecordT]): The common period, or None when a PV meter has no readings or the meters share no period. """ - measurement = self.measurement - first = await measurement.min_datetime() - last = await measurement.max_datetime() - if first is None or last is None: - return None - common_first: Optional[DateTime] = None - common_last: Optional[DateTime] = None - for key in self.config.measurement.pv_production_emr_keys or []: - dates, _ = await measurement.key_to_lists( - key=key, - start_datetime=first, - end_datetime=last.add(minutes=1), - ) - if not dates: - return None - if common_first is None or compare_datetimes(dates[0], common_first).gt: - common_first = dates[0] - if common_last is None or compare_datetimes(dates[-1], common_last).lt: - common_last = dates[-1] - if common_first is None or common_last is None: - return None - if not compare_datetimes(common_first, common_last).lt: - logger.info( - "PVForecastAkkudoktorLocal: the PV production meters share no measurement " - f"period ({common_first} .. {common_last})." - ) - return None - return PVMeterWindow(first=common_first, last=common_last) + return await self.measurement.keys_common_period( + self.config.measurement.pv_production_emr_keys or [], "PVForecastAkkudoktorLocal" + ) - async def _calibration_interval_minutes(self, start: Any, end: Any) -> int: + async def _calibration_interval_minutes(self, start: DateTime, end: DateTime) -> int: """Use native forecast slots only when every PV meter resolves them. Interpolating an hourly cumulative meter onto quarter hours would create a perfectly flat, but invented, intrahour profile. Fall back to hourly fitting until all configured production meters actually provide native slot readings. + Only valid readings count: a meter that marks its intrahour readings invalid + or unavailable resolves full hours only. """ native_minutes = self._settings.resolution_minutes meter_resolutions: list[float] = [] - for key in self.config.measurement.pv_production_emr_keys or []: - dates, _ = await self.measurement.key_to_lists( - key=key, start_datetime=start, end_datetime=end - ) + keys = self.config.measurement.pv_production_emr_keys or [] + valid_datetimes = await self.measurement.keys_valid_datetimes(keys, start, end) + for key in keys: + dates = valid_datetimes[key] if len(dates) < 3: return 60 deltas = np.asarray( @@ -1290,29 +1260,13 @@ class PVForecastAkkudoktorLocal(PVForecastProvider[PVForecastDataRecordT]): keys = self.config.measurement.pv_production_emr_keys or [] if not keys: return np.asarray([], dtype=float) - interval_seconds = int(interval.total_seconds()) - totals: Optional[np.ndarray] = None - for key in keys: - values: list[float] = [] - chunk_start = start_datetime - while compare_datetimes(chunk_start, end_datetime).lt: - chunk_end = chunk_start.add(days=ENERGY_QUERY_MAX_DAYS) - if compare_datetimes(chunk_end, end_datetime).gt: - chunk_end = end_datetime - intervals = await self.measurement.energy_intervals( - key, chunk_start, chunk_end, interval_seconds - ) - values.extend( - np.nan if slot.energy_wh is None else slot.energy_wh / 1000.0 - for slot in intervals - ) - chunk_start = chunk_end - meter_kwh = np.asarray(values, dtype=float) - totals = meter_kwh if totals is None else totals + meter_kwh - return np.asarray(totals, dtype=float) + meters_kwh = await self.measurement.meter_energy_kwh( + keys, start_datetime, end_datetime, interval + ) + return np.asarray(sum(meters_kwh.values()), dtype=float) async def _fit_calibration( - self, frame: pd.DataFrame, pv_window: Optional[PVMeterWindow] + self, frame: pd.DataFrame, pv_window: Optional[MeterPeriod] ) -> Optional[tuple[float, np.ndarray]]: """Fit correction factors from measured PV production against the model. @@ -1344,6 +1298,22 @@ class PVForecastAkkudoktorLocal(PVForecastProvider[PVForecastDataRecordT]): logger.info("PVForecastAkkudoktorLocal calibration: no PV measurements yet - skipping.") return None pv_min_datetime, reference_end = pv_window.first, pv_window.last + if compare_datetimes( + reference_end.add(hours=CALIBRATION_STALE_HOURS), self.ems_start_datetime + ).lt: + message = ( + f"PVForecastAkkudoktorLocal calibration: PV production meter " + f"'{pv_window.last_key}' last reported at {reference_end}, more than " + f"{CALIBRATION_STALE_HOURS} h ago - calibration can only use data up to then." + ) + if ( + self._stale_calibration_reported_end is not None + and compare_datetimes(self._stale_calibration_reported_end, reference_end).equal + ): + logger.debug(message) + else: + self._stale_calibration_reported_end = reference_end + logger.warning(message) lookback_days = settings.calibration_days if settings.calibration_outage_filter_enabled: @@ -1374,12 +1344,18 @@ class PVForecastAkkudoktorLocal(PVForecastProvider[PVForecastDataRecordT]): return None start, end = window.start_datetime, window.end_datetime - measured_kwh = np.asarray( - await self._pv_production_total_kwh( + try: + measured_kwh = await self._pv_production_total_kwh( start_datetime=start, end_datetime=end, interval=interval - ), - dtype=float, - ) + ) + except ValueError as exc: + self.measurement.report_conversion_failure( + "PVForecastAkkudoktorLocal calibration", + "PVForecastAkkudoktorLocal calibration: PV meter energy conversion failed - " + f"using the uncalibrated model: {exc}", + ) + return None + self.measurement.clear_conversion_failure("PVForecastAkkudoktorLocal calibration") if measured_kwh.size == 0 or not np.isfinite(measured_kwh).any(): logger.info( "PVForecastAkkudoktorLocal calibration: no usable PV measurements - skipping." @@ -1799,7 +1775,7 @@ class PVForecastAkkudoktorLocal(PVForecastProvider[PVForecastDataRecordT]): return coverage, corrections async def _snow_observations( - self, frame: pd.DataFrame, pv_window: Optional[PVMeterWindow] + self, frame: pd.DataFrame, pv_window: Optional[MeterPeriod] ) -> tuple[list[tuple[int, int, float]], Optional[float]]: """Measured PV energy per meter interval, mapped onto forecast rows. @@ -1815,8 +1791,9 @@ class PVForecastAkkudoktorLocal(PVForecastProvider[PVForecastDataRecordT]): if not settings.snow_feedback_enabled or not self.config.measurement.pv_production_emr_keys: return [], None if pv_window is None: - logger.warning( - "PVForecastAkkudoktorLocal snow feedback: no PV production readings - " + # keys_common_period already logged why, once per condition. + logger.debug( + "PVForecastAkkudoktorLocal snow feedback: no PV meter period - " "using the weather-only snow model." ) return [], None @@ -1824,11 +1801,19 @@ class PVForecastAkkudoktorLocal(PVForecastProvider[PVForecastDataRecordT]): if compare_datetimes( pv_last.add(hours=SNOW_FEEDBACK_STALE_HOURS), self.ems_start_datetime ).lt: - logger.warning( + message = ( f"PVForecastAkkudoktorLocal snow feedback: last PV production reading " f"{pv_last} is older than {SNOW_FEEDBACK_STALE_HOURS} h - the snow " "coverage relies on the weather model since then." ) + if ( + self._stale_snow_reported_end is not None + and compare_datetimes(self._stale_snow_reported_end, pv_last).equal + ): + logger.debug(message) + else: + self._stale_snow_reported_end = pv_last + logger.warning(message) resolution = pd.Timedelta(minutes=settings.resolution_minutes) row_start = self._row_start_index(frame) @@ -1845,14 +1830,20 @@ class PVForecastAkkudoktorLocal(PVForecastProvider[PVForecastDataRecordT]): return [], None start = window.start - measured = np.asarray( - await self._pv_production_total_kwh( + try: + measured = await self._pv_production_total_kwh( start_datetime=window.start_datetime, end_datetime=window.end_datetime, interval=to_duration(f"{interval_minutes} minutes"), - ), - dtype=float, - ) + ) + except ValueError as exc: + self.measurement.report_conversion_failure( + "PVForecastAkkudoktorLocal snow feedback", + "PVForecastAkkudoktorLocal snow feedback: PV meter energy conversion failed - " + f"using the weather-only snow model: {exc}", + ) + return [], None + self.measurement.clear_conversion_failure("PVForecastAkkudoktorLocal snow feedback") interval_hours = interval_minutes / 60.0 # A meter jump (reset, a sub-meter dropping out of a sum) shows up as an # impossible yield. Drop it rather than learn snow - or its absence - from it. @@ -1879,7 +1870,7 @@ class PVForecastAkkudoktorLocal(PVForecastProvider[PVForecastDataRecordT]): plane_ac: np.ndarray, plane_poa: np.ndarray, plane_tilt: np.ndarray, - pv_window: Optional[PVMeterWindow], + pv_window: Optional[MeterPeriod], ) -> pd.DataFrame: """Reduce the forecast by the (measurement-corrected) snow coverage.""" settings = self._settings diff --git a/tests/test_loadakkudoktor.py b/tests/test_loadakkudoktor.py index 32d64b79..025dcf2d 100644 --- a/tests/test_loadakkudoktor.py +++ b/tests/test_loadakkudoktor.py @@ -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 diff --git a/tests/test_measurement.py b/tests/test_measurement.py index bf834fe8..efee7ef9 100644 --- a/tests/test_measurement.py +++ b/tests/test_measurement.py @@ -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 diff --git a/tests/test_measurementenergy.py b/tests/test_measurementenergy.py index e2a6553e..6a42bbe6 100644 --- a/tests/test_measurementenergy.py +++ b/tests/test_measurementenergy.py @@ -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 diff --git a/tests/test_pvforecastakkudoktorlocal.py b/tests/test_pvforecastakkudoktorlocal.py index b445477b..46fb84d6 100644 --- a/tests/test_pvforecastakkudoktorlocal.py +++ b/tests/test_pvforecastakkudoktorlocal.py @@ -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 diff --git a/tests/test_pvforecastakkudoktorlocalsnow.py b/tests/test_pvforecastakkudoktorlocalsnow.py index 76ab22ad..6466b4cf 100644 --- a/tests/test_pvforecastakkudoktorlocalsnow.py +++ b/tests/test_pvforecastakkudoktorlocalsnow.py @@ -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