From 838bae3a927061b02b241f84764b3afe16e37f1b Mon Sep 17 00:00:00 2001 From: Shenyang Cai Date: Wed, 19 Mar 2025 20:58:02 +0000 Subject: [PATCH 1/7] chore: allow PRECEDING and FOLLOWING to appear on both side of BETWEEN when windowing --- bigframes/core/compile/compiled.py | 32 ++++++++++---- bigframes/core/compile/polars/compiler.py | 54 ++++++++++++++++------- bigframes/core/window_spec.py | 40 +++++++++++++---- tests/unit/core/test_windowspec.py | 27 ++++++++++++ 4 files changed, 122 insertions(+), 31 deletions(-) create mode 100644 tests/unit/core/test_windowspec.py diff --git a/bigframes/core/compile/compiled.py b/bigframes/core/compile/compiled.py index c3d4c10267..2300991cdf 100644 --- a/bigframes/core/compile/compiled.py +++ b/bigframes/core/compile/compiled.py @@ -22,6 +22,7 @@ import bigframes_vendored.ibis.backends.bigquery.backend as ibis_bigquery import bigframes_vendored.ibis.common.deferred as ibis_deferred # type: ignore import bigframes_vendored.ibis.expr.datatypes as ibis_dtypes +from bigframes_vendored.ibis.expr.operations import window as ibis_expr_window import bigframes_vendored.ibis.expr.operations as ibis_ops import bigframes_vendored.ibis.expr.types as ibis_types import pandas @@ -35,7 +36,12 @@ import bigframes.core.guid from bigframes.core.ordering import OrderingExpression import bigframes.core.sql -from bigframes.core.window_spec import RangeWindowBounds, RowsWindowBounds, WindowSpec +from bigframes.core.window_spec import ( + RangeWindowBounds, + RowsWindowBounds, + WindowBoundary, + WindowSpec, +) import bigframes.dtypes import bigframes.operations.aggregations as agg_ops @@ -555,14 +561,16 @@ def _ibis_window_from_spec(self, window_spec: WindowSpec): window = bigframes_vendored.ibis.window(order_by=order_by, group_by=group_by) if bounds is not None: if isinstance(bounds, RangeWindowBounds): - window = window.preceding_following( - bounds.preceding, bounds.following, how="range" - ) + window = window.between( + start=_to_ibis_boundary(bounds.start), + end=_to_ibis_boundary(bounds.end), + ).copy(how="range") if isinstance(bounds, RowsWindowBounds): - if bounds.preceding is not None or bounds.following is not None: - window = window.preceding_following( - bounds.preceding, bounds.following, how="rows" - ) + if bounds.start is not None or bounds.end is not None: + window = window.between( + start=_to_ibis_boundary(bounds.start), + end=_to_ibis_boundary(bounds.end), + ).copy(how="rows") else: raise ValueError(f"unrecognized window bounds {bounds}") return window @@ -681,3 +689,11 @@ def _as_groupable(value: ibis_types.Value): return scalar_op_compiler.to_json_string(value) else: return value + + +def _to_ibis_boundary( + boundary: Optional[WindowBoundary], +) -> Optional[ibis_expr_window.WindowBoundary]: + if boundary is None: + return None + return ibis_expr_window.WindowBoundary(boundary.value, boundary.is_preceding) diff --git a/bigframes/core/compile/polars/compiler.py b/bigframes/core/compile/polars/compiler.py index 6d5b11a5e8..de1311170c 100644 --- a/bigframes/core/compile/polars/compiler.py +++ b/bigframes/core/compile/polars/compiler.py @@ -16,9 +16,10 @@ import dataclasses import functools import itertools -from typing import cast, Sequence, Tuple, TYPE_CHECKING +from typing import cast, Optional, Sequence, Tuple, TYPE_CHECKING, Union import bigframes.core +from bigframes.core import window_spec import bigframes.core.expression as ex import bigframes.core.guid as guid import bigframes.core.nodes as nodes @@ -367,22 +368,11 @@ def compile_window(self, node: nodes.WindowOpNode): if len(window.grouping_keys) == 0: # rolling-only window # https://docs.pola.rs/api/python/stable/reference/dataframe/api/polars.DataFrame.rolling.html finite = ( - window.bounds.preceding is not None - and window.bounds.following is not None - ) - offset_n = ( - None - if window.bounds.preceding is None - else -window.bounds.preceding + window.bounds.start is not None and window.bounds.end is not None ) + offset_n = _get_offset(window.bounds) # collecting height is a massive kludge - period_n = ( - df.collect().height - if not finite - else cast(int, window.bounds.preceding) - + cast(int, window.bounds.following) - + 1 - ) + period_n = _get_period(window.bounds) or df.collect().height results = indexed_df.rolling( index_column=index_col_name, period=f"{period_n}i", @@ -395,3 +385,37 @@ def compile_window(self, node: nodes.WindowOpNode): # polars is columnar, so this is efficient # TODO: why can't just add columns? return pl.concat([df, results], how="horizontal") + + +def _get_offset( + bounds: Union[window_spec.RowsWindowBounds, window_spec.RangeWindowBounds] +) -> Optional[window_spec.OffsetType]: + if bounds.start is None: + return None + if bounds.start.is_preceding: + return -bounds.start.value + return bounds.start.value + + +def _get_period( + bounds: Union[window_spec.RowsWindowBounds, window_spec.RangeWindowBounds] +) -> Optional[int]: + """Returns None if the boundary is infinite.""" + if bounds.start is None or bounds.end is None: + return None + + if bounds.start.is_preceding: + if bounds.end.is_preceding: + result = bounds.start.value - bounds.end.value + 1 + else: + result = bounds.start.value + bounds.end.value + 1 + + else: + if bounds.end.is_preceding: + raise ValueError( + "When boundary start is FOLLOWING, boundary end cannot be PRECEDING" + ) + else: + result = bounds.end.value - bounds.start.value + 1 + + return cast(int, result) diff --git a/bigframes/core/window_spec.py b/bigframes/core/window_spec.py index b4a3d35471..0f05d9bd9e 100644 --- a/bigframes/core/window_spec.py +++ b/bigframes/core/window_spec.py @@ -15,7 +15,7 @@ from dataclasses import dataclass, replace import itertools -from typing import Mapping, Optional, Set, Tuple, Union +from typing import Generic, Mapping, Optional, Set, Tuple, TypeVar, Union import bigframes.core.expression as ex import bigframes.core.identifiers as ids @@ -74,7 +74,10 @@ def rows( Returns: WindowSpec """ - bounds = RowsWindowBounds(preceding=preceding, following=following) + bounds = RowsWindowBounds( + start=WindowBoundary.preceding(preceding), + end=WindowBoundary.following(following), + ) return WindowSpec( grouping_keys=tuple(map(ex.deref, grouping_keys)), bounds=bounds, @@ -97,7 +100,7 @@ def cumulative_rows( Returns: WindowSpec """ - bounds = RowsWindowBounds(following=0) + bounds = RowsWindowBounds(end=WindowBoundary.following(0)) return WindowSpec( grouping_keys=tuple(map(ex.deref, grouping_keys)), bounds=bounds, @@ -119,7 +122,7 @@ def inverse_cumulative_rows( Returns: WindowSpec """ - bounds = RowsWindowBounds(preceding=0) + bounds = RowsWindowBounds(start=WindowBoundary.preceding(0)) return WindowSpec( grouping_keys=tuple(map(ex.deref, grouping_keys)), bounds=bounds, @@ -130,10 +133,31 @@ def inverse_cumulative_rows( ### Struct Classes +T = TypeVar("T") + + +@dataclass(frozen=True) +class WindowBoundary(Generic[T]): + value: T + is_preceding: bool + + @classmethod + def preceding(cls, value: Optional[T]): + if value is None: + return None + return cls(value, True) + + @classmethod + def following(cls, value: Optional[T]): + if value is None: + return None + return cls(value, False) + + @dataclass(frozen=True) class RowsWindowBounds: - preceding: Optional[int] = None - following: Optional[int] = None + start: Optional[WindowBoundary[int]] = None + end: Optional[WindowBoundary[int]] = None # TODO: Expand to datetime offsets @@ -142,8 +166,8 @@ class RowsWindowBounds: @dataclass(frozen=True) class RangeWindowBounds: - preceding: Optional[OffsetType] = None - following: Optional[OffsetType] = None + start: Optional[WindowBoundary[OffsetType]] = None + end: Optional[WindowBoundary[OffsetType]] = None @dataclass(frozen=True) diff --git a/tests/unit/core/test_windowspec.py b/tests/unit/core/test_windowspec.py new file mode 100644 index 0000000000..ddb368d097 --- /dev/null +++ b/tests/unit/core/test_windowspec.py @@ -0,0 +1,27 @@ +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from bigframes.core import window_spec + + +def test_window_boundary_preceding(): + window = window_spec.WindowBoundary.preceding(1) + + assert window == window_spec.WindowBoundary(1, is_preceding=True) + + +def test_window_boundary_following(): + window = window_spec.WindowBoundary.following(1) + + assert window == window_spec.WindowBoundary(1, is_preceding=False) From d36e4ce8df78c42b1b2b4db986500d914239eeb8 Mon Sep 17 00:00:00 2001 From: Shenyang Cai Date: Wed, 19 Mar 2025 21:02:41 +0000 Subject: [PATCH 2/7] fix lint --- bigframes/core/compile/polars/compiler.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/bigframes/core/compile/polars/compiler.py b/bigframes/core/compile/polars/compiler.py index de1311170c..68507c637d 100644 --- a/bigframes/core/compile/polars/compiler.py +++ b/bigframes/core/compile/polars/compiler.py @@ -367,11 +367,7 @@ def compile_window(self, node: nodes.WindowOpNode): indexed_df = df.with_row_index(index_col_name) if len(window.grouping_keys) == 0: # rolling-only window # https://docs.pola.rs/api/python/stable/reference/dataframe/api/polars.DataFrame.rolling.html - finite = ( - window.bounds.start is not None and window.bounds.end is not None - ) offset_n = _get_offset(window.bounds) - # collecting height is a massive kludge period_n = _get_period(window.bounds) or df.collect().height results = indexed_df.rolling( index_column=index_col_name, @@ -404,6 +400,7 @@ def _get_period( if bounds.start is None or bounds.end is None: return None + # collecting height is a massive kludge if bounds.start.is_preceding: if bounds.end.is_preceding: result = bounds.start.value - bounds.end.value + 1 From 38303c6e9c35d2cf22403aab64e10e1c4be3a21a Mon Sep 17 00:00:00 2001 From: Shenyang Cai Date: Mon, 24 Mar 2025 20:00:19 +0000 Subject: [PATCH 3/7] Simplify the code by using the sign of the value for PRECEDING/FOLLOWING --- bigframes/core/block_transforms.py | 6 +- bigframes/core/compile/compiled.py | 49 ++++++++-------- bigframes/core/compile/polars/compiler.py | 28 +-------- bigframes/core/groupby/__init__.py | 8 +-- bigframes/core/window_spec.py | 69 ++++++++++++----------- bigframes/dataframe.py | 6 +- bigframes/series.py | 6 +- tests/unit/core/test_windowspec.py | 18 +++--- 8 files changed, 86 insertions(+), 104 deletions(-) diff --git a/bigframes/core/block_transforms.py b/bigframes/core/block_transforms.py index 0e9525d5af..09ef17dff5 100644 --- a/bigframes/core/block_transforms.py +++ b/bigframes/core/block_transforms.py @@ -213,8 +213,8 @@ def _interpolate_column( if interpolate_method not in ["linear", "nearest", "ffill"]: raise ValueError("interpolate method not supported") window_ordering = (ordering.OrderingExpression(ex.deref(x_values)),) - backwards_window = windows.rows(following=0, ordering=window_ordering) - forwards_window = windows.rows(preceding=0, ordering=window_ordering) + backwards_window = windows.rows(end=0, ordering=window_ordering) + forwards_window = windows.rows(start=0, ordering=window_ordering) # Note, this method may block, notnull = block.apply_unary_op(column, ops.notnull_op) @@ -450,7 +450,7 @@ def rank( ) if method == "dense" else windows.rows( - following=0, ordering=window_ordering, grouping_keys=grouping_cols + end=0, ordering=window_ordering, grouping_keys=grouping_cols ), skip_reproject_unsafe=(col != columns[-1]), ) diff --git a/bigframes/core/compile/compiled.py b/bigframes/core/compile/compiled.py index 2300991cdf..9fd74f6190 100644 --- a/bigframes/core/compile/compiled.py +++ b/bigframes/core/compile/compiled.py @@ -21,6 +21,7 @@ import bigframes_vendored.ibis import bigframes_vendored.ibis.backends.bigquery.backend as ibis_bigquery import bigframes_vendored.ibis.common.deferred as ibis_deferred # type: ignore +from bigframes_vendored.ibis.expr import builders as ibis_expr_builders import bigframes_vendored.ibis.expr.datatypes as ibis_dtypes from bigframes_vendored.ibis.expr.operations import window as ibis_expr_window import bigframes_vendored.ibis.expr.operations as ibis_ops @@ -36,12 +37,7 @@ import bigframes.core.guid from bigframes.core.ordering import OrderingExpression import bigframes.core.sql -from bigframes.core.window_spec import ( - RangeWindowBounds, - RowsWindowBounds, - WindowBoundary, - WindowSpec, -) +from bigframes.core.window_spec import RangeWindowBounds, RowsWindowBounds, WindowSpec import bigframes.dtypes import bigframes.operations.aggregations as agg_ops @@ -557,22 +553,9 @@ def _ibis_window_from_spec(self, window_spec: WindowSpec): # Unbound grouping window. Suitable for aggregations but not for analytic function application. order_by = None - bounds = window_spec.bounds window = bigframes_vendored.ibis.window(order_by=order_by, group_by=group_by) - if bounds is not None: - if isinstance(bounds, RangeWindowBounds): - window = window.between( - start=_to_ibis_boundary(bounds.start), - end=_to_ibis_boundary(bounds.end), - ).copy(how="range") - if isinstance(bounds, RowsWindowBounds): - if bounds.start is not None or bounds.end is not None: - window = window.between( - start=_to_ibis_boundary(bounds.start), - end=_to_ibis_boundary(bounds.end), - ).copy(how="rows") - else: - raise ValueError(f"unrecognized window bounds {bounds}") + if window_spec.bounds is not None: + return _add_boundary(window_spec.bounds, window) return window @@ -692,8 +675,28 @@ def _as_groupable(value: ibis_types.Value): def _to_ibis_boundary( - boundary: Optional[WindowBoundary], + boundary: typing.Union[int, float, None], ) -> Optional[ibis_expr_window.WindowBoundary]: if boundary is None: return None - return ibis_expr_window.WindowBoundary(boundary.value, boundary.is_preceding) + return ibis_expr_window.WindowBoundary(abs(boundary), preceding=boundary <= 0) + + +def _add_boundary( + bounds: typing.Union[RowsWindowBounds, RangeWindowBounds], + ibis_window: ibis_expr_builders.LegacyWindowBuilder, +) -> ibis_expr_builders.LegacyWindowBuilder: + if isinstance(bounds, RangeWindowBounds): + return ibis_window.between( + start=_to_ibis_boundary(bounds.start), + end=_to_ibis_boundary(bounds.end), + ).copy(how="range") + if isinstance(bounds, RowsWindowBounds): + if bounds.start is not None or bounds.end is not None: + return ibis_window.between( + start=_to_ibis_boundary(bounds.start), + end=_to_ibis_boundary(bounds.end), + ).copy(how="rows") + return ibis_window + else: + raise ValueError(f"unrecognized window bounds {bounds}") diff --git a/bigframes/core/compile/polars/compiler.py b/bigframes/core/compile/polars/compiler.py index 68507c637d..7c4c2f3424 100644 --- a/bigframes/core/compile/polars/compiler.py +++ b/bigframes/core/compile/polars/compiler.py @@ -367,7 +367,7 @@ def compile_window(self, node: nodes.WindowOpNode): indexed_df = df.with_row_index(index_col_name) if len(window.grouping_keys) == 0: # rolling-only window # https://docs.pola.rs/api/python/stable/reference/dataframe/api/polars.DataFrame.rolling.html - offset_n = _get_offset(window.bounds) + offset_n = window.bounds.start period_n = _get_period(window.bounds) or df.collect().height results = indexed_df.rolling( index_column=index_col_name, @@ -383,16 +383,6 @@ def compile_window(self, node: nodes.WindowOpNode): return pl.concat([df, results], how="horizontal") -def _get_offset( - bounds: Union[window_spec.RowsWindowBounds, window_spec.RangeWindowBounds] -) -> Optional[window_spec.OffsetType]: - if bounds.start is None: - return None - if bounds.start.is_preceding: - return -bounds.start.value - return bounds.start.value - - def _get_period( bounds: Union[window_spec.RowsWindowBounds, window_spec.RangeWindowBounds] ) -> Optional[int]: @@ -401,18 +391,4 @@ def _get_period( return None # collecting height is a massive kludge - if bounds.start.is_preceding: - if bounds.end.is_preceding: - result = bounds.start.value - bounds.end.value + 1 - else: - result = bounds.start.value + bounds.end.value + 1 - - else: - if bounds.end.is_preceding: - raise ValueError( - "When boundary start is FOLLOWING, boundary end cannot be PRECEDING" - ) - else: - result = bounds.end.value - bounds.start.value + 1 - - return cast(int, result) + return cast(int, bounds.end - bounds.start + 1) diff --git a/bigframes/core/groupby/__init__.py b/bigframes/core/groupby/__init__.py index 126d2f4dd2..3134df0daf 100644 --- a/bigframes/core/groupby/__init__.py +++ b/bigframes/core/groupby/__init__.py @@ -309,8 +309,8 @@ def rolling(self, window: int, min_periods=None) -> windows.Window: # To get n size window, need current row and n-1 preceding rows. window_spec = window_specs.rows( grouping_keys=tuple(self._by_col_ids), - preceding=window - 1, - following=0, + start=-(window - 1), + end=0, min_periods=min_periods or window, ) block = self._block.order_by( @@ -742,8 +742,8 @@ def rolling(self, window: int, min_periods=None) -> windows.Window: # To get n size window, need current row and n-1 preceding rows. window_spec = window_specs.rows( grouping_keys=tuple(self._by_col_ids), - preceding=window - 1, - following=0, + start=-(window - 1), + end=0, min_periods=min_periods or window, ) block = self._block.order_by( diff --git a/bigframes/core/window_spec.py b/bigframes/core/window_spec.py index 0f05d9bd9e..58df37abdd 100644 --- a/bigframes/core/window_spec.py +++ b/bigframes/core/window_spec.py @@ -52,8 +52,8 @@ def unbound( ### Rows-based Windows def rows( grouping_keys: Tuple[str, ...] = (), - preceding: Optional[int] = None, - following: Optional[int] = None, + start: Optional[int] = None, + end: Optional[int] = None, min_periods: int = 0, ordering: Tuple[orderings.OrderingExpression, ...] = (), ) -> WindowSpec: @@ -63,10 +63,12 @@ def rows( Args: grouping_keys: Columns ids of grouping keys - preceding: - number of preceding rows to include. If None, include all preceding rows + start: + The starting boundary of the window relative to the current row. For example, -1 means 1 row prior + 1 means 1 row after, and 0 means the current row. If None, the window is unbounded from the start. following: - number of following rows to include. If None, include all following rows + The ending boundary of the window relative to the current row. For example, -1 means 1 row prior + 1 means 1 row after, and 0 means the current row. If None, the window is unbounded until the end. min_periods (int, default 0): Minimum number of input rows to generate output. ordering: @@ -75,8 +77,8 @@ def rows( WindowSpec """ bounds = RowsWindowBounds( - start=WindowBoundary.preceding(preceding), - end=WindowBoundary.following(following), + start=start, + end=end, ) return WindowSpec( grouping_keys=tuple(map(ex.deref, grouping_keys)), @@ -100,7 +102,7 @@ def cumulative_rows( Returns: WindowSpec """ - bounds = RowsWindowBounds(end=WindowBoundary.following(0)) + bounds = RowsWindowBounds(end=0) return WindowSpec( grouping_keys=tuple(map(ex.deref, grouping_keys)), bounds=bounds, @@ -122,7 +124,7 @@ def inverse_cumulative_rows( Returns: WindowSpec """ - bounds = RowsWindowBounds(start=WindowBoundary.preceding(0)) + bounds = RowsWindowBounds(start=0) return WindowSpec( grouping_keys=tuple(map(ex.deref, grouping_keys)), bounds=bounds, @@ -133,31 +135,20 @@ def inverse_cumulative_rows( ### Struct Classes -T = TypeVar("T") - - -@dataclass(frozen=True) -class WindowBoundary(Generic[T]): - value: T - is_preceding: bool - - @classmethod - def preceding(cls, value: Optional[T]): - if value is None: - return None - return cls(value, True) - - @classmethod - def following(cls, value: Optional[T]): - if value is None: - return None - return cls(value, False) - - @dataclass(frozen=True) class RowsWindowBounds: - start: Optional[WindowBoundary[int]] = None - end: Optional[WindowBoundary[int]] = None + start: Optional[int] = None + end: Optional[int] = None + + def __post_init__(self): + if self.start is None: + return + if self.end is None: + return + if self.start > self.end: + raise ValueError( + f"Invalid window: start({self.start}) is greater than end({self.end})" + ) # TODO: Expand to datetime offsets @@ -166,8 +157,18 @@ class RowsWindowBounds: @dataclass(frozen=True) class RangeWindowBounds: - start: Optional[WindowBoundary[OffsetType]] = None - end: Optional[WindowBoundary[OffsetType]] = None + start: Optional[OffsetType] = None + end: Optional[OffsetType] = None + + def __post_init__(self): + if self.start is None: + return + if self.end is None: + return + if self.start > self.end: + raise ValueError( + f"Invalid window: start({self.start}) is greater than end({self.end})" + ) @dataclass(frozen=True) diff --git a/bigframes/dataframe.py b/bigframes/dataframe.py index 1d3a45e879..9fd6ff5c7b 100644 --- a/bigframes/dataframe.py +++ b/bigframes/dataframe.py @@ -2428,12 +2428,12 @@ def replace( @validations.requires_ordering() def ffill(self, *, limit: typing.Optional[int] = None) -> DataFrame: - window = windows.rows(preceding=limit, following=0) + window = windows.rows(start=None if limit is None else -limit, end=0) return self._apply_window_op(agg_ops.LastNonNullOp(), window) @validations.requires_ordering() def bfill(self, *, limit: typing.Optional[int] = None) -> DataFrame: - window = windows.rows(preceding=0, following=limit) + window = windows.rows(start=0, end=limit) return self._apply_window_op(agg_ops.FirstNonNullOp(), window) def isin(self, values) -> DataFrame: @@ -3310,7 +3310,7 @@ def _perform_join_by_index( def rolling(self, window: int, min_periods=None) -> bigframes.core.window.Window: # To get n size window, need current row and n-1 preceding rows. window_def = windows.rows( - preceding=window - 1, following=0, min_periods=min_periods or window + start=-(window - 1), end=0, min_periods=min_periods or window ) return bigframes.core.window.Window( self._block, window_def, self._block.value_columns diff --git a/bigframes/series.py b/bigframes/series.py index 5f49daa07d..a33a3fca5c 100644 --- a/bigframes/series.py +++ b/bigframes/series.py @@ -544,7 +544,7 @@ def cumsum(self) -> Series: @validations.requires_ordering() def ffill(self, *, limit: typing.Optional[int] = None) -> Series: - window = windows.rows(preceding=limit, following=0) + window = windows.rows(start=None if limit is None else -limit, end=0) return self._apply_window_op(agg_ops.LastNonNullOp(), window) pad = ffill @@ -552,7 +552,7 @@ def ffill(self, *, limit: typing.Optional[int] = None) -> Series: @validations.requires_ordering() def bfill(self, *, limit: typing.Optional[int] = None) -> Series: - window = windows.rows(preceding=0, following=limit) + window = windows.rows(start=0, end=limit) return self._apply_window_op(agg_ops.FirstNonNullOp(), window) @validations.requires_ordering() @@ -1441,7 +1441,7 @@ def sort_index(self, *, axis=0, ascending=True, na_position="last") -> Series: def rolling(self, window: int, min_periods=None) -> bigframes.core.window.Window: # To get n size window, need current row and n-1 preceding rows. window_spec = windows.rows( - preceding=window - 1, following=0, min_periods=min_periods or window + start=-(window - 1), end=0, min_periods=min_periods or window ) return bigframes.core.window.Window( self._block, window_spec, self._block.value_columns, is_series=True diff --git a/tests/unit/core/test_windowspec.py b/tests/unit/core/test_windowspec.py index ddb368d097..a630c87dda 100644 --- a/tests/unit/core/test_windowspec.py +++ b/tests/unit/core/test_windowspec.py @@ -12,16 +12,18 @@ # See the License for the specific language governing permissions and # limitations under the License. -from bigframes.core import window_spec - +import pytest -def test_window_boundary_preceding(): - window = window_spec.WindowBoundary.preceding(1) +from bigframes.core import window_spec - assert window == window_spec.WindowBoundary(1, is_preceding=True) +@pytest.mark.parametrize(("start", "end"), [(-1, -2), (1, -2), (2, 1)]) +def test_invalid_rows_window_boundary_raise_error(start, end): + with pytest.raises(ValueError): + window_spec.RowsWindowBounds(start, end) -def test_window_boundary_following(): - window = window_spec.WindowBoundary.following(1) - assert window == window_spec.WindowBoundary(1, is_preceding=False) +@pytest.mark.parametrize(("start", "end"), [(-1, -2), (1, -2), (2, 1)]) +def test_invalid_range_window_boundary_raise_error(start, end): + with pytest.raises(ValueError): + window_spec.RangeWindowBounds(start, end) From 1fefe87f7e52cb913718b22e9344e2cb486d6701 Mon Sep 17 00:00:00 2001 From: Shenyang Cai Date: Mon, 24 Mar 2025 20:03:58 +0000 Subject: [PATCH 4/7] fix lint --- bigframes/core/window_spec.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bigframes/core/window_spec.py b/bigframes/core/window_spec.py index 58df37abdd..fa4915e142 100644 --- a/bigframes/core/window_spec.py +++ b/bigframes/core/window_spec.py @@ -15,7 +15,7 @@ from dataclasses import dataclass, replace import itertools -from typing import Generic, Mapping, Optional, Set, Tuple, TypeVar, Union +from typing import Mapping, Optional, Set, Tuple, Union import bigframes.core.expression as ex import bigframes.core.identifiers as ids From 89f4d3cc23bd9bc93c180612197fc951e0731883 Mon Sep 17 00:00:00 2001 From: Shenyang Cai Date: Mon, 24 Mar 2025 20:33:27 +0000 Subject: [PATCH 5/7] fix mypy --- bigframes/core/compile/compiled.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/bigframes/core/compile/compiled.py b/bigframes/core/compile/compiled.py index 9fd74f6190..070fd3e78b 100644 --- a/bigframes/core/compile/compiled.py +++ b/bigframes/core/compile/compiled.py @@ -679,7 +679,9 @@ def _to_ibis_boundary( ) -> Optional[ibis_expr_window.WindowBoundary]: if boundary is None: return None - return ibis_expr_window.WindowBoundary(abs(boundary), preceding=boundary <= 0) + return ibis_expr_window.WindowBoundary( + abs(boundary), preceding=boundary <= 0 # type:ignore + ) def _add_boundary( @@ -687,16 +689,16 @@ def _add_boundary( ibis_window: ibis_expr_builders.LegacyWindowBuilder, ) -> ibis_expr_builders.LegacyWindowBuilder: if isinstance(bounds, RangeWindowBounds): - return ibis_window.between( + return ibis_window.range( start=_to_ibis_boundary(bounds.start), end=_to_ibis_boundary(bounds.end), - ).copy(how="range") + ) if isinstance(bounds, RowsWindowBounds): if bounds.start is not None or bounds.end is not None: - return ibis_window.between( + return ibis_window.rows( start=_to_ibis_boundary(bounds.start), end=_to_ibis_boundary(bounds.end), - ).copy(how="rows") + ) return ibis_window else: raise ValueError(f"unrecognized window bounds {bounds}") From 11a3b18044093025eaffc7e1445cb3e670d4825c Mon Sep 17 00:00:00 2001 From: Shenyang Cai Date: Mon, 24 Mar 2025 20:47:33 +0000 Subject: [PATCH 6/7] polish doc --- bigframes/core/window_spec.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/bigframes/core/window_spec.py b/bigframes/core/window_spec.py index fa4915e142..388a39f54a 100644 --- a/bigframes/core/window_spec.py +++ b/bigframes/core/window_spec.py @@ -64,11 +64,11 @@ def rows( grouping_keys: Columns ids of grouping keys start: - The starting boundary of the window relative to the current row. For example, -1 means 1 row prior - 1 means 1 row after, and 0 means the current row. If None, the window is unbounded from the start. + The window's starting boundary relative to the current row. For example, "-1" means one row prior + "1" means one row after, and "0" means the current row. If None, the window is unbounded from the start. following: - The ending boundary of the window relative to the current row. For example, -1 means 1 row prior - 1 means 1 row after, and 0 means the current row. If None, the window is unbounded until the end. + The window's ending boundary relative to the current row. For example, "-1" means one row prior + "1" means one row after, and "0" means the current row. If None, the window is unbounded until the end. min_periods (int, default 0): Minimum number of input rows to generate output. ordering: From a8263fa9a0e36301c329b13d1ab2ee86c3ecfb0e Mon Sep 17 00:00:00 2001 From: Shenyang Cai Date: Mon, 24 Mar 2025 23:41:03 +0000 Subject: [PATCH 7/7] remove float support for range rolling because Pandas does not support that --- bigframes/core/compile/compiled.py | 2 +- bigframes/core/compile/polars/compiler.py | 2 +- bigframes/core/window_spec.py | 9 +++------ 3 files changed, 5 insertions(+), 8 deletions(-) diff --git a/bigframes/core/compile/compiled.py b/bigframes/core/compile/compiled.py index 070fd3e78b..d2fd7f3ea2 100644 --- a/bigframes/core/compile/compiled.py +++ b/bigframes/core/compile/compiled.py @@ -675,7 +675,7 @@ def _as_groupable(value: ibis_types.Value): def _to_ibis_boundary( - boundary: typing.Union[int, float, None], + boundary: Optional[int], ) -> Optional[ibis_expr_window.WindowBoundary]: if boundary is None: return None diff --git a/bigframes/core/compile/polars/compiler.py b/bigframes/core/compile/polars/compiler.py index 7c4c2f3424..6fac3c9b92 100644 --- a/bigframes/core/compile/polars/compiler.py +++ b/bigframes/core/compile/polars/compiler.py @@ -391,4 +391,4 @@ def _get_period( return None # collecting height is a massive kludge - return cast(int, bounds.end - bounds.start + 1) + return bounds.end - bounds.start + 1 diff --git a/bigframes/core/window_spec.py b/bigframes/core/window_spec.py index 388a39f54a..a286234fc8 100644 --- a/bigframes/core/window_spec.py +++ b/bigframes/core/window_spec.py @@ -151,14 +151,11 @@ def __post_init__(self): ) -# TODO: Expand to datetime offsets -OffsetType = Union[float, int] - - @dataclass(frozen=True) class RangeWindowBounds: - start: Optional[OffsetType] = None - end: Optional[OffsetType] = None + # TODO(b/388916840) Support range rolling on timeseries with timedeltas. + start: Optional[int] = None + end: Optional[int] = None def __post_init__(self): if self.start is None: