r"""
Forming manufacturing cells from the hypergraph
===============================================

Following Nagy et al. (2022), communities of the activities (hyperedges) and
of the resources (vertices) suggest how the production could be divided into
cells. Louvain on the line graph groups the activities; hypergraph Louvain and
Louvain on the clique expansion group the resources. The drawing colors the
resources by their community.
"""

# %%
import matplotlib.pyplot as plt

import hatvis as hv

H = hv.datasets.load_wire_harness()
# [snippet:cells]
act = hv.louvain(H, target="edges", random_state=0)
res = hv.hypergraph_louvain(H, random_state=0)
res_clique = hv.louvain(H, random_state=0)
# [/snippet:cells]
for c in sorted(act.unique()):
    steps = H.edge_data.loc[act.index[act == c], "step"]
    print(f"activity community {c}: {len(steps)} activities, e.g. {sorted(set(steps))[:3]}")
for c, members in enumerate(hv.community.communities(res)):
    print(f"resource community {c}: {members}")
print("modularity: hypergraph Louvain", round(hv.modularity(H, res), 3),
      " clique Louvain", round(hv.modularity(H, res_clique), 3))

# %%
# The incidence matrix ordered by the two partitions shows the cells as blocks;
# the clique expansion is colored by the resource communities.
rows = list(res.sort_values(kind="stable").index)
cols = list(act.sort_values(kind="stable").index)
fig, axes = plt.subplots(1, 2, figsize=(15, 6.5), gridspec_kw={"width_ratios": [1.6, 1]})
hv.plotting.plot_incidence(H, order=(rows, cols), ax=axes[0], node_groups="type", label_size=6,
                           title="resources (rows) and activities (columns) ordered by community")
axes[0].set_xticks([])
for y in res.value_counts().sort_index().cumsum().to_numpy()[:-1]:
    axes[0].axhline(y - 0.5, color=hv.plotting.PALETTE[1], lw=1)
for x in act.value_counts().sort_index().cumsum().to_numpy()[:-1]:
    axes[0].axvline(x - 0.5, color=hv.plotting.PALETTE[1], lw=1)
hv.plotting.draw_clique(H, ax=axes[1], layout="force", node_color=res, title="clique expansion, resource communities")
plt.tight_layout()
