Algorithm Search⌘K

Algorithmadvanced

HRU greedy view selection

Also called Harinarayan-Rajaraman-Ullman algorithm, greedy cube materialization.

Choose views of a data cube lattice one at a time by largest benefit. The greedy benefit is at least (e - 1)/e, about 63 percent, of the optimal benefit, for a fixed number k of views.

Time
O(k n^2) worst
Space
O(n^2) extra
Where
k = the number of views to choose; n = the number of views in the lattice
Properties
deterministicnot exactgreedyiterative
Origin
Venky Harinarayan, Anand Rajaraman, Jeffrey D. Ullman, 1996

The HRU greedy algorithm chooses which views of a data cube to store. Harinarayan, Rajaraman and Ullman gave it in 1996. The possible GROUP BY views form a lattice: a view can answer every view that groups by fewer attributes. A query costs the size of the smallest stored view that can answer it. The algorithm stores the top view, then adds kk more views. Each time it takes the view that lowers the total cost the most. The greedy benefit is at least 1−(1−1/k)k1 - (1 - 1/k)^k times the optimal benefit, and this is more than (e−1)/e≈0.63(e - 1)/e \approx 0.63. The view selection page states the general problem, its budgets and its relation to index selection. This page holds the algorithm itself, the full proof of both bounds of the paper, the examples of the paper, and code.

In plain words

A sales table can be summed by part, by supplier, by customer, or by any group of these. Each of these summaries is a view, and a summary by more columns can produce a summary by fewer columns. The full table can produce all of them. If a summary is not stored, a question about it reads the smallest stored summary that can produce it.

The algorithm starts with only the full table stored. In each round, it looks at each summary that is not stored. It adds up how much work that summary would save, over all the questions it could answer. It stores the one that saves the most, and repeats. Each choice is good now but may not be best for all rounds. Even so, the total saving is always at least about 63 percent of the best possible saving with the same number of summaries.

The problem

The input is a set of views with a top view tt, a relation w⪯vw \preceq v (view ww can be answered from view vv), a size ∣v∣|v| for each view, and a number kk. In the cube on attribute set AA, the views are the subsets of AA, w⪯vw \preceq v means w⊆vw \subseteq v, and t=At = A. In the linear cost model of the paper, answering ww from a stored set SS costs

CS(w)=min⁡{∣u∣:u∈S, w⪯u},C_S(w) = \min\{|u| : u \in S,\ w \preceq u\},

the number of rows of the smallest stored view that can answer it. The top view is always stored. The goal is a set of kk views besides tt that minimizes ∑wCS(w)\sum_w C_S(w), or with query frequencies qwq_w, ∑wqwCS(w)\sum_w q_w C_S(w). The paper shows that this problem is NP-complete even in this simple model, by a reduction from set cover.

The algorithm

The benefit of a view vv for the current set SS is the drop in total cost when vv is added:

B(v,S)=∑w⪯vqwmax⁡(0, CS(w)−∣v∣).B(v, S) = \sum_{w \preceq v} q_w \max\big(0,\ C_S(w) - |v|\big).
  1. GREEDY(views V with top t, sizes |v|, weights q_w, number k)
  2. 1S ← {t}
  3. 2for i ← 1 to k do
  4. 3for each view v not in S, compute B(v, S) = the sum over w ⪯ v of q_w · max(0, C_S(w) - |v|)
  5. 4choose a view v not in S with the largest B(v, S)
  6. 5S ← S ∪ {v}
  7. 6return S - {t}, in the order of choice

The code keeps CS(w)C_S(w) for every view ww and lowers it after each choice, so line L3 never recomputes the minimum over SS. For a space limit instead of a count, the variant picks the view with the largest B(v,S)/∣v∣B(v, S)/|v| in line L4.

Example

This is Example 4.1 of the paper. The lattice has eight views with these sizes: a=100a = 100 (the top), b=50b = 50, c=75c = 75, d=20d = 20, e=30e = 30, f=40f = 40, g=1g = 1, h=10h = 10. View aa answers bb and cc; bb answers dd and ee; cc answers ee and ff; dd answers gg; ee answers gg and hh; ff answers hh; and the relation is transitive. With only aa stored, each of the eight views costs 100, a total of 800. Take k=3k = 3.

view round 1 round 2 round 3
b 250
c 125 50 25
d 160 60 60
e 210 60 50
f 120 70
g 99 49 49
h 90 40 30

In round 1, bb improves itself and the four views below it (dd, ee, gg, hh) from 100 to 50 each, a benefit of 250. In round 2, ff lowers its own cost from 100 to 40 and the cost of hh from 50 (through bb) to 40, a benefit of 60+10=7060 + 10 = 70. In round 3, dd improves itself and gg from 50 to 20, a benefit of 60. The greedy choice is bb, ff and dd, with benefit 250+70+60=380250 + 70 + 60 = 380 and total cost 420. A search over all 35 sets of three views shows that 380 is the best possible, so greedy is optimal here.

Greedy is not always optimal. In Example 4.2 of the paper, the top view has size 200, and three views bb, cc and dd below it have sizes 100, 99 and 100. Four chains of 20 views of size 100 hang below them: bb answers chains 1 and 2, cc chains 2 and 3, dd chains 3 and 4. With k=2k = 2, greedy first takes cc, with benefit 41⋅101=414141 \cdot 101 = 4141, and then bb or dd, with benefit 2100, for a total of 6241. The set {b,d}\{b, d\} has benefit 82⋅100=820082 \cdot 100 = 8200. The ratio is about 0.761, close to the bound 3/43/4 for k=2k = 2.

Correctness

The proof file proves both results of the paper. The core fact is that the total benefit f(X)f(X) of a set XX of views is a monotone submodular function: adding other views can only lower CS(w)C_S(w), so it can only lower the benefit of a view. Then the argument of Nemhauser, Wolsey and Fisher applies. If OO is an optimal set of kk views and GiG_i the greedy set after ii rounds, the views of OO together add at most kk times the best single benefit, so the gap to the optimum shrinks by a factor of at least 1−1/k1 - 1/k in each round. After kk rounds the gap is at most (1−1/k)k(1 - 1/k)^k of the optimum.

Theorem 1 (Theorem 4.1 of the paper). With kk views, Bgreedy≥(1−(1−1/k)k) BoptB_{greedy} \ge (1 - (1 - 1/k)^k)\, B_{opt}, and the bound is tight. For k=2k = 2 it is 3/43/4, and it decreases toward (e−1)/e(e - 1)/e as kk grows.

Theorem 2 (Theorem 4.2 of the paper, as proved here). If greedy picks by benefit per unit space and has used space ss, its benefit is at least 1−1/e1 - 1/e of the best benefit of any set of views with total size at most ss. The same proof works with any query weights.

Proof: The HRU greedy algorithm gets at least 1 - (1 - 1/k)^k of the best benefit of k views, and greedy by benefit per unit space gets at least 1 - 1/e of the best benefit in the space it usesfull

Setting. A finite set VV of views has a top view tt and a relation w⪯vw \preceq v ("ww can be answered from vv"), which is reflexive, transitive, and has w⪯tw \preceq t for every ww. Each view has a size ∣v∣>0|v| > 0 and each query ww a weight qw≥0q_w \ge 0 (1 in the plain model). For a set SS of views with t∈St \in S, the cost of ww is CS(w)=min⁡{∣u∣:u∈S, w⪯u}C_S(w) = \min\{|u| : u \in S,\ w \preceq u\}, which exists because t∈St \in S. The total cost is T(S)=∑wqwCS(w)T(S) = \sum_w q_w C_S(w). For a set XX of views, the benefit is f(X)=T({t})−T({t}∪X)f(X) = T(\{t\}) - T(\{t\} \cup X). The benefit of a view vv for SS is

B(v,S)=∑w⪯vqwmax⁡(0, CS(w)−∣v∣).B(v, S) = \sum_{w \preceq v} q_w \max\big(0,\ C_S(w) - |v|\big).

Line L3 computes this value, and lines L4 and L5 add a view with the largest one.

Lemma 1 (benefit is the gain). For t∈St \in S, T(S)−T(S∪{v})=B(v,S)T(S) - T(S \cup \{v\}) = B(v, S).

Proof. Adding vv changes only the costs of the views w⪯vw \preceq v, and for such ww the new cost is min⁡(CS(w),∣v∣)\min(C_S(w), |v|). The drop is max⁡(0,CS(w)−∣v∣)\max(0, C_S(w) - |v|), and the total drop is the weighted sum of these. □\square

So, for S={t}∪XS = \{t\} \cup X, f(X∪{v})−f(X)=B(v,{t}∪X)f(X \cup \{v\}) - f(X) = B(v, \{t\} \cup X), and the sum of the gains that line L4 records is the benefit of the chosen set.

Lemma 2 (monotone and submodular). If S⊆S′S \subseteq S', then CS′(w)≤CS(w)C_{S'}(w) \le C_S(w) for every ww, B(v,S′)≤B(v,S)B(v, S') \le B(v, S) for every vv, and ff is monotone.

Proof. A minimum over a larger set is not larger. Each term max⁡(0,C(w)−∣v∣)\max(0, C(w) - |v|) is a nondecreasing function of C(w)C(w), so the benefit cannot grow when SS grows. Monotonicity follows from Lemma 1, because each benefit is at least 0. □\square

Lemma 2 says that ff is a monotone submodular function: the gain of a view never grows when other views are added.

Lemma 3 (gain of a set). For t∈St \in S and any set YY of views, T(S)−T(S∪Y)≤∑y∈YB(y,S)T(S) - T(S \cup Y) \le \sum_{y \in Y} B(y, S).

Proof. Add the views of YY one at a time, y1,…,ymy_1, \ldots, y_m. By Lemma 1, the drop in step ii is B(yi,S∪{y1,…,yi−1})B(y_i, S \cup \{y_1, \ldots, y_{i-1}\}), which is at most B(yi,S)B(y_i, S) by Lemma 2. Sum over ii. □\square

Theorem 1 (fixed number of views). Let the greedy algorithm choose kk views with total benefit BgreedyB_{greedy}, and let BoptB_{opt} be the largest benefit of any kk views. Then Bgreedy≥(1−(1−1/k)k)Bopt>(1−1/e) BoptB_{greedy} \ge \big(1 - (1 - 1/k)^k\big) B_{opt} > (1 - 1/e)\,B_{opt}.

Proof. Let OO be an optimal set of kk views, GiG_i the set after ii choices, bi+1b_{i+1} the benefit of choice i+1i+1, and gi=Bopt−f(Gi)g_i = B_{opt} - f(G_i). Every view of OO is either in GiG_i, where its benefit for {t}∪Gi\{t\} \cup G_i is 0, or a candidate of line L4, whose benefit is at most bi+1b_{i+1}. By monotonicity and Lemma 3,

Bopt=f(O)≤f(Gi∪O)≤f(Gi)+∑o∈OB(o,{t}∪Gi)≤f(Gi)+k bi+1.B_{opt} = f(O) \le f(G_i \cup O) \le f(G_i) + \sum_{o \in O} B(o, \{t\} \cup G_i) \le f(G_i) + k\, b_{i+1}.

So gi≤k bi+1=k(gi−gi+1)g_i \le k\, b_{i+1} = k (g_i - g_{i+1}), that is, gi+1≤(1−1/k) gig_{i+1} \le (1 - 1/k)\, g_i. With g0=Boptg_0 = B_{opt}, this gives gk≤(1−1/k)kBoptg_k \le (1 - 1/k)^k B_{opt} and f(Gk)≥(1−(1−1/k)k)Boptf(G_k) \ge (1 - (1 - 1/k)^k) B_{opt}. Finally 1−x<e−x1 - x < e^{-x} for x>0x > 0, so (1−1/k)k<e−1(1 - 1/k)^k < e^{-1}. ■\blacksquare

If fewer than kk views besides tt exist, the greedy algorithm stores them all and is optimal. For k=1k = 1 the bound is 1: the first choice is the best single view.

Tightness for k=2k = 2. In Example 4.2 of the paper, the top view aa has size 200, three views bb, cc and dd below it have sizes 100, 99 and 100, and four chains of 20 views of size 100 hang below them: bb answers chains 1 and 2, cc chains 2 and 3, and dd chains 3 and 4. Greedy first takes cc, with benefit 41⋅101=414141 \cdot 101 = 4141, and then bb or dd, with benefit 21⋅100=210021 \cdot 100 = 2100, so Bgreedy=6241B_{greedy} = 6241. The set {b,d}\{b, d\} improves 82 views by 100 each, so Bopt=8200B_{opt} = 8200, and the ratio is about 0.761. With the size of cc closer to 100 and chains of LL views, the ratio is (2L+1)⋅100+(L+1)⋅100(4L+2)⋅100→3/4=1−(1−1/2)2\frac{(2L+1)\cdot 100 + (L+1)\cdot 100}{(4L+2)\cdot 100} \to 3/4 = 1 - (1 - 1/2)^2.

Theorem 2 (benefit per unit space). Run greedy with the rule "add the view with the largest B(v,S)/∣v∣B(v, S)/|v|" and stop at any step. Let GG be the chosen views, s=∑v∈G∣v∣s = \sum_{v \in G} |v| their space, and B∗B^* the largest benefit of any set of views of total size at most ss. Then f(G)≥(1−1/e) B∗f(G) \ge (1 - 1/e)\,B^*.

Proof. Let OO be a set of size at most ss with benefit B∗B^*, and σ=∑o∈O∣o∣≤s\sigma = \sum_{o \in O} |o| \le s; if B∗=0B^* = 0 there is nothing to prove, so σ>0\sigma > 0. Let v1,…,vmv_1, \ldots, v_m be the chosen views with sizes cic_i and gains bib_i, GiG_i the first ii of them, and gi=B∗−f(Gi)g_i = B^* - f(G_i). Each view o∈Oo \in O has B(o,{t}∪Gi−1)≤∣o∣ bi/ciB(o, \{t\} \cup G_{i-1}) \le |o|\, b_i / c_i, because viv_i has the largest ratio, or because the benefit of oo is 0. By Lemma 3,

B∗≤f(Gi−1)+∑o∈O∣o∣ bici=f(Gi−1)+σ bici,B^* \le f(G_{i-1}) + \sum_{o \in O} |o|\,\frac{b_i}{c_i} = f(G_{i-1}) + \sigma\,\frac{b_i}{c_i},

so gi−1≤σci(gi−1−gi)g_{i-1} \le \frac{\sigma}{c_i}(g_{i-1} - g_i), that is, gi≤(1−ci/σ) gi−1g_i \le (1 - c_i/\sigma)\, g_{i-1}. If some ci≥σc_i \ge \sigma, then gi≤0g_i \le 0, and gg stays at most 0 because ff is monotone. Otherwise every factor is in [0,1)[0, 1), and with 1−x≤e−x1 - x \le e^{-x},

gm≤B∗∏i=1m(1−ciσ)≤B∗e−s/σ≤B∗e−1,g_m \le B^* \prod_{i=1}^{m} \Big(1 - \frac{c_i}{\sigma}\Big) \le B^* e^{-s/\sigma} \le B^* e^{-1},

because s≥σs \ge \sigma. So f(G)≥(1−1/e)B∗f(G) \ge (1 - 1/e) B^*. ■\blacksquare

This is the form of the second theorem of Harinarayan, Rajaraman and Ullman: the comparison is with the best use of the space that greedy actually used. Against a fixed limit LL the bound does not hold if greedy skips a view that does not fit. With a view of size 1 and benefit 2 and a view of size LL and benefit 1.9L1.9L, greedy takes the small view first and then has no room, so it gets 2 while the best choice gets 1.9L1.9L.

Work. Precompute, for each view, the set of views below it; with nn views this takes O(n2)O(n^2) space. Keep CS(w)C_S(w) for every ww. Line L3 then costs O(∣{w⪯v}∣)=O(n)O(|\{w \preceq v\}|) = O(n) per view and O(n2)O(n^2) per round, and the update after line L5 costs O(n)O(n). With kk rounds the time is O(kn2)O(k n^2). For the cube on dd dimensions, n=2dn = 2^d and the views below the view on a set AA are the 2∣A∣2^{|A|} subsets of AA, so a round costs ∑A2∣A∣=3d\sum_A 2^{|A|} = 3^d.

Complexity

Let nn be the number of views. The sets of views below each view take O(n2)O(n^2) space. Line L3 costs O(n)O(n) per view, so O(n2)O(n^2) per round, and the update of CSC_S after line L5 costs O(n)O(n). The total is O(kn2)O(k n^2) time. For the cube on dd attributes, n=2dn = 2^d and the view on a set AA has 2∣A∣2^{|A|} views below it, so one round costs 3d3^d steps. The sizes of the views are inputs; in practice they are estimated, for example by sampling or by a sketch for the number of distinct groups, which can cost more than the greedy search.

Properties

  • Approximation, proved. At least 1−(1−1/k)k>0.631 - (1 - 1/k)^k > 0.63 of the optimal benefit, for every lattice and every kk. This is about the benefit (the saving over storing only the top view), not about the total cost.
  • Tight. The paper shows lattices with ratio arbitrarily close to the bound; for k=2k = 2, close to 3/43/4.
  • Exact for k=1k = 1. The first choice is the best single view.
  • Nonincreasing gains. By submodularity, each round gains no more than the round before.
  • Deterministic. With a fixed tie rule, the same input gives the same choice.

Variants and improvements

  • Query frequencies. With a weight qwq_w per query, the benefit sums qwmax⁡(0,CS(w)−∣v∣)q_w \max(0, C_S(w) - |v|), and the bound stays the same (Section 4.5 of the paper).
  • Space limit. Pick by benefit per unit space. The bound 1−1/e1 - 1/e holds against the best use of the space that greedy has used. Against a fixed limit, a view that does not fit can make plain greedy arbitrarily bad, so a practical version also compares with the best single view that fits.
  • Views and indexes. Gupta, Harinarayan, Rajaraman and Ullman (1997) extended the greedy method to choose indexes on the views together with the views.
  • AND-OR view graphs. Gupta (1997) generalized the lattice to graphs in which a view can be computed from several others, with greedy algorithms that keep a guarantee.
  • Maintenance cost. When the budget is the time to maintain the views, the constraint is not a count or a space limit, and the proofs of this page do not carry over.

When to use it

Use it to choose which aggregates of a star schema or a data cube to precompute, when query costs are roughly proportional to the size of the view read. It is easy to implement, and the guarantee holds for any sizes. When the cost model has indexes, joins or maintenance costs, use it as a heuristic inside a cost-based tool that uses the optimizer's estimates, as in index selection.

Pitfalls

  • Reading the bound as a bound on the cost. The 63 percent is about the benefit, the saving over the top view alone. When the best saving is small compared with the cost of the top view, 63 percent of it says little about the total cost.
  • Forgetting the top view. The top view must always be stored, or some queries cannot be answered. It is not one of the kk views.
  • Stale costs. After each choice, CS(w)C_S(w) must be lowered for every view below the new view. Using the costs of the first round makes greedy pick overlapping views, such as bb and ee in the example.
  • Bad size estimates. The algorithm is only as good as the sizes. The size of a view grouped by several attributes is often much smaller than the product of the numbers of values, and estimating it is a distinct values problem.
  • A fixed space limit. See the variant above: picking by benefit per unit space and skipping what does not fit has no guarantee.

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.

hru_greedy_view_selection.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hru-greedy-view-selection/. The authors are listed in prov/TY6PHM.jsonl.
"""The greedy view selection algorithm of Harinarayan, Rajaraman and Ullman (SIGMOD 1996).

A lattice of views has a top view, which is always stored, and a relation
"w can be answered from v" (w <= v). In the linear cost model, the cost of
answering w from a set S of stored views is the size of the smallest view
in S that w can be answered from. The benefit of a view v for S is

    B(v, S) = sum over w <= v of max(0, C_S(w) - |v|),

the total saving when v is added to S. The greedy algorithm adds, k times,
the view with the largest benefit. Each query w can have a weight (its
frequency); the default weight is 1.

`greedy_views` is the algorithm of the paper. `greedy_per_space` picks by
benefit per unit of space, the variant for a space limit.
"""

from itertools import combinations
from typing import Dict, Hashable, Iterable, List, Optional, Sequence, Set, Tuple

View = Hashable


class Lattice:
    """Views with sizes, the top view, and for each view the views below it."""

    def __init__(self, sizes: Dict[View, float], edges: Iterable[Tuple[View, View]],
                 top: View, weights: Optional[Dict[View, float]] = None):
        """`edges` holds pairs (v, w) where w can be answered from v directly."""
        self.size = dict(sizes)
        self.top = top
        self.views: List[View] = sorted(self.size, key=repr)
        children: Dict[View, List[View]] = {v: [] for v in self.views}
        for v, w in edges:
            if v not in self.size or w not in self.size:
                raise ValueError("an edge names an unknown view")
            children[v].append(w)
        self.below: Dict[View, Set[View]] = {}
        for v in self.views:
            seen = {v}
            stack = [v]
            while stack:
                for w in children[stack.pop()]:
                    if w not in seen:
                        seen.add(w)
                        stack.append(w)
            self.below[v] = seen
        if self.below[top] != set(self.views):
            raise ValueError("every view must be answerable from the top view")
        self.weight = {v: 1 for v in self.views}
        if weights:
            self.weight.update(weights)

    def costs(self, stored: Iterable[View]) -> Dict[View, float]:
        """C_S(w) for every view w: the smallest stored view that answers w."""
        stored = set(stored) | {self.top}
        cost = {}
        for w in self.views:
            cost[w] = min(self.size[u] for u in stored if w in self.below[u])
        return cost

    def total_cost(self, stored: Iterable[View]) -> float:
        cost = self.costs(stored)
        return sum(self.weight[w] * cost[w] for w in self.views)

    def benefit_of_set(self, stored: Iterable[View]) -> float:
        """The saving of a set over storing the top view alone."""
        return self.total_cost([]) - self.total_cost(stored)


def _benefit(lat: Lattice, cost: Dict[View, float], v: View) -> float:
    s = lat.size[v]
    return sum(lat.weight[w] * (cost[w] - s) for w in lat.below[v] if cost[w] > s)


def greedy_views(lat: Lattice, k: int) -> Tuple[List[View], List[float]]:
    """Pick k views (besides the top view) by largest benefit.

    Returns the views in the order of choice and the benefit of each choice.
    Ties go to the view that comes first in the sorted order of views.
    """
    stored = {lat.top}  # @line L1
    cost = lat.costs(stored)
    picks: List[View] = []
    gains: List[float] = []
    for _ in range(k):  # @line L2
        best, best_b = None, -1.0
        for v in lat.views:
            if v in stored:
                continue
            b = _benefit(lat, cost, v)  # @line L3
            if b > best_b:  # @line L4
                best, best_b = v, b
        if best is None:
            break
        stored.add(best)  # @line L5
        picks.append(best)
        gains.append(best_b)
        s = lat.size[best]
        for w in lat.below[best]:
            if cost[w] > s:
                cost[w] = s
    return picks, gains  # @line L6


def greedy_per_space(lat: Lattice) -> List[Tuple[View, float, float]]:
    """Pick views by largest benefit per unit of space, while some benefit is positive.

    Returns (view, space used so far, benefit so far) after each choice.
    """
    stored = {lat.top}
    cost = lat.costs(stored)
    out = []
    space = 0.0
    total = 0.0
    while True:
        best, best_r = None, 0.0
        for v in lat.views:
            if v in stored:
                continue
            r = _benefit(lat, cost, v) / lat.size[v]
            if r > best_r:
                best, best_r = v, r
        if best is None:
            return out
        b = _benefit(lat, cost, best)
        stored.add(best)
        space += lat.size[best]
        total += b
        out.append((best, space, total))
        for w in lat.below[best]:
            if cost[w] > lat.size[best]:
                cost[w] = lat.size[best]


def best_k_views(lat: Lattice, k: int) -> Tuple[float, Tuple[View, ...]]:
    """The largest benefit of k views, by trying every set of k views."""
    others = [v for v in lat.views if v != lat.top]
    best = (-1.0, ())
    for c in combinations(others, min(k, len(others))):
        b = lat.benefit_of_set(c)
        if b > best[0]:
            best = (b, c)
    return best


def best_within_space(lat: Lattice, space: float) -> float:
    """The largest benefit of a set of views of total size at most `space`, by brute force."""
    others = [v for v in lat.views if v != lat.top]
    best = 0.0
    for m in range(1, len(others) + 1):
        for c in combinations(others, m):
            if sum(lat.size[v] for v in c) <= space:
                best = max(best, lat.benefit_of_set(c))
    return best


def greedy_bound(k: int) -> float:
    """1 - (1 - 1/k)^k, the guarantee of Theorem 4.1 of the paper."""
    return 1 - (1 - 1 / k) ** k


def cube_lattice(dims: Sequence[str], size_of) -> Lattice:
    """The data cube lattice: one view per subset of the dimensions.

    The view on a set A answers the view on every subset of A. `size_of`
    maps a frozenset of dimensions to the size of that view.
    """
    subsets = [frozenset(c) for m in range(len(dims) + 1) for c in combinations(dims, m)]
    sizes = {s: size_of(s) for s in subsets}
    edges = [(a, a - {x}) for a in subsets for x in a]
    return Lattice(sizes, edges, frozenset(dims))
test_hru_greedy_view_selection.py 173 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hru-greedy-view-selection/. The authors are listed in prov/TY6PHM.jsonl.

import math
import unittest
from itertools import combinations
from random import Random

from hru_greedy_view_selection import (
    Lattice,
    best_k_views,
    best_within_space,
    cube_lattice,
    greedy_bound,
    greedy_per_space,
    greedy_views,
)


def example_4_1():
    """The lattice of Example 4.1 (Fig. 7) of Harinarayan, Rajaraman and Ullman."""
    sizes = {"a": 100, "b": 50, "c": 75, "d": 20, "e": 30, "f": 40, "g": 1, "h": 10}
    edges = [("a", "b"), ("a", "c"), ("b", "d"), ("b", "e"), ("c", "e"), ("c", "f"),
             ("d", "g"), ("e", "g"), ("e", "h"), ("f", "h")]
    return Lattice(sizes, edges, "a")


def example_4_2():
    """The lattice of Example 4.2 (Fig. 9): four chains of 20 views under b, c and d."""
    sizes = {"a": 200, "b": 100, "c": 99, "d": 100}
    edges = [("a", "b"), ("a", "c"), ("a", "d")]
    heads = []
    for chain in range(4):
        prev = None
        for i in range(20):
            v = "x%d_%02d" % (chain, i)
            sizes[v] = 100
            if prev is not None:
                edges.append((prev, v))
            else:
                heads.append(v)
            prev = v
    for parent, chain in [("b", 0), ("b", 1), ("c", 1), ("c", 2), ("d", 2), ("d", 3)]:
        edges.append((parent, heads[chain]))
    return Lattice(sizes, edges, "a")


def random_cube(rng, d):
    dims = "pqrs"[:d]
    dom = {x: rng.choice([2, 3, 5, 10, 20, 50]) for x in dims}
    top = rng.randint(200, 3000)

    def size_of(s):
        return min(top, math.prod(dom[x] for x in s)) if s else 1

    return cube_lattice(dims, size_of)


def random_dag(rng, n):
    """A random lattice-like order: view 0 on top, edges from lower to higher numbers."""
    sizes = {0: 1000}
    edges = []
    for v in range(1, n):
        parents = rng.sample(range(v), rng.randint(1, min(3, v)))
        edges += [(p, v) for p in parents]
        sizes[v] = rng.randint(1, min(sizes[p] for p in parents))
    return Lattice(sizes, edges, 0)


class TestExamples(unittest.TestCase):
    def test_example_4_1(self):
        lat = example_4_1()
        self.assertEqual(lat.total_cost([]), 800)
        picks, gains = greedy_views(lat, 3)
        self.assertEqual(picks, ["b", "f", "d"])
        self.assertEqual(gains, [250, 70, 60])
        self.assertEqual(lat.total_cost(picks), 420)
        self.assertEqual(best_k_views(lat, 3)[0], 380)

    def test_example_4_1_rounds(self):
        lat = example_4_1()
        from hru_greedy_view_selection import _benefit
        cost = lat.costs([])
        r1 = {v: _benefit(lat, cost, v) for v in "bcdefgh"}
        self.assertEqual(r1, {"b": 250, "c": 125, "d": 160, "e": 210, "f": 120, "g": 99, "h": 90})
        cost = lat.costs(["b"])
        r2 = {v: _benefit(lat, cost, v) for v in "cdefgh"}
        self.assertEqual(r2, {"c": 50, "d": 60, "e": 60, "f": 70, "g": 49, "h": 40})
        cost = lat.costs(["b", "f"])
        r3 = {v: _benefit(lat, cost, v) for v in "cdegh"}
        self.assertEqual(r3, {"c": 25, "d": 60, "e": 50, "g": 49, "h": 30})

    def test_example_4_2(self):
        lat = example_4_2()
        picks, gains = greedy_views(lat, 2)
        self.assertEqual(picks[0], "c")
        self.assertEqual(gains, [4141, 2100])
        best, chosen = best_k_views(lat, 2)
        self.assertEqual(best, 8200)
        self.assertEqual(set(chosen), {"b", "d"})
        self.assertGreaterEqual(sum(gains) / best, greedy_bound(2))

    def test_bound_values(self):
        self.assertEqual(greedy_bound(1), 1)
        self.assertEqual(greedy_bound(2), 0.75)
        self.assertGreater(greedy_bound(50), 1 - 1 / math.e)


class TestGuarantee(unittest.TestCase):
    def check(self, lat, k):
        picks, gains = greedy_views(lat, k)
        self.assertAlmostEqual(sum(gains), lat.benefit_of_set(picks))
        opt = best_k_views(lat, k)[0]
        self.assertGreaterEqual(sum(gains) + 1e-9, greedy_bound(k) * opt)
        self.assertLessEqual(sum(gains), opt + 1e-9)
        return sum(gains), opt

    def test_cubes(self):
        rng = Random(2)
        for _ in range(25):
            lat = random_cube(rng, rng.choice([3, 4]))
            for k in range(1, 4):
                self.check(lat, k)

    def test_random_orders(self):
        rng = Random(9)
        worse = 0
        for _ in range(30):
            lat = random_dag(rng, rng.randint(5, 11))
            for k in range(1, 4):
                g, opt = self.check(lat, k)
                worse += g < opt - 1e-9
        self.assertGreater(worse, 0)

    def test_weights(self):
        rng = Random(4)
        for _ in range(20):
            lat = random_cube(rng, 3)
            lat.weight = {v: rng.randint(0, 5) for v in lat.views}
            for k in range(1, 4):
                self.check(lat, k)

    def test_gains_do_not_grow(self):
        rng = Random(6)
        for _ in range(20):
            lat = random_dag(rng, 12)
            gains = greedy_views(lat, 6)[1]
            for x, y in zip(gains, gains[1:]):
                self.assertGreaterEqual(x, y)


class TestPerSpace(unittest.TestCase):
    def test_space_bound(self):
        rng = Random(8)
        for trial in range(20):
            lat = random_cube(rng, 3) if trial % 2 else random_dag(rng, 9)
            others = [v for v in lat.views if v != lat.top]
            table = []
            for m in range(1, len(others) + 1):
                for c in combinations(others, m):
                    table.append((sum(lat.size[v] for v in c), lat.benefit_of_set(c)))
            for v, space, total in greedy_per_space(lat):
                best = max([b for s, b in table if s <= space] + [0])
                self.assertGreaterEqual(total + 1e-9, (1 - 1 / math.e) * best)

    def test_brute_force_helper(self):
        lat = example_4_1()
        # d and e (space 20 + 30) save 160 + 140, more than b alone (250).
        self.assertEqual(best_within_space(lat, 50), 300)


if __name__ == "__main__":
    unittest.main()

History

Gray et al. proposed the data cube operator in 1996, and it raised the question of which parts of the cube to precompute. In the same year Venky Harinarayan, Anand Rajaraman and Jeffrey D. Ullman organized the views as a lattice, used the TPC-D benchmark as a running example, and gave the greedy algorithm with its bounds; the paper refers to a full version of 1995 for the proofs. Their analysis is a case of the bound of Nemhauser, Wolsey and Fisher (1978) for monotone submodular functions. Later work by Gupta and by Gupta, Harinarayan, Rajaraman and Ullman extended the method to indexes and to general view graphs.

References

  1. Venky Harinarayan, Anand Rajaraman and Jeffrey D. Ullman, Implementing data cubes efficiently, Proceedings of ACM SIGMOD 1996, 205 to 216, Section 3.2 (the linear cost model and the reduction from set cover), Section 4.1 and Fig. 6 (the benefit and the greedy algorithm), Examples 4.1 and 4.2 (Figs. 7 and 9), Section 4.3 (Theorem 4.1, the bound 1 - (1 - 1/k)^k, and Theorem 4.2 for benefit per unit space), Section 4.5 (query frequencies)
  2. An analysis of approximations for maximizing submodular set functions I, the greedy algorithm reaches 1 - (1 - 1/k)^k of the maximum of a monotone submodular function over sets of size k
  3. Selection of views to materialize in a data warehouse, the extension of the greedy method and its guarantee from the cube lattice to AND-OR view graphs

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example