"""
Soft-DTW: a differentiable alignment and its uncertainty
========================================================

Soft-DTW (Cuturi and Blondel, 2017) replaces the minimum of the DTW
recursion by a soft minimum with temperature :math:`\\gamma`. The value is
differentiable, its gradient with respect to the cost matrix is the
*expected alignment* -- a probability map that shows how certain the
alignment is -- and barycenters can be computed by gradient descent. The
soft-DTW divergence (Blondel et al., 2021) is non-negative and zero only for
identical series.
"""

import matplotlib.pyplot as plt
import numpy as np

from mvtsa import viz
from mvtsa import warping as wp
from mvtsa.datasets import random_time_warp

t = np.linspace(0, 1, 80)
x = np.sin(2 * np.pi * 2 * t) * np.exp(-2 * t)
y = random_time_warp(x, strength=0.2, random_state=3)

# %%
# Expected alignment for three temperatures
# -----------------------------------------
fig, axes = plt.subplots(1, 3, figsize=(9, 3.2))
for ax, g in zip(axes, (0.01, 0.1, 1.0), strict=True):
    value, E = wp.soft_dtw_alignment(x, y, gamma=g)
    viz.plot_alignment_uncertainty(E, path=wp.dtw_path(x, y).path, ax=ax)
    ax.set_title(f"$\\gamma$={g}, soft-DTW={value:.2f}")
fig.tight_layout()

# %%
# Divergence versus soft-DTW
# --------------------------
# Soft-DTW of a series with itself is negative; the divergence corrects it.
for g in (0.01, 0.1, 1.0):
    print(
        f"gamma {g}: sdtw(x,x)={wp.soft_dtw(x, x, gamma=g):8.3f}  "
        f"divergence(x,y)={wp.soft_dtw_divergence(x, y, g):.3f}"
    )
# %%
# Barycenters: DBA and soft-DTW
# -----------------------------
rng = np.random.default_rng(0)
coll = [
    random_time_warp(x, 0.25, random_state=s) + 0.03 * rng.normal(size=80)
    for s in range(12)
]
avg_dba = wp.dba(coll, n_iter=10)
avg_soft = wp.soft_dtw_barycenter(coll, gamma=0.1)
fig, ax = plt.subplots(figsize=(6, 3))
for c in coll:
    ax.plot(c, color="0.8", lw=0.8)
ax.plot(
    np.mean(coll, axis=0),
    color="#999999",
    lw=1.5,
    ls="--",
    label="arithmetic mean",
)
ax.plot(avg_dba, color="#285780", lw=2, label="DBA")
ax.plot(avg_soft, color="#E69F00", lw=2, label="soft-DTW barycenter")
ax.legend(frameon=False)
plt.show()
