{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Dynamic Time Warping\n\n\nThis example shows how to compute and visualize the optimal path\nwhen computing Dynamic Time Warping (DTW) between two time series and\ncompare the results with different variants of DTW. It is implemented\nas :func:`pyts.metrics.dtw`.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\nimport matplotlib.pyplot as plt\nfrom pyts.datasets import load_gunpoint\nfrom pyts.metrics import dtw, itakura_parallelogram, sakoe_chiba_band\nfrom pyts.metrics.dtw import (cost_matrix, accumulated_cost_matrix,\n                              _return_path, _multiscale_region)\n\n# Parameters\nX, _, _, _ = load_gunpoint(return_X_y=True)\nx, y = X[0], X[1]\nn_timestamps = x.size\n\nplt.figure(figsize=(13, 14))\ntimestamps = np.arange(n_timestamps + 1)\n\n# Dynamic Time Warping: classic\ndtw_classic, path_classic = dtw(x, y, dist='square',\n                                method='classic', return_path=True)\nmatrix_classic = np.zeros((n_timestamps + 1, n_timestamps + 1))\nmatrix_classic[tuple(path_classic)[::-1]] = 1.\n\nplt.subplot(2, 2, 1)\nplt.pcolor(timestamps, timestamps, matrix_classic,\n           edgecolors='k', cmap='Greys')\nplt.xlabel('x', fontsize=16)\nplt.ylabel('y', fontsize=16)\nplt.title(\"{0}\\nDTW(x, y) = {1:.2f}\".format('classic', dtw_classic),\n          fontsize=16)\n\n# Dynamic Time Warping: sakoechiba\nwindow_size = 0.1\ndtw_sakoechiba, path_sakoechiba = dtw(\n    x, y, dist='square', method='sakoechiba',\n    options={'window_size': window_size}, return_path=True\n)\nband = sakoe_chiba_band(n_timestamps, window_size=window_size)\nmatrix_sakoechiba = np.zeros((n_timestamps + 1, n_timestamps + 1))\nfor i in range(n_timestamps):\n    matrix_sakoechiba[i, np.arange(*band[:, i])] = 0.5\nmatrix_sakoechiba[tuple(path_sakoechiba)[::-1]] = 1.\n\nplt.subplot(2, 2, 2)\nplt.pcolor(timestamps, timestamps, matrix_sakoechiba,\n           edgecolors='k', cmap='Greys')\nplt.xlabel('x', fontsize=16)\nplt.ylabel('y', fontsize=16)\nplt.title(\"{0}\\nDTW(x, y) = {1:.2f}\".format('sakoechiba', dtw_sakoechiba),\n          fontsize=16)\n\n# Dynamic Time Warping: itakura\ndtw_itakura, path_itakura = dtw(\n    x, y, dist='square', method='itakura',\n    options={'max_slope': 2.}, return_path=True\n)\nparallelogram = itakura_parallelogram(n_timestamps, max_slope=2.)\nmatrix_itakura = np.zeros((n_timestamps + 1, n_timestamps + 1))\nfor i in range(n_timestamps):\n    matrix_itakura[i, np.arange(*parallelogram[:, i])] = 0.5\nmatrix_itakura[tuple(path_itakura)[::-1]] = 1.\n\nplt.subplot(2, 2, 3)\nplt.pcolor(timestamps, timestamps, matrix_itakura,\n           edgecolors='k', cmap='Greys')\nplt.xlabel('x', fontsize=16)\nplt.ylabel('y', fontsize=16)\nplt.title(\"{0}\\nDTW(x, y) = {1:.2f}\".format('itakura', dtw_itakura),\n          fontsize=16)\n\n# Dynamic Time Warping: multiscale\nresolution, radius = 5, 4\ndtw_multiscale, path_multiscale = dtw(\n    x, y, dist='square', method='multiscale',\n    options={'resolution': resolution, 'radius': radius}, return_path=True\n)\nx_padded = x.reshape(-1, resolution).mean(axis=1)\ny_padded = y.reshape(-1, resolution).mean(axis=1)\ncost_mat_res = cost_matrix(x_padded, y_padded, dist='square', region=None)\nacc_cost_mat_res = accumulated_cost_matrix(cost_mat_res)\npath_res = _return_path(acc_cost_mat_res)\nmultiscale_region = _multiscale_region(\n    n_timestamps, resolution, x_padded.size, path_res, radius=radius\n)\nmatrix_multiscale = np.zeros((n_timestamps + 1, n_timestamps + 1))\nfor i in range(n_timestamps):\n    matrix_multiscale[i, np.arange(*multiscale_region[:, i])] = 0.5\nmatrix_multiscale[tuple(path_multiscale)[::-1]] = 1.\n\nplt.subplot(2, 2, 4)\nplt.pcolor(timestamps, timestamps, matrix_multiscale,\n           edgecolors='k', cmap='Greys')\nplt.xlabel('x', fontsize=16)\nplt.ylabel('y', fontsize=16)\nplt.title(\"{0}\\nDTW(x, y) = {1:.2f}\".format('multiscale', dtw_multiscale),\n          fontsize=16)\n\nplt.suptitle(\"Dynamic Time Warping\", fontsize=22)\nplt.tight_layout()\nplt.subplots_adjust(top=0.91)\nplt.show()"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.7.3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}