"""
Comparing qualitative trends: episode alignment
===============================================

Balaskó, Bankó and Abonyi (2007) describe a signal by its sequence of
triangular episodes (concave/convex increase and decrease, steady and
linear parts) and compare two signals by aligning their episode strings
with the Needleman--Wunsch algorithm and a primitive substitution table.
Weighting the episodes by their size makes small wiggles count less. The
alignment works on a handful of symbols, so it is fast and insensitive to
the time scale.
"""

import matplotlib.pyplot as plt
import numpy as np

from mvtsa import representation as rp
from mvtsa import viz
from mvtsa import warping as wp

t = np.linspace(0, 1, 300)
rng = np.random.default_rng(4)
base = np.tanh(8 * (t - 0.3)) - 0.6 * np.exp(-(((t - 0.75) / 0.07) ** 2))
signals = {
    "reference": base,
    "slower and scaled": 2.0 * np.interp(t**1.3, t, base) + 1,
    "noisy": base + 0.04 * rng.normal(size=300),
    "different": -base,
}

# %%
# Episode strings
# ---------------
eps = {k: rp.triangular_episodes(v, sigma=8) for k, v in signals.items()}
for k, e in eps.items():
    print(f"{k:18s} {rp.episode_string(e)}")
viz.plot_episodes(signals["noisy"], eps["noisy"], smooth=8)

# %%
# Alignment scores
# ----------------
for k in ("slower and scaled", "noisy", "different"):
    score, pairs = wp.align_episodes(eps["reference"], eps[k])
    print(
        f"reference vs {k:18s}: score {score:5.2f} / 10, "
        f"episode DTW {wp.episode_dtw(eps['reference'], eps[k]):.3f}"
    )
# %%
# Parameter study: smoothing before the episode extraction
# --------------------------------------------------------
for s in (2, 8, 20):
    e_ref = rp.triangular_episodes(signals["reference"], sigma=s)
    e_noisy = rp.triangular_episodes(signals["noisy"], sigma=s)
    print(
        f"sigma {s:2d}: {len(e_noisy):3d} episodes, "
        f"score {wp.align_episodes(e_ref, e_noisy)[0]:.2f}"
    )
plt.show()
