"""
Series as images and networks
=============================

Recurrence plots (Eckmann et al., 1987) show when a trajectory returns to
earlier states; their texture reveals periodicity, drift and regime
changes. Gramian angular and Markov transition fields (Wang and Oates,
2015) encode a series as an image for image-based learning, and the
ordinal partition network (Small, 2013) describes the transitions between
ordinal patterns.
"""

import matplotlib.pyplot as plt
import numpy as np

from mvtsa import representation as rp
from mvtsa import viz

t = np.arange(600)
rng = np.random.default_rng(0)
x = np.r_[
    np.sin(2 * np.pi * t[:300] / 30), np.cumsum(rng.normal(0, 0.15, 300))
] + 0.05 * rng.normal(size=600)

# %%
# Recurrence plot of a periodic and a random-walk regime
# ------------------------------------------------------
R = rp.recurrence_plot(x, dim=3, tau=5, percentage=10)
G = rp.recurrence_network(x, dim=3, tau=5)
print(
    "recurrence rate:",
    R.mean().round(3),
    "| network:",
    {
        k: round(v, 3)
        for k, v in rp.graph_features(G).items()
        if k in ("mean_degree", "clustering")
    },
)
viz.plot_recurrence(R, title="recurrence plot (10 % recurrence rate)")

# %%
# Gramian angular and Markov transition fields
# --------------------------------------------
gaf = rp.gramian_angular_field(x[:300], n_bins=100)
mtf = rp.markov_transition_field(x[:300], n_states=8, n_bins=100)
fig, axes = plt.subplots(1, 2, figsize=(8, 3.8))
axes[0].imshow(gaf, origin="lower", cmap="RdBu_r")
axes[0].set_title("Gramian angular summation field")
axes[1].imshow(mtf, origin="lower", cmap="viridis")
axes[1].set_title("Markov transition field")

# %%
# Ordinal partition networks
# --------------------------
for name, seg in [("periodic", x[:300]), ("random walk", x[300:])]:
    N = rp.ordinal_partition_network(seg, order=4, delay=3)
    print(
        f"{name:12s}: {N.number_of_nodes()} ordinal patterns, {N.number_of_edges()} transitions, "
        f"permutation entropy {rp.permutation_entropy(seg, order=4, delay=3):.3f}"
    )
plt.show()
