Download
Download
Toni Giorgino
University of Pavia
Abstract
This introduction to the R package dtw is a (slightly) modified version of Giorgino
(2009), published in the Journal of Statistical Software.
Dynamic time warping is a popular technique for comparing time series, providing
both a distance measure that is insensitive to local compression and stretches and the
warping which optimally deforms one of the two input series onto the other. A variety of
algorithms and constraints have been discussed in the literature. The dtw package provides
an unification of them; it allows R users to compute time series alignments mixing freely a
variety of continuity constraints, restriction windows, endpoints, local distance definitions,
and so on. The package also provides functions for visualizing alignments and constraints
using several classic diagram types.
1. Introduction
Dynamic time warping (DTW) is the name of a class of algorithms for comparing series of
values with each other. The rationale behind DTW is, given two time series, to stretch or
compress them locally in order to make one resemble the other as much as possible. The dis-
tance between the two is computed, after stretching, by summing the distances of individual
aligned elements (Figure 1). DTW algorithms have been proposed around 1970 in the con-
text of speech recognition, to account for differences in speaking rates between speakers and
utterances. The technique is useful, for example, when one is willing to find a low distance
score between the sound signals corresponding to utterances now and nooow respectively,
insensitive to the prolonged duration of the o sound.
Various types of DTW algorithms differ for the input feature space, the local distance assumed,
presence of local and global constraints on the alignment, and so on. This freedom makes
DTW a very flexible alignment approach. As said, it has been popularized in the ’70s, when
it was mainly applied to isolated word recognition (Velichko and Zagoruyko 1970; Sakoe and
Chiba 1971); since then, it has been employed for clustering and classification in countless
domains: electro-cardiogram analysis (Huang and Kinsner 2002; Syeda-Mahmood et al. 2007;
Tuzcu and Nas 2005), clustering of gene expression profiles (Aach and Church 2001; Hermans
and Tsiporkova 2007), biometrics (Faundez-Zanuy 2007; Rath and Manmatha 2003), process
monitoring (Gollmer and Posten 1996), just to name a few. The term time series may even be
misleading, because the warped dimensions can be other than time, e.g., an angle for shape
2 dtw: Computing and Visualizing Dynamic Time Warping Alignments in R
recognition (Kartikeyan and Sarkar 1989; Wei et al. 2006; Tak 2007).
This paper describes the dtw package for the R statistical software (R Development Core
Team 2009), which provides a comprehensive solution for the computation and visualization
of DTW alignments, whose theory is outlined in Section 2. The stable package version is
available in source and binary form on the Comprehensive R Archive Network (CRAN), while
development versions are hosted at R-Forge (Giorgino and Tormene 2009). The package allows
users to select among a wide variety of algorithms and constraints described in the literature,
simply passing arguments to a single function, dtw, introduced in Section 3. The following
sections discuss how the user can customize the classic constraints of the algorithm (local
slope, endpoints, windowing). Finally, Section 4 describes how the alignment results can be
conveniently plotted in a variety of ways.
Note that d, the cross-distance matrix between vectors X and Y , is the only input to the
DTW algorithm: elements xi and yj only enter the computation through the arguments of f .
Therefore, the following discussion applies, with no loss of generality, to cases when X and Y
are single- or multi-variate, continuous, nominal, or mixed, as long as f (·, ·) is suitably defined.
While the most common choice is to assume the Euclidean distance, different definitions (e.g.,
those provided by the proxy package, Meyer and Buchta 2009) may be useful as well.
At the core of the technique lies the warping curve φ(k), k = 1 . . . T :
φ(k) = φx (k), φy (k) with
φx (k) ∈ {1 . . . N },
φy (k) ∈ {1 . . . M }
The warping functions φx and φy remap the time indices of X and Y respectively. Given φ,
we compute the average accumulated distortion between the warped time series X and Y :
T
X
dφ (X, Y ) = d(φx (k), φy (k)) mφ (k)/Mφ
k=1
φx (k + 1) ≥ φx (k)
Toni Giorgino 3
φy (k + 1) ≥ φy (k)
The idea underlying DTW is to find the optimal alignment φ such that
D(X, Y ) = min dφ (X, Y ) (2)
φ
In other words, one picks the deformation of the time axes of X and Y which brings the
two time series as close as possible to each other. Remarkably, despite of the large search
space, Equation 2 can be computed in O(N ·M ) time using dynamic programming. Interested
readers can find the derivation of the solution in several references, e.g., Myers et al. (1980,
Section II.F).
The output of the DTW algorithm is quite rich: first of all, the value of the function D(X, Y )
(minimum global dissimilarity, or “DTW distance”) can be assumed as the stretch-insensitive
measure of the “inherent difference” between two given time series. This distance has a
straightforward application in hierarchical clustering and classification (e.g., with k-NN clas-
sifiers). The shape of the warping curve φ itself provides information about which point
matches which, i.e., the pairwise correspondences of time points can be easily inspected.
Once obtained, the warping function can be applied to any time series, allowing one to in-
spect post-hoc aligned signals or measure time distortions.
3. Computing alignments
After loading the dtw package, alignments can be computed invoking the dtw function. In
its simplest incarnation, the function takes two vector arguments representing the input time
series, performs the minimization, and returns an object of class dtw encapsulating all the
alignment information. The elements of the result can be retrieved with the usual $ notation
(see list in Table 1).
By default, the dtw function computes a global alignment, with no windowing, a symmetric
local continuity constraint, and the Euclidean local distance. In particular, the symmetric
continuity constraint implies that arbitrary time compressions and expansions are allowed,
and that all elements must be matched:
|φx (k + 1) − φx (k)| ≤ 1,
|φy (k + 1) − φy (k)| ≤ 1. (3)
Several alternative forms for local continuity constraints however exist; Section 3.1 discusses
them and how they can be selected.
Computing global alignments means that the time series’ heads and tails are constrained to
match each other. In other words, the following endpoint constraints are imposed:
φx (1) = φy (1) = 1; (4)
φx (T ) = N ; φy (T ) = M. (5)
As we shall see in Section 3.5, one or both of these constraints can be relaxed in order to
compute partial time series matches.
As the example below shows, using dtw is straightforward.
4 dtw: Computing and Visualizing Dynamic Time Warping Alignments in R
0.6
0.2
−0.2 0
Query value
−0.6
0.4
0.0
−0.4
Index
Figure 1: Aligning two time series: a simple example. A query (solid, left axis) and a reference
(dashed, right axis) ECG time series, excerpted from aami3a.
Example 1 The aami3a time series included in the package contains a reference electro-
cardiogram from the PhysioBank dataset (Goldberger et al. 2000). We extract two non-
overlapping windows from it, and compute their optimal alignment with the default dtw set-
tings. The two extracted segments are shown in Figure 1.
R> library("dtw")
R> data("aami3a")
R> ref <- window(aami3a, start = 0, end = 2)
R> test <- window(aami3a, start = 2.7, end = 5)
R> alignment <- dtw(test, ref)
R> alignment$distance
[1] 15.824
In alignment$distance one finds the cumulative (unnormalized) cost for the alignment, i.e.,
Mφ · dφ (X, Y ), while the warping functions φx and φy are found in components $index1 and
Toni Giorgino 5
Figure 2: Block diagram of the main functions (rounded boxes) and object classes (rectangles)
of the dtw package and their relationship. Arrows going in functions are arguments, outgoing
are returned values.
$index2. They are two integer vectors of the same length, listing the matching indices in
the query and reference time series, respectively. Although the two vectors may be readily
plotted with commands built-in in R, in Section 4 we shall show how this is accomplished
even more easily with dedicated plotting commands.
Table 1: Elements in a dtw result object, as of package version 1.13-1. Remarks: k – re-
quires keep = TRUE; n – requires that the chosen step pattern is normalizable; d – unless
distance.only = TRUE; p – unless a local distance matrix is used as input .
Example 2 Compute the same alignment of the previous example, assuming the well-known
asymmetric pattern (bottom left of Figure 3).
[1] 11.497
When printed, stepPattern objects display the corresponding DTW recursion in human-
readable form; they can also be plotted via the plot() overloaded method, and transposed via
t(). Transposing a pattern means that the role of the query and reference are interchanged.
Example 3 Display the recursion formula for the properly symmetric continuity constraint
(top right in Figure 3), also known as the symmetric P = 0 from Sakoe and Chiba (1978).
R> symmetric2
The so-called symmetric recursion printed above allows an unlimited number of elements
of the query to be matched to a single element of the reference, and vice-versa; in other
words, there is no limit in the amount of time expansion or compression allowed at any point.
Once the package is loaded, an instance representing this recursion is pre-defined under the
name symmetric2, which is also the default. For this recursion, the average cost per-step
is computed by dividing the cumulative distance by N + M , where N is the length of the
query sequence and M is the length of the reference. Other step patterns require different
normalization formulas, as we shall see in Section 3.2. The normalized distance, if defined, is
stored in the $normalizedDistance component of the result.
Several step patterns have been discussed in the literature. A classic paper by Sakoe and Chiba
(1978) classifies them according to two properties: their symmetry (symmetric/asymmetric),
and the bounds imposed on the slope expressed through a parameter P . The eight step
patterns shown in Sakoe and Chiba (1978, Table I) are pre-defined in dtw, with names
symmetricP1, asymmetricP05, and so on.1 All of them are normalizable.
Rabiner and Juang (1993, Chapter 4) introduced a different classification with three at-
tributes: local continuity constraint type (in Roman numerals, I to VII); slope weighting
(Latin letters a to d ); and their being “smoothed” or not (boolean). All of Rabiner’s step
patterns are available through the three-argument function rabinerJuangStepPattern().
Slope weighting types c and d are normalizable.
Yet another classification (now obsoleted by the previous one) follows Myers et al. (1980); it
is similar to Rabiner’s, except that only four types (I)-(IV) are defined. The corresponding
instances are named like typeIId, typeIIIc and so on. The latter is a good approximation
to the slope-limited pattern proposed by Itakura (1975).
It should be noted that, in general, step patterns impose a lower and/or an upper bound to
the local slope of the alignment. In other words, they limit the maximum amount of time
stretch and compression allowed at any point of the alignment. For example, the asymmetric
step pattern limits time expansion to a factor of two; it would therefore be impossible to
completely align a query with a reference more than twice as long. The Rabiner-Juang type
IV, instead, generates the so-called Itakura parallelogram (Itakura 1975).
3.2. Normalization
Computing the average per-step distance along the warping curve is especially important in
two cases: (1) when comparing alignments between time series of different lengths, to decide
the best match (e.g., for classification); and (2) when performing partial matches. Each step
patterns requires a different normalization function. In dtw, objects of class stepPattern
“know” the proper normalization formula they require, called “normalization hint”.
Not all step patterns are normalizable. For example, the quasi-symmetric recursion (top
left in Figure 3, instance name symmetric1), like the symmetric one, does not restrict the
slope; however, it favors “diagonal” steps over stair-stepping paths. Since similar warping
curves have different weights, a path-independent per-step alignment cost is not defined. As
a consequence, only the cumulative distance value is available in the $distance component
of the result.
Table 2 lists the currently supported normalization rules, grouped by weighting type. “R-J”
1
Sakoe’s “asymmetric” property should not be confused with the asymmetric step pattern.
8 dtw: Computing and Visualizing Dynamic Time Warping Alignments in R
● ● ● ●
0
0
1 1
Reference index
Reference index
1 1 2 1
−1
−1
● ● ● ●
−1 0 −1 0
● ● ● ●
0
1 1
Reference index
Reference index
1 1 1
−1
−1
● ● ●
1 1 1
−2
−2
● ● ●
−1 0 −2 −1 0
Figure 3: Four well-known step patterns. Left to right, top to bottom: symmetric1,
symmetric2, asymmetric, rabinerJuangStepPattern(4, "c", TRUE) (i.e., Rabiner-Juang’s
type IV with slope weighting c). Numbers on transitions indicate the multiplicative weight
mφ for the local distance d(i, j), should the corresponding step be followed. See ?stepPattern
for the full list.
Toni Giorgino 9
types follow Rabiner’s aforementioned slope weight classification (cf. Figure 7 in Myers et al.
(1980)), while “S-C” refers to the symmetric/asymmetric categories introduced by Sakoe-
Chiba (cf. Table I in Sakoe and Chiba (1978)). Type (c0 ) includes asymmetric patterns
similar to R-J type (c) with test and reference interchanged. Step patterns of this category
have been used e.g., by Mori et al. (2006) (namely, instance mori2006), and by Oka (1998).
Values n and m are the number of elements actually matched in the query and reference,
respectively, i.e.,
n = φx (T ) − φx (1) + 1
m = φy (T ) − φy (1) + 1.
For global alignments, they are equal to the lengths of the input time series, i.e., n = N and
m = M.
where T0 is the maximum allowable absolute time deviation between two matched elements.
Intuitively, the constraint creates an allowed band of fixed width about the main diagonal of
the alignment plane (Figure 5).
In dtw, windowing constraints are enabled through the window.type argument of the dtw call;
it can be either a character string (e.g., "sakoechiba") or a function, specifying the shape of
the allowed window. The window size, T0 , is passed through the window.size argument.
10 dtw: Computing and Visualizing Dynamic Time Warping Alignments in R
Figure 4: Different conventions for displaying distance matrices: plot-like (left) and matrix
(right) arrangements.
Table 3: Where to find documentation for various DTW parameters. R-J is the book by
Rabiner and Juang (1993).
It should be remarked that the Sakoe-Chiba band works well when N ∼ M , but is inappropri-
ate when the lengths of the two inputs differ significantly. In particular, when |N − M | > T0 ,
the (N, M ) endpoint lies outside of the band, thus violating (5), and therefore no solution
exists for a global alignment. In general, when enforcing global and/or local constraints one
should take care that they are compatible with each other and with the time series’ lengths.
The slantedBandWindow creates a band centered around the jagged line segment which joins
element (1, 1) to element (N, M ), and is T0 elements wide along the first axis. In other words,
the “diagonal” goes from one corner to the other of the possibly rectangular cost matrix,
therefore having a slope of M/N , not 1.
Arbitrary windows can be specified by supplying a function that takes (at least) the i and j in-
teger arguments, and returns a boolean value specifying whether that match is allowed or not.
Arguments unused in dtw are passed to the windowing function. More detail on windowing
functions, including how to plot them (as in Figure 5), are given in ?dtwWindowingFunctions.
15
Reference: samples 1..17
10
5
2 4 6 8 10 12
Figure 5: The allowed region for the warping curve under the "sakoechiba" global constraint.
In this degenerate case, element (N, M ) at the upper-right is outside of the band, so the
endpoint constraint (5) can’t be satisfied: this band is too narrow to be compatible with any
global alignment.
12 dtw: Computing and Visualizing Dynamic Time Warping Alignments in R
It is worthwhile noting that in Equation 6 one compares alignments of different lengths with
each other. This is only meaningful if the average per-step distances are considered, and it is
therefore essential to use normalizable step patterns.
In dtw, open-end alignment of time series is achieved simply setting the open.end = TRUE
parameter. The element $jmin in the result will hold the size of the prefix matched, i.e., the
j that minimizes (6). This is the index of the last element matched in the reference, which
in turn equals φy (T ). Accordingly, when oc is a partial alignment result, oc$jmin equals
max(oc$index2).
Subsequence match, also called “unconstrained” or open-begin-end (OBE-DTW), is achieved
relaxing both the start-point constraint in (4) and the end-point constraint of (5). Intuitively,
subsequence matching discovers the contiguous part of the template which best matches the
whole query (Figure 6). This form is used e.g., by Rabiner et al. (1978) as algorithm UE2-1;
by Sakurai et al. (2007); and others. Formally, we define Y (p,q) as the subsequence of Y
including elements yj with p ≤ j ≤ q; the OBE-DTW problem is to minimize the cumulative
distance over the initial and final reference indices p and q simultaneously:
Y (p,q) = (yp , . . . , yq )
DOBE (X, Y ) = min D(X, Y (p,q) ) (7)
1≤p≤q≤M
In dtw, OBE-DTW alignments are computed setting both the open.begin and open.end
arguments to TRUE.2 Open-begin alignments are supported for step patterns with n-type
normalization only.
1
0.5
0
Query value
−0.5
0.5
0.0
−1
−0.5
−1.0
0 20 40 60 80 100
Index
Figure 6: A partial alignment with both endpoints free: the whole query (solid line) is
warped into a contiguous subsequence of the template (dashed). Partial alignments are com-
puted setting the open.begin = TRUE and/or open.end = TRUE arguments. Code available
in example(dtw).
14 dtw: Computing and Visualizing Dynamic Time Warping Alignments in R
function f influences how “strongly” the alignment will avoid mismatching regions. A variety
of dissimilarity functions are available, e.g., the Euclidean, squared Euclidean, Manhattan,
Gower coefficient, and many others. Each of them takes two arguments, which may be
multi-variate; for example, in speech recognition it is customary to align high-dimensional
“frames”, whose components are short-time spectral coefficients, or similar quantities. The
proxy package maintains a database of distance definitions which can be used in cross-distance
computations (see summary(pr_DB)).
To deal with multivariate time series, one provides dtw with two matrices Xic and Yjc , rather
than two vectors as for the single-variate case. The time indices i = 1 . . . N and j = 1 . . . M
are arranged along rows, while multivariate dimensions c = 1 . . . C are arranged in columns.
Multivariate time series objects (R class mts) can be used, as well.
By default, dtw assumes an Euclidean local distance, i.e.,
C
X
2
d(i, j) = (Xic − Yjc )2
c=1
Other distance functions can be selected through the dist.method character argument, which
is forwarded to the proxy::dist function.
Alternatively, the user can compute the local distance matrix by herself, and supply that
instead of the time series. This is achieved invoking dtw with one matrix argument rather
than two. According to the convention in Section 3.3, matrix rows (first index) are understood
as the index in the query sequence, and matrix columns as the index in the reference. The
following examples show both the two- and the one-argument call styles.
Example 4 Align two synthetic bivariate time series (a query with 10 time points, and a
reference of length 5), assuming the Manhattan local distance for element pairs:
[1] 83
[1] 83
The optimal alignment of strings, i.e., discrete values or categorial data, rather than of se-
quences of real values, is an ubiquitous task in bioinformatics, closely related to DTW. Func-
tions to perform alignments of strings, like Levenshtein’s distance or the Needleman-Wunsch
algorithm, are implemented, e.g., in package cba (cf. function sdists), package TraMineR
(Gabadinho et al. 2009), and in Bioconductor (Gentleman et al. 2004). The DTW algorithm
can be used to align strings, as well, by defining a local distance function over all the pairs
Toni Giorgino 15
of symbols that can be formed in the alphabets considered. A cross-distance matrix can then
be obtained from this function, and used in the single-argument call of dtw, as in the last
example.
where D is the dynamic time warping distance of Equation 2. It should be noted that, since
the DTW distance is not in general symmetric, Λ will not be, either.
As seen above, the dtw function leverages the proxy package for building the local distance
matrix. There is, however, another important relationship between the two packages. Since
dynamic time warping itself is a dissimilarity function between vectors (understood as time
series), dtw registers itself as a distance function in the database of distances pr_DB. This
feature makes it straightforward to compute many-versus-many alignments. Once the package
is loaded, if qki is given as a matrix q (again, time series are arranged in rows), Λ can be
straightforwardly computed through proxy::dist(q, q, method = "DTW").3 Computing
K × K alignments in this way is faster than iterating over the plain dtw call, because only
the numeric value of the distance is computed, while the construction of the actual warping
path is bypassed.
Equally useful is the cross-distance form of dist, which can be used, for instance, to classify
K query time series at once (arranged in a matrix q) against a given database of L templates
(matrix p). Once the K × L cross-distance matrix is computed by dist(q, p, method =
"DTW"), one could take column-wise minima to discover the template best matching each of
the K query elements. The dissimilarity matrices resulting from calls to dist can also be fed
into the usual clustering functions.
Figure 7: Left: MVM alignment of a truncated query; “jumps” may occur in the middle of
the query, e.g., around time 175. Note that since time compression is not allowed, the valley
at query index 150 does not match index 125 in the reference. Right: a type (c) DTW step
pattern equivalent to the MVM search algorithm.
φx (k) = k, with k = 1, . . . , N
φy (k) < φy (k + 1)
Due to the strictly-increasing requirement of the reference index, the minimum local slope of
the warping curve is unity, and time compression is therefore ruled out. MVM matching is
therefore undefined if the query is longer than the reference, and only one alignment exists if
their lengths are equal.
In dtw, step pattern instances implementing MVM can be built through the function
mvmStepPattern(). The elasticity integer argument limits the maximum length of a con-
tiguous subsequence which can be skipped in the reference time series. If no limit is desired,
elasticity should be made at least as large as the reference length.
Note that we entered lm according to matrix conventions: the first subscript indexes elements
in the query time series, while the second indexes the reference (right hand side of Figure 4).
Therefore, the query is understood to grow row-wise towards the bottom, while the reference
goes column-wise towards the right. Conversely, the exercise text displays the table in plot-like
conventions (ix growing rightwards and iy upwards).
The exercise requires a specific step pattern which is readily identified as the asymmetric
recursion (bottom left of Figure 3). To solve the problem and find the best global path going
through the grid, we invoke dtw with one matrix argument. From the result, we extract the
cost matrix (see next section) and the normalized distance, 7/6, thus solving the problem:
R> alignment$normalizedDistance
[1] 1.166667
A follow-up question of the same exercise requires the optimal alignment between the whole
test and any prefix of the reference; in other words, we lift the constraint on the reference
end-point. This is achieved with the setting open.end = TRUE. As above, we invoke dtw in
its matrix form; the optimal end-point (that is, φy (T )) is found in component $jmin of the
result.
R> alignmentOE <- dtw(lm, step = asymmetric, keep = TRUE, open.end = TRUE)
R> alignmentOE$jmin
[1] 5
18 dtw: Computing and Visualizing Dynamic Time Warping Alignments in R
R> alignmentOE$normalizedDistance
[1] 1
4. Displaying alignments
Plots are valuable tools to inspect time series pairs together with their alignments. Sev-
eral plotting styles are available in dtw for producing publication-quality figures. They are
achieved through the plot method overloaded for objects of type dtw.
The first two plot styles discussed below, namely two- and three-way, are used to inspect the
time series themselves along with their alignment. For this reason, the two actual input time
series must be available, and they have to be single-variate. For convenience, time series are
retrieved from the alignment object itself, if available (elements $query and $reference);
they can be overridden via the xts and yts plot arguments.
A density plot style is also available to display the relative costs of different warping curves.
It builds on the global cost matrix only, and does not therefore require the knowledge of the
two original time series.
3 2 3 2 2 2 6 6 7
6
6
3 2 3 1 1 1 5 5 5 6
5
5
1:ncol(ccm)
1:ncol(lcm)
2 2 2 1 2 2 4 4 6 7
4
4
2 1 2 2 1 3 2 4 5 5 8
3
3
1 1 1 1 2 3 2 3 4 6 9
2
2
1 1 3 3 3 3 1 2 5 8 11 14
1
1
1 2 3 4 5 6 1 2 3 4 5 6
1:nrow(lcm) 1:nrow(ccm)
Figure 8: The local distance matrix for the exercise in Section 3.9 (left) and the correspond-
ing cumulative distance matrix (right) under the asymmetric step pattern. The optimal
alignment path is superimposed.
passing the argument type = "twoway" to the plot call. The optional numeric argument
offset can be used to visually separate query and reference time series; if set, the scales
for the reference time series are displayed on the secondary (right-hand) vertical axis. Other
options affecting the visual appearance are explained in the ?dtwPlotTwoWay manual page.
R> library("dtw")
R> data("aami3a")
R> ref <- window(aami3a, start = 0, end = 2)
R> test <- window(aami3a, start = 2.7, end = 5)
R> plot(dtw(test, ref, k = TRUE), type = "two", off = 1, match.lty = 2,
+ match.indices = 20)
Timeseries alignment
1.0 0.0 −1.0
100
80
Reference index
60
d$index2
40 20
0
1.0
yts
xts
−1.0 0.0
d$index1
0 20 40 60 80 100
Query index
Figure 9: Three-way plot of the asymmetric alignment between a noisy sine and
a cosine in [0, 2π], with visual guide lines drawn every π/4. Code available in
example(dtwPlotThreeWay).
Toni Giorgino 21
100
3
0.
80
0.1
Reference index
2
1.
60
1.1
1 0.9
0.8
40
0.7
0.6 0.2
0.5 0.3
0.4
0.4 0.5
20
0.6
0.7
0.6
0.8
0.5
0.9
0.7
0.8
20 40 60 80 100
Query index
Figure 10: Cost density plot: average per-step cost density of the sine-cosine global alignment.
The local constraints and weighting are chosen from the asymmetric step pattern. Code in
example(dtwPlotDensity).
Computational details
The computing kernel of the dtw function is written in the C programming language for
22 dtw: Computing and Visualizing Dynamic Time Warping Alignments in R
efficiency. Alignment computations are quite fast, as long as the cross-distance matrices fit in
the machine’s RAM. A standard quad-core Linux x86-64 PC with 4 GB of RAM and 4 GB of
swap computes (using only one core) an unconstrained alignment of 100 × 100 time points in
7 ms, 6000 × 6000 points in under 10 s, and 8000 × 8000 points (close to the virtual memory
limit) in 10 minutes. Larger problems may be addressed by approximate strategies, e.g.,
computing a preliminary alignment between downsampled time series (Salvador and Chan
2004); indexing (Keogh and Ratanamahatana 2005); or breaking one of the sequences into
chunks and then iterating subsequence matches.
Acknowledgments
I am grateful to P. Tormene for testing the package extensively. Thanks to M. J. Harvey and
the anonymous reviewers for their valuable suggestions.
References
Aach J, Church GM (2001). “Aligning Gene Expression Time Series with Time Warping
Algorithms.” Bioinformatics, 17(6), 495–508.
Faundez-Zanuy M (2007). “On-Line Signature Recognition Based on VQ-DTW.” Pattern
Recognition, 40(3), 981–992.
Gabadinho A, Ritschard G, Studer M, Müller NS (2009). “Mining Sequence Data in R with
TraMineR: A User’s Guide.” Technical report, Department of Econometrics and Labora-
tory of Demography, University of Geneva, Geneva. URL http://mephisto.unige.ch/
TraMineR/.
Gentleman RC, Carey VJ, Bates DM, Bolstad B, Dettling M, Dudoit S, Ellis B, Gautier
L, Ge Y, Gentry J, Hornik K, Hothorn T, Huber W, Iacus S, Irizarry R, Leisch F, Li C,
Maechler M, Rossini AJ, Sawitzki G, Smith C, Smyth G, Tierney L, Yang JYH, Zhang
J (2004). “Bioconductor: Open Software Development for Computational Biology and
Bioinformatics.” Genome Biology, 5, R80. URL http://genomebiology.com/2004/5/10/
R80.
Giorgino T (2009). “Computing and Visualizing Dynamic Time Warping Alignments in R: The
dtw Package.” Journal of Statistical Software, 31(7), 1–24. URL http://www.jstatsoft.
org/v31/i07/.
Giorgino T, Tormene P (2009). dtw: Dynamic Time Warping Algorithms. R package ver-
sion 1.13-1, URL http://CRAN.R-project.org/package=dtw.
Goldberger AL, Amaral LA, Glass L, Hausdorff JM, Ivanov PC, Mark RG, Mietus JE, Moody
GB, Peng CK, Stanley HE (2000). “PhysioBank, PhysioToolkit, and PhysioNet: Compo-
nents of a new Research Resource for Complex Physiologic Signals.” Circulation, 101(23),
E215–E220.
Gollmer K, Posten C (1996). “Supervision of Bioprocesses Using a Dynamic Time Warping
Algorithm.” Control Engineering Practice, 4(9), 1287–1295.
Toni Giorgino 23
Huang B, Kinsner W (2002). “ECG Frame Classification Using Dynamic Time Warping.”
In W Kinsner, A Sebak, K Ferens (eds.), “Proceedings of the Canadian Conference on
Electrical and Computer Engineering – IEEE CCECE 2002,” volume 2, pp. 1105–1110.
IEEE Computer Society, Los Alamitos, CA, USA. doi:10.1109/CCECE.2002.1013101.
Latecki LJ, Megalooikonomou V, Wang Q, Yu D (2007). “An Elastic Partial Shape Matching
Technique.” Pattern Recognition, 40(11), 3069–3080.
Meyer D, Buchta C (2009). proxy: Distance and Similarity Measures. R package version 0.4-3,
URL http://CRAN.R-project.org/package=proxy.
Oka R (1998). “Spotting Method for Classification of Real World Data.” The Computer
Journal, 41(8), 559–565. doi:10.1093/comjnl/41.8.559.
Rath TM, Manmatha R (2003). “Word Image Matching Using Dynamic Time Warping.” In
R Manmatha (ed.), “Proceedings of the IEEE Computer Society Conference on Computer
Vision and Pattern Recognition,” volume 2, pp. II–521–II–527. IEEE Computer Society,
Los Alamitos, CA, USA.
R Development Core Team (2009). R: A Language and Environment for Statistical Computing.
R Foundation for Statistical Computing, Vienna, Austria. ISBN 3-900051-07-0, URL http:
//www.R-project.org/.
24 dtw: Computing and Visualizing Dynamic Time Warping Alignments in R
Sakoe H, Chiba S (1978). “DynaMic Programming Algorithm Optimization for Spoken Word
Recognition.” IEEE Transactions on Acoustics, Speech, and Signal Processing, 26(1), 43–
49.
Sakurai Y, Faloutsos C, Yamamuro M (2007). “Stream Monitoring Under the Time Warping
Distance.” In L Liu, A Yazici, R Chirkova, V Oria (eds.), “Proceedings of the IEEE
23rd International Conference on Data Engineering – ICDE 2007,” pp. 1046–1055. IEEE
Computer Society, Los Alamitos, CA, USA. doi:10.1109/ICDE.2007.368963.
Salvador S, Chan P (2004). “FastDTW: Toward Accurate Dynamic Time Warping in Linear
Time and Space.” In KP Unnikrishnan, R Uthurusamy, J Han (eds.), “KDD Workshop on
Mining Temporal and Sequential Data,” pp. 70–80. ACM, New York, NY, USA.
Tak YS (2007). “A Leaf Image Retrieval Scheme Based on Partial Dynamic Time Warping
and Two-Level Filtering.” In D Wei, T Miyazaki, I Paik (eds.), “Proceedings of the 7th
IEEE International Conference on Computer and Information Technology – CIT 2007,” pp.
633–638. IEEE Computer Society, Los Alamitos, CA, USA. doi:10.1109/CIT.2007.158.
Tuzcu V, Nas S (2005). “Dynamic Time Warping as a Novel Tool in Pattern Recognition
of ECG Changes in Heart Rhythm Disturbances.” In M Jamshidi, M Johnson, P Chen
(eds.), “Proceedings of the IEEE International Conference on Systems, Man and Cyber-
netics,” volume 1, pp. 182–186 Vol. 1. IEEE Computer Society, Los Alamitos, CA, USA.
doi:10.1109/ICSMC.2005.1571142.
Affiliation:
Toni Giorgino
Laboratory for Biomedical Informatics
Dipartimento di Informatica e Sistemistica
Università di Pavia
via Ferrata 1
I-27100, Pavia, Italy
E-mail: [email protected]
URL: http://www.labmedinfo.org/people/cv/giorgino.htm
Currently with:
Computational Biochemistry and Biophysics Laboratory
Research Group on Biomedical Informatics (GRIB-IMIM)
Parc de Recerca Biomèdica de Barcelona
c/ Dr. Aiguader, 88
E-08003, Barcelona, Spain