Note
Go to the end to download the full example code or to run this example in your browser via Binder.
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())
isolated vertices: ['v72']
cut km1 soed blocks imbalance normalized cut
FM 25.0 25.0 50.0 2.0 0.0 0.121
Fiedler sign 25.0 25.0 50.0 2.0 0.0 0.121
random 146.0 146.0 292.0 2.0 0.0 0.681
planted 25.0 25.0 50.0 2.0 0.0 0.121
{'cut': 108.0, 'km1': 115.0, 'soed': 223.0, 'blocks': 4.0, 'imbalance': 0.05}
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()

Total running time of the script: (0 minutes 0.654 seconds)