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
- Model
- Word RAM
- Evidence
- Proof sketchCode in 1 languages
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 has a finite set of vertices and a finite list of edges, each a subset of . Equal edges and empty edges are allowed. A join tree of is a tree whose nodes are the indices , such that for each vertex the set induces a connected subtree of (the running intersection property). is alpha-acyclic if it has a join tree. The hypergraph with no edges is alpha-acyclic.
Input. A hypergraph . Output. Whether is alpha-acyclic, and if it is, a join tree.
For a conjunctive query , the hypergraph has the variables as vertices and one edge per atom. For a natural join of relations , the edges are the attribute sets .
The algorithm
The algorithm changes a copy of each edge and keeps a set of the edges that are still there.
GYO(e_1, ..., e_m)- 1
c_i ← e_i for each i; A ← {1, ..., m}; parent ← empty map - 2
loop - 3
if some vertex x is in c_i for exactly one i in A then - 4
c_i ← c_i − {x} ▷ ear rule - 5
else if there are i ≠ j in A with c_i ⊆ c_j then - 6
A ← A − {i}; parent[i] ← j ▷ containment rule - 7
else exit the loop - 8
return (|A| ≤ 1, parent)
Line L4 is the ear rule: the vertex connects to no other edge. Line L6 is the containment rule: after the deletions, every vertex of is also in , so can hang from in the tree. An empty 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 are the edges of the join tree, and the last edge of 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 has the edges , , , and . The run below always takes the ear rule first, with the smallest vertex, and else the containment pair with the smallest , then the smallest .
| step | rule | the edges after the step |
|---|---|---|
| 1 | ear: only in | , , , , |
| 2 | ear: only in | , , , , |
| 3 | containment: , parent 2 | , , , |
| 4 | containment: , parent 2 | , , |
| 5 | ear: only in | , , |
| 6 | containment: , parent 1 | , |
| 7 | ear: only in | , |
| 8 | containment: , parent 5 | |
| 9, 10 | ear: , then |
One edge is left, so the hypergraph is alpha-acyclic. The join tree has the edges , , and . The check for : it is in , and , and these three nodes are connected through .
Now add the atom , an edge . Steps 1 to 4 are the same, and then goes into . The edges left are , and . 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: and share and , and share , and and share , and no edge holds all of , and . The smallest cyclic case is the triangle , , , where no rule applies at all.
Correctness
Let be the set of vertices that the ear rule has deleted so far. The run keeps the invariant that for each , and that no vertex of is in any with . 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 is deleted into , each vertex of that is also in a later edge is not yet in , so it is in . So 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 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 of a join tree and its neighbor . Each vertex of that is also in another edge is in , by the running intersection property. So either some vertex of is in no other edge (line L4 applies) or (line L5 applies). Each rule keeps a join tree: after line L4 the same tree works, and after line L6 the neighbors of are joined to .
The loop stops, because each step deletes one vertex occurrence or one edge, so there are at most 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. has the edges . A run applies lines L4 and L6 in some order, chosen freely among the rules that apply, until line L7 stops the loop. is the set of the remaining edges, is the current copy of , and is the set of vertices that line L4 has deleted so far. A join tree of a list of sets is a tree on in which, for each vertex , the set induces a connected subtree.
Termination. Let . At the start . Line L4 lowers by exactly 1, and line L6 lowers it by . , so there are at most steps, and the loop stops.
Lemma 1 (invariant). At each point of the run, (a) for each , and (b) no vertex of is in for any .
Proof. Part (b) follows from part (a), so we show (a). At the start and . Line L6 only makes smaller, so it keeps (a). Line L4 deletes a vertex from the copy , and is the only copy that holds . It then adds to . The new copy is equal to . For with , the copy does not change and does not hold , so it is equal to .
Lemma 2 (soundness). If the run ends with , the pairs form a join tree of .
Proof. If there is nothing to prove. Otherwise line L6 runs times. Let be the deleted edges in the order of deletion and the last edge, so at the end; is not possible, because line L6 needs a second edge . Let be the set just before the deletion of , so , and let . The parent is in . Let be the graph on with the edges for .
We show by induction on , from down to , that is a join tree of . For , is the single node . For the step from to : is with the new leaf joined to , so it is a tree. Take a vertex , and let be the set of edges of whose original edge holds .
- If , then is connected in by the induction hypothesis, and so in .
- If and no edge of holds , then is connected.
- If and for some , then at the time of the deletion of . Indeed, before that time both and are in . While , Lemma 1 (a) gives and , so two copies hold and line L4 can not delete . So stays out of , and . Line L6 runs only when , so , and . By the induction hypothesis is connected in , and is joined to , so is connected in .
For , , and is the tree of the parent links.
Lemma 3 (a rule applies). Let have a join tree , with . Then line L4 or line L6 applies.
Proof. has at least two nodes, so it has a leaf with a neighbor . Let be in for some . The path from to in starts with the edge , and is connected and holds and , so and . So each vertex of is either in no other copy, and then line L4 applies to it, or it is in . If no vertex of is of the first kind, and line L6 applies to .
Lemma 4 (the rules keep a join tree). If has a join tree before a step, it has one after the step.
Proof. After line L4 deletes from , the same tree works: the sets for do not change, and becomes empty. After line L6 deletes with , let be the neighbor of on the path from to in (so when is a neighbor of ). Build from : delete the node and join each neighbor of other than to . has one component for each neighbor of , the component of holds , and joins each other component to by one edge. So is a tree on .
Take a vertex and two nodes . The path from to in lies inside . If it does not pass through , it is also a path in . If , then and this is always the case. If , then , so holds and and the whole path from to in , which includes . In , each neighbor of in other than is joined to , and is joined to by the part of the path from to that does not use . So all neighbors of in are connected to inside in . A path from to through enters and leaves through two such neighbors, so and are connected inside in .
Theorem. For every order of the rules, the run ends with if and only if has a join tree, and then the parent links form a join tree.
Proof. If the run ends with , Lemma 2 gives the join tree. Conversely, let 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, there.
Complexity
The bounds are in the word RAM model, for a hypergraph with edges and vertices, given as lists of vertices. Let be its size.
- Number of steps. At most , since each step deletes a vertex from an edge or an edge from .
- The plain implementation. Before each step, count the occurrences of each vertex in time with a dictionary, and if there is no ear, test all pairs for containment in time with sets. That is per step and in total. The code of this page does this. It keeps the copies and the parent map, in extra space.
- Linear time. Tarjan and Yannakakis (1984) test alpha-acyclicity in 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 for which some other edge contains every vertex of that is also in an edge other than . This deletes the ear vertices of and the edge in one step, and it gives the same answer.
- Join tree output. Record 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 must stay; deleting it can make a cyclic hypergraph look acyclic.
- Containment against the original edges. Line L5 compares the reduced copies and , not the original and . In the example, is not a subset of . Only after the ear rule deletes is . 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 , , is cyclic, but with the extra edge 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.
# 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
- M. H. Graham, On the universal relation, Technical report, University of Toronto (1979), the reduction by the two deletion rules
- 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
- 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
- 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
- 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.
| 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 AMABKP Edit this page History Report an error Markdown