dtwalign - Read the Docs

33
dtwalign Release 0.1.0 Jul 09, 2019

Transcript of dtwalign - Read the Docs

Page 1: dtwalign - Read the Docs

dtwalignRelease 0.1.0

Jul 09, 2019

Page 2: dtwalign - Read the Docs
Page 3: dtwalign - Read the Docs

Contents:

1 Installation 31.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.2 Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61.3 API Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

2 Reference 23

3 Indices and tables 25

Python Module Index 27

Index 29

i

Page 4: dtwalign - Read the Docs

ii

Page 5: dtwalign - Read the Docs

dtwalign, Release 0.1.0

Comprehensive dynamic time warping module for python.

Contents: 1

Page 6: dtwalign - Read the Docs

dtwalign, Release 0.1.0

2 Contents:

Page 7: dtwalign - Read the Docs

CHAPTER 1

Installation

pip install dtwalign

1.1 Features

1.1.1 Fast computation

by Numba

1.1.2 Partial alignment

• before alignment

3

Page 8: dtwalign - Read the Docs

dtwalign, Release 0.1.0

• after alignment

1.1.3 Local constraint (step pattern)

example:

4 Chapter 1. Installation

Page 9: dtwalign - Read the Docs

dtwalign, Release 0.1.0

Symmetric2 AsymmetricP2 TypeIVc

1.1.4 Global constraint (windowing)

example:

Sakoechiba Itakura User defined

1.1. Features 5

Page 10: dtwalign - Read the Docs

dtwalign, Release 0.1.0

1.1.5 Alignment path visualization

1.2 Tutorial

1.2.1 Basic Usage

Firstly, let’s generate toy data for this tutorial.

import numpy as npimport matplotlib.pyplot as plt

np.random.seed(1234)# generate toy datax = np.sin(2 * np.pi * 3.1 * np.linspace(0, 1, 101))x += np.random.rand(x.size)y = np.sin(2 * np.pi * 3 * np.linspace(0, 1, 120))y += np.random.rand(y.size)

plt.plot(x, label="query")plt.plot(y, label="reference")plt.legend()plt.ylim(-1, 3)

6 Chapter 1. Installation

Page 11: dtwalign - Read the Docs

dtwalign, Release 0.1.0

Then run dtw() method which returns DtwResult object.

from dtwalign import dtwres = dtw(x, y)

Note: The first run takes a few seconds for jit compilation.

DTW distance

DTW distance can be refered via DtwResult object.

print("dtw distance: {}".format(res.distance))# dtw distance: 30.048812654583166print("dtw normalized distance: {}".format(res.normalized_distance))# dtw normalized distance: 0.13596747807503695

Note: If you want to calculate only dtw distance (i.e. no need to gain alignment path), give ‘distance_only’ argumentas True when runs dtw method (it makes faster).

Alignment path

DtwResult object offers a method which visualize alignment path with cumsum cost matrix.

res.plot_path()

1.2. Tutorial 7

Page 12: dtwalign - Read the Docs

dtwalign, Release 0.1.0

Alignment path array is also provided:

x_path = res.path[:, 0]y_path = res.path[:, 1]

Warp one to the other

get_warping_path() method provides an alignment path of X with fixed Y and vice versa.

# warp x to yx_warping_path = res.get_warping_path(target="query")plt.plot(x[x_warping_path], label="aligned query to reference")plt.plot(y, label="reference")plt.legend()plt.ylim(-1, 3)

8 Chapter 1. Installation

Page 13: dtwalign - Read the Docs

dtwalign, Release 0.1.0

# warp y to xy_warping_path = res.get_warping_path(target="reference")plt.plot(x, label="query")plt.plot(y[y_warping_path], label="aligned reference to query")plt.legend()plt.ylim(-1, 3)

1.2.2 Advanced Usage

1.2. Tutorial 9

Page 14: dtwalign - Read the Docs

dtwalign, Release 0.1.0

Global constraint

dtw() method can take window_type parameter to constrain the warping path globally which is also known as‘windowing’.

# run DTW with Itakura constraintres = dtw(x, y, window_type="itakura")res.plot_path()

# run DTW with Sakoechiba constraintres = dtw(x, y, window_type="sakoechiba", window_size=20)# visualize alignment path with cumsum cost matrixres.plot_path()

10 Chapter 1. Installation

Page 15: dtwalign - Read the Docs

dtwalign, Release 0.1.0

Local constraint

dtwalign package also supports local constrained optimization which is also known as ‘step pattern’. Followingstep patterns are supported:

• symmetric1

• symmetric2

• symmetricP05

• symmetricP0

• symmetricP1

• symmetricP2

• Asymmetric

• AsymmetricP0

• AsymmetricP05

• AsymmetricP1

• AsymmetricP2

• TypeIa

• TypeIb

• TypeIc

• TypeId

• TypeIas

1.2. Tutorial 11

Page 16: dtwalign - Read the Docs

dtwalign, Release 0.1.0

• TypeIbs

• TypeIcs

• TypeIds

• TypeIIa

• TypeIIb

• TypeIIc

• TypeIId

• TypeIIIc

• TypeIVc

• Mori2006

# run DTW with symmetricP2 patternres = dtw(x, y, step_pattern="symmetricP2")res.plot_path()

Partial alignment

dtw() method also be able to perform partial matching algorithm by setting open_begin and open_end. Beforesee example code, let’s make toy data via following:

x_partial = np.sin(2 * np.pi * 3 * np.linspace(0.3, 0.8, 100))x_partial += np.random.rand(x_partial.size)y_partial = np.sin(2 * np.pi * 3.1 * np.linspace(0, 1, 120))y_partial += np.random.rand(y_partial.size)

(continues on next page)

12 Chapter 1. Installation

Page 17: dtwalign - Read the Docs

dtwalign, Release 0.1.0

(continued from previous page)

plt.plot(x_partial, label="query")plt.plot(y_partial, label="reference")plt.legend()plt.ylim(-1, 3)

Open-end alignment can be performed by letting open_end be True.

res = dtw(x_partial, y_partial, open_end=True)res.plot_path()

1.2. Tutorial 13

Page 18: dtwalign - Read the Docs

dtwalign, Release 0.1.0

As above, let open_begin be True to run open-begin alignment.

Note: Open-begin requires “N” normalizable pattern. If you want to know more detail, see references.

res = dtw(x_partial, y_partial, step_pattern="asymmetric", open_begin=True)res.plot_path()

14 Chapter 1. Installation

Page 19: dtwalign - Read the Docs

dtwalign, Release 0.1.0

res = dtw(x_partial, y_partial, step_pattern="asymmetric", open_begin=True, open_→˓end=True)res.plot_path()

1.2. Tutorial 15

Page 20: dtwalign - Read the Docs

dtwalign, Release 0.1.0

Use other metric

You can use other pair-wise distance metric (default is euclidean). Metrics in scipy.spatial.distance.cdist are supported:

res = dtw(x, y, dist="minkowski")

Arbitrary function which returns distance value between x and y is also available.

res = dtw(x, y, dist=lambda x, y: np.abs(x - y))

Use pre-computed distance matrix

You can also calculate DTW with given pre-computed distance matrix like:

# calculate pair-wise distance matrix in advancefrom scipy.spatial.distance import cdistX = cdist(x[:, np.newaxis], y[:, np.newaxis], metric="euclidean")

# use `dtw_from_distance_matrix` method for computation.from dtwalign import dtw_from_distance_matrixres = dtw_from_distance_matrix(X, window_type="itakura", step_pattern="typeIVc")

Use user-defined constraints

Local constraint (step pattern)

# define local constraint (step pattern)from dtwalign.step_pattern import UserStepPatternpattern_info = [

dict(indices=[(-1,0),(0,0)],weights=[1]

),dict(

indices=[(-1,-1),(0,0)],weights=[2]

),dict(

indices=[(0,-1),(0,0)],weights=[1]

)]

user_step_pattern = UserStepPattern(pattern_info=pattern_info,normalize_guide="N+M")

# plotuser_step_pattern.plot()

16 Chapter 1. Installation

Page 21: dtwalign - Read the Docs

dtwalign, Release 0.1.0

Global constraint (windowing)

# define global constraint (windowing)from dtwalign.window import UserWindowuser_window = UserWindow(X.shape[0], X.shape[1], win_func=lambda i, j: np.abs(i ** 2 -→˓ j ** 2) < 5000)

# plotuser_window.plot()

1.2. Tutorial 17

Page 22: dtwalign - Read the Docs

dtwalign, Release 0.1.0

To compute DTW with user-specified constraints, use dtw_low method like:

# import lower dtw interfacefrom dtwalign import dtw_lowres = dtw_low(X,window=user_window,pattern=user_step_pattern)res.plot_path()

18 Chapter 1. Installation

Page 23: dtwalign - Read the Docs

dtwalign, Release 0.1.0

1.3 API Reference

1.3.1 DTW

dtwalign.dtw.dtw(x, y, dist=’euclidean’, window_type=’none’, window_size=None,step_pattern=’symmetric2’, dist_only=False, open_begin=False, open_end=False)

Perform dtw.

Parameters

• x (1D or 2D array (sample * feature)) – Query time series.

• y (1D or 2D array (sample * feature)) – Reference time series.

• dist (string or callable) – Define how to calclulate pair-wise distance betweenx and y. If a string given, it will be interpreted as metric argument of scipy.spatial.distance. If callable that defines metric between two samples, it will be used to computedistance matrix.

• window_type (string) – Window type to use. If “sakoechiba” given, Sakoechiba win-dow will be used. If “itakura” given, Itakura window will be used.

• window_size (int) – Window size to use for Sakoechiba window.

• step_pattern (string) – Step pattern to use.

• dist_only (bool) – Whether or not to obtain warping path. If true, only alignmentdistance will be calculated.

• open_begin (bool) – Whether or not perform open-ended alignment at the starting pointof query time series. If true, partial alignment will be performed.

• open_end (bool) – Whether or not perform open-ended alignment at the end point ofquery time series. If true, partial alignment will be performed.

Returns Result obj.

Return type dtwalign.result.DtwResult

dtwalign.dtw.dtw_from_distance_matrix(X, window_type=’none’, window_size=None,step_pattern=’symmetric2’, dist_only=False,open_begin=False, open_end=False)

Perform dtw using pre-computed pair-wise distance matrix.

Parameters

• X (2D array) – Pre-computed pair-wise distance matrix.

• others – see dtw() function.

Returns Result obj.

Return type dtwalign.result.DtwResult

dtwalign.dtw.dtw_low(X, window, pattern, dist_only=False, open_begin=False, open_end=False)Low-level dtw interface.

Parameters

• X (2D array) – Pair-wise distance matrix.

• window (dtwalign.window.BaseWindow object) – window object.

• pattern (dtwalign.step_pattern.BasePattern object) – step pattern ob-ject.

1.3. API Reference 19

Page 24: dtwalign - Read the Docs

dtwalign, Release 0.1.0

• others – see dtw() function.

Returns Result obj.

Return type dtwalign.result.DtwResult

1.3.2 Result

class dtwalign.result.DtwResult(cumsum_matrix, path, window, pattern)Result of DTW.

pathAlignment path. * First column: query path array * Second column: reference path array

Type 2d array

distanceAlignment distance.

Type float

normalized_distanceNormalized alignment distance.

Type float

get_warping_path(target=’query’)Get warping path.

Parameters target (string, "query" or "reference") – Specify the target to bewarped.

Returns warping_index – Warping index.

Return type 1D array

plot_path(with_=’cum’)Plot alignment path.

Parameters with (string, "win" or "cum" or None) – If given, following will beplotted with alignment path: * “win” : window matrix * “cum” : cumsum matrix

1.3.3 Step patterns

class dtwalign.step_pattern.Asymmetric

class dtwalign.step_pattern.AsymmetricP0

class dtwalign.step_pattern.AsymmetricP05

class dtwalign.step_pattern.AsymmetricP1

class dtwalign.step_pattern.AsymmetricP2

class dtwalign.step_pattern.BasePatternStep pattern base class.

plot()Show step pattern.

class dtwalign.step_pattern.Mori2006

class dtwalign.step_pattern.Symmetric1

20 Chapter 1. Installation

Page 25: dtwalign - Read the Docs

dtwalign, Release 0.1.0

class dtwalign.step_pattern.Symmetric2

class dtwalign.step_pattern.SymmetricP0Same as symmetric2 pattern.

class dtwalign.step_pattern.SymmetricP05

class dtwalign.step_pattern.SymmetricP1

class dtwalign.step_pattern.SymmetricP2

class dtwalign.step_pattern.TypeIIIc

class dtwalign.step_pattern.TypeIIa

class dtwalign.step_pattern.TypeIIb

class dtwalign.step_pattern.TypeIIc

class dtwalign.step_pattern.TypeIId

class dtwalign.step_pattern.TypeIVc

class dtwalign.step_pattern.TypeIa

class dtwalign.step_pattern.TypeIas

class dtwalign.step_pattern.TypeIb

class dtwalign.step_pattern.TypeIbs

class dtwalign.step_pattern.TypeIc

class dtwalign.step_pattern.TypeIcs

class dtwalign.step_pattern.TypeId

class dtwalign.step_pattern.TypeIds

class dtwalign.step_pattern.Unitary

class dtwalign.step_pattern.UserStepPattern(pattern_info, normalize_guide)User defined step pattern.

Parameters

• pattern_info (list) – list contains pattern information. ex) the case of symmetric2pattern:

pattern_info = [dict(

indices=[(-1,0),(0,0)],weights=[1]

),dict(

indices=[(-1,-1),(0,0)],weights=[2]

),dict(

indices=[(0,-1),(0,0)],weights=[1]

)]

• normalize_guide (string ('N','M','N+M','none')) – Guide to computenormalized distance.

1.3. API Reference 21

Page 26: dtwalign - Read the Docs

dtwalign, Release 0.1.0

1.3.4 Windows

class dtwalign.window.BaseWindowBase window class.

plot()Show window.

class dtwalign.window.ItakuraWindow(len_x, len_y)Itakura window.

Parameters

• len_x (int) – Length of query.

• len_y (int) – Length of reference.

class dtwalign.window.NoWindow(len_x, len_y)No window class which will be used for no constraint.

Parameters

• len_x (int) – Length of query.

• len_y (int) – Length of reference.

class dtwalign.window.SakoechibaWindow(len_x, len_y, size)Sakoechiba window.

Parameters

• len_x (int) – Length of query.

• len_y (int) – Length of reference.

• size (int) – Size of window width.

class dtwalign.window.UserWindow(len_x, len_y, win_func, *args, **kwargs)Initialize user defined window.

Parameters

• len_x (int) – Length of query.

• len_y (int) – Length of reference.

• win_func (callable) – Any function which returns bool.

• **kwargs (*args,) – Arguments for win_func

22 Chapter 1. Installation

Page 27: dtwalign - Read the Docs

CHAPTER 2

Reference

• Sakoe, H.; Chiba, S., Dynamic programming algorithm optimization for spoken word recognition, Acoustics,Speech, and Signal Processing

• Paolo Tormene, Toni Giorgino, Silvana Quaglini, Mario Stefanelli (2008). Matching Incomplete Time Serieswith Dynamic Time Warping: An Algorithm and an Application to Post-Stroke Rehabilitation. Artificial Intel-ligence in Medicine, 45(1), 11-34.

• Toni Giorgino (2009). Computing and Visualizing Dynamic Time Warping Alignments in R: The dtw Package.Journal of Statistical Software, 31(7), 1-24.

23

Page 28: dtwalign - Read the Docs

dtwalign, Release 0.1.0

24 Chapter 2. Reference

Page 29: dtwalign - Read the Docs

CHAPTER 3

Indices and tables

• genindex

• modindex

• search

25

Page 30: dtwalign - Read the Docs

dtwalign, Release 0.1.0

26 Chapter 3. Indices and tables

Page 31: dtwalign - Read the Docs

Python Module Index

ddtwalign.dtw, 19dtwalign.result, 20dtwalign.step_pattern, 20dtwalign.window, 22

27

Page 32: dtwalign - Read the Docs

dtwalign, Release 0.1.0

28 Python Module Index

Page 33: dtwalign - Read the Docs

Index

AAsymmetric (class in dtwalign.step_pattern), 20AsymmetricP0 (class in dtwalign.step_pattern), 20AsymmetricP05 (class in dtwalign.step_pattern), 20AsymmetricP1 (class in dtwalign.step_pattern), 20AsymmetricP2 (class in dtwalign.step_pattern), 20

BBasePattern (class in dtwalign.step_pattern), 20BaseWindow (class in dtwalign.window), 22

Ddistance (dtwalign.result.DtwResult attribute), 20dtw() (in module dtwalign.dtw), 19dtw_from_distance_matrix() (in module dt-

walign.dtw), 19dtw_low() (in module dtwalign.dtw), 19dtwalign.dtw (module), 19dtwalign.result (module), 20dtwalign.step_pattern (module), 20dtwalign.window (module), 22DtwResult (class in dtwalign.result), 20

Gget_warping_path() (dtwalign.result.DtwResult

method), 20

IItakuraWindow (class in dtwalign.window), 22

MMori2006 (class in dtwalign.step_pattern), 20

Nnormalized_distance (dtwalign.result.DtwResult

attribute), 20NoWindow (class in dtwalign.window), 22

Ppath (dtwalign.result.DtwResult attribute), 20plot() (dtwalign.step_pattern.BasePattern method), 20plot() (dtwalign.window.BaseWindow method), 22plot_path() (dtwalign.result.DtwResult method), 20

SSakoechibaWindow (class in dtwalign.window), 22Symmetric1 (class in dtwalign.step_pattern), 20Symmetric2 (class in dtwalign.step_pattern), 20SymmetricP0 (class in dtwalign.step_pattern), 21SymmetricP05 (class in dtwalign.step_pattern), 21SymmetricP1 (class in dtwalign.step_pattern), 21SymmetricP2 (class in dtwalign.step_pattern), 21

TTypeIa (class in dtwalign.step_pattern), 21TypeIas (class in dtwalign.step_pattern), 21TypeIb (class in dtwalign.step_pattern), 21TypeIbs (class in dtwalign.step_pattern), 21TypeIc (class in dtwalign.step_pattern), 21TypeIcs (class in dtwalign.step_pattern), 21TypeId (class in dtwalign.step_pattern), 21TypeIds (class in dtwalign.step_pattern), 21TypeIIa (class in dtwalign.step_pattern), 21TypeIIb (class in dtwalign.step_pattern), 21TypeIIc (class in dtwalign.step_pattern), 21TypeIId (class in dtwalign.step_pattern), 21TypeIIIc (class in dtwalign.step_pattern), 21TypeIVc (class in dtwalign.step_pattern), 21

UUnitary (class in dtwalign.step_pattern), 21UserStepPattern (class in dtwalign.step_pattern),

21UserWindow (class in dtwalign.window), 22

29