r"""
Evolving narratives in a temporal hypergraph
============================================

The synthetic news hypergraph has three periods. Snapshot turnover,
persistence of theme combinations, vertex activity over time and the
frequent itemsets per period show how the narratives change — the questions
that the hypergraph analysis of climate-change news coverage asks.
"""

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

import hatvis as hv
from hatvis.plotting import plot_activity

T = hv.datasets.make_news_transactions(150, random_state=0)
# [snippet:temporal]
print(hv.temporal.turnover(T))
print(hv.temporal.persistence(T).head(5).to_string())
top = {t: hv.frequent_itemsets(S, min_support=0.08, min_size=2).head(3) for t, S in T.snapshots().items()}
# [/snippet:temporal]
for t, fi in top.items():
    print(t, [sorted(s) for s in fi["itemset"]])
share = pd.crosstab(T.edge_data["time"], T.edge_data["narrative"].str.contains("finance"), normalize="index")
print("share of articles with the finance narrative:", share[True].round(3).to_dict())

# %%
fig, ax = plt.subplots(figsize=(7, 6))
plot_activity(T, ax=ax, title="theme activity per period")
plt.tight_layout()
