15
votes

Does anyone know of a python library that has DTW implementation? mlpy seems to have what I'm looking for, but I can't seem to install it correctly -- currently awaiting replies from the mailing list so I thought I would scope out other libraries.

2
ldd /bin/delorean libplutonium.1.21.so => /lib/libplutonium.1.21.so - AJ.
People assume that time is a strict progression of cause to effect, but actually - from a non-linear, non-subjective viewpoint - it's more like a big ball of wibbly-wobbly timey-wimey, er, stuff. - flow
@C. Reed - it was a play on @flow's Dr. Who quote :P - detly
I wrote a C extension to Python to do the central calculation in classic Dynamic Programming / Dynamic Time Warp. It runs typically 500x faster than a straight Python version. See the code and ipython notebook demonstration at github.com/dpwe/dp_python . - dpwe

2 Answers

24
votes

Had to chime in on this one. To follow up with C's response, here's an implementation that is geared more towards interfacing with data generated in NumPy. I find this to be considerably more useful since typically I'm generating data in Python and want to interface with R resources.

import numpy as np

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

rpy2.robjects.numpy2ri.activate()

# 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)

Note that this is the example problem stated on the DTW site.

10
votes

For the record, I have been able to use a mashup of R, DTW in R, and rpy2. Working with R in Python is surprisingly simple and extends python's statistical capabilities considerably. Here's an example of finding the distance between an offset noisy sine and cosine series:

    import rpy2.robjects as robjects
    r = robjects.r
    r('library("dtw")')
    idx = r.seq(0,6.28,len=100)
    template = r.cos(idx)
    query = r.sin(idx)+r('runif(100)/10')
    alignment=r.dtw(query,template,keep=r('TRUE'))
    robjects.globalenv["alignment"] =  alignment
    dist = r('alignment$distance')
    print(dist)