r"""
Null models: what is structure and what is chance?
==================================================

The configuration model keeps every vertex degree and hyperedge size; the
random model keeps only the sizes. Comparing clustering, assortativity,
modularity of the best partition and the number of 2-components of the wire
harness space with 30 samples of each null model shows which properties are
explained by the degree and size sequences alone.
"""

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

import hatvis as hv

H = hv.datasets.load_wire_harness()


def stats(G):
    # [snippet:stats]
    lab = hv.hypergraph_louvain(G, random_state=0)
    return {"two-node clustering": hv.metrics.two_node_clustering(G).mean(),
            "degree assortativity": hv.metrics.degree_assortativity(G),
            "modularity": hv.modularity(G, lab),
            "2-components": len(hv.s_connected_components(G, 2))}
    # [/snippet:stats]


obs = stats(H)
null = {"configuration": [], "random": []}
for k in range(30):
    null["configuration"].append(stats(hv.models.configuration_model(H, random_state=k)))
    null["random"].append(stats(hv.models.random_hypergraph(H.n_nodes, H.edge_sizes(), random_state=k,
                                                            nodes=H.nodes)))
rows = {"observed": obs}
for name, lst in null.items():
    df = pd.DataFrame(lst)
    rows[f"{name} mean"] = df.mean()
    rows[f"{name} std"] = df.std()
table = pd.DataFrame(rows)
print(table.round(3).to_string())

# %%
fig, axes = plt.subplots(1, 4, figsize=(14, 3.3))
for ax, key in zip(axes, obs, strict=False):
    for k, (name, lst) in enumerate(null.items()):
        ax.hist([d[key] for d in lst], bins=10, alpha=0.6, color=hv.plotting.PALETTE[k + 1], label=name)
    ax.axvline(obs[key], color=hv.plotting.INK, lw=2, label="observed")
    ax.set_title(key, fontsize=9)
axes[0].legend(frameon=False, fontsize=7)
plt.tight_layout()
