Skip to content

Two sliding-window structures: the spectrum and the skyline

← Recommenders

Two other classes that live on this page look at the last few points only and forget the old ones: the sliding DFT tells the rhythm of the last few samples, and the skyline keeps the points that nothing else beats. A desk can use the first on a series of volumes and the second on the cost and the risk of its algorithms. A robot can use them on a joint signal and on the cost and the error of its gains.

The size of the skyline of a sliding window of random points, for window sizes from 5 to 60.

1. A first example: the rhythm of the volume and the algorithms nobody beats

The first block feeds a series of daily volumes with a rhythm of four days to the sliding DFT of the last eight days and finds the strongest frequency. The second block keeps the last five (cost, risk) pairs of five algorithms and prints the positions of the ones that no other beats on both.

import numpy as np
from dense_armor.core.signals.stats.sdft import SDFT
from dense_armor.core.signals.stats.skyline import Skyline

volume = [10 + 3 * np.sin(2 * np.pi * t / 4) for t in range(20)]
s = SDFT(n=8)
for v in volume:
    _ = s.update(v)
print(int(np.argmax(np.abs(s.X[1:5]))) + 1)
algos = Skyline(window=5)
for cost, risk in [(1.0, 5.0), (3.0, 3.0), (5.0, 1.0), (4.0, 4.0), (6.0, 6.0)]:
    _ = algos.update({"cost": cost, "risk": risk})
print(sorted(algos.skyline()))
2
[0, 1, 2]

The first number is the frequency of the strongest component of the last eight days: the volume repeats every four days, which is two cycles in eight days, and the answer is 2. The sliding DFT updates the spectrum of the window in O(n) per sample, without recomputing it from scratch. The second line lists the positions, in the current window of five, of the algorithms that are not beaten by another on both cost and risk (smaller is better): the first three, which trade cost against risk, and neither of the last two, which are beaten by the second one.

The same models on the same data.

The surface is the size of the skyline of random points, which grows with the window: the median size after the window is full is 2.25 points for a window of 5, 3.56 for 20 and 4.81 for 60. The skyline stays small even when the window is large, because few points are not beaten by any other.

class or function what it does
SDFT the spectrum of the last n samples, updated in O(n) per sample
Skyline the non-dominated points of the last w points

2. What it does

The sliding DFT updates the spectrum of the last n samples in O(n) per sample, with the recursion of Jacobsen and Lyons. The sliding-window skyline keeps the points of the last w points that no other point dominates; the implementation recomputes the skyline of the window with the naive algorithm, O(W^2) per update, which is a choice of the library, not the incremental algorithm of Tao and Papadias.

Source: Jacobsen, E., Lyons, R. (2003). The Sliding DFT. IEEE Signal Processing Magazine 20(2), 74-80. Börzsönyi, S., Kossmann, D., Stocker, K. (2001). The Skyline Operator. In ICDE 2001. Section 2, page 2 (dominance), Section 3.3, page 4 (block nested loops). Tao, Y., Papadias, D. (2006). Maintaining Sliding Window Skylines. In ICDE 2006. Section 3, page 3.

3. The parameters

Parameter Meaning Default
SDFT(n) the length of the window, in samples none
Skyline(window) the number of points that the window keeps none

budget_s is 0.008 s for the SDFT and 0.015 s for the Skyline. Neither has a learn_one: fit says so, and the data go in with update.

4. The same on the paper's toy example

The two structures, on the toy examples

The same sliding-window idea appears in two other classes: the sliding DFT updates the spectrum of the last n samples in O(n) per sample, and the sliding-window skyline keeps the non-dominated points of the last w points.

SDFT vs numpy.fft, and the skyline at two times

Panel (a) compares the SDFT with numpy.fft.fft on the same window. The two agree to about 2e-07 (the check below prints the max absolute difference, with one digit). This is the default dtype of the library, float32; with set_default_dtype("float64") the same check prints 4e-15.

import numpy as np
from dense_armor.core.signals.stats.sdft import SDFT

rng = np.random.default_rng(42)
vals = rng.normal(size=20)
s = SDFT(n=8)
for v in vals:
    _ = s.update(v)
print(f'{np.max(np.abs(s.X - np.fft.fft(vals[-8:]))):.0e}')
2e-07

Panel (b) shows the skyline of a sliding window of 20 points, at two different times. The dots are the points of the window, the blue squares the skyline after 20 points, the orange triangles the skyline after 40 points. The skyline is the set of points not dominated by any other point of the window (Börzsönyi et al. 2001, Section 2, page 2).

from dense_armor.core.signals.stats.skyline import Skyline

s = Skyline(window=5)
for p in [{"x": 1.0, "y": 5.0}, {"x": 3.0, "y": 3.0},
          {"x": 5.0, "y": 1.0}, {"x": 0.5, "y": 0.5}]:
    _ = s.update(p)
sorted(s.skyline())
[3]

Only (0.5, 0.5) is not dominated in the window: it is smaller than the other three points in both coordinates, so it dominates each of them. The indices returned by skyline() are positions in the current window, from 0 (oldest) to len(window) - 1 (newest).

5. The same on a robot

A robot has a joint signal and several gains. The code is the same, with the names of the robot.

import numpy as np
from dense_armor.core.signals.stats.sdft import SDFT
from dense_armor.core.signals.stats.skyline import Skyline

speed = [0.5 * np.sin(2 * np.pi * t / 8) for t in range(40)]
s = SDFT(n=16)
for v in speed:
    _ = s.update(v)
print(int(np.argmax(np.abs(s.X[1:8]))) + 1)
gains = Skyline(window=5)
for err, energy in [(0.9, 0.2), (0.4, 0.5), (0.1, 0.9), (0.5, 0.6), (0.8, 0.8)]:
    _ = gains.update({"err": err, "energy": energy})
print(sorted(gains.skyline()))
2
[0, 1, 2]

The joint speed repeats every 8 samples, which is two cycles in 16, and the answer is 2; the gains that no other beats on error and energy are the first three.

API reference

SDFT

SDFT(n: int = 8)

Bases: Root

Sliding DFT: the N-point DFT of the last N samples, O(N) per update.

A batch DFT recomputes the sum over N samples every time a new sample arrives, so N samples cost O(N^2) in total. The sliding DFT updates the previous spectrum in place, in O(N) per sample, with the recursion::

X_new[k] = (X_old[k] - x_old + x_new) * exp(+j * 2 * pi * k / N)

where x_old is the sample leaving the window, x_new the one entering, and k = 0, ..., N-1. The sign of the exponential is the one that makes the value match numpy.fft.fft on the same window (the paper writes the same sign; the case [1, 2, 3, 4] moving to [2, 3, 4, 5] gives the same values as numpy.fft.fft in the test of this module).

The first call after __init__ computes the DFT of the buffer with numpy.fft.fft (the recursion needs a starting value).

Parameters:

Name Type Description Default
n int

window length, strictly positive.

8

Raises:

Type Description
ValueError

if n < 1.

Examples:

>>> from dense_armor.core.signals.stats.sdft import SDFT
>>> s = SDFT(n=4)
>>> for v in [1.0, 2.0, 3.0, 4.0]:
...     _ = s.update(v)
>>> s.is_ready
True
>>> float(round(s.X[0].real, 6))
10.0
References

Jacobsen, E., Lyons, R. (2003). The Sliding DFT. IEEE Signal Processing Magazine 20(2), 74-80. A course tutorial on the sliding DFT is the PDF in the task folder; the recursion above is the one in the tutorial, Equation (1), page 4 of that copy (Section "SDFT as", MATLAB code).

Source code in dense_armor/core/signals/stats/sdft.py
def __init__(self, n: int = 8) -> None:
    if n < 1:
        raise ValueError(f"n must be >= 1, got {n}")
    self.n = int(n)
    self._buffer: deque = deque(maxlen=self.n)
    self._X: np.ndarray | None = None
    self.n_seen_: int = 0

is_ready property

is_ready: bool

True once the buffer holds n samples.

X property

X: ndarray

The last computed spectrum, shape (n,).

update

update(v: float) -> SDFT

Push one sample and update the spectrum.

Before the buffer is full, the spectrum is the DFT of the samples seen so far (zero-padded to length n). Once it is full, the update uses the sliding recursion above.

Parameters:

Name Type Description Default
v float

the new sample.

required

Returns:

Type Description
SDFT

self.

Source code in dense_armor/core/signals/stats/sdft.py
def update(self, v: float) -> "SDFT":
    """Push one sample and update the spectrum.

    Before the buffer is full, the spectrum is the DFT of the
    samples seen so far (zero-padded to length ``n``). Once it is
    full, the update uses the sliding recursion above.

    Args:
        v: the new sample.

    Returns:
        self.
    """
    fv = float(v)
    if not np.isfinite(fv):
        return self
    was_full = self.is_ready
    x_old = self._buffer[0] if was_full else 0.0
    self._buffer.append(fv)
    self.n_seen_ += 1
    if not was_full:
        self._X = np.fft.fft(as_default_array(self._buffer), n=self.n)
        return self
    k = np.arange(self.n)
    rot = np.exp(1j * 2.0 * np.pi * k / self.n)
    assert self._X is not None
    self._X = (self._X - x_old + fv) * rot
    return self

update_many

update_many(values: Any) -> SDFT

Push several samples in order.

Source code in dense_armor/core/signals/stats/sdft.py
def update_many(self, values: Any) -> "SDFT":
    """Push several samples in order."""
    for v in values:
        _ = self.update(v)
    return self

spectrum

spectrum() -> np.ndarray

Return a copy of the current spectrum.

Source code in dense_armor/core/signals/stats/sdft.py
def spectrum(self) -> np.ndarray:
    """Return a copy of the current spectrum."""
    return self.X.copy()

Skyline

Skyline(
    window: int = 10, dims: Sequence[str] | None = None
)

Bases: Root

Skyline of a sliding window over a stream of points.

A point is a dict mapping a dimension name to a value. The window keeps the last window points; skyline() returns the points not dominated by any other point of the window, with their original index in the window.

Parameters:

Name Type Description Default
window int

window length, strictly positive.

10
dims Sequence[str] | None

the dimension names, in order. None takes the sorted keys of the first point seen.

None

Raises:

Type Description
ValueError

if window < 1.

Examples:

>>> from dense_armor.core.signals.stats.skyline import Skyline
>>> s = Skyline(window=3)
>>> _ = s.update({"x": 1.0, "y": 5.0})
>>> _ = s.update({"x": 3.0, "y": 3.0})
>>> _ = s.update({"x": 5.0, "y": 1.0})
>>> len(s.skyline())
3
References

Börzsönyi, S., Kossmann, D., Stocker, K. (2001). The Skyline Operator. In ICDE 2001. Section 1 page 1 and Section 2 page 2 (dominance), Section 3.3 page 4 (the naive nested loops). Tao, Y., Papadias, D. (2006). Maintaining Sliding Window Skylines on Data Streams. IEEE Transactions on Knowledge and Data Engineering 18(3), 377-391. Section 3 page 3 of the PDF (sliding window maintenance).

Source code in dense_armor/core/signals/stats/skyline.py
def __init__(self, window: int = 10, dims: Sequence[str] | None = None) -> None:
    if window < 1:
        raise ValueError(f"window must be >= 1, got {window}")
    self.window = int(window)
    self.dims = list(dims) if dims is not None else None
    self.dims_: list[str] | None = None
    self.buffer_: deque = deque(maxlen=self.window)
    self.n_seen_: int = 0
    self.n_missing_: int = 0

set_params

set_params(**params: Any) -> Skyline

Set hyper-parameters; a new window resizes the window, a new dims empties it.

Source code in dense_armor/core/signals/stats/skyline.py
def set_params(self, **params: Any) -> "Skyline":
    """Set hyper-parameters; a new ``window`` resizes the window, a new ``dims`` empties it."""
    if "window" in params and int(params["window"]) < 1:
        raise ValueError(f"window must be >= 1, got {params['window']}")
    super().set_params(**params)
    if "window" in params:
        self.window = int(self.window)
        self.buffer_ = deque(self.buffer_, maxlen=self.window)
    if "dims" in params:
        self.dims = list(self.dims) if self.dims is not None else None
        self.dims_ = None
        self.buffer_.clear()
    return self

update

update(point: Any) -> Skyline

Push one point, dropping the oldest when the window is full.

Source code in dense_armor/core/signals/stats/skyline.py
def update(self, point: Any) -> "Skyline":
    """Push one point, dropping the oldest when the window is full."""
    p = self._as_point(point)
    if p is None:
        self.n_missing_ += 1
        return self
    self.buffer_.append(p)
    self.n_seen_ += 1
    return self

update_many

update_many(points: Any) -> Skyline

Push several points in order.

Source code in dense_armor/core/signals/stats/skyline.py
def update_many(self, points: Any) -> "Skyline":
    """Push several points in order."""
    for p in points:
        _ = self.update(p)
    return self

skyline

skyline() -> list[int]

Indices (in the current window) of the non-dominated points.

The indices refer to the position of the point in the current window, from 0 (oldest) to len(window) - 1 (newest).

Source code in dense_armor/core/signals/stats/skyline.py
def skyline(self) -> list[int]:
    """Indices (in the current window) of the non-dominated points.

    The indices refer to the position of the point in the current
    window, from 0 (oldest) to ``len(window) - 1`` (newest).
    """
    pts = list(self.buffer_)
    return _skyline(pts)

skyline_points

skyline_points() -> list[np.ndarray]

The non-dominated points, as arrays in the order of dims.

Source code in dense_armor/core/signals/stats/skyline.py
def skyline_points(self) -> list[np.ndarray]:
    """The non-dominated points, as arrays in the order of ``dims``."""
    return [np.asarray(self.buffer_[i]) for i in self.skyline()]

Details

Choices

  • The figures are drawn by docs/assets/reco/make_reco_style_figures.py: random points in the unit square, the size of the skyline at each step, median over 5 seeds. The old figure of the SDFT against numpy.fft and of the skyline at two times is kept in the section of the toy examples.