### Access dtw documentation Source: https://dynamictimewarping.github.io/r Load the library and access built-in demos and help pages to get started. ```R > library(dtw) > demo(dtw) > ?dtw > ?plot.dtw ``` -------------------------------- ### Quickstart Dynamic Time Warping Source: https://dynamictimewarping.github.io/python Example demonstrating basic alignment, plotting, and step pattern usage with noisy sine and cosine waves. ```python import numpy as np ## A noisy sine wave as query idx = np.linspace(0,6.28,num=100) query = np.sin(idx) + np.random.uniform(size=100)/10.0 ## A cosine is for template; sin and cos are offset by 25 samples template = np.cos(idx) ## Find the best match with the canonical recursion formula from dtw import * alignment = dtw(query, template, keep_internals=True) ## Display the warping curve, i.e. the alignment curve alignment.plot(type="threeway") ## Align and plot with the Rabiner-Juang type VI-c unsmoothed recursion dtw(query, template, keep_internals=True, step_pattern=rabinerJuangStepPattern(6, "c"))\ .plot(type="twoway",offset=-2) ## See the recursion relation, as formula and diagram print(rabinerJuangStepPattern(6,"c")) rabinerJuangStepPattern(6,"c").plot() ## And much more! ``` -------------------------------- ### Import dtw library Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.warpArea.html Initial setup to access the dtw functionality. ```python >>> from dtw import * ``` -------------------------------- ### Importing dtw-python Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.mvmStepPattern.html Initial setup required to use the dtw library. ```python >>> import numpy as np >>> from dtw import * ``` -------------------------------- ### Install dtw-python Source: https://dynamictimewarping.github.io/python Command to install the stable version of the package via pip. ```bash pip install dtw-python ``` -------------------------------- ### Install dtw package Source: https://dynamictimewarping.github.io/r Use this command in the R console to install the stable version from CRAN. ```R > install.packages("dtw") ``` -------------------------------- ### Hand-Checkable DTW Example Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.dtw.html Demonstrate symmetric and asymmetric DTW using a custom local distance matrix. ```python >>> ldist = np.ones((6,6)) # Matrix of ones >>> ldist[1,:] = 0; ldist[:,4] = 0; # Mark a clear path of zeroes >>> ldist[1,4] = .01; # Forcely cut the corner ``` ```python >>> ds = dtw(ldist); # DTW with user-supplied local ``` ```python >>> da = dtw(ldist,step_pattern=asymmetric) # Also compute the asymmetric ``` ```python >>> plt.plot(ds.index1,ds.index2) ``` ```python >>> plt.plot(da.index1,da.index2,'ro') ``` ```python >>> float(ds.distance) 2.0 >>> float(da.distance) 2.0 ``` -------------------------------- ### DTW Backtracking Counterexample Source: https://dynamictimewarping.github.io/faq This example demonstrates a scenario where a naive backtracking algorithm based on steepest descent on the cost matrix yields an incorrect result for DTW. It highlights the complexity of the backtracking step and the importance of correct path calculation. ```R > library(dtw) > dm<-matrix(10,4,4)+diag(rep(1,4)) > al<-dtw(dm,k=T,step=symmetric2) > al$localCostMatrix [,1] [,2] [,3] [,4] [1,] *11* *10* 10 10 [2,] 10 11 *10* 10 [3,] 10 10 11 *10* [4,] 10 10 10 *11* > al$costMatrix [,1] [,2] [,3] [,4] [1,] >11< 21 31 41 [2,] 21 >32< 41 51 [3,] 31 41 >52< 61 [4,] 41 51 61 >72< ``` -------------------------------- ### Install Build Dependencies via Conda Source: https://dynamictimewarping.github.io/python Commands to install GCC and the dtw-python package when building from source on Linux. ```bash conda install gcc_linux-64 pip install dtw-python ``` -------------------------------- ### Defining the difference matrix Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.mvmStepPattern.html Example difference matrix for the MVM algorithm. ```python >>> diffmx = np.array( ... [[ 0, 1, 8, 2, 2, 4, 8 ], ... [ 1, 0, 7, 1, 1, 3, 7 ], ... [ -7, -6, 1, -5, -5, -3, 1 ], ... [ -5, -4, 3, -3, -3, -1, 3 ], ... [ -7, -6, 1, -5, -5, -3, 1 ]], dtype=np.double ) ``` -------------------------------- ### Warping area calculation result note Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.warpArea.html Example showing an alternative calculation result based on different interpolation assumptions. ```python >>> ## Result: 6 >>> ## index 2 is 2 while diag is 3_3 (+1_3) >>> ## 3 3 5_7 (+2_7) >>> ## 4 4:8 (avg to 6) 8 (+2 ) >>> ## -------- >>> ## 6 ``` -------------------------------- ### Perform DTW Alignment in Python Source: https://dynamictimewarping.github.io/faq Example of aligning two multivariate timeseries using the dtw library in Python. ```Python import numpy as np from dtw import dtw t_ref = np.linspace(0, 2*np.pi, num=100) reference = np.column_stack([np.cos(t_ref), np.sin(t_ref)]) u = np.linspace(0, 1, num=70) t_query = 2*np.pi*(u**1.5) query = np.column_stack([np.cos(t_query), np.sin(t_query)]) alignment_mv = dtw(query, reference, dist_method="euclidean", keep_internals=True) # Equivalent precomputed local cost matrix: # from scipy.spatial.distance import cdist # local_cost = cdist(query, reference, metric="euclidean") # alignment_mv = dtw(local_cost, keep_internals=True) ``` -------------------------------- ### Initialize dtw environment Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.warp.html Import necessary libraries for dtw operations. ```python >>> from dtw import * >>> import numpy as np ``` -------------------------------- ### Access Documentation Source: https://dynamictimewarping.github.io/python Commands to access help and documentation within a Python environment. ```python > from dtw import * > ?dtw > help(DTW) ``` -------------------------------- ### List pre-defined step patterns Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.StepPattern.html Overview of available step patterns including well-known, Rabiner-Juang, Sakoe-Chiba, and Rabiner-Myers types. ```python ## Well-known step patterns symmetric1 symmetric2 asymmetric ## Step patterns classified according to Rabiner-Juang (Rabiner1993) rabinerJuangStepPattern(type,slope_weighting="d",smoothed=False) ## Slope-constrained step patterns from Sakoe-Chiba (Sakoe1978) symmetricP0; asymmetricP0 symmetricP05; asymmetricP05 symmetricP1; asymmetricP1 symmetricP2; asymmetricP2 ## Step patterns classified according to Rabiner-Myers (Myers1980) typeIa; typeIb; typeIc; typeId; typeIas; typeIbs; typeIcs; typeIds; # smoothed typeIIa; typeIIb; typeIIc; typeIId; typeIIIc; typeIVc; ``` -------------------------------- ### Aligning multivariate timeseries Source: https://dynamictimewarping.github.io/faq Example of aligning two multivariate timeseries using the dtw function with a specified distance method. ```R t.ref <- seq(0, 2*pi, length.out = 100) reference <- cbind(cos(t.ref), sin(t.ref)) u <- seq(0, 1, length.out = 70) t.query <- 2*pi*(u^1.5) query <- cbind(cos(t.query), sin(t.query)) alignment.mv <- dtw(query, reference, dist.method = "Euclidean", keep.internals = TRUE) ## Equivalent precomputed local cost matrix: ## local.cost <- proxy::dist(query, reference, method = "Euclidean") ``` -------------------------------- ### Compare Distance Methods Source: https://dynamictimewarping.github.io/faq Demonstrates that passing a distance method to dtw is equivalent to passing a precomputed distance matrix. ```R r<-matrix(runif(10),5) # A 2-D timeseries of length 5 s<-matrix(runif(10),5) # Ditto myMethod<-"Manhattan" # Or anything else al1<-dtw(r,s,dist.method=myMethod) # Passing the two inputs al2<-dtw(proxy::dist(r,s,method=myMethod)) # Equivalent, passing the distance matrix all.equal(al1,al2) ``` -------------------------------- ### Create Manual Cost Matrix Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.StepPattern.html Define a custom cost matrix for manual verification of DTW algorithms. ```python >>> tm = numpy.reshape( [1, 3, 4, 4, 5, 2, 2, 3, 3, 4, 3, 1, 1, 1, 3, 4, 2, ... 3, 3, 2, 5, 3, 4, 4, 1], (5,5) ) ``` -------------------------------- ### Import dtw library Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.dtwPlotDensity.html Import necessary functions from the dtw library. ```python from dtw import * ``` -------------------------------- ### Step Patterns (Local Constraints) Source: https://dynamictimewarping.github.io/py-api/html Information on the different step patterns (local constraints or transition types) available for DTW. ```APIDOC ## Step Patterns (Local Constraints / Transition Types) ### Description Step patterns define the allowed transitions between time points in the DTW alignment, effectively controlling the local stretching or compression of the time series. The package supports a wide variety of predefined and custom step patterns. ### Functions - `mvmStepPattern()`: Implements the Minimum Variance Matching (MVM) step pattern. - `rabinerJuangStepPattern()`: Implements step patterns classified by Rabiner and Juang. - `StepPattern.get_n_patterns()`: Retrieves the number of available patterns for a given step pattern class. - `StepPattern.get_n_rows()`: Retrieves the number of rows (time points) for a given step pattern. ``` -------------------------------- ### Display Step Pattern Recursion Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.StepPattern.html Print the definition of a step pattern to understand its recursion logic. ```python >>> print(symmetric2) Step pattern recursion: g[i,j] = min( g[i-1,j-1] + 2 * d[i ,j ] , g[i ,j-1] + d[i ,j ] , g[i-1,j ] + d[i ,j ] , ) Normalization hint: N+M ``` -------------------------------- ### Perform Dynamic Time Warping Source: https://dynamictimewarping.github.io/r Demonstrates basic alignment of a noisy sine wave to a cosine template and visualization of the warping curve. ```R ## A noisy sine wave as query idx<-seq(0,6.28,len=100); query<-sin(idx)+runif(100)/10; ## A cosine is for template; sin and cos are offset by 25 samples template<-cos(idx) ## Find the best match with the canonical recursion formula library(dtw); alignment<-dtw(query,template,keep=TRUE); ## Display the warping curve, i.e. the alignment curve plot(alignment,type="threeway") ## Align and plot with the Rabiner-Juang type VI-c unsmoothed recursion plot( dtw(query,template,keep=TRUE, step=rabinerJuangStepPattern(6,"c")), type="twoway",offset=-2); ## See the recursion relation, as formula and diagram rabinerJuangStepPattern(6,"c") plot(rabinerJuangStepPattern(6,"c")) ## And much more! ``` -------------------------------- ### Load test data Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.warp.html Retrieve sample sine and cosine time series data for testing. ```python >>> (query, reference) = dtw_test_data.sin_cos() ``` -------------------------------- ### StepPattern Class Methods Source: https://dynamictimewarping.github.io/py-api/html/_sources/api/dtw.StepPattern.rst.txt This section provides documentation for the methods of the StepPattern class. ```APIDOC ## StepPattern Class Methods ### Description Provides documentation for the methods of the StepPattern class. ### Methods #### `T()` ##### Description Returns the transpose of the StepPattern. ##### Method N/A (This is a property or method call on an instance) ##### Endpoint N/A #### `get_n_patterns()` ##### Description Returns the number of patterns in the StepPattern. ##### Method N/A (This is a property or method call on an instance) ##### Endpoint N/A #### `get_n_rows()` ##### Description Returns the number of rows in the StepPattern. ##### Method N/A (This is a property or method call on an instance) ##### Endpoint N/A #### `plot()` ##### Description Plots the StepPattern. ##### Method N/A (This is a property or method call on an instance) ##### Endpoint N/A ``` -------------------------------- ### StepPattern Methods Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.StepPattern.html Methods available for interacting with StepPattern objects. ```APIDOC ## GET /step_pattern/methods ### Description Provides information and visualization for defined step patterns. ### Method GET ### Endpoint /step_pattern/{method} ### Parameters #### Path Parameters - **method** (string) - Required - The method to call: T, get_n_patterns, get_n_rows, or plot. ### Response #### Success Response (200) - **result** (any) - The output of the requested method. ``` -------------------------------- ### Prepare Time Series Data Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.dtw.html Generate a noisy sine wave query and a cosine reference signal. ```python >>> idx = np.linspace(0,6.28,num=100) >>> query = np.sin(idx) + np.random.uniform(size=100)/10.0 ``` ```python >>> reference = np.cos(idx) ``` -------------------------------- ### Perform Basic DTW Alignment Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.dtw.html Compute the alignment between the query and reference signals. ```python >>> alignment = dtw(query,reference) ``` -------------------------------- ### Visualize Cumulative Cost Matrix Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.dtw.html Compute DTW with internal storage and plot the cost matrix contour. ```python >>> alignment = dtw(query, reference, keep_internals=True) ``` ```python >>> plt.contour(alignment.costMatrix.T, origin="lower") >>> plt.plot(alignment.index1, alignment.index2, 'r-') ``` -------------------------------- ### Compare R and Python Argument Naming Source: https://dynamictimewarping.github.io/python Comparison of R and Python syntax for function arguments, highlighting the use of underscores in Python. ```python ## In R alignment = dtw(query, template, keep.int=TRUE) ## In Python alignment = dtw(query, template, keep_internals=True) ``` -------------------------------- ### Implement Block-Structured Windowing Source: https://dynamictimewarping.github.io/faq Uses a block-structured window function to enforce alignment through specific control points. ```R win.f <- function (iw, jw, window_iw, window_jw,query.size,reference.size,...) outer(window_iw, window_jw, FUN = "==") # Then use: dtw(x, y, window.type = win.f) ``` -------------------------------- ### Rabiner-Juang Step Pattern Table Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.StepPattern.html Reference table for Rabiner-Juang step pattern subtypes, rules, normalization, and bias. ```text Subtype | Rule | Norm | Unbiased --------|------------|------|--------- a | min step | -- | NO b | max step | -- | NO c | Di step | N | YES d | Di+Dj step | N+M | YES ``` -------------------------------- ### Implement Custom Windowing Source: https://dynamictimewarping.github.io/faq Defines a custom window function for the dtw alignment process. ```R win.f <- function(iw,jw,query.size, reference.size, window.size, ...) compare.window # Then use: dtw(x, y, window.type = win.f) ``` -------------------------------- ### slantedBandWindow Function Source: https://dynamictimewarping.github.io/py-api/html/_sources/api/dtw.slantedBandWindow.rst.txt Documentation for the slantedBandWindow function used in the dtw module. ```APIDOC ## slantedBandWindow ### Description This function is part of the dtw module and is used to define a slanted band window constraint for dynamic time warping algorithms. ### Module dtw ``` -------------------------------- ### Computing the alignment Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.mvmStepPattern.html Perform the DTW alignment using the MVM step pattern. ```python >>> al = dtw(costmx,step_pattern=mvmStepPattern(10)) ``` -------------------------------- ### StepPattern Class Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.dtw.html Configuration and utility methods for defining step patterns in DTW. ```APIDOC ## StepPattern Class ### Description Provides methods to manage and visualize step patterns used in the DTW algorithm. ### Methods - StepPattern.T() - StepPattern.get_n_patterns() - StepPattern.get_n_rows() - StepPattern.plot() ``` -------------------------------- ### Compare R and Python Plotting Methods Source: https://dynamictimewarping.github.io/python Comparison of R and Python syntax for calling plot methods on alignment objects. ```python ## In R plot(alignment, type="threeway") ## In Python alignment.plot(type="threeway") ## or dtwPlotThreeWay(alignment) ``` -------------------------------- ### Perform Partial Alignment Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.dtw.html Compute alignment with open-begin and open-end constraints. ```python >>> alignmentOBE = dtw(query[44:88], reference, ... keep_internals=True, ... step_pattern=asymmetric, ... open_end=True,open_begin=True) ``` ```python >>> alignmentOBE.plot(type="twoway",offset=1) ``` -------------------------------- ### noWindow Function Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.noWindow.html Defines a windowing constraint for DTW that imposes no restrictions on the warping path. ```APIDOC ## noWindow ### Description Defines a windowing constraint for DTW that imposes no restrictions on the warping path. ### Method Function Call ### Endpoint dtw.noWindow(iw, jw, query_size, reference_size) ### Parameters #### Path Parameters - **iw** (int) - Required - Index window parameter - **jw** (int) - Required - Index window parameter - **query_size** (int) - Required - Size of the query sequence - **reference_size** (int) - Required - Size of the reference sequence ``` -------------------------------- ### Calculating the cost matrix Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.mvmStepPattern.html Compute the cost matrix from the difference matrix. ```python >>> costmx = diffmx**2; ``` -------------------------------- ### Plot Step Pattern Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.StepPattern.html Visualize the step pattern recursion using matplotlib. ```python >>> import matplotlib.pyplot as plt; ... symmetricP2.plot().set_title("Sakoe's Symmetric P=2 recursion") ``` -------------------------------- ### Warp with asymmetric step pattern Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.warp.html Perform alignment using an asymmetric step pattern and warp the reference. ```python >>> alignment = dtw(query,reference,step_pattern=asymmetric) >>> wt = warp(alignment,index_reference=True); ``` -------------------------------- ### Windowing Functions Source: https://dynamictimewarping.github.io/py-api/html Details on the various windowing functions (global constraints) supported by dtw-python. ```APIDOC ## Windowing Functions (Global Constraints) ### Description These functions define the global constraints or 'windows' within which the DTW alignment is computed. This helps to limit the search space and can improve performance and relevance. ### Functions - `itakuraWindow()`: Implements the Itakura parallelogram window. - `noWindow()`: No windowing constraint is applied. - `sakoeChibaWindow()`: Implements the Sakoe-Chiba band window. - `slantedBandWindow()`: Implements a slanted band window. ``` -------------------------------- ### DTW Utility Functions Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.warpArea.html A collection of utility functions for dynamic time warping, including path counting and plotting. ```APIDOC ## DTW Utility Functions ### Description Provides various functions to assist with Dynamic Time Warping analysis and visualization. ### Functions #### `countPaths()` ##### Description Counts the number of possible warping paths. ##### Parameters None ##### Response - **count** (int) - The total number of warping paths. #### `dtw()` ##### Description Computes the optimal warping path between two time series. ##### Parameters - **x** (array-like) - The first time series. - **y** (array-like) - The second time series. - **dist_method** (str, optional) - The distance measure to use (e.g., 'euclidean', 'cosine'). Defaults to 'euclidean'. - **step_pattern** (str or object, optional) - The step pattern to use (e.g., 'symmetric2', 'pivoting'). Defaults to 'symmetric2'. - **window** (str or object, optional) - The windowing function to apply (e.g., 'sakoechiba', 'slantedband'). Defaults to None. - **upper_region** (bool, optional) - Whether to consider only the upper region of the cost matrix. Defaults to False. ##### Response - **dtw_result** (dtw object) - An object containing the warping path and cost matrix. #### `dtwPlot()` ##### Description Plots the dynamic time warping path and cost matrix. ##### Parameters - **dtw_result** (dtw object) - The result object from the `dtw()` function. ##### Response None (generates a plot) #### `dtwPlotAlignment()` ##### Description Plots the alignment of the two time series based on the warping path. ##### Parameters - **dtw_result** (dtw object) - The result object from the `dtw()` function. ##### Response None (generates a plot) #### `dtwPlotDensity()` ##### Description Plots the density of the warping paths. ##### Parameters - **dtw_result** (dtw object) - The result object from the `dtw()` function. ##### Response None (generates a plot) #### `dtwPlotThreeWay()` ##### Description Plots a three-way comparison of DTW results. ##### Parameters - **dtw_result1** (dtw object) - The first DTW result object. - **dtw_result2** (dtw object) - The second DTW result object. - **dtw_result3** (dtw object) - The third DTW result object. ##### Response None (generates a plot) #### `dtwPlotTwoWay()` ##### Description Plots a two-way comparison of DTW results. ##### Parameters - **dtw_result1** (dtw object) - The first DTW result object. - **dtw_result2** (dtw object) - The second DTW result object. ##### Response None (generates a plot) #### `warp()` ##### Description Computes the warping path using a specified step pattern. ##### Parameters - **d** (dtw object) - The dtw object. - **step_pattern** (str or object) - The step pattern to use. ##### Response - **warped_path** (list) - The computed warping path. ``` -------------------------------- ### sakoeChibaWindow Function Source: https://dynamictimewarping.github.io/py-api/html/_sources/api/dtw.sakoeChibaWindow.rst.txt The sakoeChibaWindow function generates a Sakoe-Chiba window for Dynamic Time Warping. ```APIDOC ## sakoeChibaWindow ### Description Generates a Sakoe-Chiba window. ### Method N/A (This is a function, not an API endpoint) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from dtw import sakoeChibaWindow # Example usage (assuming 'n' is defined) # window = sakoeChibaWindow(n) ``` ### Response #### Success Response (200) N/A (This is a function, returns a value) #### Response Example N/A ``` -------------------------------- ### Step Patterns Source: https://dynamictimewarping.github.io/py-api/html/index.html Different types of step patterns (transition types) that define local constraints for the DTW algorithm. ```APIDOC ## Step Patterns ### Description Defines various step patterns (also known as transition types, slope constraints, or DP-recursion rules) that impose local constraints on the DTW alignment. ### Classes and Functions - **`StepPattern`**: Base class for step patterns. - **`StepPattern.T()`**: Returns the step pattern matrix. - **`StepPattern.get_n_patterns()`**: Gets the number of patterns. - **`StepPattern.get_n_rows()`**: Gets the number of rows in the pattern. - **`StepPattern.plot()`**: Plots the step pattern. - **`rabinerJuangStepPattern()`**: Implements step patterns classified by Rabiner and Juang. - **`mvmStepPattern()`**: Implements the Minimum Variance Matching (MVM) step pattern. ### Supported Types Includes symmetric, asymmetric, slope-limited, and user-defined step patterns, covering classifications by Rabiner-Juang, Sakoe-Chiba, and Rabiner-Myers. ``` -------------------------------- ### rabinerJuangStepPattern Function Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.rabinerJuangStepPattern.html Constructs a step pattern classified according to the Rabiner-Juang scheme. ```APIDOC ## POST /rabinerJuangStepPattern ### Description Constructs a step pattern classified according to the Rabiner-Juang scheme (Rabiner1993). See documentation for the StepPattern class. ### Method POST ### Endpoint /rabinerJuangStepPattern ### Parameters #### Query Parameters - **_ptype_** (string) - Required - Type of pattern to construct. - **_slope_weighting_** (string) - Optional - Slope weighting parameter, defaults to 'd'. - **_smoothed_** (boolean) - Optional - Whether to use smoothed values, defaults to False. ### Request Example ```json { "_ptype_": "example_type", "_slope_weighting_": "w", "_smoothed_": true } ``` ### Response #### Success Response (200) - **pattern** (object) - The constructed step pattern. #### Response Example ```json { "pattern": {} } ``` ``` -------------------------------- ### DTW Class and Methods Source: https://dynamictimewarping.github.io/py-api/html/index.html The main DTW class and its associated methods for computation and plotting. ```APIDOC ## DTW Class ### Description Represents a Dynamic Time Warping computation and provides methods for analysis and visualization. ### Class - **`DTW`**: The main class for DTW computations. - **`DTW.plot()`**: Generates a plot of the DTW alignment. ``` -------------------------------- ### dtwPlotTwoWay Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.dtwPlotTwoWay.html Visualizes the query and reference time series and their alignment for inspection. ```APIDOC ## dtwPlotTwoWay ### Description Displays the query and reference time series and their alignment, arranged for visual inspection. The two vectors are displayed via matplot functions. ### Parameters - **d** (dtw object) - Required - An alignment result object. - **xts** (vector) - Optional - Query vector. - **yts** (vector) - Optional - Reference vector. - **offset** (numeric) - Optional - Displacement between the timeseries, summed to reference. - **ts_type** (string) - Optional - Graphical parameters for timeseries plotting. - **match_indices** (vector/integer) - Optional - Indices for which to draw a visual guide. - **match_col** (string) - Optional - Color of the match guide lines. - **match_lty** (string) - Optional - Line type of the match guide lines. - **xlab** (string) - Optional - X-axis label. - **ylab** (string) - Optional - Y-axis label. - **pch** (any) - Optional - Graphical parameters passed to matplot. - **kwargs** (dict) - Optional - Additional arguments passed to matplot. ``` -------------------------------- ### slantedBandWindow Function Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.slantedBandWindow.html Details on the slantedBandWindow function, which is used for creating a slanted band window for dynamic timewarping. ```APIDOC ## slantedBandWindow Function ### Description Creates a slanted band window for dynamic timewarping. ### Method N/A (This appears to be a function call within a library, not a REST API endpoint) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ### Function Signature `dtw.slantedBandWindow(_iw_ , _jw_ , _query_size_ , _reference_size_ , _window_size_)` ### Parameters - **_iw_**: Description not provided. - **_jw_**: Description not provided. - **_query_size_**: Description not provided. - **_reference_size_**: Description not provided. - **_window_size_**: Description not provided. ``` -------------------------------- ### DTW.plot Method Source: https://dynamictimewarping.github.io/py-api/html/_sources/api/dtw.DTW.rst.txt Documentation for the plot method within the DTW class. ```APIDOC ## DTW.plot ### Description Visualizes the results of the dynamic time warping calculation. ### Method Method call on DTW instance ### Endpoint ~DTW.plot ``` -------------------------------- ### Plot alignment and diagonal Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.warpArea.html Visualize the alignment path alongside the diagonal reference line. ```python >>> import matplotlib.pyplot as plt; ... ds.plot(); plt.plot([0,2.3,4.7,7]) ``` -------------------------------- ### Plotting the alignment Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.mvmStepPattern.html Visualize the computed alignment. ```python >>> al.plot() ``` -------------------------------- ### itakuraWindow Function Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.itakuraWindow.html The itakuraWindow function calculates the Itakura parallelogram window for dynamic timewarping. ```APIDOC ## itakuraWindow Function ### Description Calculates the Itakura parallelogram window for dynamic timewarping. ### Method N/A (This appears to be a function call within a library, not a REST API endpoint) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### sakoeChibaWindow Function Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.sakoeChibaWindow.html Details on the sakoeChibaWindow function, which is part of the dtw-python library. ```APIDOC ## sakoeChibaWindow Function ### Description Applies the Sakoe-Chiba window constraint to the dynamic time warping process. ### Method `dtw.sakoeChibaWindow(_iw_ , _jw_ , _query_size_ , _reference_size_ , _window_size_) ` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Default symmetric2 step pattern recursion Source: https://dynamictimewarping.github.io/faq The default recursion formula used for calculating the cost in the symmetric2 step pattern. ```text g[i,j] = min( g[i-1,j-1] + 2 * d[i ,j ] , g[i ,j-1] + d[i ,j ] , g[i-1,j ] + d[i ,j ] , ) ``` -------------------------------- ### countPaths() Source: https://dynamictimewarping.github.io/py-api/html Count the number of warping paths consistent with the constraints. ```APIDOC ## countPaths(d, debug) ### Description Count the number of warping paths consistent with the constraints. ### Parameters - **d** (object) - Required - The DTW result object. - **debug** (boolean) - Optional - Enable debug output. ``` -------------------------------- ### Calculate DTW with Itakura window constraint Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.dtwPlotDensity.html Performs Dynamic Time Warping using the Itakura window constraint. Ensure keep_internals is True to enable plotting. ```python ita = dtw(query, reference, keep_internals=True, window_type=itakuraWindow) ``` -------------------------------- ### Apply warping indices Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.warp.html Generate warping indices for both query and reference series. ```python >>> wq = warp(alignment,index_reference=False) >>> wt = warp(alignment,index_reference=True) ``` -------------------------------- ### Compute DTW Alignment Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.StepPattern.html Perform the DTW computation using an asymmetric step pattern and retain internal data. ```python >>> asy = dtw(query, reference, keep_internals=True, ... step_pattern=asymmetric); ``` -------------------------------- ### DTW Core Functions Source: https://dynamictimewarping.github.io/py-api/html/index.html Core functions for Dynamic Time Warping and related utilities. ```APIDOC ## Core DTW Functions ### Description Provides core functionalities for Dynamic Time Warping (DTW) and related algorithms. ### Functions - **`dtw()`**: Computes the Dynamic Time Warping alignment between two time series. - **`warp()`**: Applies a warping function to a time series. - **`warpArea()`**: Computes the warping area. - **`countPaths()`**: Counts the number of possible warping paths. ### Plotting Utilities - **`dtwPlot()`**: Plots the DTW alignment. - **`dtwPlotAlignment()`**: Plots a specific DTW alignment. - **`dtwPlotDensity()`**: Plots the DTW density. - **`dtwPlotThreeWay()`**: Plots a three-way DTW alignment. - **`dtwPlotTwoWay()`**: Plots a two-way DTW alignment. ``` -------------------------------- ### Plot DTW cumulative cost density with Itakura constraint Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.dtwPlotDensity.html Displays the cumulative cost density with the warping path for an alignment computed with the Itakura parallelogram constraint. ```python dtwPlotDensity(ita) ``` -------------------------------- ### Visualize Alignment Mapping Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.dtw.html Plot the warping function using the alignment indices. ```python >>> import matplotlib.pyplot as plt; ... plt.plot(alignment.index1, alignment.index2) ``` -------------------------------- ### Windowing Functions Source: https://dynamictimewarping.github.io/py-api/html/index.html Various windowing functions used to constrain the DTW search space. ```APIDOC ## Windowing Functions ### Description Implements various windowing functions that define global constraints for the DTW algorithm, limiting the search space. ### Functions - **`sakoeChibaWindow(window.size, ...)`**: Implements the Sakoe-Chiba band constraint. - **`itakuraWindow(max.slope, ...)`**: Implements the Itakura parallelogram constraint. - **`slantedBandWindow(window.size, ...)`**: Implements a slanted band window constraint. - **`noWindow()`**: Disables windowing, allowing unconstrained search. ``` -------------------------------- ### DTW Core Functions Source: https://dynamictimewarping.github.io/py-api/html This section details the core functions available in the dtw-python package for performing Dynamic Time Warping and related operations. ```APIDOC ## Core DTW Functions ### Description Provides access to the primary functions for Dynamic Time Warping calculations and visualizations. ### Functions - `countPaths()`: Counts the number of possible warping paths. - `dtw()`: Computes the Dynamic Time Warping alignment between two time series. - `dtwPlot()`: Generates a plot for a DTW alignment. - `dtwPlotAlignment()`: Plots the alignment path of a DTW result. - `dtwPlotDensity()`: Plots the density of a DTW alignment. - `dtwPlotThreeWay()`: Plots a three-way DTW alignment. - `dtwPlotTwoWay()`: Plots a two-way DTW alignment. - `warp()`: Applies a warping function to a time series. - `warpArea()`: Computes the warping area for a DTW alignment. ### Classes - `DTW`: Represents a Dynamic Time Warping object with plotting capabilities. - `DTW.plot()`: Method to plot the DTW alignment. - `StepPattern`: Abstract base class for step patterns. - `StepPattern.T()`: Returns the step pattern matrix. - `StepPattern.get_n_patterns()`: Gets the number of patterns. - `StepPattern.get_n_rows()`: Gets the number of rows in the pattern. - `StepPattern.plot()`: Plots the step pattern. ``` -------------------------------- ### Visualization Functions Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.dtw.html A collection of plotting functions for visualizing DTW alignments and density. ```APIDOC ## Visualization Functions ### Description Functions used to visualize DTW results, including alignments, density, and multi-way comparisons. ### Methods - dtwPlot() - dtwPlotAlignment() - dtwPlotDensity() - dtwPlotThreeWay() - dtwPlotTwoWay() ``` -------------------------------- ### Cluster Multivariate Timeseries (List of Matrices) Source: https://dynamictimewarping.github.io/faq Use this pseudocode when timeseries have different lengths and are stored as a list of matrices. Each matrix in the list represents a timeseries where rows are time points and columns are components. ```R ## x is a list; x[[i]] is a matrix with rows = time points, cols = components for (i in seq_len(N)) { for (j in seq_len(N)) { result[i,j] <- dtw( x[[i]], x[[j]]), distance.only = TRUE)$normalizedDistance } } ``` -------------------------------- ### Inspecting skipped elements Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.mvmStepPattern.html Retrieve the indices of the matched reference elements. ```python >>> al.index2+1 array([1, 2, 3, 6, 7]) ``` -------------------------------- ### Cluster Multivariate Timeseries (Matrix) Source: https://dynamictimewarping.github.io/faq This pseudocode demonstrates how to compute pairwise DTW distances for multivariate timeseries arranged as a matrix. Ensure data is structured as `x[time, component, series]` and handle the loops manually. ```R for (i in 1:N) { for (j in 1:N) { result[i,j] <- dtw( x[,,i], x[,,j], distance.only=T )$normalizedDistance ``` -------------------------------- ### Plot asymmetric warping result Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.warp.html Visualize the alignment result using an asymmetric step pattern. ```python >>> plt.plot(query, "b-") ... plt.plot(reference[wt], "ok", facecolors='none') ``` -------------------------------- ### StepPattern Class Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.StepPattern.html The StepPattern class characterizes the matching model and slope constraints for DTW variants. ```APIDOC ## class dtw.StepPattern(mx, hint='NA') ### Description Creates a step pattern object that lists the transitions allowed while searching for the minimum-distance path in DTW. ### Parameters #### Request Body - **mx** (object) - Required - The matrix defining the step pattern transitions. - **hint** (string) - Optional - A hint for the step pattern type, defaults to 'NA'. ### Methods - **StepPattern.T()**: Returns the transposed step pattern. - **StepPattern.get_n_patterns()**: Returns the number of patterns defined. - **StepPattern.get_n_rows()**: Returns the number of rows in the pattern. - **StepPattern.plot()**: Visualizes the step pattern. ``` -------------------------------- ### Compute alignment Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.warp.html Perform dynamic time warping on the query and reference series. ```python >>> alignment = dtw(query,reference); ``` -------------------------------- ### dtw() Source: https://dynamictimewarping.github.io/py-api/html Compute Dynamic Time Warp and find optimal alignment between two time series. ```APIDOC ## dtw(x, y, dist_method, step_pattern, ...) ### Description Compute Dynamic Time Warp and find optimal alignment between two time series. ### Parameters - **x** (array) - Required - The query time series. - **y** (array) - Optional - The reference time series. - **dist_method** (string) - Optional - The distance metric to use. - **step_pattern** (object) - Optional - The step pattern constraint. ``` -------------------------------- ### dtw() Source: https://dynamictimewarping.github.io/py-api/html/index.html Compute Dynamic Time Warp and find optimal alignment between two time series. ```APIDOC ## dtw(x, y, dist_method, step_pattern, ...) ### Description Compute Dynamic Time Warp and find optimal alignment between two time series. ### Parameters - **x** (array) - Required - The query time series. - **y** (array) - Optional - The reference time series. - **dist_method** (string) - Optional - The distance metric to use. - **step_pattern** (object) - Optional - The step pattern to constrain the alignment. ``` -------------------------------- ### Plot DTW Alignment Density Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.StepPattern.html Visualize the computed alignment as a density plot. ```python >>> dtwPlot(asy,type="density" ... ).set_title("Sine and cosine, asymmetric step") ``` -------------------------------- ### dtwPlot() Source: https://dynamictimewarping.github.io/py-api/html Plotting of dynamic time warp results. ```APIDOC ## dtwPlot(x, type) ### Description Plotting of dynamic time warp results. ### Parameters - **x** (object) - Required - The DTW result object. - **type** (string) - Optional - The type of plot to generate. ``` -------------------------------- ### StepPattern Class and Methods Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.warpArea.html The StepPattern class defines different step patterns used in DTW, with methods to access pattern information and plot them. ```APIDOC ## StepPattern Class ### Description Defines and manages step patterns for Dynamic Time Warping. ### Methods #### `StepPattern.T()` ##### Description Returns the step pattern matrix. ##### Parameters None ##### Response - **T** (numpy.ndarray) - The step pattern matrix. #### `StepPattern.get_n_patterns()` ##### Description Gets the number of patterns available in the step pattern. ##### Parameters None ##### Response - **n_patterns** (int) - The number of patterns. #### `StepPattern.get_n_rows()` ##### Description Gets the number of rows in the step pattern. ##### Parameters None ##### Response - **n_rows** (int) - The number of rows. #### `StepPattern.plot()` ##### Description Plots the step pattern. ##### Parameters None ##### Response None (generates a plot) ``` -------------------------------- ### Compute DTW alignment Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.warpArea.html Create a dtw object by aligning two sequences. ```python >>> ds = dtw( [1,2,3,4], [1,2,3,4,5,6,7,8]); ``` -------------------------------- ### DTW.plot() Method Source: https://dynamictimewarping.github.io/py-api/html/api/dtw.DTW.html Provides various methods for plotting dynamic time warp alignment objects returned by the dtw() function. ```APIDOC ## Method plot ### Description Plotting of dynamic time warp results. This method displays the alignment contained in `dtw` objects. Various plotting styles are available by passing strings to the `type` argument (may be abbreviated). ### Parameters - **x** (dtw object) - The dtw object, usually the result of a call to `dtw()`. - **d** (dtw object) - The dtw object, usually the result of a call to `dtw()`. - **xlab** (string) - Label for the query axis. - **ylab** (string) - Label for the reference axis. - **type** (string) - General style for the plot. Options include: - `alignment`: plots the warping curve in `d`. - `twoway`: plots a point-by-point comparison with matching lines; see `dtwPlotTwoWay()`. - `threeway`: vis-a-vis inspection of the timeseries and their warping curve; see `dtwPlotThreeWay()`. - `density`: displays the cumulative cost landscape with the warping path overimposed; see `dtwPlotDensity()`. - **plot_type** (string) - Type of line to be drawn, used as the `type` argument in the underlying plot call. - **...** (any) - Additional arguments, passed to plotting functions. Use with care. ### Details - `alignment`: plots the warping curve in `d`. - `twoway`: plots a point-by-point comparison, with matching lines; see `dtwPlotTwoWay()`. - `threeway`: vis-a-vis inspection of the timeseries and their warping curve; see `dtwPlotThreeWay()`. - `density`: displays the cumulative cost landscape with the warping path overimposed; see `dtwPlotDensity()`. ``` -------------------------------- ### warp() Source: https://dynamictimewarping.github.io/py-api/html/index.html Apply a warping to a given timeseries. ```APIDOC ## warp(d, index_reference) ### Description Apply a warping to a given timeseries. ### Parameters - **d** (object) - Required - The DTW result object. - **index_reference** (integer) - Optional - The index of the reference series. ```