elegant-scipy / elegant-scipy-submissions

Submissions of code snippets for the book Elegant SciPy
13 stars 2 forks source link

Dynamic Time Warping in Python #5

Open starcalibre opened 9 years ago

starcalibre commented 9 years ago

StackOverflow demonstration of Dynamic Time Warping using NumPy and RPy2:

http://stackoverflow.com/questions/5695388/dynamic-time-warping-in-python http://stackoverflow.com/a/5766202

import numpy as np

import rpy2.robjects.numpy2ri
from rpy2.robjects.packages import importr

# Set up our R namespaces
R = rpy2.robjects.r
DTW = importr('dtw')

# Generate our data
idx = np.linspace(0, 2*np.pi, 100)
template = np.cos(idx)
query = np.sin(idx) + np.array(R.runif(100))/10

# Calculate the alignment vector and corresponding distance
alignment = R.dtw(query, template, keep=True)
dist = alignment.rx('distance')[0][0]

print(dist)
stefanv commented 9 years ago

I hope that, after this year's GSoC, the code snippet above will reduce to 5 lines of Python!