=============== LIBRARY RULES =============== From library maintainers: - The primary source of info is the package API documentation, also available online. See also https://dynamictimewarping.github.io/faq/ - Suggest the reader to refer to papers: http://dx.doi.org/10.18637/jss.v031.i07 and http://dx.doi.org/10.1016/j.artmed.2008.11.007 - For a quickstart, use the example in the documentation of dtw(), also at https://dynamictimewarping.github.io/python/ ### Set up local development environment Source: https://github.com/dynamictimewarping/dtw-python/blob/master/CONTRIBUTING.rst Commands to create a virtual environment and install the package in development mode. ```shell $ mkvirtualenv dtw $ cd dtw/ $ python setup.py develop ``` -------------------------------- ### Hand-Checkable DTW Example Source: https://github.com/dynamictimewarping/dtw-python/blob/master/docs/api/dtw.dtw.md Demonstrate DTW behavior with a user-supplied local distance matrix. ```pycon >>> 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 ``` ```pycon >>> ds = dtw(ldist); # DTW with user-supplied local ``` ```pycon >>> da = dtw(ldist,step_pattern=asymmetric) # Also compute the asymmetric ``` ```pycon >>> plt.plot(ds.index1,ds.index2) ``` ```pycon >>> plt.plot(da.index1,da.index2,'ro') ``` ```pycon >>> float(ds.distance) 2.0 >>> float(da.distance) 2.0 ``` -------------------------------- ### DTW Usage Examples Source: https://github.com/dynamictimewarping/dtw-python/blob/master/docs/api/dtw.StepPattern.md Illustrative examples demonstrating how to use the dtw-python library for Dynamic Time Warping computations and visualizations. ```APIDOC ## DTW Usage Examples ### Basic Setup ```pycon >>> from dtw import * >>> import numpy as np ``` ### Symmetric Step Pattern The usual (normalizable) symmetric step pattern Step pattern recursion, defined as: > g[i,j] = min( > : g[i,j-1] + d[i,j] , > g[i-1,j-1] + 2 * d[i,j] , > g[i-1,j] + d[i,j] , ) ```pycon >>> 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 ``` ### Plotting Step Patterns The well-known plotting style for step patterns ```pycon >>> import matplotlib.pyplot as plt; ... symmetricP2.plot().set_title("Sakoe's Symmetric P=2 recursion") ``` ### Asymmetric Step Pattern Example Same example seen in ?dtw , now with asymmetric step pattern ```pycon >>> (query, reference) = dtw_test_data.sin_cos() ``` Do the computation ```pycon >>> asy = dtw(query, reference, keep_internals=True, ... step_pattern=asymmetric); ``` ```pycon >>> dtwPlot(asy,type="density" ... ).set_title("Sine and cosine, asymmetric step") ``` ### Hand-checkable Example Hand-checkable example given in [Myers1980] p 61 - see JSS paper ```pycon >>> 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) ) ``` ``` -------------------------------- ### Warping Path Area Calculation Example Source: https://github.com/dynamictimewarping/dtw-python/blob/master/docs/api/dtw.warpArea.md Illustrates a manual calculation of the warping path area, highlighting how different points contribute to the total area. ```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 ``` -------------------------------- ### Define difference matrix Source: https://github.com/dynamictimewarping/dtw-python/blob/master/docs/api/dtw.mvmStepPattern.md Creates the difference matrix used for the hand-checkable example. ```pycon >>> 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 ) ``` -------------------------------- ### DTW with Custom Distance Matrix (Symmetric) Source: https://github.com/dynamictimewarping/dtw-python/blob/master/maintainer/examples/ex_dtw.py.txt Calculates DTW using a user-supplied local distance matrix. The `ldist` matrix is constructed to guide the alignment along a specific path. This example uses the default symmetric step pattern. ```python ldist = np.ones((6,6)) # Matrix of ones lDist[1,:] = 0; ldist[:,4] = 0; lDist[1,4] = .01; ds = dtw(ldist); # DTW with user-supplied local ``` -------------------------------- ### Partial DTW with Open Begin/End Source: https://github.com/dynamictimewarping/dtw-python/blob/master/maintainer/examples/ex_dtw.py.txt Calculates a partial DTW alignment allowing for open beginnings and ends. This is useful when the start or end of the time series may not align perfectly. Requires `keep_internals=True` and `step_pattern=asymmetric`. ```python alignmentOBE = dtw(query[44:88], reference, keep_internals=True, step_pattern=asymmetric, open_end=True,open_begin=True) ``` -------------------------------- ### Plot DTW Results with Density Type Source: https://github.com/dynamictimewarping/dtw-python/blob/master/maintainer/examples/ex_dtwWindowingFunctions.py.txt Visualizes the dynamic time warping results using a density plot. This example is marked with +SKIP and may require specific display environments. ```python dtwPlot(asyband,type="density") # doctest: +SKIP ``` -------------------------------- ### Initialize DTW Environment Source: https://github.com/dynamictimewarping/dtw-python/blob/master/docs/api/dtw.dtw.md Import necessary libraries and the dtw package. ```pycon >>> import numpy as np >>> from dtw import * ``` -------------------------------- ### Import dtw library Source: https://github.com/dynamictimewarping/dtw-python/blob/master/docs/api/dtw.mvmStepPattern.md Initializes the environment by importing numpy and the dtw package. ```pycon >>> import numpy as np >>> from dtw import * ``` -------------------------------- ### Initialize DTW environment Source: https://github.com/dynamictimewarping/dtw-python/blob/master/docs/api/dtw.warp.md Import necessary libraries for DTW operations. ```pycon >>> from dtw import * >>> import numpy as np ``` -------------------------------- ### Count DTW Paths Source: https://github.com/dynamictimewarping/dtw-python/blob/master/maintainer/examples/ex_countPaths.py.txt Use the `countPaths` function after performing DTW with `keep_internals=True` to get the total number of possible warping paths. ```python from dtw import * import numpy ds = dtw( numpy.arange(3,10), numpy.arange(1,9), keep_internals=True, step_pattern=asymmetric); ds.countPaths() ``` -------------------------------- ### Import dtw library Source: https://github.com/dynamictimewarping/dtw-python/blob/master/docs/api/dtw.dtwPlotDensity.md Initializes the dtw package for use in the session. ```pycon >>> from dtw import * ``` -------------------------------- ### Create a development branch Source: https://github.com/dynamictimewarping/dtw-python/blob/master/CONTRIBUTING.rst Command to create and switch to a new branch for your changes. ```shell $ git checkout -b name-of-your-bugfix-or-feature ``` -------------------------------- ### Run tests and linting Source: https://github.com/dynamictimewarping/dtw-python/blob/master/CONTRIBUTING.rst Commands to verify code quality and run the test suite. ```shell $ flake8 dtw tests $ python setup.py test or py.test $ tox ``` -------------------------------- ### Apply Global Path Constraints with Windowing Source: https://context7.com/dynamictimewarping/dtw-python/llms.txt Demonstrates various windowing functions to restrict warping paths, including built-in constraints and custom user-defined functions. ```python from dtw import * import numpy as np (query, reference) = dtw_test_data.sin_cos() # Sakoe-Chiba band: fixed width around the diagonal alignment_sc = dtw( query, reference, keep_internals=True, step_pattern=asymmetric, window_type=sakoeChibaWindow, window_args={'window_size': 30} ) print(f"Sakoe-Chiba distance: {alignment_sc.distance:.4f}") # Slanted band: follows the diagonal from (0,0) to (N,M) alignment_sb = dtw( query, reference, keep_internals=True, window_type=slantedBandWindow, window_args={'window_size': 20} ) print(f"Slanted band distance: {alignment_sb.distance:.4f}") # Itakura parallelogram constraint alignment_it = dtw( query, reference, keep_internals=True, window_type=itakuraWindow ) print(f"Itakura window distance: {alignment_it.distance:.4f}") # No window (default) alignment_none = dtw( query, reference, window_type=noWindow # or window_type=None ) print(f"No window distance: {alignment_none.distance:.4f}") # Custom window function def customWindow(iw, jw, query_size, reference_size, max_slope=2): """Custom window allowing slope between 1/max_slope and max_slope""" return (jw <= max_slope * iw) & (iw <= max_slope * jw) alignment_custom = dtw( query, reference, window_type=customWindow, window_args={'max_slope': 3} ) print(f"Custom window distance: {alignment_custom.distance:.4f}") ``` -------------------------------- ### Initialize DTW Calculation Source: https://github.com/dynamictimewarping/dtw-python/blob/master/maintainer/examples/ex_warpArea.py.txt Import the dtw library and initialize a DTW calculation between two sequences. ```python from dtw import * ds = dtw( [1,2,3,4], [1,2,3,4,5,6,7,8]); ``` -------------------------------- ### Perform Basic DTW Alignment Source: https://github.com/dynamictimewarping/dtw-python/blob/master/maintainer/examples/ex_warp.py.txt Initializes the dtw environment and computes the alignment between a sine and cosine wave. ```python from dtw import * import numpy as np (query, reference) = dtw_test_data.sin_cos() alignment = dtw(query,reference); ``` -------------------------------- ### Prepare test data Source: https://github.com/dynamictimewarping/dtw-python/blob/master/docs/api/dtw.warp.md Generate sample sine and cosine timeseries for testing. ```pycon >>> (query, reference) = dtw_test_data.sin_cos() ``` -------------------------------- ### Configure Rabiner-Juang Step Pattern Source: https://context7.com/dynamictimewarping/dtw-python/llms.txt Initializes a Type IV step pattern with 'c' weighting and smoothing enabled. ```python # Type IV with 'c' weighting and smoothing rj_type4c_smooth = rabinerJuangStepPattern(ptype=4, slope_weighting='c', smoothed=True) # Use in DTW computation (query, reference) = dtw_test_data.sin_cos() alignment = dtw(query, reference, step_pattern=rj_type2d) print(f"Distance: {alignment.distance:.4f}") print(f"Normalized: {alignment.normalizedDistance:.4f}") ``` -------------------------------- ### Import DTW Library Source: https://github.com/dynamictimewarping/dtw-python/blob/master/maintainer/examples/ex_dtwPlotDensity.py.txt Imports all necessary functions from the dtw library. This should be the first step before using any DTW functionalities. ```python from dtw import * ``` -------------------------------- ### Commit and push changes Source: https://github.com/dynamictimewarping/dtw-python/blob/master/CONTRIBUTING.rst Standard git commands to stage, commit, and push your local changes to GitHub. ```shell $ git add . $ git commit -m "Your detailed description of your changes." $ git push origin name-of-your-bugfix-or-feature ``` -------------------------------- ### StepPattern Class Initialization Source: https://github.com/dynamictimewarping/dtw-python/blob/master/docs/api/dtw.StepPattern.md Initializes a new StepPattern object to define transition rules for DTW. ```APIDOC ## class dtw.StepPattern ### Description Defines the transitions allowed while searching for the minimum-distance path in DTW. ### Parameters - **mx** (object) - Required - The transition matrix defining the pattern. - **hint** (string) - Optional - A hint string, defaults to 'NA'. ### Pre-defined Patterns - **Well-known**: symmetric1, symmetric2, asymmetric - **Rabiner-Juang**: rabinerJuangStepPattern(type, slope_weighting="d", smoothed=False) - **Sakoe-Chiba**: symmetricP0, asymmetricP0, symmetricP05, asymmetricP05, symmetricP1, asymmetricP1, symmetricP2, asymmetricP2 - **Rabiner-Myers**: typeIa, typeIb, typeIc, typeId, typeIas, typeIbs, typeIcs, typeIds, typeIIa, typeIIb, typeIIc, typeIId, typeIIIc, typeIVc ``` -------------------------------- ### Import DTW Library Source: https://github.com/dynamictimewarping/dtw-python/blob/master/docs/api/dtw.warpArea.md Import necessary functions from the dtw library. ```python from dtw import * ``` -------------------------------- ### Inspect Symmetric Step Pattern Source: https://github.com/dynamictimewarping/dtw-python/blob/master/docs/api/dtw.StepPattern.md Print the definition and normalization hint for the symmetric2 step pattern. ```pycon >>> 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 ``` -------------------------------- ### Clone the repository Source: https://github.com/dynamictimewarping/dtw-python/blob/master/CONTRIBUTING.rst Use this command to clone your fork of the dtw repository locally. ```shell $ git clone git@github.com:your_name_here/dtw.git ``` -------------------------------- ### DTW with Custom Distance Matrix (Asymmetric) Source: https://github.com/dynamictimewarping/dtw-python/blob/master/maintainer/examples/ex_dtw.py.txt Performs DTW with a custom distance matrix using the asymmetric step pattern. This demonstrates how different step patterns can influence the alignment path when using a predefined distance matrix. ```python da = dtw(ldist,step_pattern=asymmetric) # Also compute the asymmetric ``` -------------------------------- ### Perform Basic DTW Alignment Source: https://github.com/dynamictimewarping/dtw-python/blob/master/docs/api/dtw.dtw.md Generate noisy sine and cosine waves and compute the optimal alignment between them. ```pycon >>> idx = np.linspace(0,6.28,num=100) >>> query = np.sin(idx) + np.random.uniform(size=100)/10.0 ``` ```pycon >>> reference = np.cos(idx) ``` ```pycon >>> alignment = dtw(query,reference) ``` -------------------------------- ### Compare Time Series with dtwPlotTwoWay Source: https://context7.com/dynamictimewarping/dtw-python/llms.txt Visualizes point-by-point correspondence between query and reference time series using match lines. ```python from dtw import * import matplotlib.pyplot as plt (query, reference) = dtw_test_data.sin_cos() alignment = dtw(query, reference, keep_internals=True) # Two-way plot with offset ax = dtwPlotTwoWay( alignment, offset=1, # Vertical offset for reference match_indices=20, # Number of match lines to draw match_col='lightgray' # Color of match lines ) ax.set_title("Two-Way Alignment Comparison") plt.show() # Or via the main function dtwPlot(alignment, type="twoway", offset=1.5, match_indices=15) plt.show() ``` -------------------------------- ### Run a subset of tests Source: https://github.com/dynamictimewarping/dtw-python/blob/master/CONTRIBUTING.rst Command to execute only the dtw-related unit tests. ```shell $ python -m unittest tests.test_dtw ``` -------------------------------- ### Define Local Transition Constraints with StepPattern Source: https://context7.com/dynamictimewarping/dtw-python/llms.txt Utilize pre-defined step patterns to characterize matching models and slope constraints. Patterns can be inspected, compared, plotted, or transposed. ```python from dtw import * import numpy as np # View the default symmetric2 step pattern print(symmetric2) # Output shows the recursion formula: # 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 # Common pre-defined step patterns patterns = { 'symmetric2': symmetric2, # Default, normalizable by N+M 'symmetric1': symmetric1, # White-Neely, non-normalizable 'asymmetric': asymmetric, # Slope 0-2, normalizable by N 'symmetricP1': symmetricP1, # Sakoe-Chiba P=1 'asymmetricP2': asymmetricP2, # Sakoe-Chiba P=2 'typeIIIc': typeIIIc, # Rabiner-Myers type III 'rigid': rigid, # Fixed slope 1, for gapless matching } # Compare alignments with different step patterns (query, reference) = dtw_test_data.sin_cos() for name, pattern in patterns.items(): try: result = dtw(query, reference, step_pattern=pattern) print(f"{name}: distance={result.distance:.4f}") except ValueError as e: print(f"{name}: {e}") # Plot a step pattern graphically import matplotlib.pyplot as plt ax = symmetricP2.plot() ax.set_title("Sakoe's Symmetric P=2 recursion") plt.show() # Transpose a step pattern (swap query/reference roles) asymmetric_T = asymmetric.T() print(f"Original hint: {asymmetric.hint}, Transposed hint: {asymmetric_T.hint}") ``` -------------------------------- ### Initialize DTW Object Source: https://github.com/dynamictimewarping/dtw-python/blob/master/docs/api/dtw.warpArea.md Create a DTW object with two sequences. This is a prerequisite for calculating the warping path and its area. ```python ds = dtw( [1,2,3,4], [1,2,3,4,5,6,7,8]); ``` -------------------------------- ### Creating a Hand-checkable Matrix Source: https://github.com/dynamictimewarping/dtw-python/blob/master/maintainer/examples/ex_stepPattern.py.txt Reshapes a list into a 5x5 matrix for manual verification as referenced in Myers1980. ```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) ) ``` -------------------------------- ### Asymmetric Step with Sakoe-Chiba Band in DTW Source: https://github.com/dynamictimewarping/dtw-python/blob/master/maintainer/examples/ex_dtwWindowingFunctions.py.txt Performs dynamic time warping with an asymmetric step pattern and Sakoe-Chiba window. Requires keep_internals=True to access window details. ```python asyband = dtw(query,reference, keep_internals=True, step_pattern=asymmetric, window_type=sakoeChibaWindow, window_args={'window_size': 30} ) ``` -------------------------------- ### Construct Rabiner-Juang Patterns Source: https://context7.com/dynamictimewarping/dtw-python/llms.txt Generate specific step patterns based on the Rabiner-Juang classification scheme, allowing for configuration of type, slope weighting, and smoothing. ```python from dtw import * # Create Rabiner-Juang step patterns # type: 1-7 (Roman numerals I-VII) # slope_weighting: 'a', 'b', 'c', 'd' # smoothed: True/False # Type II with 'd' weighting (normalizable by N+M) rj_type2d = rabinerJuangStepPattern(ptype=2, slope_weighting='d', smoothed=False) print(rj_type2d) ``` -------------------------------- ### Load Default Test Data for DTW Source: https://github.com/dynamictimewarping/dtw-python/blob/master/maintainer/examples/ex_dtwWindowingFunctions.py.txt Loads the default sine and cosine test data for dynamic time warping. Ensure numpy is imported. ```python from dtw import * import numpy as np (query, reference) = dtw_test_data.sin_cos() ``` -------------------------------- ### Perform Asymmetric DTW Computation Source: https://github.com/dynamictimewarping/dtw-python/blob/master/docs/api/dtw.StepPattern.md Load test data and compute the DTW alignment using an asymmetric step pattern. ```pycon >>> (query, reference) = dtw_test_data.sin_cos() ``` ```pycon >>> asy = dtw(query, reference, keep_internals=True, ... step_pattern=asymmetric); ``` ```pycon >>> dtwPlot(asy,type="density" ... ).set_title("Sine and cosine, asymmetric step") ``` -------------------------------- ### Basic DTW Alignment Source: https://github.com/dynamictimewarping/dtw-python/blob/master/maintainer/examples/ex_dtw.py.txt Performs DTW between a noisy sine wave and a cosine wave to find the optimal alignment. Requires numpy and dtw libraries. ```python import numpy as np from dtw import * idx = np.linspace(0,6.28,num=100) query = np.sin(idx) + np.random.uniform(size=100)/10.0 reference = np.cos(idx) alignment = dtw(query,reference) ``` -------------------------------- ### DTW with Symmetric Step and Global Parallelogram Constraint Source: https://github.com/dynamictimewarping/dtw-python/blob/master/maintainer/examples/ex_dtwPlotDensity.py.txt Performs DTW with a symmetric step pattern and a global parallelogram-shaped constraint. This allows for longer horizontal stretches within the window. ```python ita = dtw(query, reference, keep_internals=True, step_pattern=typeIIIc) ``` -------------------------------- ### Plotting Step Patterns Source: https://github.com/dynamictimewarping/dtw-python/blob/master/maintainer/examples/ex_stepPattern.py.txt Visualizes a step pattern using matplotlib. ```python >>> import matplotlib.pyplot as plt; # doctest: +SKIP ... symmetricP2.plot().set_title("Sakoe's Symmetric P=2 recursion") ``` -------------------------------- ### Visualize Cumulative Cost Landscape with dtwPlotDensity() Source: https://context7.com/dynamictimewarping/dtw-python/llms.txt Displays the cumulative cost matrix as a density plot with the optimal warping path. Supports normalization and various local or global constraints. ```python from dtw import * import matplotlib.pyplot as plt (query, reference) = dtw_test_data.sin_cos() alignment = dtw(query, reference, keep_internals=True) # Density plot of cumulative cost ax = dtwPlotDensity(alignment) ax.set_title("Cost Landscape with Warping Path") plt.show() # Normalized density (average cost per step) ax = dtwPlotDensity(alignment, normalize=True) ax.set_title("Normalized Cost Density") plt.show() # Compare local vs global Itakura constraint # Local constraint via step pattern ita_local = dtw(query, reference, keep_internals=True, step_pattern=typeIIIc) dtwPlotDensity(ita_local) plt.title("Local Itakura-like constraint (typeIIIc)") plt.show() # Global constraint via window ita_global = dtw(query, reference, keep_internals=True, window_type=itakuraWindow) dtwPlotDensity(ita_global) plt.title("Global Itakura window constraint") plt.show() ``` -------------------------------- ### Minimum Variance Matching (MVM) Step Pattern Source: https://context7.com/dynamictimewarping/dtw-python/llms.txt Creates a step pattern for MVM to find non-contiguous matches, requiring an elasticity parameter to define skip limits. ```python import numpy as np from dtw import * # Example from Latecki et al. paper (Fig. 5) 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) # Cost matrix is squared differences costmx = diffmx ** 2 # Create MVM step pattern with elasticity (max skippable elements) mvm_pattern = mvmStepPattern(elasticity=10) # Compute MVM alignment alignment = dtw(costmx, step_pattern=mvm_pattern) # Elements 4 and 5 (1-indexed) are skipped print(f"Matched reference indices: {alignment.index2 + 1}") # Output: [1 2 3 6 7] print(f"Distance: {alignment.distance}") ``` -------------------------------- ### Perform Partial Alignment Source: https://github.com/dynamictimewarping/dtw-python/blob/master/docs/api/dtw.dtw.md Compute alignment with open-begin and open-end constraints using an asymmetric step pattern. ```pycon >>> alignmentOBE = dtw(query[44:88], reference, ... keep_internals=True, ... step_pattern=asymmetric, ... open_end=True,open_begin=True) ``` ```pycon >>> alignmentOBE.plot(type="twoway",offset=1) ``` -------------------------------- ### Displaying Symmetric Step Pattern Source: https://github.com/dynamictimewarping/dtw-python/blob/master/maintainer/examples/ex_stepPattern.py.txt Displays the recursion definition for the symmetric2 step pattern. ```python >>> print(symmetric2) #doctest: +NORMALIZE_WHITESPACE 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 ``` -------------------------------- ### Visualize Asymmetric Alignment Source: https://github.com/dynamictimewarping/dtw-python/blob/master/maintainer/examples/ex_warp.py.txt Plots the query signal against the warped reference signal using an asymmetric step pattern. ```python plt.plot(query, "b-") # doctest: +SKIP plt.plot(reference[wt], "ok", facecolors='none') ``` -------------------------------- ### Compute DTW Alignment with Custom Step Pattern Source: https://github.com/dynamictimewarping/dtw-python/blob/master/maintainer/examples/ex_mvmStepPattern.py.txt Computes a DTW alignment using a pre-defined cost matrix and a custom step pattern. Ensure the cost matrix is properly formatted before computation. ```python import numpy as np from dtw import * 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 ) costmx = diffmx**2; al = dtw(costmx,step_pattern=mvmStepPattern(10)) ``` -------------------------------- ### dtw.dtwPlotAlignment Source: https://github.com/dynamictimewarping/dtw-python/blob/master/docs/api/dtw.dtwPlotAlignment.md Visualizes the alignment path of a Dynamic Time Warping (DTW) computation. ```APIDOC ## dtw.dtwPlotAlignment ### Description Plots the alignment path of a DTW computation. This function is useful for visualizing how two time series are aligned. ### Method N/A (This is a function call, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python import dtw # Assuming 'd' is a DTW alignment object computed previously # For example: # from dtw import dtw # x = [1, 2, 3, 4, 5] # y = [1, 1, 2, 3, 4, 5, 5] # alignment = dtw(x, y, keep_internals=True) # d = alignment.distance dtw.dtwPlotAlignment(d, xlab='Query index', ylab='Reference index') ``` ### Response #### Success Response (200) N/A (This function generates a plot, it does not return a value in the traditional sense, though it might return a matplotlib Axes object depending on the backend and kwargs). #### Response Example N/A (This function generates a plot.) ``` -------------------------------- ### Annotate Warping with dtwPlotThreeWay Source: https://context7.com/dynamictimewarping/dtw-python/llms.txt Creates a three-panel visualization showing the query, reference, and warping curve simultaneously. ```python from dtw import * import matplotlib.pyplot as plt (query, reference) = dtw_test_data.sin_cos() alignment = dtw(query, reference, keep_internals=True) # Three-way visualization ax = dtwPlotThreeWay( alignment, match_indices=10, # Number of guide lines match_col='red' # Color of guide lines ) plt.tight_layout() plt.show() # Via main function alignment.plot(type="threeway", match_indices=15) plt.show() ``` -------------------------------- ### Visualize warped query Source: https://github.com/dynamictimewarping/dtw-python/blob/master/docs/api/dtw.warp.md Plot the original reference and the warped query timeseries. ```pycon >>> import matplotlib.pyplot as plt; ... plt.plot(reference); ... plt.plot(query[wq]); ... plt.gca().set_title("Warping query") ``` -------------------------------- ### DTW Step Pattern Methods Source: https://github.com/dynamictimewarping/dtw-python/blob/master/docs/api/dtw.StepPattern.md This section details the methods available for manipulating and understanding DTW step patterns within the dtw-python library. ```APIDOC ## DTW Step Pattern Methods ### T() Transpose a step pattern. ### get_n_patterns() Number of rules in the recursion. ### get_n_rows() Total number of steps in the recursion. ### plot() Provide a visual description of a StepPattern object ``` -------------------------------- ### Compute alignment with Itakura window Source: https://github.com/dynamictimewarping/dtw-python/blob/master/docs/api/dtw.dtwPlotDensity.md Calculates the alignment using the itakuraWindow global constraint. ```pycon >>> ita = dtw(query, reference, keep_internals=True, window_type=itakuraWindow) ``` -------------------------------- ### Plot Step Pattern Source: https://github.com/dynamictimewarping/dtw-python/blob/master/docs/api/dtw.StepPattern.md Visualize a step pattern using matplotlib. ```pycon >>> import matplotlib.pyplot as plt; ... symmetricP2.plot().set_title("Sakoe's Symmetric P=2 recursion") ``` -------------------------------- ### Visualize warped reference Source: https://github.com/dynamictimewarping/dtw-python/blob/master/docs/api/dtw.warp.md Plot the original query and the warped reference timeseries. ```pycon >>> import matplotlib.pyplot as plt; ... plt.plot(query); ... plt.plot(reference[wt]); ... plt.gca().set_title("Warping reference") ``` -------------------------------- ### Apply asymmetric warping Source: https://github.com/dynamictimewarping/dtw-python/blob/master/docs/api/dtw.warp.md Compute alignment with an asymmetric step pattern and warp the reference. ```pycon >>> alignment = dtw(query,reference,step_pattern=asymmetric) >>> wt = warp(alignment,index_reference=True); ``` -------------------------------- ### Compute alignment with MVM Source: https://github.com/dynamictimewarping/dtw-python/blob/master/docs/api/dtw.mvmStepPattern.md Performs the DTW alignment using the mvmStepPattern with an elasticity of 10. ```pycon >>> al = dtw(costmx,step_pattern=mvmStepPattern(10)) ``` -------------------------------- ### Step Patterns Source: https://context7.com/dynamictimewarping/dtw-python/llms.txt Step patterns define the local transition constraints and slope characteristics for DTW variants. The package provides numerous pre-defined patterns and tools to construct custom ones. ```APIDOC ## Step Patterns ### StepPattern - Define Local Transition Constraints #### Description Represents the local transition constraints and slope characteristics for a DTW variant. Includes pre-defined patterns and methods for manipulation. #### Common Pre-defined Step Patterns - **symmetric2**: Default, normalizable by N+M. - **symmetric1**: White-Neely, non-normalizable. - **asymmetric**: Slope 0-2, normalizable by N. - **symmetricP1**: Sakoe-Chiba P=1. - **asymmetricP2**: Sakoe-Chiba P=2. - **typeIIIc**: Rabiner-Myers type III. - **rigid**: Fixed slope 1, for gapless matching. #### Methods - **`StepPattern.plot()`**: Generates a graphical representation of the step pattern. - **`StepPattern.T()`**: Transposes the step pattern (swaps query/reference roles). #### Request Example ```python from dtw import * import numpy as np import matplotlib.pyplot as plt # View the default symmetric2 step pattern print(symmetric2) # Compare alignments with different step patterns (query, reference) = dtw_test_data.sin_cos() patterns = { 'symmetric2': symmetric2, 'symmetric1': symmetric1, 'asymmetric': asymmetric, 'symmetricP1': symmetricP1, 'asymmetricP2': asymmetricP2, 'typeIIIc': typeIIIc, 'rigid': rigid, } for name, pattern in patterns.items(): try: result = dtw(query, reference, step_pattern=pattern) print(f"{name}: distance={result.distance:.4f}") except ValueError as e: print(f"{name}: {e}") # Plot a step pattern graphically ax = asymmetricP2.plot() ax.set_title("Sakoe's Symmetric P=2 recursion") plt.show() # Transpose a step pattern asymmetric_T = asymmetric.T() print(f"Original hint: {asymmetric.hint}, Transposed hint: {asymmetric_T.hint}") ``` ### rabinerJuangStepPattern() - Construct Rabiner-Juang Patterns #### Description Constructs step patterns according to the Rabiner-Juang classification scheme. #### Parameters - **ptype** (int) - Type of pattern (1-7). - **slope_weighting** (str) - Slope weighting subtype ('a', 'b', 'c', 'd'). - **smoothed** (bool) - Whether the pattern should be smoothed. #### Request Example ```python from dtw import * # Create Rabiner-Juang step patterns # Type II with 'd' weighting (normalizable by N+M) rj_type2d = rabinerJuangStepPattern(ptype=2, slope_weighting='d', smoothed=False) print(rj_type2d) ``` ``` -------------------------------- ### Plotting Asymmetric DTW Alignment Path Source: https://github.com/dynamictimewarping/dtw-python/blob/master/maintainer/examples/ex_dtw.py.txt Visualizes the alignment path for DTW calculated with a custom distance matrix and the asymmetric step pattern. The plot uses red circles to highlight the path, showing how the asymmetric pattern affects the traversal. ```python plt.plot(da.index1,da.index2,'ro') # doctest: +SKIP ``` -------------------------------- ### Access Test Data with dtw_test_data Source: https://context7.com/dynamictimewarping/dtw-python/llms.txt Provides sample datasets like noisy sine/cosine waves and ECG waveforms for testing and experimentation. ```python from dtw import * import matplotlib.pyplot as plt # Noisy sine vs cosine (query, reference) = dtw_test_data.sin_cos() print(f"Query shape: {query.shape}, Reference shape: {reference.shape}") plt.plot(query, label='Query (noisy sine)') plt.plot(reference, label='Reference (cosine)') plt.legend() plt.title("Sin/Cos Test Data") plt.show() # ANSI/AAMI EC13 ECG waveforms (aami3a, aami3b) = dtw_test_data.aami() ``` -------------------------------- ### Plotting Warped Query with Reference Source: https://github.com/dynamictimewarping/dtw-python/blob/master/maintainer/examples/ex_dtw.py.txt Visualizes the warped query time series alongside the reference time series. This helps in understanding how the query is stretched or compressed to match the reference. ```python plt.plot(reference); plt.plot(alignment.index2,query[alignment.index1]) # doctest: +SKIP ``` -------------------------------- ### Performing Asymmetric DTW Computation Source: https://github.com/dynamictimewarping/dtw-python/blob/master/maintainer/examples/ex_stepPattern.py.txt Computes DTW using an asymmetric step pattern on test data. ```python >>> (query, reference) = dtw_test_data.sin_cos() Do the computation >>> asy = dtw(query, reference, keep_internals=True, ... step_pattern=asymmetric); ``` -------------------------------- ### Perform Asymmetric DTW Alignment Source: https://github.com/dynamictimewarping/dtw-python/blob/master/maintainer/examples/ex_warp.py.txt Computes alignment using an asymmetric step pattern to ensure each query index maps to exactly one reference index. ```python alignment = dtw(query,reference,step_pattern=asymmetric) wt = warp(alignment,index_reference=True); ``` -------------------------------- ### Plotting Symmetric DTW Alignment Path Source: https://github.com/dynamictimewarping/dtw-python/blob/master/maintainer/examples/ex_dtw.py.txt Visualizes the alignment path for DTW calculated with a custom distance matrix and the symmetric step pattern. The path should follow the low-distance areas defined in `ldist`. ```python plt.plot(ds.index1,ds.index2) # doctest: +SKIP ``` -------------------------------- ### Plotting Asymmetric DTW Results Source: https://github.com/dynamictimewarping/dtw-python/blob/master/maintainer/examples/ex_stepPattern.py.txt Visualizes the density plot of an asymmetric DTW computation. ```python >>> dtwPlot(asy,type="density" # doctest: +SKIP ... ).set_title("Sine and cosine, asymmetric step") ``` -------------------------------- ### Plot density for local constraint alignment Source: https://github.com/dynamictimewarping/dtw-python/blob/master/docs/api/dtw.dtwPlotDensity.md Visualizes the cumulative cost density for the alignment computed with local constraints. ```pycon >>> dtwPlotDensity(ita) ``` -------------------------------- ### Plot asymmetric warping results Source: https://github.com/dynamictimewarping/dtw-python/blob/master/docs/api/dtw.warp.md Visualize the query against the warped reference using an asymmetric step pattern. ```pycon >>> plt.plot(query, "b-") ... plt.plot(reference[wt], "ok", facecolors='none') ``` -------------------------------- ### dtwPlotDensity() Source: https://context7.com/dynamictimewarping/dtw-python/llms.txt Displays the cumulative cost matrix as a density plot with the optimal warping path superimposed. ```APIDOC ## dtwPlotDensity(alignment, normalize=False) ### Description Displays the cumulative cost matrix as a density plot with the optimal warping path superimposed. Supports normalization of the cost density. ### Parameters #### Arguments - **alignment** (dtw object) - Required - The result object from a dtw() call. - **normalize** (bool) - Optional - If True, displays average cost per step. ``` -------------------------------- ### Plot DTW Results Source: https://github.com/dynamictimewarping/dtw-python/blob/master/maintainer/examples/ex_warpArea.py.txt Visualize the DTW alignment and plot an additional line for comparison. Requires matplotlib. ```python import matplotlib.pyplot as plt; ds.plot(); plt.plot([0,2.3,4.7,7]) # doctest: +SKIP ``` -------------------------------- ### DTW with Itakura Window Constraint Source: https://github.com/dynamictimewarping/dtw-python/blob/master/maintainer/examples/ex_dtwPlotDensity.py.txt Applies Dynamic Time Warping using the Itakura parallelogram window constraint. This constraint is local and arises from slope restrictions, not a global limitation. ```python query, reference = dtw_test_data.sin_cos() ita = dtw(query, reference, keep_internals=True, window_type=itakuraWindow) ``` -------------------------------- ### dtw.dtwPlotTwoWay Source: https://github.com/dynamictimewarping/dtw-python/blob/master/docs/api/dtw.dtwPlotTwoWay.md Visualizes the alignment between query and reference time series using pointwise comparison. ```APIDOC ## dtw.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. - **xlab** (string) - Optional - Label for the x-axis. - **ylab** (string) - Optional - Label for the y-axis. - **pch** (any) - Optional - Graphical parameters for timeseries plotting. - **...** (any) - Optional - Additional arguments passed to matplot. ### Notes When offset is set, values on the left axis only apply to the query, and the reference is shifted vertically. ``` -------------------------------- ### Plotting Unwarped Query and Inverse-Warped Reference Source: https://github.com/dynamictimewarping/dtw-python/blob/master/maintainer/examples/ex_dtw.py.txt Plots the original query time series and the inverse-warped reference time series. This provides another perspective on the alignment by showing the reference adjusted to the query's timeline. ```python plt.plot(query) # doctest: +SKIP plt.plot(alignment.index1,reference[alignment.index2]) ``` -------------------------------- ### rabinerJuangStepPattern Function Source: https://github.com/dynamictimewarping/dtw-python/blob/master/docs/api/dtw.rabinerJuangStepPattern.md Constructs a pattern classified according to the Rabiner-Juang scheme. Refer to the StepPattern class documentation for more details. ```APIDOC ## dtw.rabinerJuangStepPattern(ptype, slope_weighting='d', smoothed=False) ### Description Construct a pattern classified according to the Rabiner-Juang scheme (Rabiner1993). See documentation for the StepPattern class. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Load and Inspect aami Dataset Source: https://github.com/dynamictimewarping/dtw-python/blob/master/maintainer/examples/ex_aami.py.txt Loads the aami dataset and prints the first row (timestamps) and second row (values) with specific print options. ```python from dtw import *; import numpy as np (aami3a, aami3b) = dtw_test_data.aami() ``` ```python with np.printoptions(precision=3): print(aami3a[0,:]) # doctest: +NORMALIZE_WHITESPACE ``` ```python with np.printoptions(precision=3): print(aami3a[1,:]) # doctest: +NORMALIZE_WHITESPACE ``` -------------------------------- ### Compute alignment Source: https://github.com/dynamictimewarping/dtw-python/blob/master/docs/api/dtw.warp.md Calculate the alignment between query and reference timeseries. ```pycon >>> alignment = dtw(query,reference); ``` -------------------------------- ### Plot DTW Path and Diagonal Source: https://github.com/dynamictimewarping/dtw-python/blob/master/docs/api/dtw.warpArea.md Visualize the dynamic time warping path and a reference diagonal line using matplotlib. ```python import matplotlib.pyplot as plt; ds.plot(); plt.plot([0,2.3,4.7,7]) ``` -------------------------------- ### Analyze Cumulative Cost Matrix Source: https://github.com/dynamictimewarping/dtw-python/blob/master/docs/api/dtw.dtw.md Visualize the cost matrix using contour plots when keep_internals is enabled. ```pycon >>> alignment = dtw(query, reference, keep_internals=True) ``` ```pycon >>> plt.contour(alignment.costMatrix.T, origin="lower") >>> plt.plot(alignment.index1, alignment.index2, 'r-') ``` -------------------------------- ### Apply Warping to Time Series with warp() Source: https://context7.com/dynamictimewarping/dtw-python/llms.txt Converts warping curves into explicit index mappings to align one time series to another. Asymmetric step patterns are often preferred for natural reference warping. ```python from dtw import * import numpy as np import matplotlib.pyplot as plt (query, reference) = dtw_test_data.sin_cos() alignment = dtw(query, reference) # Get warping indices for query (default) wq = warp(alignment, index_reference=False) # Get warping indices for reference wt = warp(alignment, index_reference=True) # Plot warped query against reference plt.figure(figsize=(10, 4)) plt.subplot(1, 2, 1) plt.plot(reference, label='Reference') plt.plot(query[wq], label='Warped Query', linestyle='--') plt.legend() plt.title("Query Warped to Reference") # Plot warped reference against query plt.subplot(1, 2, 2) plt.plot(query, label='Query') plt.plot(reference[wt], label='Warped Reference', linestyle='--') plt.legend() plt.title("Reference Warped to Query") plt.tight_layout() plt.show() # Asymmetric step pattern makes warping reference "natural" # because every query index has exactly one image alignment_asym = dtw(query, reference, step_pattern=asymmetric) wt_asym = warp(alignment_asym, index_reference=True) plt.plot(query, 'b-', label='Query') plt.plot(reference[wt_asym], 'ko', fillstyle='none', label='Warped Reference') plt.legend() plt.title("Asymmetric: Natural Reference Warping") plt.show() ``` -------------------------------- ### Core DTW Computation - dtw() Source: https://context7.com/dynamictimewarping/dtw-python/llms.txt The main entry point for computing DTW alignments between two time series. It finds the optimal warping path that minimizes the cumulative distance between aligned elements, supporting various step patterns, windowing constraints, and open-ended alignments. ```APIDOC ## dtw() - Compute Dynamic Time Warp Alignment ### Description Computes the optimal warping path that minimizes the cumulative distance between two time series, supporting various step patterns, windowing constraints, and open-ended alignments. ### Method `dtw()` ### Parameters - **query** (array-like) - The first time series. - **reference** (array-like) - The second time series. - **step_pattern** (StepPattern, optional) - The step pattern to use for alignment. Defaults to `symmetric2`. - **window_type** (str, optional) - The type of window constraint to apply (e.g., 'sakoechiba', 'slantedband'). - **window_args** (dict, optional) - Arguments for the window constraint. - **open_begin** (bool, optional) - Whether to allow open-ended alignment at the beginning. Defaults to `False`. - **open_end** (bool, optional) - Whether to allow open-ended alignment at the end. Defaults to `False`. - **distance_only** (bool, optional) - If `True`, only the distance is computed, without the warping path. Defaults to `False`. - **keep_internals** (bool, optional) - If `True`, internal computation details are kept. Defaults to `False`. ### Request Example ```python import numpy as np from dtw import * idx = np.linspace(0, 6.28, num=100) query = np.sin(idx) + np.random.uniform(size=100) / 10.0 reference = np.cos(idx) alignment = dtw(query, reference) print(f"Distance: {alignment.distance}") alignment_constrained = dtw( query, reference, step_pattern=asymmetric, window_type="sakoechiba", window_args={'window_size': 30}, keep_internals=True ) ldist = np.ones((6, 6)) ds = dtw(ldist) print(f"Distance from cost matrix: {ds.distance}") partial_alignment = dtw( query[44:88], reference, keep_internals=True, step_pattern=asymmetric, open_end=True, open_begin=True ) print(f"Partial match ends at reference index: {partial_alignment.jmin}") dist_only = dtw(query, reference, distance_only=True) print(f"Distance (fast): {dist_only.distance}") ``` ### Response #### Success Response (200) - **distance** (float) - The cumulative distance of the optimal alignment. - **normalizedDistance** (float) - The normalized distance. - **N** (int) - Length of the query time series. - **M** (int) - Length of the reference time series. - **index1** (list) - Indices of the query time series in the warping path. - **index2** (list) - Indices of the reference time series in the warping path. - **jmin** (int) - The ending index of the partial match (for open-ended alignments). #### Response Example ```json { "distance": 15.7, "normalizedDistance": 0.157, "N": 100, "M": 100, "index1": [0, 0, 1, 2, 3, ...], "index2": [0, 1, 1, 2, 3, ...], "jmin": 95 } ``` ``` -------------------------------- ### Compute cost matrix Source: https://github.com/dynamictimewarping/dtw-python/blob/master/docs/api/dtw.mvmStepPattern.md Calculates the cost matrix by squaring the difference matrix. ```pycon >>> costmx = diffmx**2; ``` -------------------------------- ### Plot alignment Source: https://github.com/dynamictimewarping/dtw-python/blob/master/docs/api/dtw.mvmStepPattern.md Visualizes the computed alignment. ```pycon >>> al.plot() ``` -------------------------------- ### Visualize Alignment Mapping Source: https://github.com/dynamictimewarping/dtw-python/blob/master/docs/api/dtw.dtw.md Plot the warping function index mapping using matplotlib. ```pycon >>> import matplotlib.pyplot as plt; ... plt.plot(alignment.index1, alignment.index2) ``` -------------------------------- ### Compute alignment with local constraints Source: https://github.com/dynamictimewarping/dtw-python/blob/master/docs/api/dtw.dtwPlotDensity.md Calculates the alignment using the typeIIIc step pattern, which enforces local slope restrictions. ```pycon >>> (query, reference) = dtw_test_data.sin_cos() >>> ita = dtw(query, reference, keep_internals=True, step_pattern=typeIIIc) ```