{"id":8133,"library":"dtw-python","title":"DTW for Python","description":"dtw-python is a comprehensive Python library that provides a faithful, functionally equivalent implementation of Dynamic Time Warping (DTW) algorithms, mirroring the capabilities of the popular R 'dtw' package. It enables optimal alignment between two time series, even if they have different lengths or time axes, and supports various local (slope) and global (window) constraints. The library is currently at version 1.7.4 and maintains an active, though irregular, release cadence, with several updates per year. It is widely used for classification and clustering tasks across domains like bioinformatics, econometrics, and general time series analysis.","status":"active","version":"1.7.4","language":"en","source_language":"en","source_url":"https://github.com/DynamicTimeWarping/dtw-python","tags":["time-series","dynamic-time-warping","dtw","signal-processing","alignment","similarity"],"install":[{"cmd":"pip install dtw-python","lang":"bash","label":"Standard installation"},{"cmd":"pip install dtw-python[plots]","lang":"bash","label":"With plotting capabilities"}],"dependencies":[{"reason":"Core dependency for numerical operations and array handling.","package":"numpy","optional":false},{"reason":"Used for distance calculations (e.g., `scipy.spatial.distance.cdist`) and other scientific computing tasks. Pre-installing can speed up `dtw-python` installation.","package":"scipy","optional":false},{"reason":"Required for plotting functions like `alignment.plot()`. Included with `dtw-python[plots]` installation.","package":"matplotlib","optional":true}],"imports":[{"note":"The package name for pip is 'dtw-python', but the import statement is simply 'import dtw'.","wrong":"from dtw-python import dtw","symbol":"dtw","correct":"import dtw"},{"note":"Common for interactive use, imports core functions like `dtw` and `rabinerJuangStepPattern` directly.","symbol":"*","correct":"from dtw import *"}],"quickstart":{"code":"import numpy as np\nfrom dtw import *\n\n# Create two noisy sine waves\nidx = np.linspace(0, 6.28, num=100)\nquery = np.sin(idx) + np.random.uniform(size=100) / 10.0\ntemplate = np.cos(idx)\n\n# Compute DTW alignment\nalignment = dtw(query, template, keep_internals=True)\n\n# Print the distance\nprint(f\"DTW Distance: {alignment.distance:.2f}\")\n\n# Optionally, visualize the alignment (requires matplotlib)\ntry:\n    import matplotlib.pyplot as plt\n    alignment.plot(type=\"threeway\")\n    plt.title(\"DTW Alignment\")\n    plt.show()\nexcept ImportError:\n    print(\"Matplotlib not installed. Install with `pip install dtw-python[plots]` to enable plotting.\")","lang":"python","description":"This quickstart demonstrates how to compute Dynamic Time Warping between two NumPy arrays. It defines a query and a template time series, then uses the `dtw()` function to find their optimal alignment. The resulting `alignment` object contains the DTW distance and can be used for plotting the warping path (if `matplotlib` is installed)."},"warnings":[{"fix":"Adjust all indices (e.g., `index1`, `index2`, `index1s`, `index2s` attributes of alignment objects) to be 0-based when working in Python.","message":"Indexing in `dtw-python` is 0-based, consistent with Python conventions. This differs from the 1-based indexing used in the R 'dtw' package, which can be a source of error when porting code or comparing results directly.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Use Pythonic underscore-separated full argument names in function calls (e.g., `dtw(..., keep_internals=True)`).","message":"Function argument names in Python use underscores (e.g., `keep_internals`) while the R version commonly uses dots (e.g., `keep.int`). Python does not accept abbreviated argument names.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Install `matplotlib` separately (`pip install matplotlib`) or install `dtw-python` with the `plots` extra: `pip install dtw-python[plots]`.","message":"Plotting functionality, such as `alignment.plot()`, relies on `matplotlib`. If `matplotlib` is not installed, these methods will raise an `ImportError` or fail silently.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Review your `dist_method` choice and input data. Consider using a more robust distance metric like 'euclidean' if `NaN`s appear unexpectedly, or preprocess data to handle potential division by zero or undefined values if using cosine distance.","message":"The `dtw` function may return `NaN` values in the cost matrix, particularly when using certain `dist_method` arguments like 'cosine' with inappropriate input data. This can lead to `ParameterError: DTW cost matrix C has NaN values.`","severity":"gotcha","affected_versions":"All versions"},{"fix":"Ensure your system's C compiler is up-to-date. If using Conda, `conda install gcc_linux-64` before `pip install dtw-python` may resolve the issue.","message":"Uncommon build issues related to `undefined symbol: alloca` or `C99 mode` can arise when compiling from source on older systems or with outdated compilers.","severity":"gotcha","affected_versions":"All versions (when building from source)"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"The correct import statement is `import dtw` or `from dtw import dtw` (or `from dtw import *`). The package name `dtw-python` is for `pip install`.","cause":"Attempting to import `dtw` directly from a module named `dtw-python`, which is the PyPI package name but not the internal module name.","error":"ImportError: cannot import name 'dtw' from 'dtw-python'"},{"fix":"Inspect the input time series for `NaN`s, `inf`s, or problematic values (e.g., all zeros if using cosine distance). Consider changing the `dist_method` parameter to a more numerically stable option like 'euclidean' if the current metric is not essential.","cause":"The local distance function (specified by `dist_method`) produced `NaN` values, often due to inputs incompatible with the chosen metric (e.g., zero vectors with cosine distance).","error":"librosa.util.exceptions.ParameterError: DTW cost matrix C has NaN values."},{"fix":"Explicitly set the `step_pattern`, `dist_method`, and `window_type` arguments in `dtw-python` to match the configuration used in the other library for a fair comparison. Pay attention to 0-based vs 1-based indexing conventions.","cause":"Differences often stem from varying default step patterns, local distance metrics, or windowing functions used across implementations. `dtw-python` defaults to `symmetric2` step pattern.","error":"Unexpected DTW distance or path results compared to R's 'dtw' package or other Python DTW libraries."}]}