Algorithm Search⌘K

Algorithmcore

GYO reduction

Also called Graham-Yu-Ozsoyoglu reduction, GYO algorithm, Graham reduction.

Test whether a hypergraph is alpha-acyclic by repeatedly deleting vertices in one edge only and edges contained in another edge.

Time
O(m^3 v^2) worst
Space
O(m v) extra
Where
m = the number of edges; v = the number of vertices

The GYO reduction decides whether a hypergraph is alpha-acyclic. It applies two deletion rules while one of them applies: delete a vertex that is in only one edge, and delete an edge that is a subset of another edge. The hypergraph is alpha-acyclic if and only if at most one edge is left at the end, and the edge deletions then give a join tree. In databases the vertices are the attributes or variables of a query and the edges are its relations, so the test tells whether a join can be evaluated by the Yannakakis algorithm without first combining relations. The name comes from Graham, and from Yu and Ozsoyoglu, who found the reduction independently in 1979.

In plain words

Think of each table of a query as a set of column names. Some columns occur in only one table. They do not connect that table to any other table, so you can forget them. Some tables, after this, have only columns that another table also has. Such a table hangs off the other table like a leaf off a branch, so you can put it aside and remember where it hangs.

Do these two steps again and again. If everything goes away except one table, the tables fit together like a tree, and the remembered "hangs off" links are that tree. If you get stuck with two or more tables, the tables form a real cycle, such as three tables that each share one column with the next one.

The problem

A hypergraph H=(V,E)H = (V, E) has a finite set VV of vertices and a finite list E=(e1,…,em)E = (e_1, \ldots, e_m) of edges, each a subset of VV. Equal edges and empty edges are allowed. A join tree of HH is a tree TT whose nodes are the indices 1,…,m1, \ldots, m, such that for each vertex xx the set {i:x∈ei}\{ i : x \in e_i \} induces a connected subtree of TT (the running intersection property). HH is alpha-acyclic if it has a join tree. The hypergraph with no edges is alpha-acyclic.

Input. A hypergraph HH. Output. Whether HH is alpha-acyclic, and if it is, a join tree.

For a conjunctive query Q(xˉ): ⁣−R1(uˉ1),…,Rm(uˉm)Q(\bar x) \mathbin{:\!-} R_1(\bar u_1), \ldots, R_m(\bar u_m), the hypergraph has the variables as vertices and one edge var(uˉi)\mathrm{var}(\bar u_i) per atom. For a natural join of relations R1,…,RmR_1, \ldots, R_m, the edges are the attribute sets att(Ri)\mathrm{att}(R_i).

The algorithm

The algorithm changes a copy cic_i of each edge and keeps a set AA of the edges that are still there.

  1. GYO(e_1, ..., e_m)
  2. 1c_i ← e_i for each i; A ← {1, ..., m}; parent ← empty map
  3. 2loop
  4. 3if some vertex x is in c_i for exactly one i in A then
  5. 4c_i ← c_i − {x} ▷ ear rule
  6. 5else if there are i ≠ j in A with c_i ⊆ c_j then
  7. 6A ← A − {i}; parent[i] ← j ▷ containment rule
  8. 7else exit the loop
  9. 8return (|A| ≤ 1, parent)

Line L4 is the ear rule: the vertex xx connects eie_i to no other edge. Line L6 is the containment rule: after the deletions, every vertex of cic_i is also in cjc_j, so eie_i can hang from eje_j in the tree. An empty cic_i is a subset of any other edge, so it goes too. When one edge is left, line L4 empties it, and the loop stops. The pairs {i,parent[i]}\{i, \mathit{parent}[i]\} are the edges of the join tree, and the last edge of AA is its root.

Either rule may be applied first, and the choice does not change the answer (see Correctness). Two equal edges are a case of line L5: one of them goes.

Example

The query Q: ⁣−R1(A,B,C),R2(B,C,D),R3(C,D,E),R4(D,F),R5(A,B)Q \mathbin{:\!-} R_1(A, B, C), R_2(B, C, D), R_3(C, D, E), R_4(D, F), R_5(A, B) has the edges e1=ABCe_1 = ABC, e2=BCDe_2 = BCD, e3=CDEe_3 = CDE, e4=DFe_4 = DF and e5=ABe_5 = AB. The run below always takes the ear rule first, with the smallest vertex, and else the containment pair (i,j)(i, j) with the smallest ii, then the smallest jj.

step rule the edges after the step
1 ear: EE only in e3e_3 e1=ABCe_1 = ABC, e2=BCDe_2 = BCD, e3=CDe_3 = CD, e4=DFe_4 = DF, e5=ABe_5 = AB
2 ear: FF only in e4e_4 e1=ABCe_1 = ABC, e2=BCDe_2 = BCD, e3=CDe_3 = CD, e4=De_4 = D, e5=ABe_5 = AB
3 containment: e3⊆e2e_3 \subseteq e_2, parent 2 e1=ABCe_1 = ABC, e2=BCDe_2 = BCD, e4=De_4 = D, e5=ABe_5 = AB
4 containment: e4⊆e2e_4 \subseteq e_2, parent 2 e1=ABCe_1 = ABC, e2=BCDe_2 = BCD, e5=ABe_5 = AB
5 ear: DD only in e2e_2 e1=ABCe_1 = ABC, e2=BCe_2 = BC, e5=ABe_5 = AB
6 containment: e2⊆e1e_2 \subseteq e_1, parent 1 e1=ABCe_1 = ABC, e5=ABe_5 = AB
7 ear: CC only in e1e_1 e1=ABe_1 = AB, e5=ABe_5 = AB
8 containment: e1⊆e5e_1 \subseteq e_5, parent 5 e5=ABe_5 = AB
9, 10 ear: AA, then BB e5=∅e_5 = \emptyset

One edge is left, so the hypergraph is alpha-acyclic. The join tree has the edges e3−e2e_3 - e_2, e4−e2e_4 - e_2, e2−e1e_2 - e_1 and e1−e5e_1 - e_5. The check for DD: it is in e2e_2, e3e_3 and e4e_4, and these three nodes are connected through e2e_2.

Now add the atom R6(A,D)R_6(A, D), an edge e6=ADe_6 = AD. Steps 1 to 4 are the same, and then e5=ABe_5 = AB goes into e1=ABCe_1 = ABC. The edges left are ABCABC, BCDBCD and ADAD. Each vertex is in two of them, and no edge is inside another one, so both rules stop with three edges. The hypergraph is not alpha-acyclic: ABCABC and BCDBCD share BB and CC, BCDBCD and ADAD share DD, and ADAD and ABCABC share AA, and no edge holds all of AA, CC and DD. The smallest cyclic case is the triangle ABAB, BCBC, CACA, where no rule applies at all.

Correctness

Let DD be the set of vertices that the ear rule has deleted so far. The run keeps the invariant that ci=ei∖Dc_i = e_i \setminus D for each i∈Ai \in A, and that no vertex of DD is in any cic_i with i∈Ai \in A. A vertex is deleted only when it is in one remaining edge, so after that it is in none.

  • If at most one edge is left, the parent links form a join tree. Take the edges in the reverse order of their deletion. When eie_i is deleted into eje_j, each vertex of eie_i that is also in a later edge is not yet in DD, so it is in ci⊆cj⊆ejc_i \subseteq c_j \subseteq e_j. So eie_i hangs from an edge that holds all the vertices that it shares with the rest of the tree, and the running intersection property holds.
  • If HH has a join tree, the run ends with at most one edge, in any order of the rules. While two or more edges are left, take a leaf ℓ\ell of a join tree and its neighbor pp. Each vertex of cℓc_\ell that is also in another edge is in cpc_p, by the running intersection property. So either some vertex of cℓc_\ell is in no other edge (line L4 applies) or cℓ⊆cpc_\ell \subseteq c_p (line L5 applies). Each rule keeps a join tree: after line L4 the same tree works, and after line L6 the neighbors of ii are joined to jj.

The loop stops, because each step deletes one vertex occurrence or one edge, so there are at most ∑i∣ei∣+m\sum_i |e_i| + m steps. The full proofs are in the correctness proof.

Proof: The GYO reduction ends with at most one edge if and only if the hypergraph has a join treefull

We use the pseudocode of the page. HH has the edges e1,…,eme_1, \ldots, e_m. A run applies lines L4 and L6 in some order, chosen freely among the rules that apply, until line L7 stops the loop. AA is the set of the remaining edges, cic_i is the current copy of eie_i, and DD is the set of vertices that line L4 has deleted so far. A join tree of a list of sets (fi)i∈I(f_i)_{i \in I} is a tree on II in which, for each vertex xx, the set Sx={i∈I:x∈fi}S_x = \{ i \in I : x \in f_i \} induces a connected subtree.

Termination. Let Φ=∑i∈A∣ci∣+∣A∣\Phi = \sum_{i \in A} |c_i| + |A|. At the start Φ=∑i∣ei∣+m\Phi = \sum_i |e_i| + m. Line L4 lowers Φ\Phi by exactly 1, and line L6 lowers it by ∣ci∣+1≥1|c_i| + 1 \ge 1. Φ≥0\Phi \ge 0, so there are at most ∑i∣ei∣+m\sum_i |e_i| + m steps, and the loop stops.

Lemma 1 (invariant). At each point of the run, (a) ci=ei∖Dc_i = e_i \setminus D for each i∈Ai \in A, and (b) no vertex of DD is in cic_i for any i∈Ai \in A.

Proof. Part (b) follows from part (a), so we show (a). At the start D=∅D = \emptyset and ci=eic_i = e_i. Line L6 only makes AA smaller, so it keeps (a). Line L4 deletes a vertex xx from the copy cic_i, and cic_i is the only copy that holds xx. It then adds xx to DD. The new copy ci∖{x}c_i \setminus \{x\} is equal to ei∖(D∪{x})e_i \setminus (D \cup \{x\}). For k∈Ak \in A with k≠ik \ne i, the copy ck=ek∖Dc_k = e_k \setminus D does not change and does not hold xx, so it is equal to ek∖(D∪{x})e_k \setminus (D \cup \{x\}). □\square

Lemma 2 (soundness). If the run ends with ∣A∣≤1|A| \le 1, the pairs {i,parent[i]}\{i, \mathit{parent}[i]\} form a join tree of e1,…,eme_1, \ldots, e_m.

Proof. If m=0m = 0 there is nothing to prove. Otherwise line L6 runs m−∣A∣m - |A| times. Let i1,…,im−1i_1, \ldots, i_{m-1} be the deleted edges in the order of deletion and rr the last edge, so ∣A∣=1|A| = 1 at the end; ∣A∣=0|A| = 0 is not possible, because line L6 needs a second edge j∈Aj \in A. Let AtA_t be the set AA just before the deletion of iti_t, so At={it,it+1,…,im−1,r}A_t = \{ i_t, i_{t+1}, \ldots, i_{m-1}, r \}, and let Am={r}A_m = \{r\}. The parent jt=parent[it]j_t = \mathit{parent}[i_t] is in At∖{it}=At+1A_t \setminus \{i_t\} = A_{t+1}. Let TtT_t be the graph on AtA_t with the edges {is,js}\{i_s, j_s\} for s≥ts \ge t.

We show by induction on tt, from t=mt = m down to t=1t = 1, that TtT_t is a join tree of (ei)i∈At(e_i)_{i \in A_t}. For t=mt = m, TmT_m is the single node rr. For the step from t+1t + 1 to tt: TtT_t is Tt+1T_{t+1} with the new leaf iti_t joined to jt∈At+1j_t \in A_{t+1}, so it is a tree. Take a vertex xx, and let SxS_x be the set of edges of AtA_t whose original edge holds xx.

  • If x∉eitx \notin e_{i_t}, then Sx⊆At+1S_x \subseteq A_{t+1} is connected in Tt+1T_{t+1} by the induction hypothesis, and so in TtT_t.
  • If x∈eitx \in e_{i_t} and no edge of At+1A_{t+1} holds xx, then Sx={it}S_x = \{i_t\} is connected.
  • If x∈eitx \in e_{i_t} and x∈ekx \in e_k for some k∈At+1k \in A_{t+1}, then x∉Dx \notin D at the time of the deletion of iti_t. Indeed, before that time both iti_t and kk are in AA. While x∉Dx \notin D, Lemma 1 (a) gives x∈citx \in c_{i_t} and x∈ckx \in c_k, so two copies hold xx and line L4 can not delete xx. So xx stays out of DD, and x∈eit∖D=citx \in e_{i_t} \setminus D = c_{i_t}. Line L6 runs only when cit⊆cjtc_{i_t} \subseteq c_{j_t}, so x∈cjt⊆ejtx \in c_{j_t} \subseteq e_{j_t}, and jt∈Sx∩At+1j_t \in S_x \cap A_{t+1}. By the induction hypothesis Sx∩At+1S_x \cap A_{t+1} is connected in Tt+1T_{t+1}, and iti_t is joined to jtj_t, so SxS_x is connected in TtT_t.

For t=1t = 1, A1={1,…,m}A_1 = \{1, \ldots, m\}, and T1T_1 is the tree of the parent links. □\square

Lemma 3 (a rule applies). Let (ci)i∈A(c_i)_{i \in A} have a join tree TT, with ∣A∣≥2|A| \ge 2. Then line L4 or line L6 applies.

Proof. TT has at least two nodes, so it has a leaf ℓ\ell with a neighbor pp. Let x∈cℓx \in c_\ell be in ckc_k for some k≠ℓk \ne \ell. The path from ℓ\ell to kk in TT starts with the edge {ℓ,p}\{\ell, p\}, and SxS_x is connected and holds ℓ\ell and kk, so p∈Sxp \in S_x and x∈cpx \in c_p. So each vertex of cℓc_\ell is either in no other copy, and then line L4 applies to it, or it is in cpc_p. If no vertex of cℓc_\ell is of the first kind, cℓ⊆cpc_\ell \subseteq c_p and line L6 applies to (ℓ,p)(\ell, p). □\square

Lemma 4 (the rules keep a join tree). If (ci)i∈A(c_i)_{i \in A} has a join tree before a step, it has one after the step.

Proof. After line L4 deletes xx from cic_i, the same tree TT works: the sets SyS_y for y≠xy \ne x do not change, and SxS_x becomes empty. After line L6 deletes ii with ci⊆cjc_i \subseteq c_j, let njn_j be the neighbor of ii on the path from ii to jj in TT (so nj=jn_j = j when jj is a neighbor of ii). Build T′T' from TT: delete the node ii and join each neighbor of ii other than njn_j to jj. T−iT - i has one component for each neighbor of ii, the component of njn_j holds jj, and T′T' joins each other component to jj by one edge. So T′T' is a tree on A∖{i}A \setminus \{i\}.

Take a vertex yy and two nodes u,w∈Sy∖{i}u, w \in S_y \setminus \{i\}. The path from uu to ww in TT lies inside SyS_y. If it does not pass through ii, it is also a path in T′T'. If y∉ciy \notin c_i, then i∉Syi \notin S_y and this is always the case. If y∈ciy \in c_i, then y∈cjy \in c_j, so SyS_y holds ii and jj and the whole path from ii to jj in TT, which includes njn_j. In T′T', each neighbor of ii in SyS_y other than njn_j is joined to jj, and njn_j is joined to jj by the part of the path from ii to jj that does not use ii. So all neighbors of ii in SyS_y are connected to jj inside Sy∖{i}S_y \setminus \{i\} in T′T'. A path from uu to ww through ii enters and leaves ii through two such neighbors, so uu and ww are connected inside Sy∖{i}S_y \setminus \{i\} in T′T'. □\square

Theorem. For every order of the rules, the run ends with ∣A∣≤1|A| \le 1 if and only if e1,…,eme_1, \ldots, e_m has a join tree, and then the parent links form a join tree.

Proof. If the run ends with ∣A∣≤1|A| \le 1, Lemma 2 gives the join tree. Conversely, let HH have a join tree. By Lemma 4 and induction on the steps, the current copies have a join tree at each point of the run. The run ends at line L7, where no rule applies, so by Lemma 3, ∣A∣≤1|A| \le 1 there. ■\blacksquare

Complexity

The bounds are in the word RAM model, for a hypergraph with mm edges and vv vertices, given as lists of vertices. Let s=∑i∣ei∣≤mvs = \sum_i |e_i| \le m v be its size.

  • Number of steps. At most s+ms + m, since each step deletes a vertex from an edge or an edge from AA.
  • The plain implementation. Before each step, count the occurrences of each vertex in O(s)O(s) time with a dictionary, and if there is no ear, test all pairs for containment in O(m2v)O(m^2 v) time with sets. That is O(s+m2v)O(s + m^2 v) per step and O((s+m)(s+m2v))=O(m3v2)O((s + m)(s + m^2 v)) = O(m^3 v^2) in total. The code of this page does this. It keeps the copies cic_i and the parent map, in O(mv)O(m v) extra space.
  • Linear time. Tarjan and Yannakakis (1984) test alpha-acyclicity in O(s+v+m)O(s + v + m) time. They order the vertices by maximum cardinality search and check the order, a method that also tests whether a graph is chordal. A join tree comes out of the same pass.

Properties

  • The order of the rules does not matter. Every order of the rules gives the same yes or no answer, by the two parts of the proof above. The join tree can differ.
  • Certificate in both cases. A yes answer comes with a join tree. A no answer leaves a reduced hypergraph with at least two edges, in which every vertex is in at least two edges and no edge is inside another. These edges show the part of the query that is cyclic.
  • Deterministic and exact. No heuristic is involved. It decides alpha-acyclicity, not the stronger beta or gamma forms (see acyclic hypergraph).

Variants and improvements

  • Ears of whole edges. Some books state one rule: delete an ear, an edge ee for which some other edge ff contains every vertex of ee that is also in an edge other than ee. This deletes the ear vertices of ee and the edge ee in one step, and it gives the same answer.
  • Join tree output. Record parent[i]←j\mathit{parent}[i] \leftarrow j at line L6, as above. The Yannakakis algorithm then runs its semijoin passes along this tree. The deletion order is a bottom-up order of the tree: each edge is deleted before its parent.
  • Linear-time test. Use the Tarjan and Yannakakis method when the hypergraph is large.
  • Width measures. When GYO fails, hypertree width and fractional hypertree width measure how far the hypergraph is from acyclic. Acyclic hypergraphs are exactly those with hypertree width 1.

When to use it

Use GYO in a query optimizer to detect acyclic conjunctive queries, which have polynomial evaluation by the Yannakakis algorithm, and to build their join tree. For queries of a few dozen relations the plain version is fast and easy to check. Use the linear-time test of Tarjan and Yannakakis when the hypergraph has thousands of edges, for example in a constraint satisfaction solver.

Pitfalls

  • Deleting a vertex too soon. Line L3 asks for a vertex in exactly one remaining edge. A vertex in two edges that are both still in AA must stay; deleting it can make a cyclic hypergraph look acyclic.
  • Containment against the original edges. Line L5 compares the reduced copies cic_i and cjc_j, not the original eie_i and eje_j. In the example, e3=CDEe_3 = CDE is not a subset of e2=BCDe_2 = BCD. Only after the ear rule deletes EE is c3=CD⊆c2c_3 = CD \subseteq c_2. A test on the original edges stops there and rejects an acyclic hypergraph.
  • A spanning tree is not a join tree. A tree that connects the relations that share attributes need not have the running intersection property. Build the tree from the parent links, not from a plain spanning tree of the "shares an attribute" graph.
  • Alpha-acyclicity is not closed under subsets of edges. The triangle ABAB, BCBC, CACA is cyclic, but with the extra edge ABCABC it is alpha-acyclic. Removing a relation from an acyclic query can make it cyclic.

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.

gyo_reduction.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/gyo-reduction/. The authors are listed in prov/AMABKP.jsonl.
"""The GYO reduction (Graham 1979; Yu and Ozsoyoglu 1979).

A hypergraph is a list of edges. Each edge is an iterable of vertices; vertices must be
hashable and sortable (str or int). Edges are named by their index in the list, and two
edges may be equal. The reduction applies two rules while one applies:

  ear rule:         delete a vertex that occurs in exactly one remaining edge;
  containment rule: delete an edge that is a subset of another remaining edge.

The hypergraph is alpha-acyclic if and only if at most one edge remains. Each edge that the
containment rule deletes gets the edge that contains it as its parent, and these parent links
form a join tree of the original edges.
"""


def gyo_reduction(edges, rng=None):
    """Run the GYO reduction.

    Return (acyclic, parent, steps). parent maps the index of each deleted edge to the index
    of the edge that contained it. steps lists the rule applications in order, as
    ("vertex", v, i) for the ear rule on vertex v in edge i, and ("edge", i, j) for the
    containment rule that deletes edge i into edge j. If rng (a random.Random) is given, the
    next rule is chosen at random among all that apply; otherwise the first one in a fixed
    order is taken (vertex rules first, smallest vertex, then smallest pair of indices)."""
    cur = {i: set(e) for i, e in enumerate(edges)}                       # @line L1
    parent = {}                                                          # @line L1
    steps = []
    while True:                                                          # @line L2
        count = {}
        for i in cur:
            for v in cur[i]:
                count.setdefault(v, []).append(i)
        ears = sorted((v, occ[0]) for v, occ in count.items() if len(occ) == 1)  # @line L3
        pairs = []
        if rng is not None or not ears:
            keys = sorted(cur)
            for i in keys:                                               # @line L5
                for j in keys:
                    if i != j and cur[i] <= cur[j]:
                        pairs.append((i, j))
        moves = [("vertex", v, i) for v, i in ears] + [("edge", i, j) for i, j in pairs]
        if not moves:                                                    # @line L7
            break
        move = moves[0] if rng is None else moves[rng.randrange(len(moves))]
        if move[0] == "vertex":
            _, v, i = move
            cur[i].discard(v)                                            # @line L4
        else:
            _, i, j = move
            del cur[i]                                                   # @line L6
            parent[i] = j                                                # @line L6
        steps.append(move)
    return len(cur) <= 1, parent, steps                                  # @line L8


def is_alpha_acyclic(edges) -> bool:
    return gyo_reduction(edges)[0]


def is_join_tree(edges, tree_edges) -> bool:
    """Check that tree_edges (pairs of edge indices) form a tree on all the edges of the
    hypergraph and that, for each vertex, the edges that contain it induce a connected
    subtree (the running intersection property)."""
    m = len(edges)
    if m == 0:
        return not tree_edges
    if len(tree_edges) != m - 1:
        return False
    adj = {i: set() for i in range(m)}
    for a, b in tree_edges:
        if a == b or not (0 <= a < m and 0 <= b < m):
            return False
        adj[a].add(b)
        adj[b].add(a)
    if len(_component(adj, 0, set(range(m)))) != m:
        return False
    vertices = sorted(set().union(*[set(e) for e in edges]))
    for v in vertices:
        holders = {i for i in range(m) if v in set(edges[i])}
        start = min(holders)
        if _component(adj, start, holders) != holders:
            return False
    return True


def _component(adj, start, allowed) -> set:
    seen = {start}
    stack = [start]
    while stack:
        a = stack.pop()
        for b in adj[a]:
            if b in allowed and b not in seen:
                seen.add(b)
                stack.append(b)
    return seen


def join_tree(edges):
    """Return the tree edges of a join tree built from the GYO parent links, or None if the
    hypergraph is not alpha-acyclic."""
    acyclic, parent, _ = gyo_reduction(edges)
    if not acyclic:
        return None
    return sorted((i, j) for i, j in parent.items())
test_gyo_reduction.py 132 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/gyo-reduction/. The authors are listed in prov/AMABKP.jsonl.

import itertools
import random

from gyo_reduction import gyo_reduction, is_alpha_acyclic, is_join_tree, join_tree


def all_trees(m):
    """Yield the edge lists of all labeled trees on the nodes 0 .. m - 1 (Pruefer codes)."""
    if m == 1:
        yield []
        return
    if m == 2:
        yield [(0, 1)]
        return
    for code in itertools.product(range(m), repeat=m - 2):
        degree = [1] * m
        for x in code:
            degree[x] += 1
        tree = []
        for x in code:
            leaf = min(i for i in range(m) if degree[i] == 1)
            tree.append((leaf, x))
            degree[leaf] -= 1
            degree[x] -= 1
        u, w = [i for i in range(m) if degree[i] == 1]
        tree.append((u, w))
        yield tree


def brute_force_acyclic(edges):
    """The definition: some tree on the edges has the running intersection property."""
    if not edges:
        return True
    return any(is_join_tree(edges, t) for t in all_trees(len(edges)))


def random_hypergraph(rng, m, domain):
    return [frozenset(rng.sample(domain, rng.randint(0, min(3, len(domain))))) for _ in range(m)]


def test_page_example():
    edges = [set("ABC"), set("BCD"), set("CDE"), set("DF"), set("AB")]
    acyclic, parent, steps = gyo_reduction(edges)
    assert acyclic
    assert steps == [
        ("vertex", "E", 2),
        ("vertex", "F", 3),
        ("edge", 2, 1),
        ("edge", 3, 1),
        ("vertex", "D", 1),
        ("edge", 1, 0),
        ("vertex", "C", 0),
        ("edge", 0, 4),
        ("vertex", "A", 4),
        ("vertex", "B", 4),
    ]
    assert parent == {2: 1, 3: 1, 1: 0, 0: 4}
    # A cyclic case: the triangle stays after the pendant edge CD goes.
    acyclic, parent, steps = gyo_reduction([set("AB"), set("BC"), set("CA"), set("CD")])
    assert not acyclic
    assert steps == [("vertex", "D", 3), ("edge", 3, 1)]
    assert is_join_tree(edges, join_tree(edges))


def test_hand_cases():
    assert is_alpha_acyclic([])
    assert is_alpha_acyclic([set()])
    assert is_alpha_acyclic([set("AB")])
    assert is_alpha_acyclic([set("AB"), set("AB")])
    assert is_alpha_acyclic([set("AB"), set("CD")])
    assert is_alpha_acyclic([set("AB"), set("BC"), set("CD")])
    assert not is_alpha_acyclic([set("AB"), set("BC"), set("CA")])
    # Adding the edge ABC makes the triangle alpha-acyclic.
    assert is_alpha_acyclic([set("AB"), set("BC"), set("CA"), set("ABC")])
    assert not is_alpha_acyclic([set("AB"), set("BC"), set("CD"), set("DA")])
    # The 4-cycle with a chord edge ABC is still cyclic: ACD remains a cycle part.
    assert not is_alpha_acyclic([set("AB"), set("BC"), set("CD"), set("DA"), set("ABC")])
    assert is_alpha_acyclic([set("AB"), set("BC"), set("CD"), set("DA"), set("ABC"), set("ACD")])
    # Three edges of size 2 out of a 3-set, plus a vertex outside.
    assert not is_alpha_acyclic([set("ABE"), set("BCE"), set("CAE")])


def test_against_brute_force():
    rng = random.Random(20261118)
    for trial in range(400):
        m = rng.randint(1, 5) if trial % 8 else 6
        domain = list("ABCDEF"[: rng.randint(3, 6)])
        edges = random_hypergraph(rng, m, domain)
        expected = brute_force_acyclic(edges)
        assert is_alpha_acyclic(edges) == expected, edges
        tree = join_tree(edges)
        if expected:
            assert is_join_tree(edges, tree), (edges, tree)
        else:
            assert tree is None


def test_order_does_not_matter():
    rng = random.Random(7)
    for _ in range(150):
        m = rng.randint(1, 6)
        domain = list("ABCDE")
        edges = random_hypergraph(rng, m, domain)
        first = is_alpha_acyclic(edges)
        for _ in range(4):
            acyclic, parent, _ = gyo_reduction(edges, rng=rng)
            assert acyclic == first
            if acyclic:
                assert is_join_tree(edges, sorted(parent.items()))


def test_cycles_are_cyclic():
    for n in range(3, 8):
        names = [f"v{i}" for i in range(n)]
        cycle = [{names[i], names[(i + 1) % n]} for i in range(n)]
        assert not is_alpha_acyclic(cycle)
        path = cycle[:-1]
        assert is_alpha_acyclic(path)
        assert is_alpha_acyclic(cycle + [set(names)])


def test_number_of_steps():
    # Each step deletes one vertex occurrence or one edge, so the number of steps is at most
    # the total size of the edges plus the number of edges.
    rng = random.Random(3)
    for _ in range(100):
        edges = random_hypergraph(rng, rng.randint(1, 6), list("ABCDE"))
        _, _, steps = gyo_reduction(edges)
        assert len(steps) <= sum(len(e) for e in edges) + len(edges)

History

Graham described the reduction in a 1979 technical report on the universal relation at the University of Toronto. Yu and Ozsoyoglu gave the same reduction at COMPSAC 1979 to decide whether a distributed query is a tree query. Beeri, Fagin, Maier and Yannakakis (1983) proved that the reduction ends with an empty hypergraph exactly when the schema has a join tree, and that this is equivalent to several other conditions, such as the existence of a semijoin full reducer. Tarjan and Yannakakis (1984) gave the linear-time test.

References

  1. M. H. Graham, On the universal relation, Technical report, University of Toronto (1979), the reduction by the two deletion rules
  2. Clement T. Yu and M. Zehra Ozsoyoglu, An algorithm for tree-query membership of a distributed query, Proceedings of COMPSAC 79, IEEE Computer Society, 306 to 312 (1979), the reduction used to decide whether a query is a tree query
  3. Catriel Beeri, Ronald Fagin, David Maier and Mihalis Yannakakis, On the desirability of acyclic database schemes, Journal of the ACM 30(3), 479 to 513 (1983), the theorem that a hypergraph is acyclic if and only if the Graham reduction ends with an empty hypergraph, among the other equivalent conditions
  4. Robert E. Tarjan and Mihalis Yannakakis, Simple linear-time algorithms to test chordality of graphs, test acyclicity of hypergraphs, and selectively reduce acyclic hypergraphs, SIAM Journal on Computing 13(3), 566 to 579 (1984), the linear-time acyclicity test by maximum cardinality search
  5. Serge Abiteboul, Richard Hull and Victor Vianu, Foundations of Databases, Addison-Wesley (1995), Chapter 6 (static analysis and optimization), the section on acyclic joins, with the GYO algorithm and join trees

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
  • History with a source
  • a scene preset for the example