fix(devices): use the nearest valid measurement of a key

DataSequence.key_to_value took the record nearest in time and returned
the key from it, even when that record did not hold the key. Feeders
write measurement keys one at a time, seconds apart, and every write
creates its own record. A battery temperature written at 10:00:00 and a
SoC written at 10:00:01 then gave no temperature for a lookup at 10:01,
so battery temperature, SoC factor, charge/discharge power and the
inverter temperature fell back to the reference operating point (25 degC,
SoC 0.5, 45 degC). Profiles with a temperature or SoC dependent charge
limit were evaluated there, e.g. with too high a charge power for a cold
battery.

key_to_value now returns the nearest value of the key itself: records
where the key is None or NaN are skipped, as dropna does for the other
key accessors. The search window and its bounds are unchanged; without
a window only an exact match counts.

Additional changes
Developer docs describe key_to_value as the nearest valid value of a key

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Assisted-by: Claude Code (claude-opus-5-5)
This commit is contained in:
Christin
2026-11-28 08:08:37 +01:00
committed by Bobby Noelte
co-authored by Claude Opus 5.5
parent 12527597b1
commit b2c5820925
4 changed files with 94 additions and 6 deletions
+1 -1
View File
@@ -137,7 +137,7 @@ These methods do not modify sequence state and require no locking:
| `key_to_lists(key, ...)` | Extract parallel date and value lists. | | `key_to_lists(key, ...)` | Extract parallel date and value lists. |
| `key_to_series(key, ...)` | Extract a `pd.Series` indexed by datetime. | | `key_to_series(key, ...)` | Extract a `pd.Series` indexed by datetime. |
| `key_to_array(key, ...)` | Extract a resampled `np.ndarray` at a fixed interval. | | `key_to_array(key, ...)` | Extract a resampled `np.ndarray` at a fixed interval. |
| `key_to_value(key, dt)` | Scalar lookup nearest to a datetime. | | `key_to_value(key, dt)` | Nearest valid value of a key to a datetime (records without the key are skipped). |
| `to_dataframe(...)` | Convert all records to a `pd.DataFrame`. | | `to_dataframe(...)` | Convert all records to a `pd.DataFrame`. |
| `delete_by_datetime(...)` | Delete records within a datetime range. | | `delete_by_datetime(...)` | Delete records within a datetime range. |
| `key_delete_by_datetime(key, ...)` | Set a field to `None` across a datetime range. | | `key_delete_by_datetime(key, ...)` | Set a field to `None` across a datetime range. |
+34 -5
View File
@@ -1077,12 +1077,17 @@ class DataSequence(DataABC, DatabaseRecordProtocolMixin[DataRecordT], Generic[Da
) -> Optional[float]: ) -> Optional[float]:
"""Returns the value corresponding to the specified key that is nearest to the given datetime. """Returns the value corresponding to the specified key that is nearest to the given datetime.
Only records with a value for the key count. Records where the key is None
or NaN are skipped, e.g. a record that was written for another key a few
seconds later.
Args: Args:
key (str): The key of the attribute in DataRecord to extract. key (str): The key of the attribute in DataRecord to extract.
target_datetime (datetime): The datetime to search for. target_datetime (datetime): The datetime to search for.
time_window: Optional total width of the symmetric search window centered on time_window: Optional total width of the symmetric search window centered on
``target_datetime``. If provided and no exact match exists, the nearest ``target_datetime``. If provided, the nearest valid value within this
record within this window is returned. window is returned; of two equally near values the later one. If not
provided, only a record at exactly ``target_datetime`` counts.
Returns: Returns:
Optional[float]: The value nearest to the given datetime, or None if no valid records are found. Optional[float]: The value nearest to the given datetime, or None if no valid records are found.
@@ -1093,11 +1098,35 @@ class DataSequence(DataABC, DatabaseRecordProtocolMixin[DataRecordT], Generic[Da
self._validate_key(key) self._validate_key(key)
# Ensure datetime objects are normalized # Ensure datetime objects are normalized
db_target = DatabaseTimestamp.from_datetime(to_datetime(target_datetime)) target = to_datetime(target_datetime)
db_target = DatabaseTimestamp.from_datetime(target)
record = await self.db_get_record(db_target, time_window=time_window) if time_window is None:
record = await self.db_get_record(db_target)
value = getattr(record, key, None)
return None if value is None or pd.isna(value) else value
return getattr(record, key, None) search_start, search_end = self._search_window(db_target, time_window)
if isinstance(search_end, DatabaseTimestamp):
# Like db_get_record(), accept a value at exactly half the window after the target.
search_end = self._db_timestamp_after(search_end)
max_distance = time_window.total_seconds() / 2
nearest_value = None
async for record in self.db_iterate_records(search_start, search_end):
value = getattr(record, key, None)
if record.date_time is None or value is None or pd.isna(value):
continue
distance = compare_datetimes(record.date_time, target).time_diff
if abs(distance) <= max_distance:
# Records come in ascending order: before the target each valid value is
# nearer than the previous one.
nearest_value, max_distance = value, abs(distance)
if distance >= 0:
# The first valid value at or after the target is the nearest on this side.
break
return nearest_value
async def key_to_lists( async def key_to_lists(
self, self,
+43
View File
@@ -956,6 +956,49 @@ class TestDataSequence:
result = await sequence.key_to_value("data_value", datetime(2023, 11, 5, 12), time_window=to_duration("48 hours")) result = await sequence.key_to_value("data_value", datetime(2023, 11, 5, 12), time_window=to_duration("48 hours"))
assert result == 1.0 assert result == 1.0
async def test_key_to_value_skips_nearer_record_without_the_key(self, sequence) -> None:
"""A record written for another key a second later does not hide the value.
Feeders write measurement keys one at a time, seconds apart. Every write
creates its own record, in which all other keys are None.
"""
t0 = to_datetime("2024-01-15T10:00:00+00:00")
await sequence.update_value(t0, "temp", 3.0)
await sequence.update_value(t0.add(seconds=1), "data_value", 0.5)
window = to_duration("1 hour")
assert await sequence.key_to_value("temp", t0.add(minutes=1), time_window=window) == 3.0
assert await sequence.key_to_value("temp", t0.add(seconds=1), time_window=window) == 3.0
assert await sequence.key_to_value("data_value", t0, time_window=window) == 0.5
async def test_key_to_value_skips_nan_and_takes_nearest_valid_side(self, sequence) -> None:
"""NaN counts as missing; the nearest valid value wins on either side."""
t0 = to_datetime("2024-01-15T10:00:00+00:00")
await sequence.update_value(t0, "temp", 3.0)
await sequence.update_value(t0.add(minutes=4), "temp", float("nan"))
await sequence.update_value(t0.add(minutes=6), "temp", 7.0)
window = to_duration("1 hour")
# The NaN at 10:04 is skipped: 10:06 is nearer to 10:04 than 10:00 ...
assert await sequence.key_to_value("temp", t0.add(minutes=4), time_window=window) == 7.0
# ... and 10:00 is nearer to 10:02 than 10:06.
assert await sequence.key_to_value("temp", t0.add(minutes=2), time_window=window) == 3.0
async def test_key_to_value_ignores_values_outside_the_window(self, sequence) -> None:
"""A valid value outside the window stays out, even with other records inside."""
t0 = to_datetime("2024-01-15T10:00:00+00:00")
await sequence.update_value(t0, "temp", 3.0)
await sequence.update_value(t0.add(minutes=50), "data_value", 0.5)
# The 1 hour window spans 10:30 ... 11:30 around 11:00.
result = await sequence.key_to_value(
"temp", t0.add(hours=1), time_window=to_duration("1 hour")
)
assert result is None
# Exact match only without a window.
assert await sequence.key_to_value("temp", t0.add(minutes=50)) is None
assert await sequence.key_to_value("temp", t0) == 3.0
async def test_key_to_dict(self, sequence): async def test_key_to_dict(self, sequence):
record1 = self.create_test_record(datetime(2023, 11, 5), 0.8) record1 = self.create_test_record(datetime(2023, 11, 5), 0.8)
record2 = self.create_test_record(datetime(2023, 11, 6), 0.9) record2 = self.create_test_record(datetime(2023, 11, 6), 0.9)
+16
View File
@@ -1487,6 +1487,22 @@ class TestMeasurementAccess:
assert point.charge_power_w == pytest.approx(2500.0) assert point.charge_power_w == pytest.approx(2500.0)
assert point.discharge_power_w is None assert point.discharge_power_w is None
@pytest.mark.asyncio
async def test_keys_written_seconds_apart_are_all_read(self) -> None:
"""Every key is read, even when a newer record only holds another key."""
from akkudoktoreos.core.coreabc import get_measurement
from akkudoktoreos.utils.datetimeutil import to_datetime
now = to_datetime()
measurement = get_measurement()
await measurement.update_value(
now.subtract(seconds=60), {"battery1-temperature-degc": 3.0}
)
await measurement.update_value(now.subtract(seconds=59), {"battery1-soc-factor": 0.35})
point = await make_settings().measure_operating_point(now)
assert point.temperature_degC == pytest.approx(3.0)
assert point.soc_factor == pytest.approx(0.35)
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_empty_store_yields_reference_point(self): async def test_empty_store_yields_reference_point(self):
point = await make_settings().measure_operating_point() point = await make_settings().measure_operating_point()