|
| 1 | +""" |
| 2 | +DTWC++ DTW Variants — Compare all 5 DTW distance measures. |
| 3 | +
|
| 4 | +Demonstrates: Standard DTW, DDTW, WDTW, ADTW, Soft-DTW. |
| 5 | +""" |
| 6 | + |
| 7 | +import numpy as np |
| 8 | +import dtwcpp |
| 9 | + |
| 10 | +# Create two time series |
| 11 | +np.random.seed(42) |
| 12 | +t = np.linspace(0, 4 * np.pi, 200) |
| 13 | +x = np.sin(t).tolist() |
| 14 | +y = np.sin(t + 0.5).tolist() # phase-shifted version |
| 15 | + |
| 16 | +print("=== DTW Variant Comparison ===") |
| 17 | +print(f"Series length: {len(x)}") |
| 18 | +print() |
| 19 | + |
| 20 | +# Standard DTW |
| 21 | +d_std = dtwcpp.dtw_distance(x, y, band=-1) |
| 22 | +print(f"Standard DTW: {d_std:.4f}") |
| 23 | + |
| 24 | +# Banded DTW (Sakoe-Chiba) |
| 25 | +d_banded = dtwcpp.dtw_distance(x, y, band=20) |
| 26 | +print(f"Banded DTW (b=20): {d_banded:.4f}") |
| 27 | + |
| 28 | +# DDTW — Derivative DTW (shape-based, ignores amplitude) |
| 29 | +d_ddtw = dtwcpp.ddtw_distance(x, y, band=-1) |
| 30 | +print(f"DDTW (derivative): {d_ddtw:.4f}") |
| 31 | + |
| 32 | +# WDTW — Weighted DTW (penalizes off-diagonal alignment) |
| 33 | +d_wdtw_lo = dtwcpp.wdtw_distance(x, y, band=-1, g=0.01) |
| 34 | +d_wdtw_hi = dtwcpp.wdtw_distance(x, y, band=-1, g=0.5) |
| 35 | +print(f"WDTW (g=0.01): {d_wdtw_lo:.4f} (lenient)") |
| 36 | +print(f"WDTW (g=0.50): {d_wdtw_hi:.4f} (strict)") |
| 37 | + |
| 38 | +# ADTW — Amerced DTW (penalizes non-diagonal steps) |
| 39 | +d_adtw_lo = dtwcpp.adtw_distance(x, y, band=-1, penalty=0.1) |
| 40 | +d_adtw_hi = dtwcpp.adtw_distance(x, y, band=-1, penalty=5.0) |
| 41 | +print(f"ADTW (p=0.1): {d_adtw_lo:.4f} (lenient)") |
| 42 | +print(f"ADTW (p=5.0): {d_adtw_hi:.4f} (strict)") |
| 43 | + |
| 44 | +# Soft-DTW — Differentiable (for gradient-based optimization) |
| 45 | +d_soft_lo = dtwcpp.soft_dtw_distance(x, y, gamma=0.01) |
| 46 | +d_soft_hi = dtwcpp.soft_dtw_distance(x, y, gamma=10.0) |
| 47 | +print(f"Soft-DTW (g=0.01): {d_soft_lo:.4f} (~ hard DTW)") |
| 48 | +print(f"Soft-DTW (g=10): {d_soft_hi:.4f} (smooth)") |
| 49 | + |
| 50 | +# Soft-DTW gradient — unique to Soft-DTW, enables optimization |
| 51 | +grad = dtwcpp.soft_dtw_gradient(x, y, gamma=1.0) |
| 52 | +print(f"\nSoft-DTW gradient norm: {np.linalg.norm(grad):.4f}") |
| 53 | +print(f"Gradient shape: {len(grad)} (same as input series)") |
| 54 | + |
| 55 | +# --- Preprocessing: derivative transform --- |
| 56 | +dx = dtwcpp.derivative_transform(x) |
| 57 | +print(f"\nDerivative transform: first 5 values = {[f'{v:.3f}' for v in dx[:5]]}") |
| 58 | + |
| 59 | +# --- Z-normalization --- |
| 60 | +z = dtwcpp.z_normalize([10, 20, 30, 40, 50]) |
| 61 | +print(f"Z-normalize([10..50]) = [{', '.join(f'{v:.3f}' for v in z)}]") |
| 62 | +print(f" Mean = {np.mean(z):.6f}, Std = {np.std(z):.6f}") |
0 commit comments