Dynamic Time Warping (DTW) is a method to align two sequences such that they have minimum distance. For instance, two trajectories that are very similar but one of them performed in a longer time. Here is an example of my code with python. Here is my ROS package with C++ for DTW.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
import numpy as np import matplotlib.pyplot as plt from scipy.spatial.distance import euclidean from fastdtw import fastdtw start=0 end=2*np.pi step=0.1 k=2 x1=np.arange(start,end,k*step) x2=np.arange(start,end/k,step) noise=np.random.uniform(start,end,len(x2))/10 y1=np.sin(x1)+1*np.sin(2*x1)+noise y2=np.sin(k*x2)+1*np.sin(k*2*x2) sin1=plt.plot(x1,y1) plt.setp(sin1,color='b',linewidth=2.0) sin2=plt.plot(x2,y2) plt.setp(sin2,color='r',linewidth=2.0) time_series_A=zip(x1,y1) time_series_B=zip(x2,y2) distance, path = fastdtw(time_series_A, time_series_B, dist=euclidean) print distance print path index_a,index_b=zip(*path) for i in index_a: x1=time_series_A[i][0] y1=time_series_A[i][1] x2=time_series_B[i][0] y2=time_series_B[i][1] plt.plot([x1, x2], [y1, y2], color='k', linestyle='-', linewidth=2) plt.show() |

[…] time. The alignment should be is such way that minimizes the distance between these two sequences. Here I have done DTW between two-time series with python. I found a good c++ library for Fast Dynamic […]

Hey, I think you are getting the for loop wrong because you are not including index_b!

Might be a python2 thing, I’m not sure.

Anyway I was able to reproduce the second plot in python3 with the slightly modified code below.

import matplotlib.pyplot as plt

from scipy.spatial.distance import euclidean

from fastdtw import fastdtw

start=0

end=2*np.pi

step=0.1

k=2

x1=np.arange(start,end,k*step)

x2=np.arange(start,end/k,step)

noise=np.random.uniform(start,end,len(x2))/10

y1=np.sin(x1)+1*np.sin(2*x1)+noise

y2=np.sin(k*x2)+1*np.sin(k*2*x2)

sin1=plt.plot(x1,y1)

plt.setp(sin1,color=’b’,linewidth=2.0)

sin2=plt.plot(x2,y2)

plt.setp(sin2,color=’r’,linewidth=2.0)

time_series_A=list(zip(x1,y1))

time_series_B=list(zip(x2,y2))

distance, path = fastdtw(time_series_A, time_series_B, dist=euclidean)

print(distance)

print(path)

for i,j in path:

x1=time_series_A[i][0]

y1=time_series_A[i][1]

x2=time_series_B[j][0]

y2=time_series_B[j][1]

plt.plot([x1, x2], [y1, y2], color=’k’, linestyle=’-‘, linewidth=2)

plt.show()

Thanks for your comment, I think I did it in python v2.7, I will check it later but I think it almost clear what we try to do with DTW, cheers