r"""
Balanced partitioning and normalized cuts
=========================================

Fiduccia–Mattheyses refinement minimizes the number of cut hyperedges under
a balance constraint. A planted two-block hypergraph is split by multi-start
FM, by the sign of the Fiedler vector of the normalized Laplacian and at
random; the cut-net, connectivity−1 and normalized-cut values compare the
results. Recursive bisection gives a four-way partition.
"""

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

import hatvis as hv
from hatvis import partition

H, truth = hv.models.planted_partition(80, 2, 200, sizes=(2, 3, 4), p_in=0.85, random_state=2)
# [snippet:fm]
fm = partition.fm_bisection(H, imbalance=0.05, n_starts=10, random_state=0)
Hc = H.remove_isolated()                            # an isolated vertex would get its own block
fiedler = (hv.spectral.fiedler_vector(Hc) > 0).astype(int).reindex(H.nodes, fill_value=0)
rnd = pd.Series(np.random.default_rng(0).permutation([0, 1] * 40), index=H.nodes)
table = pd.DataFrame({name: partition.cut_metrics(H, p) for name, p in
                      {"FM": fm, "Fiedler sign": fiedler, "random": rnd, "planted": truth}.items()}).T
table["normalized cut"] = [partition.normalized_cut(H, p.index[p == 0]) for p in (fm, fiedler, rnd, truth)]
# [/snippet:fm]
print("isolated vertices:", H.isolated_nodes())
print(table.round(3))
four = partition.recursive_bisection(H, 4, random_state=0)
print(partition.cut_metrics(H, four).round(3).to_dict())

# %%
fig, ax = plt.subplots(figsize=(6.5, 3.8))
table[["cut", "km1"]].plot.bar(ax=ax, color=hv.plotting.PALETTE[:2], rot=0)
ax.set_ylabel("total weight of cut hyperedges")
plt.tight_layout()
