mirror of
https://github.com/Akkudoktor-EOS/EOS.git
synced 2026-11-25 15:06:20 +01:00
fix(pvforecast): align the calibration window to the UTC slot grid
Additional fixes PV meter energy comes from the quality-aware conversion. Calibration rows are binned by interval start with end-stamped rows. The fit covers only the period every PV meter covers and stays inside its lookback. The meter resolution is judged only where every PV meter reports. Snow feedback derives its window from the same slot window helper and shares one PV meter read per forecast with calibration. Window bounds and pandas timestamps are converted in one place, always to UTC; fit days are counted in the configured zone. Calibration tests write meters in bulk, stamp them in the configured zone and check every azimuth bin; snow feedback has its own slot window test. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Assisted-by: Claude Code (claude-opus-5-5)
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
6fad58655f
commit
2bfb6eafab
@@ -33,6 +33,7 @@ import asyncio
|
|||||||
import math
|
import math
|
||||||
import time
|
import time
|
||||||
from collections.abc import Callable, Iterable
|
from collections.abc import Callable, Iterable
|
||||||
|
from dataclasses import dataclass
|
||||||
from typing import Any, Literal, Optional, Self
|
from typing import Any, Literal, Optional, Self
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
@@ -48,7 +49,13 @@ from akkudoktoreos.prediction.pvforecastabc import (
|
|||||||
PVForecastDataRecordT,
|
PVForecastDataRecordT,
|
||||||
PVForecastProvider,
|
PVForecastProvider,
|
||||||
)
|
)
|
||||||
from akkudoktoreos.utils.datetimeutil import compare_datetimes, to_datetime, to_duration
|
from akkudoktoreos.utils.datetimeutil import (
|
||||||
|
DateTime,
|
||||||
|
Duration,
|
||||||
|
compare_datetimes,
|
||||||
|
to_datetime,
|
||||||
|
to_duration,
|
||||||
|
)
|
||||||
|
|
||||||
OPENMETEO_URL = "https://api.open-meteo.com/v1/forecast"
|
OPENMETEO_URL = "https://api.open-meteo.com/v1/forecast"
|
||||||
|
|
||||||
@@ -76,6 +83,9 @@ MAX_PAST_DAYS = 92
|
|||||||
|
|
||||||
TRANSPOSITION_MODELS = ("isotropic", "klucher", "haydavies", "reindl", "king", "perez")
|
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`.
|
# pvlib SAPM cell temperature parameter set per EOS `mountingplace`.
|
||||||
MOUNTING_TEMPERATURE_MODEL = {
|
MOUNTING_TEMPERATURE_MODEL = {
|
||||||
"free": "open_rack_glass_glass",
|
"free": "open_rack_glass_glass",
|
||||||
@@ -83,6 +93,99 @@ 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.
|
||||||
|
|
||||||
|
This is the one conversion from EOS datetimes to pandas in this module, so every
|
||||||
|
window bound carries the same UTC timezone object.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
moment: A DateTime or a pandas timestamp, e.g. a row label of the UTC model
|
||||||
|
frame. A timezone-naive pandas timestamp is taken as UTC, the zone of the
|
||||||
|
model frame.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The same instant as a UTC pandas timestamp.
|
||||||
|
"""
|
||||||
|
timestamp = moment if isinstance(moment, pd.Timestamp) else pd.Timestamp(moment.isoformat())
|
||||||
|
if timestamp.tzinfo is None:
|
||||||
|
return timestamp.tz_localize("UTC")
|
||||||
|
return timestamp.tz_convert("UTC")
|
||||||
|
|
||||||
|
|
||||||
|
def _utc_datetime(timestamp: pd.Timestamp) -> DateTime:
|
||||||
|
"""Convert a UTC pandas timestamp back to a UTC DateTime."""
|
||||||
|
return to_datetime(timestamp.to_pydatetime(), in_timezone="UTC")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class SlotWindow:
|
||||||
|
"""Whole slots of the UTC epoch grid that a fit compares.
|
||||||
|
|
||||||
|
Attributes:
|
||||||
|
start: Start of the first slot, UTC.
|
||||||
|
end: End of the last slot, UTC.
|
||||||
|
"""
|
||||||
|
|
||||||
|
start: pd.Timestamp
|
||||||
|
end: pd.Timestamp
|
||||||
|
|
||||||
|
@property
|
||||||
|
def start_datetime(self) -> DateTime:
|
||||||
|
"""Start of the first slot as a UTC DateTime."""
|
||||||
|
return _utc_datetime(self.start)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def end_datetime(self) -> DateTime:
|
||||||
|
"""End of the last slot as a UTC DateTime."""
|
||||||
|
return _utc_datetime(self.end)
|
||||||
|
|
||||||
|
|
||||||
|
def _slot_window(
|
||||||
|
interval_minutes: int,
|
||||||
|
lookback_start: DateTime,
|
||||||
|
last: DateTime,
|
||||||
|
earliest: Iterable[DateTime | pd.Timestamp],
|
||||||
|
) -> Optional[SlotWindow]:
|
||||||
|
"""Measurement window that holds whole slots of the UTC epoch grid.
|
||||||
|
|
||||||
|
Meter readings arrive at arbitrary stamps (e.g. 00:04:50). A window bound off
|
||||||
|
the slot grid shifts every comparison slot off the rows of the UTC model frame
|
||||||
|
resampled to the slot length, which then reindex to NaN. Both bounds are
|
||||||
|
therefore snapped to the same UTC grid, also in zones with a :30 or :45 offset.
|
||||||
|
The window never reaches outside the lookback or the data.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
interval_minutes: Slot length in minutes.
|
||||||
|
lookback_start: Earliest start the lookback allows; rounded up to the grid.
|
||||||
|
last: Latest moment with data; rounded down to give the window end.
|
||||||
|
earliest: First moments that carry data (meter, model rows); each is
|
||||||
|
rounded up, so the window starts at the first slot they fully cover.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The window, or None when no whole slot fits.
|
||||||
|
"""
|
||||||
|
freq = f"{interval_minutes}min"
|
||||||
|
start = max(_utc_timestamp(moment).ceil(freq) for moment in (lookback_start, *earliest))
|
||||||
|
end = _utc_timestamp(last).floor(freq)
|
||||||
|
if start >= end:
|
||||||
|
return None
|
||||||
|
return SlotWindow(start=start, end=end)
|
||||||
|
|
||||||
|
|
||||||
def normalize_akkudoktor_settings(data: Any) -> Any:
|
def normalize_akkudoktor_settings(data: Any) -> Any:
|
||||||
"""Translate feature-branch PV settings without modifying the caller's data.
|
"""Translate feature-branch PV settings without modifying the caller's data.
|
||||||
|
|
||||||
@@ -951,9 +1054,20 @@ class PVForecastAkkudoktorLocal(PVForecastProvider[PVForecastDataRecordT]):
|
|||||||
frame.index = pd.DatetimeIndex(frame.index) - interval
|
frame.index = pd.DatetimeIndex(frame.index) - interval
|
||||||
|
|
||||||
raw_ac = frame["ac_power"].to_numpy(dtype=float).copy()
|
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
|
||||||
|
if (
|
||||||
|
calibrate
|
||||||
|
and self.config.measurement.pv_production_emr_keys
|
||||||
|
and (
|
||||||
|
settings.calibration_enabled
|
||||||
|
or (settings.snow_enabled and settings.snow_feedback_enabled)
|
||||||
|
)
|
||||||
|
):
|
||||||
|
pv_window = await self._pv_measurement_window()
|
||||||
if calibrate:
|
if calibrate:
|
||||||
# The fit needs the raw model to compare against, which is exactly `frame`.
|
# The fit needs the raw model to compare against, which is exactly `frame`.
|
||||||
calibration = await self._fit_calibration(frame)
|
calibration = await self._fit_calibration(frame, pv_window)
|
||||||
if calibration is not None:
|
if calibration is not None:
|
||||||
global_factor, factors = calibration
|
global_factor, factors = calibration
|
||||||
frame = self._apply_calibration(
|
frame = self._apply_calibration(
|
||||||
@@ -971,6 +1085,7 @@ class PVForecastAkkudoktorLocal(PVForecastProvider[PVForecastDataRecordT]):
|
|||||||
np.vstack(plane_ac),
|
np.vstack(plane_ac),
|
||||||
np.vstack(plane_poa),
|
np.vstack(plane_poa),
|
||||||
np.vstack(plane_tilt),
|
np.vstack(plane_tilt),
|
||||||
|
pv_window,
|
||||||
)
|
)
|
||||||
return frame
|
return frame
|
||||||
|
|
||||||
@@ -1006,22 +1121,39 @@ class PVForecastAkkudoktorLocal(PVForecastProvider[PVForecastDataRecordT]):
|
|||||||
total += min(limits)
|
total += min(limits)
|
||||||
return total
|
return total
|
||||||
|
|
||||||
async def _pv_measurement_window(self) -> Optional[tuple[Any, Any]]:
|
def _row_start_index(self, frame: pd.DataFrame) -> pd.DatetimeIndex:
|
||||||
"""First and last timestamp that actually carries PV production readings.
|
"""Start of the interval each forecast row covers.
|
||||||
|
|
||||||
|
Rows carry interval-start stamps unless ``shift_to_interval_start`` is off; then
|
||||||
|
they keep Open-Meteo's interval-end stamps and each row covers the interval
|
||||||
|
before its label.
|
||||||
|
"""
|
||||||
|
row_start = pd.DatetimeIndex(frame.index)
|
||||||
|
if not self._settings.shift_to_interval_start:
|
||||||
|
row_start = row_start - pd.Timedelta(minutes=self._settings.resolution_minutes)
|
||||||
|
return row_start
|
||||||
|
|
||||||
|
async def _pv_measurement_window(self) -> Optional[PVMeterWindow]:
|
||||||
|
"""Period that every configured PV production meter covers with readings.
|
||||||
|
|
||||||
The measurement store holds every meter, not just the PV ones. Load meters
|
The measurement store holds every meter, not just the PV ones. Load meters
|
||||||
routinely reach further than the PV meter in both directions, so deriving
|
routinely reach further than the PV meter in both directions, so deriving
|
||||||
the calibration window from the store as a whole would place it where no
|
the calibration window from the store as a whole would place it where no
|
||||||
PV reading exists - which silently skips calibration or downgrades it to
|
PV reading exists - which silently skips calibration or downgrades it to
|
||||||
hourly fitting.
|
hourly fitting. With several PV meters only their common period counts:
|
||||||
|
outside it the summed meters are not the plant.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The common period, or None when a PV meter has no readings or the meters
|
||||||
|
share no period.
|
||||||
"""
|
"""
|
||||||
measurement = self.measurement
|
measurement = self.measurement
|
||||||
first = await measurement.min_datetime()
|
first = await measurement.min_datetime()
|
||||||
last = await measurement.max_datetime()
|
last = await measurement.max_datetime()
|
||||||
if first is None or last is None:
|
if first is None or last is None:
|
||||||
return None
|
return None
|
||||||
earliest: Any = None
|
common_first: Optional[DateTime] = None
|
||||||
latest: Any = None
|
common_last: Optional[DateTime] = None
|
||||||
for key in self.config.measurement.pv_production_emr_keys or []:
|
for key in self.config.measurement.pv_production_emr_keys or []:
|
||||||
dates, _ = await measurement.key_to_lists(
|
dates, _ = await measurement.key_to_lists(
|
||||||
key=key,
|
key=key,
|
||||||
@@ -1029,14 +1161,20 @@ class PVForecastAkkudoktorLocal(PVForecastProvider[PVForecastDataRecordT]):
|
|||||||
end_datetime=last.add(minutes=1),
|
end_datetime=last.add(minutes=1),
|
||||||
)
|
)
|
||||||
if not dates:
|
if not dates:
|
||||||
continue
|
return None
|
||||||
if earliest is None or compare_datetimes(dates[0], earliest).lt:
|
if common_first is None or compare_datetimes(dates[0], common_first).gt:
|
||||||
earliest = dates[0]
|
common_first = dates[0]
|
||||||
if latest is None or compare_datetimes(dates[-1], latest).gt:
|
if common_last is None or compare_datetimes(dates[-1], common_last).lt:
|
||||||
latest = dates[-1]
|
common_last = dates[-1]
|
||||||
if earliest is None or latest is None:
|
if common_first is None or common_last is None:
|
||||||
return None
|
return None
|
||||||
return earliest, latest
|
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)
|
||||||
|
|
||||||
async def _calibration_interval_minutes(self, start: Any, end: Any) -> int:
|
async def _calibration_interval_minutes(self, start: Any, end: Any) -> int:
|
||||||
"""Use native forecast slots only when every PV meter resolves them.
|
"""Use native forecast slots only when every PV meter resolves them.
|
||||||
@@ -1130,18 +1268,52 @@ class PVForecastAkkudoktorLocal(PVForecastProvider[PVForecastDataRecordT]):
|
|||||||
return factors
|
return factors
|
||||||
|
|
||||||
async def _pv_production_total_kwh(
|
async def _pv_production_total_kwh(
|
||||||
self, start_datetime: Any, end_datetime: Any, interval: Any
|
self, start_datetime: DateTime, end_datetime: DateTime, interval: Duration
|
||||||
) -> np.ndarray:
|
) -> np.ndarray:
|
||||||
"""Sum configured cumulative PV meters using main's async energy conversion."""
|
"""Sum the configured cumulative PV meters per interval of [start, end).
|
||||||
totals = None
|
|
||||||
for key in self.config.measurement.pv_production_emr_keys or []:
|
|
||||||
values = await self.measurement._energy_from_meter_readings(
|
|
||||||
key, start_datetime, end_datetime, interval
|
|
||||||
)
|
|
||||||
totals = values if totals is None else totals + values
|
|
||||||
return np.asarray([] if totals is None else totals, dtype=float)
|
|
||||||
|
|
||||||
async def _fit_calibration(self, frame: pd.DataFrame) -> Optional[tuple[float, np.ndarray]]:
|
Uses the quality-aware energy conversion of the measurement store: each meter
|
||||||
|
is interpolated at the slot boundaries, so a meter reporting at arbitrary
|
||||||
|
stamps still yields the energy of exactly that slot. A slot a meter does not
|
||||||
|
fully cover (gap, reset, before its first or after its last reading) is NaN,
|
||||||
|
never zero, so it cannot pull a fitted factor down.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
start_datetime: Start of the first slot, on the slot grid.
|
||||||
|
end_datetime: End of the last slot, on the slot grid.
|
||||||
|
interval: Slot length.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Energy in kWh per slot, NaN where any meter lacks full coverage; empty when
|
||||||
|
no PV meter is configured.
|
||||||
|
"""
|
||||||
|
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)
|
||||||
|
|
||||||
|
async def _fit_calibration(
|
||||||
|
self, frame: pd.DataFrame, pv_window: Optional[PVMeterWindow]
|
||||||
|
) -> Optional[tuple[float, np.ndarray]]:
|
||||||
"""Fit correction factors from measured PV production against the model.
|
"""Fit correction factors from measured PV production against the model.
|
||||||
|
|
||||||
The comparison runs on past intervals, where the Open-Meteo rows are analysed
|
The comparison runs on past intervals, where the Open-Meteo rows are analysed
|
||||||
@@ -1150,6 +1322,10 @@ class PVForecastAkkudoktorLocal(PVForecastProvider[PVForecastDataRecordT]):
|
|||||||
from the error of the *weather forecast*, and only the former is systematic
|
from the error of the *weather forecast*, and only the former is systematic
|
||||||
enough to correct.
|
enough to correct.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
frame: Raw model frame of the forecast run.
|
||||||
|
pv_window: Common period of the PV meters, read once per forecast run.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
(global_factor, per_azimuth_bin_factors) or None when there is not enough
|
(global_factor, per_azimuth_bin_factors) or None when there is not enough
|
||||||
data to fit anything.
|
data to fit anything.
|
||||||
@@ -1164,36 +1340,39 @@ class PVForecastAkkudoktorLocal(PVForecastProvider[PVForecastDataRecordT]):
|
|||||||
)
|
)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
pv_window = await self._pv_measurement_window()
|
|
||||||
if pv_window is None:
|
if pv_window is None:
|
||||||
logger.info("PVForecastAkkudoktorLocal calibration: no PV measurements yet - skipping.")
|
logger.info("PVForecastAkkudoktorLocal calibration: no PV measurements yet - skipping.")
|
||||||
return None
|
return None
|
||||||
pv_min_datetime, reference_end = pv_window
|
pv_min_datetime, reference_end = pv_window.first, pv_window.last
|
||||||
|
|
||||||
lookback_days = settings.calibration_days
|
lookback_days = settings.calibration_days
|
||||||
if settings.calibration_outage_filter_enabled:
|
if settings.calibration_outage_filter_enabled:
|
||||||
lookback_days = max(lookback_days, settings.calibration_reference_days)
|
lookback_days = max(lookback_days, settings.calibration_reference_days)
|
||||||
reference_start = reference_end.subtract(days=lookback_days)
|
reference_start = reference_end.subtract(days=lookback_days)
|
||||||
interval_minutes = await self._calibration_interval_minutes(reference_start, reference_end)
|
# Judge the meter resolution only where every PV meter reports.
|
||||||
|
resolution_start = (
|
||||||
|
pv_min_datetime
|
||||||
|
if compare_datetimes(pv_min_datetime, reference_start).gt
|
||||||
|
else reference_start
|
||||||
|
)
|
||||||
|
interval_minutes = await self._calibration_interval_minutes(resolution_start, reference_end)
|
||||||
interval_hours = interval_minutes / 60.0
|
interval_hours = interval_minutes / 60.0
|
||||||
interval = to_duration(f"{interval_minutes} minutes")
|
interval = to_duration(f"{interval_minutes} minutes")
|
||||||
end = reference_end.start_of("hour")
|
# Bin the model rows by the interval they cover, like the meter slots.
|
||||||
if interval_minutes < 60:
|
model_frame = frame.set_axis(self._row_start_index(frame))
|
||||||
end = reference_end.start_of("minute").set(
|
|
||||||
minute=(reference_end.minute // interval_minutes) * interval_minutes
|
|
||||||
)
|
|
||||||
start = end.subtract(days=lookback_days)
|
|
||||||
if compare_datetimes(start, pv_min_datetime).lt:
|
|
||||||
start = pv_min_datetime.start_of("minute").add(minutes=interval_minutes)
|
|
||||||
# The model side only exists for the weather window that was requested.
|
# The model side only exists for the weather window that was requested.
|
||||||
model_start = to_datetime(frame.index[0].to_pydatetime())
|
window = _slot_window(
|
||||||
if compare_datetimes(start, model_start).lt:
|
interval_minutes,
|
||||||
start = model_start.start_of("minute").add(minutes=interval_minutes)
|
reference_start,
|
||||||
if compare_datetimes(start, end).ge:
|
reference_end,
|
||||||
|
(pv_min_datetime, model_frame.index[0]),
|
||||||
|
)
|
||||||
|
if window is None:
|
||||||
logger.info(
|
logger.info(
|
||||||
"PVForecastAkkudoktorLocal calibration: measurement window too short - skipping."
|
"PVForecastAkkudoktorLocal calibration: measurement window too short - skipping."
|
||||||
)
|
)
|
||||||
return None
|
return None
|
||||||
|
start, end = window.start_datetime, window.end_datetime
|
||||||
|
|
||||||
measured_kwh = np.asarray(
|
measured_kwh = np.asarray(
|
||||||
await self._pv_production_total_kwh(
|
await self._pv_production_total_kwh(
|
||||||
@@ -1211,10 +1390,12 @@ class PVForecastAkkudoktorLocal(PVForecastProvider[PVForecastDataRecordT]):
|
|||||||
# interval energy below; hourly meters stay hourly and native 15-minute meters
|
# interval energy below; hourly meters stay hourly and native 15-minute meters
|
||||||
# retain the shape that matters to the EMS.
|
# retain the shape that matters to the EMS.
|
||||||
samples_frame = (
|
samples_frame = (
|
||||||
frame[["ac_power", "solar_azimuth"]].resample(f"{interval_minutes}min").mean()
|
model_frame[["ac_power", "solar_azimuth"]]
|
||||||
|
.resample(f"{interval_minutes}min", origin="epoch")
|
||||||
|
.mean()
|
||||||
)
|
)
|
||||||
grid = pd.date_range(
|
grid = pd.date_range(
|
||||||
start=pd.Timestamp(start.in_timezone("UTC").isoformat()),
|
start=window.start,
|
||||||
periods=len(measured_kwh),
|
periods=len(measured_kwh),
|
||||||
freq=f"{interval_minutes}min",
|
freq=f"{interval_minutes}min",
|
||||||
)
|
)
|
||||||
@@ -1222,14 +1403,14 @@ class PVForecastAkkudoktorLocal(PVForecastProvider[PVForecastDataRecordT]):
|
|||||||
modelled_kwh = samples_frame["ac_power"].to_numpy(dtype=float) / 1000.0 * interval_hours
|
modelled_kwh = samples_frame["ac_power"].to_numpy(dtype=float) / 1000.0 * interval_hours
|
||||||
azimuth = samples_frame["solar_azimuth"].to_numpy(dtype=float)
|
azimuth = samples_frame["solar_azimuth"].to_numpy(dtype=float)
|
||||||
snow_possible = np.zeros(len(samples_frame), dtype=bool)
|
snow_possible = np.zeros(len(samples_frame), dtype=bool)
|
||||||
if "snow_possible" in frame.columns:
|
if "snow_possible" in model_frame.columns:
|
||||||
# Snow on the modules is a transient loss, not a model error. The day-level
|
# Snow on the modules is a transient loss, not a model error. The day-level
|
||||||
# outage filter catches fully covered days, but partly covered ones would
|
# outage filter catches fully covered days, but partly covered ones would
|
||||||
# still drag the factor down.
|
# still drag the factor down.
|
||||||
snow_possible = (
|
snow_possible = (
|
||||||
frame["snow_possible"]
|
model_frame["snow_possible"]
|
||||||
.astype(float)
|
.astype(float)
|
||||||
.resample(f"{interval_minutes}min")
|
.resample(f"{interval_minutes}min", origin="epoch")
|
||||||
.max()
|
.max()
|
||||||
.reindex(grid)
|
.reindex(grid)
|
||||||
.fillna(0.0)
|
.fillna(0.0)
|
||||||
@@ -1270,11 +1451,13 @@ class PVForecastAkkudoktorLocal(PVForecastProvider[PVForecastDataRecordT]):
|
|||||||
.tz_convert(self.config.general.timezone)
|
.tz_convert(self.config.general.timezone)
|
||||||
.normalize()
|
.normalize()
|
||||||
)
|
)
|
||||||
fit_start = pd.Timestamp(
|
# Count the fit days in the configured zone, where the outage filter's days are.
|
||||||
end.subtract(days=settings.calibration_days)
|
timezone = self.config.general.timezone
|
||||||
.in_timezone(self.config.general.timezone)
|
fit_start = (
|
||||||
.isoformat()
|
_utc_timestamp(end.in_timezone(timezone).subtract(days=settings.calibration_days))
|
||||||
).normalize()
|
.tz_convert(timezone)
|
||||||
|
.normalize()
|
||||||
|
)
|
||||||
|
|
||||||
if settings.calibration_outage_filter_enabled and usable.any():
|
if settings.calibration_outage_filter_enabled and usable.any():
|
||||||
samples = pd.DataFrame(
|
samples = pd.DataFrame(
|
||||||
@@ -1616,10 +1799,14 @@ class PVForecastAkkudoktorLocal(PVForecastProvider[PVForecastDataRecordT]):
|
|||||||
return coverage, corrections
|
return coverage, corrections
|
||||||
|
|
||||||
async def _snow_observations(
|
async def _snow_observations(
|
||||||
self, frame: pd.DataFrame
|
self, frame: pd.DataFrame, pv_window: Optional[PVMeterWindow]
|
||||||
) -> tuple[list[tuple[int, int, float]], Optional[float]]:
|
) -> tuple[list[tuple[int, int, float]], Optional[float]]:
|
||||||
"""Measured PV energy per meter interval, mapped onto forecast rows.
|
"""Measured PV energy per meter interval, mapped onto forecast rows.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
frame: Model frame of the forecast run.
|
||||||
|
pv_window: Common period of the PV meters, read once per forecast run.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
(observations, interval_hours): (first_row, end_row_exclusive, kWh) per
|
(observations, interval_hours): (first_row, end_row_exclusive, kWh) per
|
||||||
complete meter interval within the lookback, and the meter interval length.
|
complete meter interval within the lookback, and the meter interval length.
|
||||||
@@ -1627,14 +1814,13 @@ class PVForecastAkkudoktorLocal(PVForecastProvider[PVForecastDataRecordT]):
|
|||||||
settings = self._settings
|
settings = self._settings
|
||||||
if not settings.snow_feedback_enabled or not self.config.measurement.pv_production_emr_keys:
|
if not settings.snow_feedback_enabled or not self.config.measurement.pv_production_emr_keys:
|
||||||
return [], None
|
return [], None
|
||||||
pv_window = await self._pv_measurement_window()
|
|
||||||
if pv_window is None:
|
if pv_window is None:
|
||||||
logger.warning(
|
logger.warning(
|
||||||
"PVForecastAkkudoktorLocal snow feedback: no PV production readings - "
|
"PVForecastAkkudoktorLocal snow feedback: no PV production readings - "
|
||||||
"using the weather-only snow model."
|
"using the weather-only snow model."
|
||||||
)
|
)
|
||||||
return [], None
|
return [], None
|
||||||
pv_first, pv_last = pv_window
|
pv_first, pv_last = pv_window.first, pv_window.last
|
||||||
if compare_datetimes(
|
if compare_datetimes(
|
||||||
pv_last.add(hours=SNOW_FEEDBACK_STALE_HOURS), self.ems_start_datetime
|
pv_last.add(hours=SNOW_FEEDBACK_STALE_HOURS), self.ems_start_datetime
|
||||||
).lt:
|
).lt:
|
||||||
@@ -1645,30 +1831,24 @@ class PVForecastAkkudoktorLocal(PVForecastProvider[PVForecastDataRecordT]):
|
|||||||
)
|
)
|
||||||
|
|
||||||
resolution = pd.Timedelta(minutes=settings.resolution_minutes)
|
resolution = pd.Timedelta(minutes=settings.resolution_minutes)
|
||||||
row_start = pd.DatetimeIndex(frame.index)
|
row_start = self._row_start_index(frame)
|
||||||
if not settings.shift_to_interval_start:
|
|
||||||
row_start = row_start - resolution
|
|
||||||
|
|
||||||
lookback_start = pv_last.subtract(days=settings.snow_lookback_days)
|
lookback_start = pv_last.subtract(days=settings.snow_lookback_days)
|
||||||
interval_minutes = await self._calibration_interval_minutes(lookback_start, pv_last)
|
resolution_start = (
|
||||||
|
pv_first if compare_datetimes(pv_first, lookback_start).gt else lookback_start
|
||||||
|
)
|
||||||
|
interval_minutes = await self._calibration_interval_minutes(resolution_start, pv_last)
|
||||||
interval = pd.Timedelta(minutes=interval_minutes)
|
interval = pd.Timedelta(minutes=interval_minutes)
|
||||||
|
|
||||||
def floor_to_interval(value: pd.Timestamp) -> pd.Timestamp:
|
window = _slot_window(interval_minutes, lookback_start, pv_last, (pv_first, row_start[0]))
|
||||||
return value.floor(f"{interval_minutes}min")
|
if window is None:
|
||||||
|
|
||||||
start = max(
|
|
||||||
floor_to_interval(pd.Timestamp(lookback_start.in_timezone("UTC").isoformat())),
|
|
||||||
pd.Timestamp(pv_first.in_timezone("UTC").isoformat()).ceil(f"{interval_minutes}min"),
|
|
||||||
row_start[0].tz_convert("UTC").ceil(f"{interval_minutes}min"),
|
|
||||||
)
|
|
||||||
end = floor_to_interval(pd.Timestamp(pv_last.in_timezone("UTC").isoformat()))
|
|
||||||
if start >= end:
|
|
||||||
return [], None
|
return [], None
|
||||||
|
start = window.start
|
||||||
|
|
||||||
measured = np.asarray(
|
measured = np.asarray(
|
||||||
await self._pv_production_total_kwh(
|
await self._pv_production_total_kwh(
|
||||||
start_datetime=to_datetime(start.to_pydatetime()),
|
start_datetime=window.start_datetime,
|
||||||
end_datetime=to_datetime(end.to_pydatetime()),
|
end_datetime=window.end_datetime,
|
||||||
interval=to_duration(f"{interval_minutes} minutes"),
|
interval=to_duration(f"{interval_minutes} minutes"),
|
||||||
),
|
),
|
||||||
dtype=float,
|
dtype=float,
|
||||||
@@ -1699,6 +1879,7 @@ class PVForecastAkkudoktorLocal(PVForecastProvider[PVForecastDataRecordT]):
|
|||||||
plane_ac: np.ndarray,
|
plane_ac: np.ndarray,
|
||||||
plane_poa: np.ndarray,
|
plane_poa: np.ndarray,
|
||||||
plane_tilt: np.ndarray,
|
plane_tilt: np.ndarray,
|
||||||
|
pv_window: Optional[PVMeterWindow],
|
||||||
) -> pd.DataFrame:
|
) -> pd.DataFrame:
|
||||||
"""Reduce the forecast by the (measurement-corrected) snow coverage."""
|
"""Reduce the forecast by the (measurement-corrected) snow coverage."""
|
||||||
settings = self._settings
|
settings = self._settings
|
||||||
@@ -1708,7 +1889,7 @@ class PVForecastAkkudoktorLocal(PVForecastProvider[PVForecastDataRecordT]):
|
|||||||
scale = np.where(raw_ac > 0.0, calibrated_ac / raw_ac, 1.0)
|
scale = np.where(raw_ac > 0.0, calibrated_ac / raw_ac, 1.0)
|
||||||
clear_ac = plane_ac * scale[np.newaxis, :]
|
clear_ac = plane_ac * scale[np.newaxis, :]
|
||||||
|
|
||||||
observations, _ = await self._snow_observations(frame)
|
observations, _ = await self._snow_observations(frame, pv_window)
|
||||||
coverage, corrections = self._simulate_snow_coverage(
|
coverage, corrections = self._simulate_snow_coverage(
|
||||||
snowfall_cm=weather["snowfall_cm"].to_numpy(dtype=float),
|
snowfall_cm=weather["snowfall_cm"].to_numpy(dtype=float),
|
||||||
snow_depth_cm=weather["snow_depth_cm"].to_numpy(dtype=float),
|
snow_depth_cm=weather["snow_depth_cm"].to_numpy(dtype=float),
|
||||||
@@ -1740,7 +1921,7 @@ class PVForecastAkkudoktorLocal(PVForecastProvider[PVForecastDataRecordT]):
|
|||||||
frame["snow_coverage"] = plant_coverage
|
frame["snow_coverage"] = plant_coverage
|
||||||
|
|
||||||
if plant_coverage.max() > 0.0 or corrections:
|
if plant_coverage.max() > 0.0 or corrections:
|
||||||
now = pd.Timestamp(self.ems_start_datetime.in_timezone("UTC").isoformat())
|
now = _utc_timestamp(self.ems_start_datetime)
|
||||||
position = int(pd.DatetimeIndex(frame.index).searchsorted(now))
|
position = int(pd.DatetimeIndex(frame.index).searchsorted(now))
|
||||||
current = float(plant_coverage[min(position, len(plant_coverage) - 1)])
|
current = float(plant_coverage[min(position, len(plant_coverage) - 1)])
|
||||||
logger.info(
|
logger.info(
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
"""Tests for the native (pvlib) PV forecast provider."""
|
"""Tests for the native (pvlib) PV forecast provider."""
|
||||||
|
|
||||||
|
from typing import Any, Optional
|
||||||
from unittest.mock import AsyncMock, Mock, patch
|
from unittest.mock import AsyncMock, Mock, patch
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
@@ -15,7 +16,11 @@ from akkudoktoreos.prediction.pvforecastakkudoktor import PVForecastAkkudoktor
|
|||||||
from akkudoktoreos.prediction.pvforecastakkudoktorlocal import (
|
from akkudoktoreos.prediction.pvforecastakkudoktorlocal import (
|
||||||
PVForecastAkkudoktorLocal,
|
PVForecastAkkudoktorLocal,
|
||||||
PVForecastAkkudoktorLocalCommonSettings,
|
PVForecastAkkudoktorLocalCommonSettings,
|
||||||
|
SlotWindow,
|
||||||
|
_slot_window,
|
||||||
|
_utc_timestamp,
|
||||||
)
|
)
|
||||||
|
from akkudoktoreos.utils.datetimeutil import DateTime, compare_datetimes, to_datetime
|
||||||
|
|
||||||
LATITUDE = 52.52
|
LATITUDE = 52.52
|
||||||
LONGITUDE = 13.405
|
LONGITUDE = 13.405
|
||||||
@@ -65,6 +70,14 @@ def synthetic_openmeteo(resolution_minutes: int = 15, models: list[str] | None =
|
|||||||
return data
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
async def _fit(
|
||||||
|
instance: PVForecastAkkudoktorLocal, frame: pd.DataFrame
|
||||||
|
) -> Optional[tuple[float, np.ndarray]]:
|
||||||
|
"""Fit the calibration as a forecast run does: read the PV meter window, then fit."""
|
||||||
|
return await instance._fit_calibration(frame, await instance._pv_measurement_window())
|
||||||
|
|
||||||
|
|
||||||
@pytest_asyncio.fixture
|
@pytest_asyncio.fixture
|
||||||
async def pvforecast_instance(config_eos):
|
async def pvforecast_instance(config_eos):
|
||||||
config_eos.merge_settings_from_dict(
|
config_eos.merge_settings_from_dict(
|
||||||
@@ -286,7 +299,7 @@ async def _feed_native_quarter_hour_measurements(
|
|||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_calibration_is_off_by_default(pvforecast_instance):
|
async def test_calibration_is_off_by_default(pvforecast_instance):
|
||||||
frame = await pvforecast_instance._forecast_frame(synthetic_openmeteo(), calibrate=False)
|
frame = await pvforecast_instance._forecast_frame(synthetic_openmeteo(), calibrate=False)
|
||||||
assert await pvforecast_instance._fit_calibration(frame) is None
|
assert await _fit(pvforecast_instance, frame) is None
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
@@ -295,7 +308,7 @@ async def test_calibration_skips_without_measurement_keys(pvforecast_instance):
|
|||||||
calibration_enabled=True
|
calibration_enabled=True
|
||||||
)
|
)
|
||||||
frame = await pvforecast_instance._forecast_frame(synthetic_openmeteo(), calibrate=False)
|
frame = await pvforecast_instance._forecast_frame(synthetic_openmeteo(), calibrate=False)
|
||||||
assert await pvforecast_instance._fit_calibration(frame) is None
|
assert await _fit(pvforecast_instance, frame) is None
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
@@ -310,7 +323,7 @@ async def test_calibration_recovers_a_systematic_bias(pvforecast_instance):
|
|||||||
frame = await pvforecast_instance._forecast_frame(synthetic_openmeteo(), calibrate=False)
|
frame = await pvforecast_instance._forecast_frame(synthetic_openmeteo(), calibrate=False)
|
||||||
await _feed_measurements(pvforecast_instance, frame, bias=0.8, key="pv_bias_emr")
|
await _feed_measurements(pvforecast_instance, frame, bias=0.8, key="pv_bias_emr")
|
||||||
|
|
||||||
calibration = await pvforecast_instance._fit_calibration(frame)
|
calibration = await _fit(pvforecast_instance, frame)
|
||||||
assert calibration is not None
|
assert calibration is not None
|
||||||
global_factor, factors = calibration
|
global_factor, factors = calibration
|
||||||
assert global_factor == pytest.approx(0.8, abs=0.03)
|
assert global_factor == pytest.approx(0.8, abs=0.03)
|
||||||
@@ -342,7 +355,7 @@ async def test_calibration_excludes_recent_demand_limited_outage(pvforecast_inst
|
|||||||
)
|
)
|
||||||
|
|
||||||
with caplog.at_level("INFO"):
|
with caplog.at_level("INFO"):
|
||||||
calibration = await pvforecast_instance._fit_calibration(frame)
|
calibration = await _fit(pvforecast_instance, frame)
|
||||||
|
|
||||||
assert calibration is not None
|
assert calibration is not None
|
||||||
global_factor, factors = calibration
|
global_factor, factors = calibration
|
||||||
@@ -383,7 +396,7 @@ async def test_calibration_uses_real_quarter_hour_measurements(pvforecast_instan
|
|||||||
== 15
|
== 15
|
||||||
)
|
)
|
||||||
with caplog.at_level("INFO"):
|
with caplog.at_level("INFO"):
|
||||||
calibration = await pvforecast_instance._fit_calibration(frame)
|
calibration = await _fit(pvforecast_instance, frame)
|
||||||
|
|
||||||
assert calibration is not None
|
assert calibration is not None
|
||||||
global_factor, _ = calibration
|
global_factor, _ = calibration
|
||||||
@@ -405,7 +418,7 @@ async def test_calibration_factor_is_clamped(pvforecast_instance):
|
|||||||
frame = await pvforecast_instance._forecast_frame(synthetic_openmeteo(), calibrate=False)
|
frame = await pvforecast_instance._forecast_frame(synthetic_openmeteo(), calibrate=False)
|
||||||
await _feed_measurements(pvforecast_instance, frame, bias=0.2, key="pv_clamp_emr")
|
await _feed_measurements(pvforecast_instance, frame, bias=0.2, key="pv_clamp_emr")
|
||||||
|
|
||||||
calibration = await pvforecast_instance._fit_calibration(frame)
|
calibration = await _fit(pvforecast_instance, frame)
|
||||||
assert calibration is not None
|
assert calibration is not None
|
||||||
global_factor, _ = calibration
|
global_factor, _ = calibration
|
||||||
assert global_factor == pytest.approx(0.9)
|
assert global_factor == pytest.approx(0.9)
|
||||||
@@ -724,3 +737,325 @@ def test_file_migration_rejects_invalid_local_settings(config_eos, invalid):
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("interval_minutes", "lookback_start", "last", "earliest", "expected"),
|
||||||
|
[
|
||||||
|
pytest.param(
|
||||||
|
15,
|
||||||
|
"2025-06-01T00:00:00Z",
|
||||||
|
"2025-06-02T00:07:00Z",
|
||||||
|
["2025-06-01T00:04:50Z"],
|
||||||
|
("2025-06-01T00:15:00Z", "2025-06-02T00:00:00Z"),
|
||||||
|
id="unaligned-earliest-rounds-up-to-first-covered-slot",
|
||||||
|
),
|
||||||
|
pytest.param(
|
||||||
|
15,
|
||||||
|
"2025-06-01T00:00:00Z",
|
||||||
|
"2025-06-02T00:00:00Z",
|
||||||
|
["2025-06-01T00:15:00Z"],
|
||||||
|
("2025-06-01T00:15:00Z", "2025-06-02T00:00:00Z"),
|
||||||
|
id="on-grid-earliest-is-kept",
|
||||||
|
),
|
||||||
|
pytest.param(
|
||||||
|
15,
|
||||||
|
"2025-06-01T00:07:00Z",
|
||||||
|
"2025-06-02T00:00:00Z",
|
||||||
|
["2025-05-01T00:04:50Z", pd.Timestamp("2025-05-31T23:45:00Z")],
|
||||||
|
("2025-06-01T00:15:00Z", "2025-06-02T00:00:00Z"),
|
||||||
|
id="lookback-limited-rounds-up-into-the-lookback",
|
||||||
|
),
|
||||||
|
pytest.param(
|
||||||
|
60,
|
||||||
|
"2025-06-01T06:00:00+05:45",
|
||||||
|
"2025-06-02T06:00:00+05:45",
|
||||||
|
[pd.Timestamp("2025-05-31T23:45:00")],
|
||||||
|
("2025-06-01T01:00:00Z", "2025-06-02T00:00:00Z"),
|
||||||
|
id="quarter-hour-offset-zone-on-utc-grid-naive-model-stamp-is-utc",
|
||||||
|
),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_slot_window_bounds_share_the_utc_slot_grid(
|
||||||
|
interval_minutes: int,
|
||||||
|
lookback_start: str,
|
||||||
|
last: str,
|
||||||
|
earliest: list[str | pd.Timestamp],
|
||||||
|
expected: tuple[str, str],
|
||||||
|
) -> None:
|
||||||
|
window = _slot_window(
|
||||||
|
interval_minutes,
|
||||||
|
to_datetime(lookback_start),
|
||||||
|
to_datetime(last),
|
||||||
|
[value if isinstance(value, pd.Timestamp) else to_datetime(value) for value in earliest],
|
||||||
|
)
|
||||||
|
|
||||||
|
assert window == SlotWindow(start=pd.Timestamp(expected[0]), end=pd.Timestamp(expected[1]))
|
||||||
|
assert window.start_datetime.timezone_name == "UTC"
|
||||||
|
assert compare_datetimes(window.start_datetime, to_datetime(expected[0])).equal
|
||||||
|
|
||||||
|
|
||||||
|
def test_slot_window_without_a_whole_slot_is_none() -> None:
|
||||||
|
window = _slot_window(
|
||||||
|
60,
|
||||||
|
to_datetime("2025-06-01T00:00:00Z"),
|
||||||
|
to_datetime("2025-06-01T01:30:00Z"),
|
||||||
|
[to_datetime("2025-06-01T00:10:00Z")],
|
||||||
|
)
|
||||||
|
|
||||||
|
assert window is None
|
||||||
|
|
||||||
|
|
||||||
|
def _unaligned_meter_series(
|
||||||
|
frame: pd.DataFrame,
|
||||||
|
bias: float,
|
||||||
|
first: DateTime,
|
||||||
|
until: DateTime,
|
||||||
|
cadence_minutes: int,
|
||||||
|
timezone: str = "UTC",
|
||||||
|
interval_start_labels: bool = True,
|
||||||
|
) -> pd.Series:
|
||||||
|
"""Cumulative readings of a real-world-like meter: jittered cadence, unaligned stamps.
|
||||||
|
|
||||||
|
Home Assistant style meters report whenever they change, so neither the first
|
||||||
|
reading nor any later reading falls on a slot boundary. The meter measures
|
||||||
|
``bias`` times the modelled power; the stamps carry ``timezone``.
|
||||||
|
"""
|
||||||
|
row_start = pd.DatetimeIndex(frame.index)
|
||||||
|
row_length = row_start[1] - row_start[0]
|
||||||
|
if not interval_start_labels:
|
||||||
|
row_start = row_start - row_length
|
||||||
|
epoch = pd.Timestamp(0, tz="UTC")
|
||||||
|
energy_kwh = frame["ac_power"].to_numpy(dtype=float) * row_length.total_seconds() / 3600.0
|
||||||
|
# Cumulative energy at every row boundary, interpolated to the meter stamps.
|
||||||
|
boundaries = pd.DatetimeIndex([*row_start, row_start[-1] + row_length]) - epoch
|
||||||
|
cumulative = np.concatenate([[0.0], np.cumsum(energy_kwh * bias / 1000.0)])
|
||||||
|
jitter = [0, 21, 47, 13, 34]
|
||||||
|
stamps = []
|
||||||
|
stamp = _utc_timestamp(first)
|
||||||
|
end = _utc_timestamp(until)
|
||||||
|
while stamp < end:
|
||||||
|
stamps.append(stamp)
|
||||||
|
stamp += pd.Timedelta(minutes=cadence_minutes, seconds=jitter[len(stamps) % len(jitter)])
|
||||||
|
index = pd.DatetimeIndex(stamps)
|
||||||
|
values = np.interp(
|
||||||
|
(index - epoch).total_seconds(), boundaries.total_seconds(), cumulative
|
||||||
|
).round(3)
|
||||||
|
return pd.Series(values, index=index.tz_convert(timezone))
|
||||||
|
|
||||||
|
|
||||||
|
async def _feed_meters(instance: PVForecastAkkudoktorLocal, meters: dict[str, pd.Series]) -> None:
|
||||||
|
"""Configure ``meters`` as the PV production meters and store their readings."""
|
||||||
|
instance.config.measurement.pv_production_emr_keys = list(meters)
|
||||||
|
measurement = get_measurement()
|
||||||
|
for key, series in meters.items():
|
||||||
|
await measurement.key_from_series(key, series)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def recorded_windows(monkeypatch) -> list[tuple[DateTime, DateTime]]:
|
||||||
|
"""Record the (start, end) of every PV production energy query."""
|
||||||
|
windows: list[tuple[DateTime, DateTime]] = []
|
||||||
|
production_total_kwh = PVForecastAkkudoktorLocal._pv_production_total_kwh
|
||||||
|
|
||||||
|
async def recording_production_total_kwh(self, start_datetime, end_datetime, interval):
|
||||||
|
windows.append((start_datetime, end_datetime))
|
||||||
|
return await production_total_kwh(self, start_datetime, end_datetime, interval)
|
||||||
|
|
||||||
|
monkeypatch.setattr(
|
||||||
|
PVForecastAkkudoktorLocal, "_pv_production_total_kwh", recording_production_total_kwh
|
||||||
|
)
|
||||||
|
return windows
|
||||||
|
|
||||||
|
|
||||||
|
def _calibration_settings(**overrides: Any) -> PVForecastAkkudoktorLocalCommonSettings:
|
||||||
|
"""Calibration over 30 days with 45-degree azimuth bins.
|
||||||
|
|
||||||
|
The bins expose a slot shift between measured and modelled energy: on a clear-sky
|
||||||
|
day a shift lowers the morning bins and raises the evening ones (or the reverse),
|
||||||
|
while the global factor barely moves.
|
||||||
|
"""
|
||||||
|
settings: dict[str, Any] = {
|
||||||
|
"calibration_enabled": True,
|
||||||
|
"calibration_days": 30,
|
||||||
|
"calibration_reference_days": 30,
|
||||||
|
"calibration_azimuth_bin_degrees": 45,
|
||||||
|
**overrides,
|
||||||
|
}
|
||||||
|
return PVForecastAkkudoktorLocalCommonSettings(**settings)
|
||||||
|
|
||||||
|
|
||||||
|
def _assert_fitted_bias(
|
||||||
|
calibration: Optional[tuple[float, np.ndarray]], bias: float, cadence_minutes: int = 5
|
||||||
|
) -> None:
|
||||||
|
"""The global factor and every azimuth-bin factor recover the meter bias.
|
||||||
|
|
||||||
|
An hourly meter is interpolated linearly across the curved dawn and dusk
|
||||||
|
production, which moves those bins by a few percent in the same direction;
|
||||||
|
a slot shift would move east and west bins in opposite directions.
|
||||||
|
"""
|
||||||
|
assert calibration is not None
|
||||||
|
global_factor, factors = calibration
|
||||||
|
assert global_factor == pytest.approx(bias, abs=0.01)
|
||||||
|
np.testing.assert_allclose(factors, bias, atol=0.02 if cadence_minutes <= 15 else 0.05)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("timezone", "first", "cadence_minutes", "interval_minutes", "expected_start"),
|
||||||
|
[
|
||||||
|
pytest.param(
|
||||||
|
"UTC", "2025-06-09T00:04:50Z", 5, 15, "2025-06-09T00:15:00Z", id="meter-start-15min"
|
||||||
|
),
|
||||||
|
pytest.param(
|
||||||
|
"Asia/Kathmandu",
|
||||||
|
"2025-06-09T00:04:50Z",
|
||||||
|
5,
|
||||||
|
15,
|
||||||
|
"2025-06-09T00:15:00Z",
|
||||||
|
id="meter-start-15min-offset-zone",
|
||||||
|
),
|
||||||
|
pytest.param(
|
||||||
|
"Asia/Kathmandu",
|
||||||
|
"2025-06-09T00:04:50Z",
|
||||||
|
60,
|
||||||
|
60,
|
||||||
|
"2025-06-09T01:00:00Z",
|
||||||
|
id="meter-start-hourly-offset-zone",
|
||||||
|
),
|
||||||
|
pytest.param(
|
||||||
|
"UTC", "2025-05-31T20:04:50Z", 5, 15, "2025-05-31T23:45:00Z", id="model-start-15min"
|
||||||
|
),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
async def test_calibration_with_short_unaligned_meter_history(
|
||||||
|
pvforecast_instance,
|
||||||
|
recorded_windows,
|
||||||
|
timezone: str,
|
||||||
|
first: str,
|
||||||
|
cadence_minutes: int,
|
||||||
|
interval_minutes: int,
|
||||||
|
expected_start: str,
|
||||||
|
):
|
||||||
|
"""A PV meter younger than the lookback window must still be fitted.
|
||||||
|
|
||||||
|
Regression: the window start was taken from the first PV reading (e.g. 00:04:50)
|
||||||
|
without snapping it to the slot grid, so the model grid (00:19:50, 00:34:50, ...)
|
||||||
|
never hit a resampled model row and every interval was discarded as NaN. The
|
||||||
|
window must start at the first slot the readings fully cover and hold whole
|
||||||
|
slots on the UTC grid, also in zones with a quarter-hour offset, and measured
|
||||||
|
and modelled energy must line up slot by slot.
|
||||||
|
"""
|
||||||
|
pvforecast_instance.config.merge_settings_from_dict(
|
||||||
|
{"general": {"timezone_override": timezone}}
|
||||||
|
)
|
||||||
|
assert pvforecast_instance.config.general.timezone == timezone
|
||||||
|
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(first), START, cadence_minutes, timezone=timezone
|
||||||
|
)
|
||||||
|
await _feed_meters(pvforecast_instance, {f"pv_unaligned_emr_{cadence_minutes}": meter})
|
||||||
|
|
||||||
|
calibration = await _fit(pvforecast_instance, frame)
|
||||||
|
|
||||||
|
_assert_fitted_bias(calibration, 0.8, cadence_minutes)
|
||||||
|
start, end = recorded_windows[0]
|
||||||
|
assert compare_datetimes(start, to_datetime(expected_start)).equal
|
||||||
|
slot_seconds = interval_minutes * 60
|
||||||
|
assert start.timestamp() % slot_seconds == 0
|
||||||
|
assert end.timestamp() % slot_seconds == 0
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_calibration_bins_interval_end_labels_by_interval_start(pvforecast_instance):
|
||||||
|
"""With ``shift_to_interval_start=False`` the rows keep Open-Meteo's end stamps.
|
||||||
|
|
||||||
|
Each row still covers the interval before its label, so the fit must bin it into
|
||||||
|
the meter slot of that interval, not into the next one.
|
||||||
|
"""
|
||||||
|
pvforecast_instance.config.pvforecast.akkudoktor = _calibration_settings(
|
||||||
|
shift_to_interval_start=False
|
||||||
|
)
|
||||||
|
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, interval_start_labels=False
|
||||||
|
)
|
||||||
|
await _feed_meters(pvforecast_instance, {"pv_end_labels_emr": meter})
|
||||||
|
|
||||||
|
calibration = await _fit(pvforecast_instance, frame)
|
||||||
|
|
||||||
|
_assert_fitted_bias(calibration, 0.8)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_calibration_window_is_common_to_all_pv_meters(
|
||||||
|
pvforecast_instance, recorded_windows
|
||||||
|
):
|
||||||
|
"""Every PV meter must cover the window; one meter alone does not count.
|
||||||
|
|
||||||
|
Meter A runs the whole period, meter B starts later and stops earlier. The fit
|
||||||
|
may only use the period both report, which is also where their sum is the plant.
|
||||||
|
"""
|
||||||
|
pvforecast_instance.config.pvforecast.akkudoktor = _calibration_settings()
|
||||||
|
frame = await pvforecast_instance._forecast_frame(synthetic_openmeteo(), calibrate=False)
|
||||||
|
meter_a = _unaligned_meter_series(frame, 0.4, to_datetime("2025-06-09T00:04:50Z"), START, 5)
|
||||||
|
meter_b = _unaligned_meter_series(
|
||||||
|
frame, 0.4, to_datetime("2025-06-11T03:02:10Z"), to_datetime("2025-06-13T20:00:00Z"), 5
|
||||||
|
)
|
||||||
|
await _feed_meters(pvforecast_instance, {"pv_common_a_emr": meter_a, "pv_common_b_emr": meter_b})
|
||||||
|
|
||||||
|
calibration = await _fit(pvforecast_instance, frame)
|
||||||
|
|
||||||
|
_assert_fitted_bias(calibration, 0.8)
|
||||||
|
start, end = recorded_windows[0]
|
||||||
|
assert compare_datetimes(start, to_datetime("2025-06-11T03:15:00Z")).equal
|
||||||
|
assert compare_datetimes(end, to_datetime("2025-06-13T19:45:00Z")).equal
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_forecast_reads_the_pv_meter_window_once(pvforecast_instance, monkeypatch):
|
||||||
|
"""Calibration and snow feedback share one scan of the PV meter readings."""
|
||||||
|
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_read_once_emr": meter})
|
||||||
|
reads = 0
|
||||||
|
measurement_window = PVForecastAkkudoktorLocal._pv_measurement_window
|
||||||
|
|
||||||
|
async def counting_measurement_window(self):
|
||||||
|
nonlocal reads
|
||||||
|
reads += 1
|
||||||
|
return await measurement_window(self)
|
||||||
|
|
||||||
|
monkeypatch.setattr(
|
||||||
|
PVForecastAkkudoktorLocal, "_pv_measurement_window", counting_measurement_window
|
||||||
|
)
|
||||||
|
|
||||||
|
await pvforecast_instance._forecast_frame(synthetic_openmeteo())
|
||||||
|
|
||||||
|
assert reads == 1
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_snow_feedback_window_is_on_the_slot_grid(pvforecast_instance, recorded_windows):
|
||||||
|
"""Snow feedback compares the same whole UTC slots as the calibration fit."""
|
||||||
|
pvforecast_instance.config.pvforecast.akkudoktor = _calibration_settings(
|
||||||
|
calibration_enabled=False, snow_lookback_days=7
|
||||||
|
)
|
||||||
|
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_snow_window_emr": meter})
|
||||||
|
pv_window = await pvforecast_instance._pv_measurement_window()
|
||||||
|
assert pv_window is not None
|
||||||
|
|
||||||
|
observations, interval_hours = await pvforecast_instance._snow_observations(frame, pv_window)
|
||||||
|
|
||||||
|
assert interval_hours == 0.25
|
||||||
|
assert observations
|
||||||
|
start, end = recorded_windows[0]
|
||||||
|
assert compare_datetimes(start, to_datetime("2025-06-09T00:15:00Z")).equal
|
||||||
|
# The end is the last slot boundary before the last reading.
|
||||||
|
assert end.timestamp() % 900 == 0
|
||||||
|
assert compare_datetimes(end, pv_window.last).le
|
||||||
|
assert compare_datetimes(end.add(minutes=15), pv_window.last).gt
|
||||||
|
|||||||
@@ -418,7 +418,9 @@ async def test_calibration_skips_intervals_with_possible_snow(snow_instance, cap
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
raw = await snow_instance._forecast_frame(fixture["openmeteo"], calibrate=False)
|
raw = await snow_instance._forecast_frame(fixture["openmeteo"], calibrate=False)
|
||||||
calibration = await snow_instance._fit_calibration(raw)
|
calibration = await snow_instance._fit_calibration(
|
||||||
|
raw, await snow_instance._pv_measurement_window()
|
||||||
|
)
|
||||||
assert calibration is not None
|
assert calibration is not None
|
||||||
factors[snow_enabled] = calibration[0]
|
factors[snow_enabled] = calibration[0]
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user