Algorithmadvanced
Bottom-up cube computation (BUC)
Also called BUC, iceberg cube computation.
Compute an iceberg cube from the group-by ALL toward more specific group-bys, and skip each partition whose row count is below the threshold.
- Time
- O(2^D n (log n + q)) worstO(D n log n) best
- Space
- Θ(n + D) extra
- Where
- D = the number of cube dimensions; minsup = the threshold on COUNT(*); n = the number of input rows; q = the number of aggregates
- Model
- Word RAM
- Properties
- deterministicexactnot in placeofflinerecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Kevin Beyer, Raghu Ramakrishnan, 1999
Bottom-up cube computation (BUC) computes an iceberg cube: the cells of the data cube whose group holds at least rows, which is CUBE with HAVING COUNT(*) >= minsup. It starts with the cell where every dimension is ALL, sorts the rows on one more dimension, and splits them into blocks with the same value. It goes on only into blocks that hold at least rows, because a block that is too small cannot have a qualifying cell below it. Earlier methods such as PipeSort and PipeHash go the other way, from the finest group-by to coarser ones, so they cannot skip a fine cell that is too small.
In plain words
A shop wants totals for every mix of product, city and year, but only where at least three sales happened. You start with one pile that holds every sale and write its total. Then you split the pile by product. A product pile with fewer than three sales cannot give a mix with three sales, so you put it away at once. For each big product pile, you split it by city, then by year, and write the totals of the piles that are big enough. When the product splits are done, you split the full pile by city, and then by year, in the same way. Each mix is reached by one path, so no total is written twice.
The problem
The input is a relation of rows, cube dimensions , aggregates , and a threshold . A cell is a tuple where each is a value of or the marker ALL. Its group is the set of rows that agree with on every dimension where is not ALL. The output is every cell with , with of . With , it is the full CUBE of Gray et al. without empty cells. A null is a value like any other here, as in SQL GROUP BY, and is different from ALL.
The cost model is the word RAM, with the rows in memory. It counts row operations, and does not count the output.
The algorithm
is a working copy of the rows, and is a global tuple of entries. A call works on a range of that holds the rows of the current cell.
BUC(R, minsup) ▷ R has n rows and D dimensions- 1
X ← a copy of the rows of R; cell ← (ALL, ..., ALL) - 2
if n ≥ minsup then BUC-REC(0, n, 1) BUC-REC(lo, hi, d0) ▷ X[lo .. hi - 1] are the rows of cell- 3
output cell with f_1, ..., f_q of X[lo .. hi - 1] - 4
for d ← d0 to D do - 5
sort X[lo .. hi - 1] on dimension d ▷ counting sort when A_d has few values - 6
i ← lo - 7
while i < hi do - 8
j ← i + 1; while j < hi and X[j].A_d = X[i].A_d do j ← j + 1 - 9
if j - i ≥ minsup then ▷ a smaller block is skipped - 10
cell[d] ← X[i].A_d; BUC-REC(i, j, d + 1); cell[d] ← ALL - 11
i ← j
A call only fixes dimensions after the last one its cell fixes, so the dimensions of each cell are fixed in increasing order. The inner calls of line L10 only reorder the rows inside their block, so the blocks of line L8 stay correct while the loop of line L7 runs. The next value of sorts the whole range again.
Example
The relation has 8 sales (product, city, year, amount): (tea, Hanoi, 2023, 4), (tea, Hue, 2023, 3), (coffee, Hanoi, 2023, 5), (tea, Hanoi, 2024, 2), (coffee, Hanoi, 2024, 6), (coffee, Hue, 2024, 1), (tea, Hanoi, 2024, 7), (juice, Hue, 2023, 8). The cube dimensions are product, city and year, the aggregates are COUNT(*) and SUM(amount), and .
| call | blocks on the next dimensions | cells output |
|---|---|---|
| (ALL, ALL, ALL) | product: coffee 3, juice 1 (skip), tea 4; city: Hanoi 5, Hue 3; year: 2023 4, 2024 4 | (ALL, ALL, ALL): 8, 36 |
| (coffee, ALL, ALL) | city: Hanoi 2, Hue 1; year: 2023 1, 2024 2 (all skip) | (coffee, ALL, ALL): 3, 12 |
| (tea, ALL, ALL) | city: Hanoi 3, Hue 1 (skip); year: 2023 2, 2024 2 (skip) | (tea, ALL, ALL): 4, 16 |
| (tea, Hanoi, ALL) | year: 2023 1, 2024 2 (skip) | (tea, Hanoi, ALL): 3, 13 |
| (ALL, Hanoi, ALL) | year: 2023 2 (skip), 2024 3 | (ALL, Hanoi, ALL): 5, 24 |
| (ALL, Hanoi, 2024) | none | (ALL, Hanoi, 2024): 3, 15 |
| (ALL, Hue, ALL) | year: 2023 2, 2024 1 (skip) | (ALL, Hue, ALL): 3, 12 |
| (ALL, ALL, 2023) | none | (ALL, ALL, 2023): 4, 20 |
| (ALL, ALL, 2024) | none | (ALL, ALL, 2024): 4, 16 |
The iceberg cube has 9 cells, and 13 blocks are skipped. The full cube of this relation has 29 non-empty cells, out of possible ones. With , BUC sorts each row times, for 56 row sorts. With it sorts 49.
Correctness
The key fact is a lemma about one call. Let a call run with a cell that fixes a set of dimensions, all before , and let hold exactly , with . Then the call outputs once each cell that agrees with on , fixes for some , and has , and no other cell. The proof is by induction on . Line L3 outputs itself ( empty). For not empty, let be its smallest dimension: the block of line L8 for the value holds restricted to , and the induction applies to the call on it. If that block is smaller than , then is a subset of the block, so too, and skipping it loses nothing. This is the monotone property of COUNT that the pruning needs. Since is fixed by , each is reached by exactly one path. The top call of line L2 has empty, so the output is the whole iceberg cube. The full proof is in the proof file.
Proof: BUC outputs each cell of the iceberg cube exactly oncefull
Number the dimensions . For a cell , let be the set of dimensions with , and let be the multiset of rows of that agree with on . The iceberg cube is the set of cells with , each with the aggregates of . We write for the largest element of a set of dimensions, with .
Lemma (monotone count). If agrees with on and , then , so .
Proof. A row of agrees with on , hence on , where and agree.
Lemma (blocks). At line L8, the range holds exactly the rows of whose value on dimension is .
Proof. Line L5 sorts the range on , so equal values of are adjacent. A call of line L10 for an earlier block only permutes the rows inside that block, so the rows after it are not moved, and the earlier blocks keep their sets of rows. The scan of line L8 starts at the first row of a run of equal values and stops at its end.
Lemma (one call). Consider a call where the global cell is , , holds exactly , and . The call outputs exactly the cells such that
- agrees with on ,
- for some , and
- ,
each exactly once, with the aggregates of . When the call returns, the global cell is again and holds the same multiset of rows.
Proof. By induction on . Call the set of cells that satisfy 1 to 3 the target set of the call.
Line L3 outputs with the aggregates of . This is the target cell with , which is in the target set by the assumption .
Every other target cell has a non-empty , with a smallest element . In the loop of line L4 at this , let . Every row of has and lies in by the monotone count lemma. So there is a block for at line L8, and by the blocks lemma it holds exactly , where is with . Since and they agree there, , so line L9 makes the call with the global cell . This call satisfies the assumptions of the lemma: , its range holds , and . The cell is in its target set, with . By induction, is output in that call.
Conversely, every cell output by the call is either at line L3 or a cell output by an inner call at line L10 for some and . By induction, such a cell agrees with on , has with , and has enough rows. It is in the target set of the call, with .
Uniqueness: a target cell with empty is and is output only at line L3, since every inner call outputs cells that fix one more dimension. A target cell with not empty is output only in the inner call for and : an inner call for another fixes , and an inner call for another has a different value at . That inner call outputs it once, by induction.
The cell is restored by the last assignment of line L10, and the range keeps its multiset because sorting and the inner calls only permute it.
Theorem. BUC outputs every cell of exactly once, with its aggregates, and no other cell.
Proof. If , then by the monotone count lemma every cell has , so is empty, and line L2 makes no call. Otherwise, line L2 calls with , , and holding . The lemma applies with , and its target set is , since every set of dimensions is a subset of .
Sorting work. With , the lemma shows that BUC makes one call for each non-empty cell. The call for a cell with sorts its rows once for each with , which is times. Each row lies in exactly one cell for each . So each row is sorted times. The sets with number , so the sum is . For a larger , the calls are a subset of these.
Complexity
- Sorting work. With , every row is sorted exactly times. A row lies in one cell of each of the group-bys, and the call of a cell that fixes sorts its rows on the dimensions after , with . The sum of over all is . A larger can only remove calls.
- Time. With a comparison sort, the sorts cost in the worst case, and the aggregates cost per row per cell, at most . With a counting sort on a dimension with few values, a sort is linear in its range plus the number of values. When no value of any dimension occurs times, only the top call runs, and the cost is .
- Output. The full cube has at most cells for dimensions with values each, and at most non-empty cells. The iceberg condition can make the output much smaller than both.
- Space. BUC needs the copy and a recursion depth of at most calls. It does not keep any group-by in memory to compute another one.
Properties
- Depth-first order. The output comes cell by cell in the order of the calls, not group-by by group-by. A consumer that wants one group-by at a time must collect them.
- Pruning needs a monotone condition. COUNT(*) minsup works because the count of a cell is at most the count of its block. SUM of non-negative values works for the same reason. AVG does not, because a small cell can have a larger average than its block.
- Each cell from its rows. Every cell is computed from its own rows, so a holistic aggregate such as MEDIAN works with no extra state. The price is that no group-by is computed from a smaller parent result.
- Deterministic. The output set does not depend on how the sort breaks ties.
Variants and improvements
- One-row blocks. A block of one row gives the same aggregates for all its cells below, so a system can write them all at once and stop the recursion there.
- Order of the dimensions. Putting the dimension with the most values first makes the blocks small soon, so the pruning starts early. This is a heuristic.
- PipeSort. Agarwal et al. compute the full cube from the finest group-by down. Group-bys that are prefixes of one sort order share one sort, and each group-by is computed from a parent with more attributes. This saves sorts for a dense cube, but it cannot use an iceberg condition, because a fine cell that fails the condition is still needed for the coarser cells.
- PipeHash. It is the same idea with hash tables, computing several smaller group-bys from one parent result in memory.
- Disk. If the rows do not fit in memory, the input is first split on one dimension into partitions that fit, and BUC runs on each.
When to use it
Use BUC for a sparse cube with many dimensions, where most cells are small, or when only cells with a minimum count are wanted. For a dense cube with few dimensions and no threshold, the top-down methods that share sorts or compute a group-by from a parent result can do less work.
Pitfalls
- A non-monotone condition. Pruning on AVG, or on SUM with negative values, drops cells that should be in the output.
- Null against ALL. A null in a dimension is a group of its own. Using null as the ALL marker merges it with the subtotal row. SQL keeps them apart with the
GROUPINGfunction. - Empty input. SQL CUBE on an empty input gives one row for (ALL, ..., ALL) with COUNT 0. Any removes that row, so BUC outputs nothing.
- Too many cells. With and large, the output can approach rows even when the input is small.
Implementations
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/bottom-up-cube/. The authors are listed in prov/78FNHM.jsonl.
"""Bottom-up cube computation (BUC) of an iceberg cube.
The input is a list of rows (tuples), the cube dimensions (column positions)
and a list of aggregates. The answer is every cell of the data cube whose
group holds at least minsup rows: for each subset S of the dimensions and each
value combination of S that occurs, a row with the values of S, the marker
ALL in the other dimensions, and the aggregates of the rows of that group.
BUC starts with the cell (ALL, ..., ALL) of the whole input. It sorts the
rows of a cell on one more dimension, splits them into blocks of equal value,
and recurses only into blocks of at least minsup rows. COUNT(*) of a block
can only shrink when more dimensions are fixed, so a small block has no
qualifying cell below it.
SQL semantics: a null value of a dimension is a value like any other and forms
its own group; count_star counts every row; the other aggregates skip nulls;
sum, avg, min and max of no non-null value give None.
"""
from collections.abc import Sequence
from fractions import Fraction
from numbers import Number
class _All:
"""The ALL marker of a dimension that is not grouped in a cell."""
__slots__ = ()
def __repr__(self) -> str:
return "ALL"
ALL = _All()
AGG_FUNCS = ("count_star", "count", "sum", "avg", "min", "max")
def _vkey(v: object) -> tuple:
"""Sort order of one dimension value: None first, then numbers, then strings."""
if v is None:
return (0, 0)
if isinstance(v, Number):
return (1, v)
if isinstance(v, str):
return (2, v)
return (3, repr(v))
def _agg(func: str, vals: list) -> object:
"""One SQL aggregate over the values of a group. count_star counts all."""
if func == "count_star":
return len(vals)
nn = [v for v in vals if v is not None]
if func == "count":
return len(nn)
if not nn:
return None
if func == "sum":
return sum(nn)
if func == "avg":
total = sum(nn)
if all(isinstance(v, (int, Fraction)) for v in nn):
return Fraction(total, 1) / len(nn)
return total / len(nn)
if func == "min":
return min(nn)
return max(nn)
def buc(rows: Sequence[tuple], dims: Sequence[int], aggs: Sequence[tuple],
minsup: int = 1, stats: dict | None = None) -> list:
"""Return the cells of the iceberg cube, in the depth-first order of BUC.
rows are tuples; dims are the positions of the D cube dimensions; aggs is a
list of (func, column), with column None for count_star. Each output row is
a tuple of D dimension values (ALL where a dimension is not grouped)
followed by the aggregates. A cell is output when its group has at least
minsup >= 1 rows. If stats is a dict, it gets "calls" (the recursive calls,
one per output cell), "sorted" (the rows sorted, summed over all sorts) and
"pruned" (the blocks skipped because they are smaller than minsup).
"""
if minsup < 1:
raise ValueError("minsup must be at least 1")
for f, _ in aggs:
if f not in AGG_FUNCS:
raise ValueError("unknown aggregate %r" % (f,))
dims = list(dims)
D = len(dims)
X = list(rows) # @line L1
cell = [ALL] * D # @line L1
out: list = []
counters = {"calls": 0, "sorted": 0, "pruned": 0}
def emit(lo: int, hi: int) -> None:
group = X[lo:hi]
vals = [_agg(f, [None if c is None else r[c] for r in group]) for f, c in aggs]
out.append(tuple(cell) + tuple(vals))
def rec(lo: int, hi: int, d0: int) -> None:
counters["calls"] += 1
emit(lo, hi) # @line L3
for d in range(d0, D): # @line L4
col = dims[d]
X[lo:hi] = sorted(X[lo:hi], key=lambda r: _vkey(r[col])) # @line L5
counters["sorted"] += hi - lo
i = lo # @line L6
while i < hi: # @line L7
v = X[i][col]
j = i + 1 # @line L8
while j < hi and X[j][col] == v: # @line L8
j += 1
if j - i >= minsup: # @line L9
cell[d] = v # @line L10
rec(i, j, d + 1) # @line L10
cell[d] = ALL # @line L10
else:
counters["pruned"] += 1
i = j # @line L11
if len(X) >= minsup: # @line L2
rec(0, len(X), 0) # @line L2
if stats is not None:
stats.update(counters)
return out
def cube_size(cards: Sequence[int]) -> int:
"""The number of cells of the full cube when every value combination occurs: prod(C_i + 1)."""
n = 1
for c in cards:
n *= c + 1
return n
dbrel.py 522 lines
# SPDX-License-Identifier: MIT
# Shared helper of the databases pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Naive relations, operators by definition, SQL three-valued logic and a page-counting disk.
This is the reference that the tests of the databases pages compare against.
Every operator here follows its definition directly, with nested loops and no
index, hash table or sort of the input. Do not use it as a fast engine.
Relations
Relation(schema, rows, mode) holds a tuple of distinct attribute names and
a collections.Counter from tuples to positive counts. mode is "bag" (the
default, SQL semantics) or "set" (relational theory); in set mode every
count is 1. rows may be an iterable of tuples (duplicates add up) or a
mapping from tuples to counts. Two relations are equal when they have the
same attributes (in any column order) and the same count for each tuple.
The mode is not compared.
Operators (each returns a new Relation in the mode of its input)
select(rel, pred) keeps a row only when pred(row) is True
where(rel, pred) the same as select (the SQL WHERE filter)
project(rel, attrs) bag: counts add up; set: duplicates removed
rename(rel, mapping) mapping is {old: new}
union(r, s) bag: UNION ALL (counts add); set: union
difference(r, s) bag: monus max(0, m - n); set: r - s
intersection(r, s) bag: min(m, n); set: intersection
product(r, s) attributes must be disjoint; counts multiply
natural_join(r, s) nested loops on the common attributes
theta_join(r, s, pred) select(product(r, s), pred)
semijoin(r, s), antijoin(r, s)
distinct(rel) every count becomes 1
aggregate(rel, group_attrs, aggs)
aggs is a list of (func, attr, out) with func in
count_star, count, count_distinct, sum, avg, min, max
A predicate receives the row as a dict from attribute name to value. It may
return True, False or None (UNKNOWN). Only True keeps the row.
Nulls
NULL is None. Joins follow SQL: a common attribute that is None in either
row never matches. aggregate follows SQL: GROUP BY puts all nulls of a
column in one group, every aggregate except count_star skips nulls, and
sum, avg, min and max of no non-null value give None while count gives 0.
With no grouping attributes, aggregate returns one row even for an empty
input, as SQL does.
Expressions
evaluate(expr, db, mode) evaluates a tree of nested tuples:
("scan", name)
("select", pred, e) ("project", attrs, e)
("rename", mapping, e) ("distinct", e)
("union", e1, e2) ("difference", e1, e2)
("intersection", e1, e2) ("product", e1, e2)
("join", e1, e2) ("theta_join", pred, e1, e2)
("semijoin", e1, e2) ("antijoin", e1, e2)
("aggregate", group_attrs, aggs, e)
db maps a name to a Relation. Each scanned relation is first put in mode.
Three-valued logic
tv_and, tv_or and tv_not are the strong Kleene connectives on True, False
and None. cmp3(op, x, y) compares with op in =, <>, !=, <, <=, >, >= and
returns None when x or y is None.
Disk
Disk counts page reads and writes. load(rows, per_page) puts an existing
input on the disk without counting it. paginate(rows, per_page) splits a
list of rows into pages.
Random data
random_relation(rng, schema, n, domain, mode, null_rate) draws n rows.
"""
from collections import Counter
from collections.abc import Callable, Hashable, Iterable, Mapping, Sequence
from fractions import Fraction
from numbers import Number
import random
BAG = "bag"
SET = "set"
MODES = (BAG, SET)
# ---------------------------------------------------------------- ordering
def value_key(v: object) -> tuple:
"""A total order on the values of one column: None first, then numbers, then strings."""
if v is None:
return (0, 0)
if isinstance(v, Number):
return (1, v)
if isinstance(v, str):
return (2, v)
if isinstance(v, tuple):
return (3, tuple(value_key(x) for x in v))
return (4, repr(v))
def row_key(t: Sequence) -> tuple:
"""A total order on tuples that tolerates None. Use it to sort rows in tests."""
return tuple(value_key(v) for v in t)
# ---------------------------------------------------------------- relations
class Relation:
"""A relation: a schema (tuple of names), a Counter of tuples and a mode."""
__slots__ = ("schema", "rows", "mode")
def __init__(self, schema: Sequence[str], rows: Iterable | Mapping = (), mode: str = BAG) -> None:
if mode not in MODES:
raise ValueError("mode must be 'bag' or 'set'")
schema = tuple(schema)
if len(set(schema)) != len(schema):
raise ValueError("duplicate attribute in schema %r" % (schema,))
counts: Counter = Counter()
items = rows.items() if isinstance(rows, Mapping) else ((t, 1) for t in rows)
for t, c in items:
t = tuple(t)
if len(t) != len(schema):
raise ValueError("tuple %r does not fit schema %r" % (t, schema))
if c < 0:
raise ValueError("negative count for %r" % (t,))
if c:
counts[t] += c
if mode == SET:
counts = Counter({t: 1 for t in counts})
self.schema = schema
self.rows = counts
self.mode = mode
def index(self, attr: str) -> int:
return self.schema.index(attr)
def reorder(self, schema: Sequence[str]) -> "Relation":
"""The same relation with its columns in the order of schema."""
schema = tuple(schema)
if sorted(schema) != sorted(self.schema):
raise ValueError("schemas %r and %r differ" % (self.schema, schema))
pos = [self.schema.index(a) for a in schema]
return Relation(schema, {tuple(t[i] for i in pos): c for t, c in self.rows.items()}, self.mode)
def with_mode(self, mode: str) -> "Relation":
return Relation(self.schema, self.rows, mode)
def as_dict(self, t: Sequence) -> dict:
return dict(zip(self.schema, t))
def sorted_rows(self) -> list:
"""Every tuple, repeated by its count, in row_key order."""
out = []
for t in sorted(self.rows, key=row_key):
out.extend([t] * self.rows[t])
return out
def __iter__(self):
return iter(self.sorted_rows())
def __len__(self) -> int:
return sum(self.rows.values())
def __eq__(self, other: object) -> bool:
if not isinstance(other, Relation):
return NotImplemented
if sorted(self.schema) != sorted(other.schema):
return False
return self.rows == other.reorder(self.schema).rows
def __repr__(self) -> str:
body = ", ".join("%r: %d" % (t, self.rows[t]) for t in sorted(self.rows, key=row_key))
return "Relation(%r, {%s}, %r)" % (self.schema, body, self.mode)
def _mode2(r: Relation, s: Relation) -> str:
if r.mode != s.mode:
raise ValueError("operands have modes %r and %r" % (r.mode, s.mode))
return r.mode
def _same_schema(r: Relation, s: Relation) -> Relation:
"""s with its columns in the order of r; the attribute sets must be equal."""
if sorted(r.schema) != sorted(s.schema):
raise ValueError("union-incompatible schemas %r and %r" % (r.schema, s.schema))
return s.reorder(r.schema)
# ---------------------------------------------------------------- three-valued logic
def tv_and(a: bool | None, b: bool | None) -> bool | None:
if a is False or b is False:
return False
if a is None or b is None:
return None
return True
def tv_or(a: bool | None, b: bool | None) -> bool | None:
if a is True or b is True:
return True
if a is None or b is None:
return None
return False
def tv_not(a: bool | None) -> bool | None:
return None if a is None else not a
_CMP = {
"=": lambda x, y: x == y,
"<>": lambda x, y: x != y,
"!=": lambda x, y: x != y,
"<": lambda x, y: x < y,
"<=": lambda x, y: x <= y,
">": lambda x, y: x > y,
">=": lambda x, y: x >= y,
}
def cmp3(op: str, x: object, y: object) -> bool | None:
"""SQL comparison: None (UNKNOWN) if either side is NULL."""
if op not in _CMP:
raise ValueError("unknown comparison %r" % (op,))
if x is None or y is None:
return None
return bool(_CMP[op](x, y))
def is_true(v: bool | None) -> bool:
"""The WHERE test: only True passes; False and None (UNKNOWN) do not."""
return v is True
# ---------------------------------------------------------------- operators
def select(rel: Relation, pred: Callable[[dict], bool | None]) -> Relation:
out = {t: c for t, c in rel.rows.items() if pred(rel.as_dict(t)) is True}
return Relation(rel.schema, out, rel.mode)
where = select
def project(rel: Relation, attrs: Sequence[str]) -> Relation:
attrs = tuple(attrs)
pos = [rel.index(a) for a in attrs]
out: Counter = Counter()
for t, c in rel.rows.items():
out[tuple(t[i] for i in pos)] += c
return Relation(attrs, out, rel.mode)
def rename(rel: Relation, mapping: Mapping[str, str]) -> Relation:
for a in mapping:
if a not in rel.schema:
raise ValueError("no attribute %r to rename" % (a,))
return Relation(tuple(mapping.get(a, a) for a in rel.schema), rel.rows, rel.mode)
def union(r: Relation, s: Relation) -> Relation:
mode = _mode2(r, s)
s = _same_schema(r, s)
out = Counter(r.rows)
out.update(s.rows)
return Relation(r.schema, out, mode)
def difference(r: Relation, s: Relation) -> Relation:
mode = _mode2(r, s)
s = _same_schema(r, s)
out = {t: max(0, c - s.rows.get(t, 0)) for t, c in r.rows.items()}
return Relation(r.schema, out, mode)
def intersection(r: Relation, s: Relation) -> Relation:
mode = _mode2(r, s)
s = _same_schema(r, s)
out = {t: min(c, s.rows.get(t, 0)) for t, c in r.rows.items()}
return Relation(r.schema, out, mode)
def product(r: Relation, s: Relation) -> Relation:
mode = _mode2(r, s)
common = [a for a in r.schema if a in s.schema]
if common:
raise ValueError("product needs disjoint schemas; common: %r" % (common,))
out: Counter = Counter()
for t, c in r.rows.items():
for u, d in s.rows.items():
out[t + u] += c * d
return Relation(r.schema + s.schema, out, mode)
def _matches(r: Relation, s: Relation, t: tuple, u: tuple, common: Sequence[str]) -> bool:
for a in common:
x, y = t[r.index(a)], u[s.index(a)]
if x is None or y is None or x != y:
return False
return True
def natural_join(r: Relation, s: Relation) -> Relation:
"""Nested loops over both inputs. With no common attribute it is the product."""
mode = _mode2(r, s)
common = [a for a in r.schema if a in s.schema]
rest = [a for a in s.schema if a not in common]
rest_pos = [s.index(a) for a in rest]
out: Counter = Counter()
for t, c in r.rows.items():
for u, d in s.rows.items():
if _matches(r, s, t, u, common):
out[t + tuple(u[i] for i in rest_pos)] += c * d
return Relation(r.schema + tuple(rest), out, mode)
def theta_join(r: Relation, s: Relation, pred: Callable[[dict], bool | None]) -> Relation:
return select(product(r, s), pred)
def semijoin(r: Relation, s: Relation) -> Relation:
"""Rows of r (with their counts) that join with at least one row of s."""
_mode2(r, s)
common = [a for a in r.schema if a in s.schema]
out = {t: c for t, c in r.rows.items() if any(_matches(r, s, t, u, common) for u in s.rows)}
return Relation(r.schema, out, r.mode)
def antijoin(r: Relation, s: Relation) -> Relation:
"""Rows of r (with their counts) that join with no row of s."""
_mode2(r, s)
common = [a for a in r.schema if a in s.schema]
out = {t: c for t, c in r.rows.items() if not any(_matches(r, s, t, u, common) for u in s.rows)}
return Relation(r.schema, out, r.mode)
def distinct(rel: Relation) -> Relation:
return Relation(rel.schema, {t: 1 for t in rel.rows}, rel.mode)
AGG_FUNCS = ("count_star", "count", "count_distinct", "sum", "avg", "min", "max")
def _avg(vals: list) -> object:
total = sum(vals)
if all(isinstance(v, (int, Fraction)) for v in vals):
return Fraction(total, 1) / len(vals)
return total / len(vals)
def agg_value(func: str, vals: list) -> object:
"""One SQL aggregate over a list of column values (with repeats). count_star counts all."""
if func == "count_star":
return len(vals)
nn = [v for v in vals if v is not None]
if func == "count":
return len(nn)
if func == "count_distinct":
seen: list = []
for v in nn:
if v not in seen:
seen.append(v)
return len(seen)
if not nn:
return None
if func == "sum":
return sum(nn)
if func == "avg":
return _avg(nn)
if func == "min":
return min(nn)
if func == "max":
return max(nn)
raise ValueError("unknown aggregate %r" % (func,))
def aggregate(rel: Relation, group_attrs: Sequence[str], aggs: Sequence[tuple]) -> Relation:
"""gamma_{G; f(A) -> B}(rel) by definition.
aggs is a list of (func, attr, out); attr is ignored for count_star and may
be None. For each distinct group key, in row_key order, the whole input is
scanned. Each result row has count 1 in either mode.
"""
group_attrs = tuple(group_attrs)
gpos = [rel.index(a) for a in group_attrs]
for func, attr, _ in aggs:
if func not in AGG_FUNCS:
raise ValueError("unknown aggregate %r" % (func,))
if func != "count_star":
rel.index(attr)
keys: list = []
for t in rel.rows:
k = tuple(t[i] for i in gpos)
if k not in keys:
keys.append(k)
if not group_attrs and not keys:
keys = [()]
out: Counter = Counter()
for k in sorted(keys, key=row_key):
row = list(k)
for func, attr, _ in aggs:
vals: list = []
for t, c in rel.rows.items():
if tuple(t[i] for i in gpos) == k:
vals.extend([None if func == "count_star" else t[rel.index(attr)]] * c)
row.append(agg_value(func, vals))
out[tuple(row)] = 1
schema = group_attrs + tuple(o for _, _, o in aggs)
return Relation(schema, out, rel.mode)
# ---------------------------------------------------------------- evaluation
def evaluate(expr: tuple, db: Mapping[str, Relation], mode: str = BAG) -> Relation:
"""Evaluate an expression tree of nested tuples over db, in mode."""
if mode not in MODES:
raise ValueError("mode must be 'bag' or 'set'")
op = expr[0]
ev = lambda e: evaluate(e, db, mode)
if op == "scan":
return db[expr[1]].with_mode(mode)
if op == "select":
return select(ev(expr[2]), expr[1])
if op == "project":
return project(ev(expr[2]), expr[1])
if op == "rename":
return rename(ev(expr[2]), expr[1])
if op == "distinct":
return distinct(ev(expr[1]))
if op == "aggregate":
return aggregate(ev(expr[3]), expr[1], expr[2])
if op == "theta_join":
return theta_join(ev(expr[2]), ev(expr[3]), expr[1])
binary = {
"union": union, "difference": difference, "intersection": intersection,
"product": product, "join": natural_join, "semijoin": semijoin, "antijoin": antijoin,
}
if op in binary:
return binary[op](ev(expr[1]), ev(expr[2]))
raise ValueError("unknown operator %r" % (op,))
# ---------------------------------------------------------------- disk
def paginate(rows: Sequence, per_page: int) -> list:
"""Split rows into pages of per_page rows; the last page may be shorter."""
if per_page < 1:
raise ValueError("per_page must be at least 1")
rows = list(rows)
return [rows[i:i + per_page] for i in range(0, len(rows), per_page)]
class Disk:
"""Pages on a simulated disk. Each read_page and write_page call costs one I/O."""
def __init__(self) -> None:
self.pages: dict = {}
self.reads = 0
self.writes = 0
self._next = 0
def alloc(self) -> int:
pid = self._next
self._next += 1
self.pages[pid] = ()
return pid
def write_page(self, pid: int, rows: Iterable) -> None:
if pid not in self.pages:
raise KeyError("page %r was not allocated" % (pid,))
self.pages[pid] = tuple(rows)
self.writes += 1
def read_page(self, pid: int) -> list:
self.reads += 1
return list(self.pages[pid])
def free(self, pid: int) -> None:
del self.pages[pid]
def load(self, rows: Sequence, per_page: int) -> list:
"""Store an input file without counting I/O; return its page ids in order."""
ids = []
for page in paginate(rows, per_page):
pid = self.alloc()
self.pages[pid] = tuple(page)
ids.append(pid)
return ids
def io(self) -> int:
return self.reads + self.writes
def reset_counters(self) -> None:
self.reads = 0
self.writes = 0
# ---------------------------------------------------------------- random data
def random_relation(rng: random.Random, schema: Sequence[str], n: int,
domain: int | Sequence | Mapping = 4, mode: str = BAG,
null_rate: float = 0.0) -> Relation:
"""n rows drawn with rng. domain is a size k (values 0 to k - 1), a list of
values, or a dict from attribute to either. Each value is None with
probability null_rate. In set mode duplicates collapse, so there may be
fewer than n rows."""
schema = tuple(schema)
def values(a: str) -> list:
d = domain[a] if isinstance(domain, Mapping) else domain
return list(range(d)) if isinstance(d, int) else list(d)
doms = [values(a) for a in schema]
rows = []
for _ in range(n):
t = []
for d in doms:
if null_rate and rng.random() < null_rate:
t.append(None)
else:
t.append(rng.choice(d))
rows.append(tuple(t))
return Relation(schema, rows, mode)
test_bottom_up_cube.py 135 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bottom-up-cube/. The authors are listed in prov/78FNHM.jsonl.
"""Tests of BUC against the iceberg cube by definition: all 2^D group-bys with dbrel.aggregate."""
import random
from collections import Counter
from itertools import combinations, product
import pytest
import dbrel
from bottom_up_cube import ALL, buc, cube_size
SALES = [
("tea", "Hanoi", 2023, 4), ("tea", "Hue", 2023, 3), ("coffee", "Hanoi", 2023, 5),
("tea", "Hanoi", 2024, 2), ("coffee", "Hanoi", 2024, 6), ("coffee", "Hue", 2024, 1),
("tea", "Hanoi", 2024, 7), ("juice", "Hue", 2023, 8),
]
def reference(rows, ncols, dims, aggs, minsup):
"""Every group-by of every subset of dims, by definition, with HAVING COUNT(*) >= minsup."""
schema = ["c%d" % i for i in range(ncols)]
rel = dbrel.Relation(schema, rows)
spec = [("count_star", None, "n")] + [
(f, None if c is None else schema[c], "a%d" % i) for i, (f, c) in enumerate(aggs)]
out = Counter()
for k in range(len(dims) + 1):
for subset in combinations(range(len(dims)), k):
g = [schema[dims[i]] for i in subset]
res = dbrel.aggregate(rel, g, spec)
for t in res.rows:
if t[len(g)] < minsup:
continue
cell = [ALL] * len(dims)
for pos, i in enumerate(subset):
cell[i] = t[pos]
out[tuple(cell) + t[len(g) + 1:]] += 1
return out
def test_worked_example():
st = {}
got = buc(SALES, [0, 1, 2], [("count_star", None), ("sum", 3)], minsup=3, stats=st)
assert got == [
(ALL, ALL, ALL, 8, 36),
("coffee", ALL, ALL, 3, 12),
("tea", ALL, ALL, 4, 16),
("tea", "Hanoi", ALL, 3, 13),
(ALL, "Hanoi", ALL, 5, 24),
(ALL, "Hanoi", 2024, 3, 15),
(ALL, "Hue", ALL, 3, 12),
(ALL, ALL, 2023, 4, 20),
(ALL, ALL, 2024, 4, 16),
]
assert st == {"calls": 9, "sorted": 49, "pruned": 13}
full = buc(SALES, [0, 1, 2], [("count_star", None)], minsup=1)
assert len(full) == 29
assert len(buc(SALES, [0, 1, 2], [("count_star", None)], minsup=2)) == 16
def test_against_definition_random():
rng = random.Random(1999)
funcs = ["count_star", "count", "sum", "avg", "min", "max"]
for _ in range(150):
D = rng.randint(1, 4)
ncols = D + 1
n = rng.randint(0, 25)
doms = [rng.randint(1, 4) for _ in range(D)]
rows = []
for _ in range(n):
t = [None if rng.random() < 0.15 else rng.randrange(c) for c in doms]
t.append(None if rng.random() < 0.2 else rng.randint(-5, 9))
rows.append(tuple(t))
dims = list(range(D))
rng.shuffle(dims)
aggs = [(f, None if f == "count_star" else D) for f in rng.sample(funcs, rng.randint(1, 4))]
minsup = rng.randint(1, 5)
st = {}
got = buc(rows, dims, aggs, minsup, st)
assert Counter(got) == reference(rows, ncols, dims, aggs, minsup)
assert st["calls"] == len(got)
if minsup == 1:
assert st["sorted"] == n * (2 ** D - 1)
def test_input_is_not_changed():
rows = list(SALES)
buc(rows, [2, 1, 0], [("max", 3)], minsup=2)
assert rows == SALES
def test_full_cube_size():
cards = [2, 3, 2]
rows = [t + (1,) for t in product(*[range(c) for c in cards])]
got = buc(rows, [0, 1, 2], [("count_star", None)], minsup=1)
assert len(got) == cube_size(cards) == 3 * 4 * 3
assert len(set(got)) == len(got)
def test_pruning_is_monotone_and_saves_work():
rng = random.Random(42)
rows = [(rng.randrange(6), rng.randrange(6), i, rng.randrange(3)) for i in range(60)]
dims = [0, 1, 2]
prev = None
work = []
for minsup in range(1, 8):
st = {}
cells = set(buc(rows, dims, [("count_star", None)], minsup, st))
if prev is not None:
assert cells <= prev
prev = cells
work.append(st["sorted"])
assert work == sorted(work, reverse=True)
# Dimension 2 is unique per row, so with minsup = 2 no cell fixes it.
assert all(c[2] is ALL for c in buc(rows, dims, [("count_star", None)], 2))
assert work[1] < work[0]
def test_edge_cases():
assert buc([], [0, 1], [("count_star", None)], minsup=1) == []
one = buc([(1, 2, 5)], [0, 1], [("count_star", None), ("sum", 2)], minsup=1)
assert len(one) == 4 and all(c[2:] == (1, 5) for c in one)
same = [(7, "a", i) for i in range(5)]
cells = buc(same, [0, 1], [("count_star", None), ("avg", 2), ("min", 2)], minsup=5)
assert cells == [(ALL, ALL, 5, 2, 0), (7, ALL, 5, 2, 0), (7, "a", 5, 2, 0), (ALL, "a", 5, 2, 0)]
assert buc(same, [0, 1], [("count_star", None)], minsup=6) == []
nulls = [(None, 1, None), (None, 2, 3), (0, 1, None)]
got = buc(nulls, [0], [("count_star", None), ("count", 2), ("sum", 2)], minsup=1)
assert got == [(ALL, 3, 1, 3), (None, 2, 1, 3), (0, 1, 0, None)]
assert buc(SALES, [], [("count_star", None)], minsup=1) == [(8,)]
with pytest.raises(ValueError):
buc(SALES, [0], [("count_star", None)], minsup=0)
with pytest.raises(ValueError):
buc(SALES, [0], [("median", 3)], minsup=1)
History
Gray et al. defined the CUBE operator in 1996 and 1997. Agarwal et al. (1996) gave PipeSort and PipeHash, which compute all group-bys of a full cube and share work among them. Beyer and Ramakrishnan (1999) turned the order around for sparse and iceberg cubes. In the lattice of group-bys drawn with ALL at the bottom, BUC works upward, from ALL toward the finest group-by.
References
- Kevin Beyer and Raghu Ramakrishnan, Bottom-up computation of sparse and iceberg CUBEs, Proceedings of ACM SIGMOD 1999, 359 to 370, the BUC algorithm and its pruning by minimum support
- Sameet Agarwal, Rakesh Agrawal, Prasad M. Deshpande, Ashish Gupta, Jeffrey F. Naughton, Raghu Ramakrishnan and Sunita Sarawagi, On the computation of multidimensional aggregates, Proceedings of VLDB 1996, 506 to 521, the PipeSort and PipeHash methods
- Jim Gray, Surajit Chaudhuri, Adam Bosworth, Andrew Layman, Don Reichart, Murali Venkatrao, Frank Pellow and Hamid Pirahesh, Data cube, a relational aggregation operator generalizing group-by, cross-tab, and sub-totals, Data Mining and Knowledge Discovery 1(1), 29 to 53 (1997), the CUBE operator and the ALL value
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 | W2 basic |
|
Tag 78FNHM Edit this page History Report an error Markdown