|
| 1 | +# Copyright 2025 Google LLC, LeanFrame Authors |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Windowed operations on DataFrames.""" |
| 16 | + |
| 17 | +from __future__ import annotations |
| 18 | + |
| 19 | +from typing import TYPE_CHECKING, Any |
| 20 | + |
| 21 | +import ibis |
| 22 | + |
| 23 | +if TYPE_CHECKING: |
| 24 | + from leanframe.core.frame import DataFrame |
| 25 | + |
| 26 | + |
| 27 | +class Rolling: |
| 28 | + """Windowed operations on DataFrames.""" |
| 29 | + |
| 30 | + def __init__( |
| 31 | + self, |
| 32 | + obj: DataFrame, |
| 33 | + window: int, |
| 34 | + min_periods: int | None = None, |
| 35 | + ): |
| 36 | + """Initialize a Rolling object. |
| 37 | +
|
| 38 | + Args: |
| 39 | + obj: The DataFrame to apply rolling operations to. |
| 40 | + window: The size of the moving window. |
| 41 | + min_periods: Minimum number of observations in window required to |
| 42 | + have a value. Defaults to window size. |
| 43 | + """ |
| 44 | + self._obj = obj |
| 45 | + self._window = window |
| 46 | + self._min_periods = min_periods if min_periods is not None else window |
| 47 | + |
| 48 | + def _apply_aggregation(self, op: str, **kwargs: Any) -> DataFrame: |
| 49 | + from leanframe.core.frame import DataFrame |
| 50 | + |
| 51 | + t = self._obj._data |
| 52 | + |
| 53 | + w = ibis.window(preceding=self._window - 1, following=0) |
| 54 | + |
| 55 | + exprs = [] |
| 56 | + for c in t.columns: |
| 57 | + col = t[c] |
| 58 | + |
| 59 | + if op == "count": |
| 60 | + agg = col.count() |
| 61 | + elif op == "sum": |
| 62 | + agg = col.sum() |
| 63 | + elif op == "mean": |
| 64 | + agg = col.mean() |
| 65 | + elif op == "std": |
| 66 | + agg = col.std(how="sample") |
| 67 | + else: |
| 68 | + raise NotImplementedError(f"Unsupported operation: {op}") |
| 69 | + |
| 70 | + agg_over = agg.over(w) |
| 71 | + |
| 72 | + if op == "count": |
| 73 | + # For count, min_periods applies to the TOTAL number of rows in the window (including nulls) |
| 74 | + # We can trick Ibis into counting all rows by coalescing the column. |
| 75 | + valid_count = ibis.coalesce(col, 0).count().over(w) |
| 76 | + else: |
| 77 | + # For others, min_periods applies to the number of non-null observations |
| 78 | + valid_count = col.count().over(w) |
| 79 | + |
| 80 | + final_expr = ibis.ifelse( |
| 81 | + valid_count >= self._min_periods, agg_over, ibis.null() |
| 82 | + ).name(c) |
| 83 | + exprs.append(final_expr) |
| 84 | + |
| 85 | + return DataFrame(t.select(exprs)) |
| 86 | + |
| 87 | + def count(self) -> DataFrame: |
| 88 | + """Calculate the rolling count.""" |
| 89 | + return self._apply_aggregation("count") |
| 90 | + |
| 91 | + def sum(self) -> DataFrame: |
| 92 | + """Calculate the rolling sum.""" |
| 93 | + return self._apply_aggregation("sum") |
| 94 | + |
| 95 | + def mean(self) -> DataFrame: |
| 96 | + """Calculate the rolling mean.""" |
| 97 | + return self._apply_aggregation("mean") |
| 98 | + |
| 99 | + def std(self) -> DataFrame: |
| 100 | + """Calculate the rolling standard deviation.""" |
| 101 | + return self._apply_aggregation("std") |
0 commit comments