# Dynamic Time Warping with Python

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. DTW applied two sinusoidal time series in the presence of noise
Article Rating
Subscribe
Notify of This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks […] 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 […] 2 years ago

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]
y1=time_series_A[i]
x2=time_series_B[j]
y2=time_series_B[j]

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

3
0