r"""
Expansions, line graphs and Laplacian spectra
=============================================

The same hypergraph seen through four graphs — clique expansion, star
expansion, 1-line graph and 2-line graph — and through the spectra of three
Laplacians. The example is the cyber-physical production system of the
HyperGodot paper: 15 entities and 7 tasks.
"""

# %%
import matplotlib.pyplot as plt
import numpy as np

import hatvis as hv
from hatvis.plotting import draw_bipartite, draw_clique, draw_line_graph

H = hv.datasets.load_manufacturing_cps()
# [snippet:spectra]
spectra = {kind: np.sort(np.linalg.eigvalsh(hv.laplacian(H, kind))) for kind in ("normalized", "bolla", "clique")}
for kind, ev in spectra.items():
    print(f"{kind:>10}: zero eigenvalues = {np.sum(ev < 1e-9)}, largest = {ev[-1]:.3f}")
print("algebraic connectivity:", round(hv.spectral.algebraic_connectivity(H), 4))
# [/snippet:spectra]

# %%
fig, axes = plt.subplots(2, 2, figsize=(11, 9))
draw_clique(H, ax=axes[0, 0], title="clique expansion", layout="force")
draw_bipartite(H, ax=axes[0, 1], title="star expansion")
draw_line_graph(H, s=1, ax=axes[1, 0])
draw_line_graph(H, s=2, ax=axes[1, 1])
plt.tight_layout()

# %%
fig, ax = plt.subplots(figsize=(6.5, 3.5))
for k, (kind, ev) in enumerate(spectra.items()):
    ax.plot(ev / ev.max(), "o-", ms=4, label=kind, color=hv.plotting.PALETTE[k])
ax.set_xlabel("index")
ax.set_ylabel("eigenvalue / largest")
ax.legend(frameon=False)
plt.tight_layout()
