r"""
Acyclic hypergraphs and join trees
==================================

A hypergraph is :math:`\alpha`-acyclic if the GYO reduction (removing ear
vertices and contained hyperedges) empties it. Acyclic hypergraphs have join
trees: the hyperedges can be arranged in a tree in which the hyperedges that
contain a vertex form a subtree. Join trees make joins of relational tables
and inference on graphical models efficient; the 3-cycle of pairs is the
smallest non-acyclic example.
"""

# %%
import matplotlib.pyplot as plt
import networkx as nx

import hatvis as hv
from hatvis import problems

# [snippet:gyo]
schema = hv.Hypergraph({"Orders": ["order", "customer", "date"], "Lines": ["order", "item", "qty"],
                        "Items": ["item", "supplier", "price"], "Customers": ["customer", "city"]})
cycle = hv.Hypergraph({"R": ["a", "b"], "S": ["b", "c"], "T": ["a", "c"]})
for H in (schema, cycle):
    ok, steps = problems.gyo_reduction(H)
    print(f"alpha-acyclic: {ok}; first steps: {steps[:4]}")
tree = problems.join_tree(schema)
# [/snippet:gyo]
print("join tree edges:", sorted(tuple(sorted(e)) for e in tree.edges))

# %%
fig, axes = plt.subplots(1, 2, figsize=(11, 4.5))
hv.plotting.draw_hypergraph(schema, layout="force", ax=axes[0], title="database schema as a hypergraph",
                            random_state=2)
pos = nx.spring_layout(tree, seed=0)
nx.draw_networkx(tree, pos, ax=axes[1], node_color=hv.plotting.BRAND, font_color="white", node_size=1400,
                 font_size=8, edge_color=hv.plotting.GRAY)
nx.draw_networkx_edge_labels(tree, pos, ax=axes[1], font_size=7,
                             edge_labels={(a, b): ",".join(sorted(set(schema.members(a)) & set(schema.members(b))))
                                          for a, b in tree.edges})
axes[1].set_title("join tree (shared attributes on the links)")
axes[1].axis("off")
plt.tight_layout()
