Data structureresearch
FlatFAT
Also called flat fixed-size aggregator tree.
A complete binary tree in an array that keeps partial aggregates of a window under any associative operator, with O(log n) operator calls per single update and amortized O(1) resizing.
- Time
- O(n) worst · buildO(log n) amortized · queryO(m + m log(n/m)) update
- Space
- O(W) extra
- Where
- W = the number of values in the window; m = the number of leaves written by one update; n = the number of leaves of the tree (a power of two)
- Model
- Word RAM
- Properties
- deterministicexactnot externalnot in placeonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Kanat Tangwongsan, Martin Hirzel, Scott Schneider, Kun Lung Wu, 2015
FlatFAT, short for flat fixed-size aggregator, is a complete binary tree stored in an array in which each internal node holds the combination of the values below it under an associative operator . Tangwongsan, Hirzel, Schneider and Wu (2015) use it to answer a sliding-window aggregation query: the window values are the leaves, used as a circular buffer, and a change to leaves costs calls of . The operator needs only associativity and an identity, so it can be non-commutative and non-invertible, such as concatenation, max or a product of matrices. It is a segment tree with a fixed layout, and the two-stacks queue and the DABA queue are faster alternatives for windows that are strictly first in, first out.
In plain words
You must always know the largest of the last few thousand readings, and readings come and go all the time. Put the readings in a row of boxes. Above each pair of boxes, write the larger of the two. Above each pair of those notes, write the larger again, and go on up to a single note at the top, which is the answer. When a reading changes, only the notes on its path to the top can change, and there are few of them, because each level halves the number of notes. The same scheme works for any way of combining two values that does not care how you group them. It does not need the values to be numbers, and it does not need a way to undo a combination.
The abstract type
The tree keeps an array of values from a set with an associative operator and an identity , for a fixed capacity . The operations are:
- new(): set the leaves to the values , padded with .
- update(): for each pair in the set of changes, set .
- aggregate(): return .
- prefix(): return .
- suffix(): return .
A FIFO window on top of the tree adds insert(), which appends as the youngest value, evict(), which removes the oldest value, and query(), which returns for the window values , oldest first. Order matters: for concatenation, the query of the window "c", "d", "e" must be "cde" and not "ecd".
Representation
The capacity is a power of two, . The array holds the tree: the root is , the children of node are and , and leaf is . This page counts leaves from 0; the paper counts them from 1 and puts leaf at . No pointers are stored, and the array is filled level by level, which is why the tree is called flat. Each internal node holds , which by associativity is the combination of the leaves below , in order from left to right. A leaf that holds no value holds .
The FIFO window uses the leaves as a circular buffer with a front (the slot of the oldest value), a back (the slot for the next value) and a count . When the values are in one block and the root is the answer. When the buffer wraps, the paper calls it inverted: the oldest values are at the right end of the array and the youngest at the left, and the root then holds them in the wrong order.
Operations
FLATFAT(n, ⊕, e) ▷ n = 2^L leaves; leaf i is T[n + i]; the root is T[1]NEW(v)- 1
T[n .. 2n - 1] ← v, padded with e - 2
for h ← n - 1 down to 1 do - 3
T[h] ← T[2h] ⊕ T[2h + 1] UPDATE(C) ▷ C is a set of pairs (i, x) with distinct i- 4
for each (i, x) in C do T[n + i] ← x; add ⌊(n + i) / 2⌋ to the set D - 5
while D is not empty do ▷ D holds the changed nodes of one level - 6
for each h in D do T[h] ← T[2h] ⊕ T[2h + 1] - 7
D ← {⌊h / 2⌋ : h in D and h > 1} AGGREGATE()- 8
return T[1] PREFIX(i) ▷ a_0 ⊕ ... ⊕ a_i- 9
h ← n + i; a ← T[h] - 10
while h > 1 do - 11
if h is odd then a ← T[h - 1] ⊕ a ▷ the left sibling comes before i h ← ⌊h / 2⌋return aSUFFIX(j) ▷ a_j ⊕ ... ⊕ a_{n-1}- 12
h ← n + j; a ← T[h]; while h > 1 do - 13
if h is even then a ← a ⊕ T[h + 1]; h ← ⌊h / 2⌋ return aINSERT(x) ▷ the FIFO window: front F, back B, count c- 14
if c = n then copy the c values, oldest first, into a new tree of 2n leaves; F ← 0; B ← c - 15
UPDATE({(B, x)}); B ← (B + 1) mod n; c ← c + 1 EVICT()- 16
UPDATE({(F, e)}); F ← (F + 1) mod n; c ← c - 1 - 17
if n > 1 and c < n / 4 then copy the c values into a new tree of n / 2 leaves; F ← 0; B ← c mod (n / 2) QUERY()- 18
if c = 0 then return e; if F < B or B = 0 then return AGGREGATE() - 19
return SUFFIX(F) ⊕ PREFIX(B - 1) ▷ inverted: the old part, then the young part
The update repairs one level at a time, from the leaves up. All leaves are at the same depth, so the set always holds nodes of a single level, and a node is repaired only after both its children are correct. When two changed leaves share an ancestor, the ancestor is in once and is repaired once, which is where the batch update saves work over single updates.
PREFIX climbs from leaf to the root. Each time the current node is a right child, its left sibling covers the leaves just before the part already collected, so the sibling goes on the left. SUFFIX is the mirror image.
Example
Take concatenation of strings, which is associative but not commutative, with and the leaves a, b, c, d, e, f, g, h. NEW makes 7 calls. The two children of the root hold "abcd" and "efgh", and the root holds "abcdefgh".
An update writes "C" into leaf 2 and "F" into leaf 5. The changed leaves are and . Line L6 repairs and , then and , then : 5 calls, and the root is "abCdeFgh". Two single updates would cost calls, because they repair the root twice.
PREFIX(5) starts at , which is a right child, so it computes "F" = "eF". The next node, , is a left child, so nothing is added. The node after that, , is a right child, so the result is "eF" = "abCdeF". That is 2 calls for 3 levels.
Now use a FIFO window that starts with one leaf. Insert a, b, c and d. The tree doubles from 1 to 2 leaves at b and from 2 to 4 at c, so the leaves are a, b, c, d with and . Evict twice: the leaves become , , c, d with . Insert "e": it goes into slot 0, and . The leaves are now "e", , "c", "d", and the root holds "ecd", which is the wrong order. The buffer is inverted (), so line L19 returns SUFFIX(2) PREFIX(0) = "cd" "e" = "cde" with 2 calls.
Correctness
The invariant is that every internal node holds the combination, in order, of the leaves below it. NEW sets it bottom-up, and UPDATE restores it on exactly the ancestors of the changed leaves, level by level, so that each node is set from two correct children. PREFIX keeps the combination of the leaves from the leftmost leaf below the current node to leaf , and it reaches the root with the leftmost leaf 0. For the window, the slots that hold no value hold , so the root is the answer when the values form one block. When the buffer wraps, the window is the suffix from followed by the prefix up to , and associativity joins them. The full proofs are in the correctness proof; every statement there is a theorem.
Proof: FlatFAT keeps every node equal to the aggregate of its leaves, and its operations meet the stated boundsfull
We use the line numbers of the pseudocode. The operator is associative and has the identity ; it need not be commutative or invertible. The tree has leaves for an integer , stored in the array : the root is , the children of node are and , and leaf (for ) is . All leaves are at depth . For a node , let and be the positions of the leftmost and the rightmost leaf below , so the leaves below are the contiguous block , where is the value of leaf . For we write ; by associativity the bracketing does not matter, but the order does.
Invariant (I). For every internal node , .
Lemma 1 (new). After lines L1 to L3, (I) holds, and the build makes exactly calls of .
Proof. Line L2 visits the internal nodes in the order . The children and of are larger than , so they are leaves or nodes that were already set. By induction on this order, and with , because the left block ends just before the right block starts. Line L3 sets to their combination, which is by associativity. There are internal nodes and one call each.
Lemma 2 (update). Suppose (I) holds and an update writes distinct leaves (lines L4 to L7). Then (I) holds after it, and the number of calls of is at most , where .
Proof. Let be the set of the changed leaves. A node needs repair exactly when it is an ancestor of a leaf in ; every other node has the same leaves below it as before, so (I) still holds for it. We show by induction on the iterations of line L5 that the -th iteration handles the set of all ancestors of at depth , and that when it handles a node, both children are already correct. Line L4 puts into the parents of the changed leaves, which are all at depth , because all leaves are at depth . The children of a node in are leaves, which hold their new values. Line L7 maps to the set of the parents of its nodes, which is . A child of a node in is either in , and so was repaired in iteration , or not an ancestor of , and so was already correct. Line L6 then sets each node of from its two correct children, as in Lemma 1. The loop stops after , so every ancestor is repaired once.
For the cost, iteration makes calls, because each changed leaf has one ancestor at each depth and depth has nodes. Let . The depths with are those with ; there are of them, and they give at most calls. The other depths give at most calls. If is a power of two, then and , so the total is at most . Otherwise and , so the total is less than .
For the bound is calls. The bound is exact when is a power of two and the changed leaves are , because then each depth below has distinct ancestors and the depths above it are full.
Lemma 3 (prefix and suffix). If (I) holds, PREFIX() returns and SUFFIX() returns , each with at most calls of .
Proof. For PREFIX, we claim that at the test of line L10, holds . At line L9, is the leaf and . If is odd, it is a right child, its sibling covers the block that ends just before , and ; line L11 puts on the left of , so the claim holds for the parent. If is even, it is a left child and , so the claim holds without a call. At the root, . The loop climbs levels and makes at most one call per level. SUFFIX is the mirror image: a left child adds its right sibling on the right of (line L13), and .
The FIFO window
The window keeps , the slot of the oldest value, , the slot for the next value, and the count . The window holds the values in the slots , taken modulo , oldest first.
Invariant (W). The window values are in these slots in this order, every other leaf holds , and (I) holds.
Lemma 4. INSERT and EVICT keep (W), and a resize keeps (W) with .
Proof. A resize (lines L14 and L17) reads the values oldest first, builds a new tree with them in the leaves and elsewhere (Lemma 1), and sets and . INSERT first makes room if ; then slot is free and holds . Line L15 writes the new value there with an update (Lemma 2) and advances , so the new value is the youngest. EVICT (line L16) writes into slot , which is the oldest value, and advances .
Theorem 1 (query). Under (W), QUERY returns , where are the window values oldest first.
Proof. If the result is . If and , the values fill the slots ; if , they fill the slots . In both cases they are in order from left to right, and every other leaf holds . By (I) the root is the combination of all leaves in order, and the identities drop out, so line L18 is correct. Otherwise , and (with only when ). Then the window wraps: its values are the leaves followed by the leaves , and the leaves between hold . By Lemma 3 and associativity, line L19 returns , which is the window in order.
Costs
Theorem 2 (worst case). Without a resize, INSERT and EVICT make at most calls of , and QUERY at most . A resize to leaves makes calls.
Proof. INSERT and EVICT are updates with (Lemma 2). QUERY makes no call on line L18 and two climbs and one combine on line L19 (Lemma 3). A resize is one build (Lemma 1).
Theorem 3 (amortized resizing). Start from an empty window with . Over any sequence of inserts and evicts, the resizes make at most calls of in total, so amortized calls per operation.
Proof. Right after each resize the tree is at most half full: a doubling from to happens at , and a halving from to happens at , so . Charge each resize to the operations since the previous one. A doubling from to costs calls, and it needs to grow from at most to , so at least inserts paid for it; this is at most 4 calls per operation. For a halving from to , consider the state right after the previous resize to . It was a doubling from , which left , or a halving from , which left (that halving happened at the first evict that took below , so went from to ). Now , so at least evicts happened, and the halving costs calls, at most 2 per operation. The first doubling, from , costs one call and follows one insert.
Space. The array has entries. A halving from happens as soon as , so after every operation . This gives , and the extra space is for a window of values.
Complexity
All costs count calls of in the word RAM, so a call is one step when takes constant time.
- Theorem (Tangwongsan et al., Theorem 4.2). NEW makes calls. An update that writes leaves makes at most calls. PREFIX and SUFFIX make at most calls each, and AGGREGATE makes none. The proof on this page gives the slightly sharper bound with , which is exact for evenly spaced leaves when is a power of two.
- Theorem (worst case per tuple). In the FIFO window, insert and evict each make at most calls when no resize happens, and query makes at most . One resize to leaves makes calls, so the worst case of a single insert is .
- Theorem (amortized resizing). From one leaf, the doubling and halving rule spends at most 4 calls per insert or evict on resizes, amortized. So insert and evict cost amortized calls, and the window keeps leaves, which is space.
The queries do not change the tree, so a window that is queried after every tuple pays for the update and for the query. The two-stacks queue and DABA do better for this case: amortized and worst case calls per operation.
Variants
- The paper's resize rule. When the buffer is full, the paper compacts it in place if at most 3/4 of the slots hold values, and doubles it otherwise. After an eviction, it halves the buffer if fewer than 1/4 of the slots hold values. Resizing then costs amortized . Compaction matters only for windows that are not FIFO (Section 5.2), where evictions leave holes in the middle; in a FIFO window there are no holes, and the code on this page uses plain doubling.
- Windows that are not FIFO and late data. Because UPDATE can write any leaf, a value that arrives late but still has a slot in the buffer is written into that slot in calls, and an eviction in the middle writes . A value older than the front has no slot in the circular buffer of this page, so it must be dropped or counted as late, or the window must use a structure for out-of-order data such as the FiBA tree of Tangwongsan, Hirzel and Schneider (2019).
- Batches. With slicing or panes, the leaves are partial aggregates of slices instead of single tuples, as in stream slicing and pane-based aggregation, and when the buffer does not wrap, SUFFIX() gives the window of the youngest values from slot on, so one tree can answer several window sizes that end at the same time.
- Invertible operators. When has an inverse, as for a sum, a single running total with subtract-on-evict costs and the tree is not needed. A Fenwick tree also needs an inverse to answer a range from two prefixes.
When to use it
Use FlatFAT when the operator is associative but has no inverse, when the window changes in batches or out of FIFO order, or when one structure must answer many sub-ranges of the window through PREFIX and SUFFIX. For a strictly FIFO window with one change at a time, the two-stacks queue or DABA is cheaper. For an invertible operator, a running total is cheapest.
Pitfalls
- Order in the inverted buffer. When the buffer wraps, the root holds the values in the wrong order. This is harmless for max or sum and wrong for concatenation, list collection or matrix products. Test with a non-commutative operator.
- The identity. Empty slots must hold the identity of , not 0 or None, unless the operator treats that value as the identity.
- Repairing an ancestor twice. A batch update that applies single updates one after another is correct but costs calls; the bound needs the level-by-level repair.
- Resizing in the worst case. A doubling copies the whole window and rebuilds the tree, so one insert can cost . Systems with a latency limit per tuple need a structure with a worst-case bound, such as DABA.
- A power of two. The layout assumes that is a power of two. Other sizes must be rounded up and padded with the identity.
Implementations
The paper's Reactive Aggregator, built on FlatFAT, was implemented in IBM InfoSphere Streams and measured against the method of Arasu and Widom on a two-core Xeon machine; these results are measurements, and this page does not repeat their numbers. The Python code on this page has the tree, the batch update, PREFIX, SUFFIX and the FIFO window with doubling and halving, and it counts calls of . Its tests check every query against recomputation of the window from scratch, with concatenation, max and sum, and they check the call counts against the bounds above.
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/flatfat/. The authors are listed in prov/6M9DHR.jsonl.
"""FlatFAT, the flat fixed-size aggregator of Tangwongsan, Hirzel, Schneider
and Wu (PVLDB 2015), and a FIFO sliding window on top of it.
The tree is a complete binary tree with n leaves (n a power of two) stored in
an array: the root is at index 1, the children of node h are 2h and 2h + 1,
and leaf i (0-based) is at index n + i. Every internal node holds the
combination of its two children with an associative operator op, which need
not be commutative or invertible. Empty leaves hold the identity of op.
Positions are 0-based here: prefix(i) = a[0] op ... op a[i] and
suffix(j) = a[j] op ... op a[n-1].
"""
from typing import Any, Callable
class FlatFAT:
def __init__(self, n: int, op: Callable[[Any, Any], Any], identity: Any):
if n < 1 or n & (n - 1):
raise ValueError("n must be a power of two")
self.n, self._op, self.identity = n, op, identity
self.calls = 0 # calls of op, for the tests of the cost bounds
self.tree = [identity] * (2 * n)
def op(self, a, b):
self.calls += 1
return self._op(a, b)
def new(self, values) -> None:
"""Set the leaves to values (padded with the identity) and build."""
values = list(values)
if len(values) > self.n:
raise ValueError("too many values")
n = self.n
self.tree[n:] = values + [self.identity] * (n - len(values)) # @line L1
for h in range(n - 1, 0, -1): # @line L2
self.tree[h] = self.op(self.tree[2 * h], self.tree[2 * h + 1]) # @line L3
def update(self, changes) -> None:
"""Write several leaves, then repair each changed ancestor once."""
n = self.n
level = set()
for i, v in changes:
if not 0 <= i < n:
raise IndexError(i)
self.tree[n + i] = v # @line L4
level.add((n + i) // 2)
while level: # @line L5
for h in sorted(level):
self.tree[h] = self.op(self.tree[2 * h], self.tree[2 * h + 1]) # @line L6
level = {h // 2 for h in level if h > 1} # @line L7
def aggregate(self):
return self.tree[1] # @line L8
def prefix(self, i: int):
"""a[0] op ... op a[i], with at most log2(n) calls of op."""
h = self.n + i # @line L9
acc = self.tree[h]
while h > 1: # @line L10
if h & 1: # h is a right child: its left sibling is all before i
acc = self.op(self.tree[h - 1], acc) # @line L11
h //= 2
return acc
def suffix(self, j: int):
"""a[j] op ... op a[n-1], with at most log2(n) calls of op."""
h = self.n + j # @line L12
acc = self.tree[h]
while h > 1:
if not h & 1: # h is a left child: its right sibling is all after j
acc = self.op(acc, self.tree[h + 1]) # @line L13
h //= 2
return acc
def leaves(self) -> list:
return self.tree[self.n:]
class FifoWindow:
"""A FIFO sliding window on a FlatFAT used as a circular buffer.
front is the slot of the oldest value and back the slot of the next value.
The buffer doubles when it is full and halves when it is less than a
quarter full, so it is at most half full right after each resize."""
def __init__(self, op: Callable[[Any, Any], Any], identity: Any, capacity: int = 1):
self._op, self.identity = op, identity
self.fat = FlatFAT(capacity, op, identity)
self.front, self.back, self.count = 0, 0, 0
self.resizes = 0
self.resize_calls = 0 # op calls spent to build the resized trees
self.calls_retired = 0 # op calls of trees that a resize replaced
@property
def calls(self) -> int:
return self.calls_retired + self.fat.calls
def capacity(self) -> int:
return self.fat.n
def _values(self) -> list:
n = self.fat.n
return [self.fat.tree[n + (self.front + k) % n] for k in range(self.count)]
def _resize(self, n: int) -> None:
vals = self._values()
self.calls_retired += self.fat.calls
self.fat = FlatFAT(n, self._op, self.identity)
self.fat.new(vals)
self.resize_calls += self.fat.calls
self.front, self.back = 0, len(vals) % n
self.resizes += 1
def insert(self, v) -> None:
if self.count == self.fat.n: # @line L14
self._resize(2 * self.fat.n)
self.fat.update([(self.back, v)]) # @line L15
self.back = (self.back + 1) % self.fat.n
self.count += 1
def evict(self):
"""Remove and return the oldest value."""
if self.count == 0:
raise IndexError("evict from an empty window")
old = self.fat.tree[self.fat.n + self.front]
self.fat.update([(self.front, self.identity)]) # @line L16
self.front = (self.front + 1) % self.fat.n
self.count -= 1
if self.fat.n > 1 and self.count < self.fat.n // 4: # @line L17
self._resize(self.fat.n // 2)
return old
def query(self):
"""The op of all values in the window, oldest first."""
if self.count == 0:
return self.identity
if self.front < self.back or self.back == 0: # @line L18
return self.fat.aggregate() # the other leaves hold the identity
# inverted: the oldest values are at the end of the array
return self.fat.op(self.fat.suffix(self.front), self.fat.prefix(self.back - 1)) # @line L19
test_flatfat.py 146 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/flatfat/. The authors are listed in prov/6M9DHR.jsonl.
import random
from collections import deque
from functools import reduce
import pytest
from flatfat import FifoWindow, FlatFAT
CONCAT = (lambda a, b: a + b, "") # associative, not commutative
MAX = (lambda a, b: a if b is None else b if a is None else max(a, b), None)
SUM = (lambda a, b: a + b, 0)
def scratch(op, identity, values):
return reduce(op, values, identity)
def ceil_log2(x: float) -> int:
k = 0
while 2**k < x:
k += 1
return k
def test_page_example():
fat = FlatFAT(8, *CONCAT)
fat.new("abcdefgh")
assert fat.calls == 7
assert fat.aggregate() == "abcdefgh"
assert fat.tree[2:4] == ["abcd", "efgh"]
fat.calls = 0
fat.update([(2, "C"), (5, "F")])
assert fat.aggregate() == "abCdeFgh"
assert fat.calls == 5 # 2 (level 1) + 2 (level 2) + 1 (root)
fat.calls = 0
assert fat.prefix(5) == "abCdeF" and fat.calls == 2
fat.calls = 0
assert fat.suffix(2) == "CdeFgh" and fat.calls == 2
fat.calls = 0
assert fat.prefix(4) == "abCde" and fat.calls == 1
@pytest.mark.parametrize("op", [CONCAT, MAX, SUM])
def test_prefix_suffix_and_bounds(op):
rng = random.Random(11)
for n in (1, 2, 4, 8, 16, 64):
L = n.bit_length() - 1
values = [rng.choice("xyz") if op is CONCAT else rng.randint(-9, 9) for _ in range(n)]
fat = FlatFAT(n, *op)
fat.new(values)
assert fat.calls == n - 1
for i in range(n):
fat.calls = 0
assert fat.prefix(i) == scratch(op[0], op[1], values[: i + 1])
assert fat.calls <= L
fat.calls = 0
assert fat.suffix(i) == scratch(op[0], op[1], values[i:])
assert fat.calls <= L
assert fat.aggregate() == scratch(op[0], op[1], values)
def test_update_bound():
"""m distinct writes cost at most m*r + m - 1 <= m(1 + r) calls, r = ceil(log2(n/m))."""
rng = random.Random(7)
for n in (2, 8, 32, 128):
fat = FlatFAT(n, *CONCAT)
values = [rng.choice("pq") for _ in range(n)]
fat.new(values)
for _ in range(40):
m = rng.randint(1, n)
pos = rng.sample(range(n), m)
changes = [(i, rng.choice("pqr")) for i in pos]
for i, v in changes:
values[i] = v
fat.calls = 0
fat.update(changes)
r = ceil_log2(n / m)
assert fat.calls <= m * r + m - 1 <= m * (1 + r)
assert fat.aggregate() == "".join(values)
assert fat.leaves() == values
def test_update_bound_is_tight():
for n in (4, 16, 64):
m = 1
while m <= n:
fat = FlatFAT(n, *SUM)
fat.new([0] * n)
fat.calls = 0
fat.update([(k * (n // m), 1) for k in range(m)])
assert fat.calls == m * ceil_log2(n / m) + m - 1
m *= 2
@pytest.mark.parametrize("op", [CONCAT, MAX, SUM])
def test_fifo_window_matches_scratch(op):
rng = random.Random(2015)
for _ in range(15):
w = FifoWindow(*op)
window = deque()
ops = 0
top = 1
for _ in range(300):
if window and rng.random() < 0.48:
assert w.evict() == window.popleft()
else:
v = rng.choice("abcde") if op is CONCAT else rng.randint(-20, 20)
w.insert(v)
window.append(v)
ops += 1
top = max(top, w.capacity())
assert w.count == len(window)
assert w.capacity() == 1 or len(window) >= w.capacity() // 4
before = w.calls
assert w.query() == scratch(op[0], op[1], window)
assert w.calls - before <= 2 * (w.capacity().bit_length() - 1) + 1
# every resize to capacity c costs c - 1 calls and is paid for by
# at least c/4 operations since the previous resize
assert w.resize_calls <= 4 * ops
def test_sliding_window_of_fixed_size():
"""The classic use: a count-based window of the last 5 values."""
rng = random.Random(3)
w = FifoWindow(*MAX)
values = [rng.randint(0, 99) for _ in range(200)]
for k, v in enumerate(values):
w.insert(v)
if w.count > 5:
w.evict()
assert w.query() == max(values[max(0, k - 4): k + 1])
def test_errors():
with pytest.raises(ValueError):
FlatFAT(6, *SUM)
with pytest.raises(ValueError):
FlatFAT(2, *SUM).new([1, 2, 3])
with pytest.raises(IndexError):
FlatFAT(2, *SUM).update([(2, 1)])
with pytest.raises(IndexError):
FifoWindow(*SUM).evict()
assert FifoWindow(*SUM).query() == 0
History
Arasu and Widom (2004) kept precomputed partial aggregates over intervals of the window to share work between sliding-window aggregates with different ranges. Tangwongsan, Hirzel, Schneider and Wu (2015) gave FlatFAT as a general structure for any associative operator, stored it in a flat array, gave exact operator counts, and added the circular buffer with resizing for windows whose size changes over time. The same group later gave DABA (2017) for FIFO windows with worst-case calls, and FiBA (2019) for out-of-order windows.
References
- Kanat Tangwongsan, Martin Hirzel, Scott Schneider and Kun-Lung Wu, General incremental sliding-window aggregation, PVLDB 8(7), 2015, pages 702 to 713, Section 4 (the FlatFAT layout, Theorem 4.1 with O(m + m log(n/m)) time and O(n) space, and Theorem 4.2 with the exact operator counts of new, update, prefix, suffix and aggregate), Section 5.1 (the circular buffer, the query suffix(F) and prefix(B) of an inverted buffer, and the resizing rule), Section 5.2 (windows that are not FIFO), Section 6 (the experiments)
- Kanat Tangwongsan, Martin Hirzel and Scott Schneider, Optimal and general out-of-order sliding-window aggregation, PVLDB 12(10), 2019, pages 1167 to 1180, the FiBA tree for out-of-order insertions and evictions, which the same authors give as the successor for windows that are not in order (general locator)
- Resource sharing in continuous sliding-window aggregates, the earlier tree of partial aggregates that FlatFAT is compared with (general locator; the page numbers are not confirmed here)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 6M9DHR Edit this page History Report an error Markdown