Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix single element access for moving window #672

Merged
merged 3 commits into from
Sep 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion RELEASE_NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,12 @@
- In `OrderedRingBuffer` and `MovingWindow`:
- Support for integer indices is added.
- Add `count_covered` method to count the number of elements covered by the used time range.

- Add `at` method to `MovingWindow` to access a single element and use it in `__getitem__` magic to fully support single element access.



## Bug Fixes

- Fix rendering of diagrams in the documentation.
- The `__getitem__` magic of the `MovingWindow` is fixed to support the same functionality that the `window` method provides.
- Fixes incorrect implementation of single element access in `__getitem__` magic of `MovingWindow`.
56 changes: 49 additions & 7 deletions src/frequenz/sdk/timeseries/_moving_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,48 @@ def capacity(self) -> int:
"""
return self._buffer.maxlen

# pylint before 3.0 only accepts names with 3 or more chars
def at(self, key: int | datetime) -> float: # pylint: disable=invalid-name
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I actually hate this check failing because names are short. Fortunately is going away in pylint 3.

image

https://pylint.readthedocs.io/en/latest/user_guide/messages/convention/invalid-name.html#predefined-naming-patterns

We could disable it now by customizing the name regexes, but I'm not sure it is worth it.

llucax marked this conversation as resolved.
Show resolved Hide resolved
"""
Return the sample at the given index or timestamp.

In contrast to the [`window`][frequenz.sdk.timeseries.MovingWindow.window] method,
which expects a slice as argument, this method expects a single index as argument
and returns a single value.

Args:
key: The index or timestamp of the sample to return.

Returns:
The sample at the given index or timestamp.

Raises:
IndexError: If the buffer is empty or the index is out of bounds.
"""
if self._buffer.count_valid() == 0:
raise IndexError("The buffer is empty.")

if isinstance(key, datetime):
assert self._buffer.oldest_timestamp is not None
assert self._buffer.newest_timestamp is not None
if (
key < self._buffer.oldest_timestamp
or key > self._buffer.newest_timestamp
):
raise IndexError(
f"Timestamp {key} is out of range [{self._buffer.oldest_timestamp}, "
f"{self._buffer.newest_timestamp}]"
)
return self._buffer[self._buffer.to_internal_index(key)]

if isinstance(key, int):
_logger.debug("Returning value at index %s ", key)
timestamp = self._buffer.get_timestamp(key)
assert timestamp is not None
return self._buffer[self._buffer.to_internal_index(timestamp)]

raise TypeError("Key has to be either a timestamp or an integer.")

def window(
self,
start: datetime | int | None,
Expand All @@ -251,6 +293,10 @@ def window(
"""
Return an array containing the samples in the given time interval.

In contrast to the [`at`][frequenz.sdk.timeseries.MovingWindow.at] method,
which expects a single index as argument, this method expects a slice as argument
and returns an array.

Args:
start: The start of the time interval. If `None`, the start of the
window is used.
Expand Down Expand Up @@ -372,15 +418,11 @@ def __getitem__(self, key: SupportsIndex | datetime | slice) -> float | ArrayLik
raise ValueError("Slicing with a step other than 1 is not supported.")
return self.window(key.start, key.stop)

if self._buffer.count_valid() == 0:
raise IndexError("The buffer is empty.")

if isinstance(key, datetime):
_logger.debug("Returning value at time %s ", key)
return self._buffer[self._buffer.to_internal_index(key)]
return self.at(key)

if isinstance(key, SupportsIndex):
_logger.debug("Returning value at index %s ", key)
return self._buffer[key]
return self.at(key.__index__())

raise TypeError(
"Key has to be either a timestamp or an integer "
Expand Down
30 changes: 24 additions & 6 deletions tests/timeseries/test_moving_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,18 +80,36 @@ def dt(i: int) -> datetime: # pylint: disable=invalid-name

async def test_access_window_by_index() -> None:
"""Test indexing a window by integer index."""
window, sender = init_moving_window(timedelta(seconds=1))
window, sender = init_moving_window(timedelta(seconds=2))
async with window:
await push_logical_meter_data(sender, [1])
assert np.array_equal(window[0], 1.0)
await push_logical_meter_data(sender, [1, 2, 3])
assert np.array_equal(window[0], 2.0)
assert np.array_equal(window[1], 3.0)
assert np.array_equal(window[-1], 3.0)
assert np.array_equal(window[-2], 2.0)
with pytest.raises(IndexError):
_ = window[3]
with pytest.raises(IndexError):
_ = window[-3]


async def test_access_window_by_timestamp() -> None:
"""Test indexing a window by timestamp."""
window, sender = init_moving_window(timedelta(seconds=1))
window, sender = init_moving_window(timedelta(seconds=2))
async with window:
await push_logical_meter_data(sender, [1])
assert np.array_equal(window[UNIX_EPOCH], 1.0)
await push_logical_meter_data(sender, [0, 1, 2])
assert np.array_equal(window[dt(1)], 1.0)
assert np.array_equal(window.at(dt(1)), 1.0)
assert np.array_equal(window[dt(2)], 2.0)
assert np.array_equal(window.at(dt(2)), 2.0)
with pytest.raises(IndexError):
_ = window[dt(0)]
with pytest.raises(IndexError):
_ = window.at(dt(0))
with pytest.raises(IndexError):
_ = window[dt(3)]
with pytest.raises(IndexError):
_ = window.at(dt(3))


async def test_access_window_by_int_slice() -> None:
Expand Down