r"""
Seriation of the incidence matrix
=================================

The incidence matrix of the wire harness manufacturing space (31 resources,
70 activities) is unreadable in its original order. The iterative
barycentric seriation of HAT-VIS, correspondence analysis and hierarchical
clustering with optimal leaf ordering reorder rows and columns so that
co-occurring resources and activities form blocks. The Moore stress (lower is
better) and the bond energy (higher is better) quantify the improvement.
"""

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

import hatvis as hv
from hatvis.plotting import plot_incidence

H = hv.datasets.load_wire_harness()
# [snippet:orders]
quality = {}
orders = {"original": (H.nodes, H.edges)}
for method in ("barycentric", "correspondence", "hierarchical"):
    orders[method] = hv.seriate(H, method)
for name, (rows, cols) in orders.items():
    quality[name] = hv.seriation.seriation_quality(H, rows, cols)
print(pd.DataFrame(quality).T)
# [/snippet:orders]

# %%
fig, axes = plt.subplots(1, 4, figsize=(15, 7.5))
for ax, (name, oc) in zip(axes, orders.items(), strict=False):
    plot_incidence(H, order=oc, ax=ax, transpose=True, labels=False, title=name)
plt.tight_layout()
