Computing and Visualizing Dynamic Time Warping Alignments in R : The dtw Package

This introduction to the R package dtw is a (slightly) modiﬁed 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 uniﬁcation of them; it allows R users to compute time series alignments mixing freely a variety of continuity constraints, restriction windows, endpoints, local distance deﬁnitions, and so on. The package also provides functions for visualizing alignments and constraints using several classic diagram types.


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 distance 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 context 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 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.

Definition of the algorithm
In the following exposition, the choice of symbols will follow roughly the one in Chapter 4 of Rabiner and Juang (1993), which is an excellent reference on the subject.We assume that we want to compare two time series: a test, or query, X = (x 1 , . . ., x N ); and a reference Y = (y 1 , . . ., y M ).For clarity, in the following we shall reserve the symbol i = 1 . . .N for indexing the elements in X and j = 1 . . .M for those in Y .We also assume that a nonnegative, local dissimilarity function f is defined between any pair of elements x i and y j , with the shortcut: Note that d, the cross-distance matrix between vectors X and Y , is the only input to the DTW algorithm: elements x i and y j 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 : 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 : where m φ (k) is a per-step weighting coefficient and M φ is the corresponding normalization constant, which ensures that the accumulated distortions are comparable along different paths.
To ensure reasonable warps, constraints are usually imposed on φ.For example, monotonicity is imposed to preserve their time ordering and avoid meaningless loops: The idea underlying DTW is to find the optimal alignment φ such that 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 classifiers).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 inspect post-hoc aligned signals or measure time distortions.

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: 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: 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.Example 1 The aami3a time series included in the package contains a reference electrocardiogram from the PhysioBank dataset (Goldberger et al. 2000).We extract two nonoverlapping windows from it, and compute their optimal alignment with the default dtw settings.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 $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.

Step patterns and local slope constraints
The elegant formulation of the DTW alignment problem lends itself to a variety of extensions.For example, one usually wants to limit the number of consecutive elements which are "skipped" in either time series, i.e., are left unmatched (skipping elements is often entirely disallowed by a continuity constraint, indeed Example 2 Compute the same alignment of the previous example, assuming the well-known asymmetric pattern (bottom left of Figure 3).

R> alignment <-dtw(test,ref,step.pattern=asymmetric) R> alignment$distance
[1] 11.497 When printed, stepPattern objects display the corresponding DTW recursion in humanreadable 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).

Normalization hint: N+M
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 attributes: 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).

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.

Query index
Reference index 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.
Slope weighting Symmetry Formula Hint (Rabiner-Juang) Values n and m are the number of elements actually matched in the query and reference, respectively, i.e., For global alignments, they are equal to the lengths of the input time series, i.e., n = N and m = M .

A note on indexing conventions and axes
As a general rule, we stick to the convention that the first argument and indices refer to the query time series, and the second to the reference.This implies that when we print alignment-related matrices such as d(i, j), the query index grows row-wise towards the bottom.The reader should not confuse this layout with plot axes, where the query and reference are usually arranged along the abscissa and ordinate respectively (Figure 4).

Windowing and global constraints
A global constraint, or window, explicitly forbids warping curves to enter some region of the (i, j) plane.A global constraint translates an a-priori knowledge about the fact that the time distortion is limited.For example, the well-known Sakoe-Chiba band (Sakoe and Chiba 1978) enforces the additional constraint where T 0 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.typeargument 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, T 0 , is passed through the window.sizeargument.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 inappropriate when the lengths of the two inputs differ significantly.In particular, when |N − M | > T 0 , 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 T 0 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 integer 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.
R> dtwWindow.plot(sakoeChibaWindow,window.size=2,reference=17,query=13) Reference: samples 1..17 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.

Unconstrained endpoints: Prefix and subsequence matches
Normally, the DTW distance is understood as a global alignment, i.e., subject to the conditions (4) and ( 5).In certain applications, partial matches are useful, and one consequently relaxes one or both the constraints.Interested readers can find a review of partial matching algorithms, applications, and the interplay with normalization, in a paper by Tormene et al. (2009).
The open-end (OE-DTW) or prefix-matching algorithm is defined by relaxing the end-point constraint (5).The algorithm therefore returns the prefix of the reference which best matches the query; it has been used e.g., by Sakoe (1979) and Mori et al. (2006).Open-end matching is achieved, in principle, by constructing several incomplete versions Y (p) of the reference Y , each truncated at the index p = 1, . . ., M .One then computes their corresponding DTW distances from X, and picks the best match: 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 y j 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: In dtw, OBE-DTW alignments are computed setting both the open.beginand open.endarguments to TRUE.2 Open-begin alignments are supported for step patterns with n-type normalization only.

Dealing with multivariate time series
As seen in Section 2, the actual time series values only enter the DTW algorithm through their cross-distance matrix, i.e., matrix d in Equation 1.In practice, the choice for the local distance 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 X ic and Y jc , 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., Other distance functions can be selected through the dist.methodcharacter 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.The optimal alignment of strings, i.e., discrete values or categorial data, rather than of sequences of real values, is an ubiquitous task in bioinformatics, closely related to DTW.Functions 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 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.

Computing several alignments at once
A common situation, arising e.g., in clustering and classification of time series, is to compute several DTW distances between pairs of elements in a database.For instance, we assume to have a database {Q k } of K time series, each of which is a single-variate vector Q k = (q k1 , . . ., q kN ).We also assume that all Q k have the same length N .The database can therefore be encoded as a K × N matrix, {Q k } = q ki .To compute DTW alignments between all possible couples, we iterate two indices h and k over the rows of q, thus obtaining a K × K self-dissimilarity matrix: 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 q ki is given as a matrix q (again, time series are arranged in rows), Λ can be straightforwardly computed through proxy::dist(q, q, method = "DTW").3Computing 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.

Minimal variance matching
Latecki et al. (2007) proposed the minimal variance matching (MVM) algorithm to align a given test to a reference, allowing arbitrary portions of the template to be skipped (Figure 7, left-hand side).Interestingly, MVM may be considered a special case of DTW with a large step pattern (Figure 7, right-hand side).
Like the asymmetric step pattern, the MVM algorithm constrains each query element to match exactly one time point in the template, so the degenerate empty-to-empty match is not allowed.Vice-versa, an arbitrary number of template elements can remain unmatched.
Matched reference points must be in strict increasing order, although arbitrary gaps are allowed in the sequence.This translates into the continuity constraints 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 contiguous 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.
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.

Retrieving cost matrices
If the parameter keep.internals is TRUE, the local distance matrix and the cumulative cost matrix are preserved after the calculation, and stored in the result elements $localCostMatrix and $costMatrix, respectively.The matrices can be printed and manipulated as usual.
Figure 8, for example, shows how to display them along with the alignment path superimposed.In the left panel one can hand-check the result of the exercise solved in the previous section: no better warping path exists that passes by (1, 1) through (6, 6) under the constraints of the asymmetric pattern, and the cumulative cost is indeed found in the upper-right element of the right panel.

Displaying alignments
Plots are valuable tools to inspect time series pairs together with their alignments.Several 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.

Two-way plotting
One intuitive alignment visualization style places both time series in the same plane, and connects the matching point pairs with segments (see e.g., Figure 1).This plot style is selected 1:ncol(lcm) Figure 8: The local distance matrix for the exercise in Section 3.9 (left) and the corresponding 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.
Example 5 Generate the plot in Figure 1.

Three-way plotting
Another effective layout to display alignments places the query time series horizontally in a small lower panel, the reference time series vertically on the left; a larger inner panel holds the warping curve (Figure 7).In this way, matching points can be recovered by tracing indices on the query time series, moving upwards until the warping curve is met, and then moving leftwards to discover the index of the reference matched.The advantage of this method is that the warping curve is directly exposed, so it becomes easy to visualize the impact of the local and global constraints.
Three-way plots can be achieved with the type = "threeway" argument to the plot call.Match lines can also be explicitly visualized, as shown in Figure 9; documentation for all options is available in ?dtwPlotThreeWay.

Displaying the cost density
A third plot style displays the "cost density" of alignments, and can therefore be useful to inspect qualitatively how much "slack" is present around the optimal alignment (Figure 10).By default, the cumulative distance distribution is displayed as a density distribution with contours superimposed.The result is a terse display of the cumulative distance matrix, analogous to the right panel of Figure 8.
For normalizable step patterns, a plot of the per-step density can also be requested with the normalize = TRUE argument.Since the density plot is based on the cumulative distance matrix, keep = TRUE is required in the dtw function call.Density plotting is selected with the type = "density" parameter to the plot call, and documented in ?dtwPlotDensity.

Computational details
The computing kernel of the dtw function is written in the C programming language for 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.

Figure 1 :
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.

Figure 2 :
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.

Figure 4 :
Figure 4: Different conventions for displaying distance matrices: plot-like (left) and matrix (right) arrangements.

Figure 5 :
Figure5: 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.

Figure 6 :
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 computed setting the open.begin= TRUE and/or open.end= TRUE arguments.Code available in example(dtw).

Figure 7 :
Figure7: 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.

Figure 9 :
Figure9: 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).

Figure 10 :
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).

Table 1 :
, users of dtw have access to almost the full range of step patterns defined in the literature, with no programming burden.Step patterns are represented by objects of class stepPattern.Patterns are selected by passing an appropriate instance to the step.patternargument of the dtw function call, as in the following example: Elements in a dtw result object, as of package version 1.13-1.Remarks: k -requires 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 .
An analogous plot style, suitable for larger alignments, is presented in Section 4.3.