r"""
Membership-aware layout: similarity with fewer intrusions
=========================================================

The similarity layout gives meaningful positions but hulls drawn around
hyperedges often contain foreign vertices. The membership-aware layout of
hatvis alternates a stress-majorization step towards the similarity
distances with a projection that moves non-members out of the hyperedge
discs, and keeps the iterate with the fewest intrusions. It is compared with
classical MDS and Sammon mapping on the whole wire harness space and on a
14-activity part of production line 1.
"""

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

import hatvis as hv
from hatvis.plotting import draw_hypergraph

W = hv.datasets.load_wire_harness()
part = W.restrict_edges([e for e in W.edges if W.edge_data.loc[e, "line"] == 1 and W.edge_data.loc[e, "type"]
                         in ("t16", "t19", "t24", "t2", "t11")]).remove_isolated()


def compare(H):
    # [snippet:compare]
    layouts = {"classical MDS": hv.layout_similarity(H, jitter=0.01, random_state=0),
               "Sammon mapping": hv.layout_similarity(H, method="sammon"),
               "membership-aware": hv.layout_membership(H, random_state=0)}
    quality = pd.DataFrame({name: hv.layout_quality(H, pos) for name, pos in layouts.items()}).T
    # [/snippet:compare]
    return layouts, quality


layouts_w, q_w = compare(W)
layouts_p, q_p = compare(part)
print("whole space (31 resources, 70 activities):\n", q_w.round(3).to_string())
print("line-1 part:\n", q_p.round(3).to_string())

# %%
fig, axes = plt.subplots(1, 3, figsize=(17, 6))
for ax, (name, pos) in zip(axes, layouts_p.items(), strict=False):
    draw_hypergraph(part, pos=pos, ax=ax, style="smooth", legend=False, pad=0.02,
                    title=f"{name}: {int(q_p.loc[name, 'intrusions'])} intrusions")
plt.tight_layout()
