### Install dtaidistance from GitHub Source: https://github.com/wannesm/dtaidistance/blob/master/docs/usage/installation.md Installs the latest development version of dtaidistance directly from its GitHub repository using pip. Similar to PyPI installation, it offers an option to skip OpenMP. ```bash pip install git+https://github.com/wannesm/dtaidistance.git#egg=dtaidistance ``` ```bash pip install --global-option=--noopenmp git+https://github.com/wannesm/dtaidistance.git#egg=dtaidistance ``` -------------------------------- ### Compile and Install dtaidistance from Source Source: https://github.com/wannesm/dtaidistance/blob/master/docs/usage/installation.md Instructions for compiling and installing dtaidistance directly from its source code. This includes building C extensions and installing the package, with options for OpenMP and compiler arguments. ```bash python3 setup.py build_ext --inplace python3 setup.py install ``` ```bash python3 setup.py --noopenmp build_ext --inplace ``` ```bash # To see all options: python3 setup.py -h ``` -------------------------------- ### Troubleshoot dtaidistance PyPI Installation Source: https://github.com/wannesm/dtaidistance/blob/master/docs/usage/installation.md Commands and Python code to help diagnose and resolve installation issues with dtaidistance from PyPI. This includes checking C extension import status and reinstalling with specific build isolation options. ```python import dtw dtw.try_import_c(verbose=True) ``` ```bash pip install -v --upgrade --force-reinstall --no-build-isolation --no-binary dtaidistance dtaidistance ``` -------------------------------- ### Install dtaidistance from PyPI Source: https://github.com/wannesm/dtaidistance/blob/master/docs/usage/installation.md Installs the dtaidistance package using pip. Requires Python 3. This command assumes OpenMP is available. An alternative command is provided for systems without OpenMP. ```bash pip install dtaidistance ``` ```bash pip install --global-option=--noopenmp dtaidistance ``` -------------------------------- ### Install dtaidistance with specific OpenMP compiler flags Source: https://github.com/wannesm/dtaidistance/blob/master/docs/usage/installation.md Installs dtaidistance from PyPI using pip with alternative global options to specify compiler flags for OpenMP detection. Useful when OpenMP is installed but not automatically detected. ```bash pip install --global-option=--forcegnugcc dtaidistance # To include -lomp: pip install --global-option=--forcellvm dtaidistance # To remove the -Xpreprocessor option: pip install --global-option=--noxpreprocessor dtaidistance ``` -------------------------------- ### Compile and Run DTAIDistance C Benchmark Source: https://github.com/wannesm/dtaidistance/blob/master/docs/usage/installation.md This snippet demonstrates how to compile the C source files for DTAIDistance algorithms using GCC, including OpenMP support, and then run the benchmark executable. It shows the necessary compiler flags and linking steps. ```bash $ gcc -c -o DTAIDistanceC/dd_benchmark.o DTAIDistanceC/dd_benchmark.c -Wall -g -Xpreprocessor -fopenmp $ gcc -c -o DTAIDistanceC/dd_dtw_openmp.o DTAIDistanceC/dd_dtw_openmp.c -Wall -g -Xpreprocessor -fopenmp $ gcc -c -o DTAIDistanceC/dd_ed.o DTAIDistanceC/dd_ed.c -Wall -g -Xpreprocessor -fopenmp $ gcc -o dd_benchmark DTAIDistanceC/dd_benchmark.o DTAIDistanceC/dd_dtw.o DTAIDistanceC/dd_dtw_openmp.o DTAIDistanceC/dd_ed.o -Wall -g -Xpreprocessor -fopenmp -lomp $ ./dd_benchmark Benchmarking ... OpenMP is supported Creating result array of size 17997000 Execution time = 7.000000 ``` -------------------------------- ### Install OpenMP via Homebrew on macOS Source: https://github.com/wannesm/dtaidistance/blob/master/docs/usage/openmp.md Installs LLVM and the libomp library using Homebrew on macOS. Sets environment variables for the clang compiler and library paths to ensure OpenMP is recognized during compilation. ```shell brew install llvm libomp export CC=/usr/local/opt/llvm/bin/clang export LDFLAGS="-L/usr/local/opt/llvm/lib" export CPPFLAGS="-I/usr/local/opt/llvm/include" ``` -------------------------------- ### Compile dtaidistance from Source with specific compiler flags Source: https://github.com/wannesm/dtaidistance/blob/master/docs/usage/installation.md Commands for compiling dtaidistance from source, specifying compiler flags to aid OpenMP detection when it's installed but not found. Options include forcing GCC, Clang, or removing preprocessor flags. ```bash # To include -lgomp (when using GOMP instead of OMP): python3 setup.py --forcegnugcc build_ext --inplace # To include -lomp: python3 setup.py --forcellvm build_ext --inplace # To remove the -Xpreprocessor option: python3 setup.py --noxpreprocessor build_ext --inplace ``` -------------------------------- ### Install dtaidistance from Conda/Anaconda Source: https://github.com/wannesm/dtaidistance/blob/master/docs/usage/installation.md Installs the dtaidistance package using the conda package manager from the conda-forge channel. This method provides precompiled binary versions for various operating systems. ```bash conda install -c conda-forge dtaidistance ``` -------------------------------- ### best_path Source: https://github.com/wannesm/dtaidistance/blob/master/docs/modules/subsequence/localconcurrences.md Find the best path starting from the given row and column in the data structure. ```APIDOC ## GET /best_path ### Description Find the best path starting from the given row and column. ### Method GET ### Endpoint /best_path ### Parameters #### Query Parameters - **row** (int) - Required - Row index in datastructure - **col** (int) - Required - Column index in datastructure - **wp** (object) - Optional - Warping paths, default is None and taken from the object. ### Response #### Success Response (200) - **path** (list of tuples) - List of tuples (index in series1, index in series2) #### Response Example { "path": [ [0, 0], [1, 1], [2, 2] ] } ``` -------------------------------- ### Force LLVM/OpenMP compilation for dtaidistance on macOS Source: https://github.com/wannesm/dtaidistance/blob/master/docs/usage/openmp.md Installs the dtaidistance Python package from a GitHub repository, forcing the use of LLVM and OpenMP for compilation. This ensures that the C extension is built with parallel processing capabilities enabled. ```shell pip install --global-option=--forcellvm git+https://github.com/wannesm/dtaidistance.git ``` -------------------------------- ### Force GCC/OpenMP compilation for dtaidistance on Linux Source: https://github.com/wannesm/dtaidistance/blob/master/docs/usage/openmp.md Installs the dtaidistance Python package from a GitHub repository, forcing the use of GCC and OpenMP for compilation. This ensures that the C extension is built with parallel processing capabilities enabled using the GNU toolchain. ```shell pip install --global-option=--forcegnugcc git+https://github.com/wannesm/dtaidistance.git ``` -------------------------------- ### Compile with OpenMP using GCC on Linux Source: https://github.com/wannesm/dtaidistance/blob/master/docs/usage/openmp.md Compiles a C file named 'myfile.c' using the GCC compiler with OpenMP support enabled. The '-Xpreprocessor -fopenmp' flags activate OpenMP, and '-lgomp' links the GNU OpenMP library. ```c gcc -Xpreprocessor -fopenmp -lgomp myfile.c ``` -------------------------------- ### Compile with OpenMP using clang on macOS Source: https://github.com/wannesm/dtaidistance/blob/master/docs/usage/openmp.md Compiles a C file named 'myfile.c' using the clang compiler with OpenMP support enabled. The '-Xpreprocessor -fopenmp' flags activate OpenMP, and '-lomp' links the OpenMP library. ```c clang -Xpreprocessor -fopenmp -lomp myfile.c ``` -------------------------------- ### dtaidistance.dtw.best_path Source: https://github.com/wannesm/dtaidistance/blob/master/docs/modules/dtw.md Computes the optimal warping path from a given warping paths matrix. It supports specifying a starting row and column, and can find either the minimal or maximal path. ```APIDOC ## POST /dtaidistance.dtw.best_path ### Description Compute the optimal path from the nxm warping paths matrix. This function can start from a specified row and column, and find either the minimal or maximal path. ### Method POST ### Endpoint /dtaidistance.dtw.best_path ### Parameters #### Path Parameters None #### Query Parameters * **row** (int) - Optional - If given, start from this row (instead of lower-right corner) * **col** (int) - Optional - If given, start from this column (instead of lower-right corner) * **use_max** (bool) - Optional - Find maximal path instead of minimal path. Defaults to False. * **penalty** (float) - Optional - The penalty used. If this is used, then paths should be expressed as the internal representation. Defaults to 0. #### Request Body * **paths** (array) - Required - Warping paths matrix ### Request Example ```json { "paths": [[0.0, 1.0], [1.0, 0.0]], "row": 0, "col": 0, "use_max": false, "penalty": 0.0 } ``` ### Response #### Success Response (200) * **best_path** (array) - Array of (row, col) or (ts_1_idx, ts_2_idx) representing the best path #### Response Example ```json { "best_path": [[0, 0], [1, 1]] } ``` ``` -------------------------------- ### Compile C code for float datatype with dtaidistance Source: https://github.com/wannesm/dtaidistance/blob/master/docs/usage/advanced.md This snippet demonstrates how to clone the dtaidistance repository, navigate to the C compilation directory, and compile the C code to use the float datatype. It also includes steps for rebuilding and installing the package. This is useful for reducing memory usage or potentially increasing performance on certain hardware. ```default git clone https://github.com/wannesm/dtaidistance.git cd dtaidistance/dtaidistance/jinja make float # make int cd ../.. make build pip install . ``` -------------------------------- ### Get Amplitude Bounds of a Path Source: https://github.com/wannesm/dtaidistance/blob/master/docs/modules/explain/explainpair.md Computes the amplitude bounds for a given path. This function can operate on the original optimal path or on linear segments derived from it, providing insights into the path's variations. ```python def get_bounds(on_segments=False): """ Compute the amplitude bounds * **Parameters:** **on_segments** – Compute the bounds based on the linear segments instead of the original optimal path * **Returns:** """ pass ``` -------------------------------- ### K-Means DBA Clustering with dtaidistance Source: https://github.com/wannesm/dtaidistance/blob/master/docs/usage/clustering.md Implements K-Means clustering for time series using DTW Barycenter Averaging (DBA). The example shows clustering the 'Trace' dataset and applying preprocessing steps like differencing and low-pass filtering to improve results. It uses the KMeans class with parameters for the number of clusters (k), maximum iterations, and DBA iterations. ```python model = KMeans(k=4, max_it=10, max_dba_it=10, dists_options={"window": 40}) cluster_idx, performed_it = model.fit(series, use_c=True, use_parallel=False) ``` ```python series = dtaidistance.preprocessing.differencing(series, smooth=0.1) model = KMeans(k=4, max_it=10, max_dba_it=10, dists_options={"window": 40}) cluster_idx, performed_it = model.fit(series, use_c=True, use_parallel=False) ``` -------------------------------- ### DTWSettings Class Initialization (Python) Source: https://github.com/wannesm/dtaidistance/blob/master/docs/modules/dtw.md Initializes DTWSettings with various parameters to control DTW behavior. Parameters include window size, pruning options, distance limits, step constraints, length difference tolerance, penalty values, psi relaxation, inner distance metric, and C extension usage. ```python dtaidistance.dtw.DTWSettings(window=None, use_pruning=False, max_dist=None, max_step=None, max_length_diff=None, penalty=None, psi=None, inner_dist='squared euclidean', use_ndim=False, use_c=False) ``` -------------------------------- ### SAMatch Class Initialization (Python) Source: https://github.com/wannesm/dtaidistance/blob/master/docs/modules/subsequence/subsequencealignment.md Shows how to initialize the SAMatch class, which represents a subsequence alignment match. It takes an index and an alignment object as parameters. ```python from dtaidistance.subsequence import SAMatch # Assuming 'idx' and 'alignment' are defined previously # match = SAMatch(idx, alignment) ``` -------------------------------- ### SAMatches Class Initialization (Python) Source: https://github.com/wannesm/dtaidistance/blob/master/docs/modules/subsequence/subsequencealignment.md Demonstrates the initialization of the SAMatches class, used for managing multiple subsequence alignment matches. It can be initialized with an existing SAMatches object or a list of matches. ```python from dtaidistance.subsequence import SAMatches # Assuming 'sa' is a SubsequenceAlignment object # matches_obj = SAMatches(sa) ``` -------------------------------- ### Explain Warping Path with ExplainPair Source: https://github.com/wannesm/dtaidistance/blob/master/docs/modules/explain/explainpair.md Demonstrates how to use the ExplainPair class to analyze the warping path between two time series. It shows how to instantiate ExplainPair, calculate an approximate distance, and plot the warping path. Requires dtaidistance version 2.4.0 or higher. ```python from dtaidistance.explain.dsw import ExplainPair ts_a = [1, 2, 3, 4, 5] ts_b = [1, 2, 3, 4, 5] ep = ExplainPair(ts_a, ts_b, delta_rel=2, delta_abs=0) print(ep.distance_approx()) ep.plot_warping("/path/to/figure.png") ``` -------------------------------- ### Get Documentation for dtw.distance Source: https://github.com/wannesm/dtaidistance/blob/master/README.md Retrieves and prints the docstring for the `dtw.distance` function, providing information about its arguments and usage. ```python from dtaidistance import dtw print(dtw.distance.__doc__) ``` -------------------------------- ### Get Best Match from SubsequenceAlignment (Python) Source: https://github.com/wannesm/dtaidistance/blob/master/docs/modules/subsequence/subsequencealignment.md Retrieves the single best match from a SubsequenceAlignment object. This method considers minimum and maximum lengths for the match. ```python from dtaidistance.subsequence import subsequence_search import numpy as np query = np.array([1., 2, 0]) series = np.array([1., 0, 1, 2, 1, 0, 2, 0, 3, 0, 0]) sa = subsequence_search(query, series) best = sa.best_match(minlength=2) ``` -------------------------------- ### Get Path for Best Match (Python) Source: https://github.com/wannesm/dtaidistance/blob/master/docs/modules/subsequence/subsequencealignment.md Retrieves the indices in the series that form the best path for a match at a specific index in the matching function. This helps visualize the alignment. ```python from dtaidistance.subsequence import subsequence_search import numpy as np query = np.array([1., 2, 0]) series = np.array([1., 0, 1, 2, 1, 0, 2, 0, 3, 0, 0]) sa = subsequence_search(query, series) mf = sa.matching_function() path = sa.matching_function_bestpath(idx=np.argmax(mf)) ``` -------------------------------- ### Subsequence Search with dtaidistance (Python) Source: https://github.com/wannesm/dtaidistance/blob/master/docs/modules/subsequence/subsequencealignment.md Demonstrates how to perform a subsequence search using the dtaidistance library. It initializes a SubsequenceAlignment object with a query and series, then retrieves the matching function and finds the best matches. ```python import numpy as np from dtaidistance.subsequence import subsequence_search query = np.array([1., 2, 0]) series = np.array([1., 0, 1, 2, 1, 0, 2, 0, 3, 0, 0]) sa = subsequence_search(query, series) mf = sa.matching_function() sa.kbest_matches(k=2) ``` -------------------------------- ### estimate_settings_from_mean Source: https://github.com/wannesm/dtaidistance/blob/master/docs/modules/subsequence/localconcurrences.md Estimates settings based on the mean of the time series. ```APIDOC ## POST /estimate_settings_from_mean ### Description Estimates settings based on the mean of the time series. ### Method POST ### Endpoint /estimate_settings_from_mean ### Parameters #### Request Body - **series** (array) - Required - The first time series. - **series2** (array) - Optional - The second time series. - **tau_mean** (float) - Optional - Threshold for mean differences (default: 0.33). ### Request Example { "series": [1.0, 2.0, 3.0, 4.0, 5.0] } ### Response #### Success Response (200) - **settings** (object) - An object containing estimated settings. #### Response Example { "settings": { "tau": 0.4, "delta": -0.15 } } ``` -------------------------------- ### Get Amplitude Variations of a Path Source: https://github.com/wannesm/dtaidistance/blob/master/docs/modules/explain/explainpair.md Computes the amplitude variations along a path. Similar to `get_bounds`, this can be based on the original path or its linear segments, offering different perspectives on path dynamics. ```python def get_variations(on_segments=False): """ Compute the amplitude variations * **Parameters:** **on_segments** – Compute the variations based on the linear segments instead of the original optimal path * **Returns:** """ pass ``` -------------------------------- ### LocalConcurrences Methods Source: https://github.com/wannesm/dtaidistance/blob/master/docs/modules/subsequence/localconcurrences.md Documentation for key methods within the LocalConcurrences class, including alignment, best match retrieval, and plotting. ```APIDOC ## LocalConcurrences Methods ### `align()` #### Description Performs alignment of the time series based on local concurrences. #### Method `align()` #### Endpoint N/A (Python Method) #### Parameters None ### `align_fast()` #### Description Performs a faster alignment of the time series. #### Method `align_fast()` #### Endpoint N/A (Python Method) #### Parameters None ### `best_match()` #### Description Returns the single best local concurrences match between the time series. #### Method `best_match()` #### Endpoint N/A (Python Method) #### Parameters None ### `best_matches(k=None, minlen=2, buffer=0, restart=True, detectknee=None, bufferedargmax=None)` #### Description Yields the next best LocalConcurrent match. Stops at k matches or when a knee is detected. #### Method `best_matches(k=None, minlen=2, buffer=0, restart=True, detectknee=None, bufferedargmax=None)` #### Endpoint N/A (Python Method) #### Parameters * **k** (int) - Optional - Number of matches to yield. Use None for all matches. * **minlen** (int) - Optional - Consider only matches of length longer than minlen. Default: 2. * **buffer** (int) - Optional - Matches cannot be closer than buffer to each other. Default: 0. * **restart** (bool) - Optional - Start searching from start, ignore previous calls to kbest_matches. Default: True. * **detectknee** (dict) - Optional - Arguments for util.DetectKnee. * **bufferedargmax** (dict) - Optional - Arguments for util.BufferedArgMax. #### Returns Yields an LCMatch object. ### `best_matches_knee(alpha=0.3, thr_value=0, **kwargs)` #### Description Finds best matches using knee detection. #### Method `best_matches_knee(alpha=0.3, thr_value=0, **kwargs)` #### Endpoint N/A (Python Method) #### Parameters * **alpha** (float) - Optional - Knee detection parameter. Default: 0.3. * **thr_value** (float) - Optional - Threshold value for knee detection. Default: 0. * **kwargs** - Additional keyword arguments. ### `best_matches_store(k=1, minlen=2, buffer=0, restart=True, detectknee=None, keep=False, matches=None, tqdm=None, bufferedargmax=None)` #### Description Gets the best matches and stores them in an LCMatches object. #### Method `best_matches_store(k=1, minlen=2, buffer=0, restart=True, detectknee=None, keep=False, matches=None, tqdm=None, bufferedargmax=None)` #### Endpoint N/A (Python Method) #### Parameters * **k** (int) - Optional - Number of matches to store. Default: 1. * **minlen** (int) - Optional - Consider only matches of length longer than minlen. Default: 2. * **buffer** (int) - Optional - Matches cannot be closer than buffer to each other. Default: 0. * **restart** (bool) - Optional - Start searching from start, ignore previous calls to kbest_matches. Default: True. * **detectknee** (dict) - Optional - Arguments for util.DetectKnee. * **keep** (bool) - Optional - Keep mask to search incrementally for multiple calls of kbest_matches. Default: False. * **matches** (LCMatches) - Optional - Existing LCMatches object to append to. * **tqdm** (object) - Optional - Progress bar object (e.g., from tqdm). * **bufferedargmax** (dict) - Optional - Arguments for util.BufferedArgMax. #### Returns An LCMatches object containing the stored matches. ### `distance(do_sqrt=True)` (for LCMatch) #### Description Calculates the distance for a LocalConcurrences match. #### Method `distance(do_sqrt=True)` #### Endpoint N/A (Python Method) #### Parameters * **do_sqrt** (bool) - Optional - Whether to return the square root of the distance. Default: True. ### `plot(begin=None, end=None, showlegend=False, showpaths=True, showboundaries=True, makepositive=True, showpathidx=False, figure=None, **kwargs)` #### Description Plots the local concurrences, including paths and boundaries. #### Method `plot(begin=None, end=None, showlegend=False, showpaths=True, showboundaries=True, makepositive=True, showpathidx=False, figure=None, **kwargs)` #### Endpoint N/A (Python Method) #### Parameters * **begin** (slice) - Optional - Slice with the start index of time series. * **end** (slice) - Optional - Slice with the end index of time series. * **showlegend** (bool) - Optional - Whether to show the legend. Default: False. * **showpaths** (bool) - Optional - Whether to show the paths. Default: True. * **showboundaries** (bool) - Optional - Whether to show the boundaries. Default: True. * **makepositive** (bool) - Optional - Whether to make the plot positive. Default: True. * **showpathidx** (bool) - Optional - Whether to show path indices. Default: False. * **figure** (matplotlib.figure.Figure) - Optional - A figure object to plot on. Default: None. * **kwargs** - Additional keyword arguments for plotting. #### Returns Returns a matplotlib figure object. ``` -------------------------------- ### Get K Best Matches from SubsequenceAlignment (Python) Source: https://github.com/wannesm/dtaidistance/blob/master/docs/modules/subsequence/subsequencealignment.md Yields the next best k matches from a SubsequenceAlignment object. Users can specify the number of matches (k), overlap, and minimum/maximum lengths. ```python from dtaidistance.subsequence import subsequence_search import numpy as np query = np.array([1., 2, 0]) series = np.array([1., 0, 1, 2, 1, 0, 2, 0, 3, 0, 0]) sa = subsequence_search(query, series) for match in sa.kbest_matches(k=3, overlap=0.1, minlength=2): print(match) ``` -------------------------------- ### dtaidistance.subsequence.localconcurrences.LoCoSettings Class Source: https://github.com/wannesm/dtaidistance/blob/master/docs/modules/subsequence/localconcurrences.md Configuration settings for LocalConcurrences. ```APIDOC ## dtaidistance.subsequence.localconcurrences.LoCoSettings Class ### Description Configuration settings for LocalConcurrences, allowing customization of various parameters. ### Method Class Definition ### Endpoint N/A (Python Class) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **only_triu** (bool) - Optional - Only consider upper triangular matrix in warping paths. Default: False. * **penalty** (float) - Optional - Base penalty per missing step in the joint path. Default: None. * **psi** (float) - Optional - Threshold parameter. Default: None. * **window** (int) - Optional - Window size for DTW. Default: None. * **gamma** (float) - Optional - Affinity transformation parameter. Default: 1. * **tau** (float) - Optional - Threshold parameter. Default: 0. * **delta** (float) - Optional - Penalty parameter. Default: 0. * **delta_factor** (float) - Optional - Penalty factor parameter. Default: 1. * **use_c** (bool) - Optional - Use C implementation for performance. Default: False. * **step_type** (str) - Optional - Type of steps to use. Default: None. ### Request Example ```python from dtaidistance.subsequence.localconcurrences import LoCoSettings settings = LoCoSettings(only_triu=True, penalty=0.5, window=10) ``` ### Response #### Success Response (200) N/A (Python Class) #### Response Example N/A (Python Class) ``` -------------------------------- ### Get DTW Distance and Warping Paths Source: https://github.com/wannesm/dtaidistance/blob/master/README.md Computes both the DTW distance and the full matrix representing all possible warping paths between two time series. This allows for detailed analysis of the alignment. ```python from dtaidistance import dtw s1 = [0, 0, 1, 2, 1, 0, 1, 0, 0] s2 = [0, 1, 2, 0, 0, 0, 0, 0, 0] distance, paths = dtw.warping_paths(s1, s2) print(distance) print(paths) ``` -------------------------------- ### Get Best Matches using Range Factor (Python) Source: https://github.com/wannesm/dtaidistance/blob/master/docs/modules/subsequence/subsequencealignment.md Retrieves best matches where the difference between the best match and subsequent matches is within a specified range factor. This helps in finding matches with similar quality. ```python from dtaidistance.subsequence import subsequence_search import numpy as np query = np.array([1., 2, 0]) series = np.array([1., 0, 1, 2, 1, 0, 2, 0, 3, 0, 0]) sa = subsequence_search(query, series) for match in sa.best_matches_rangefactor(max_rangefactor=2, overlap=0, minlength=2): print(match) ``` -------------------------------- ### estimate_settings_from_ssm Source: https://github.com/wannesm/dtaidistance/blob/master/docs/modules/subsequence/localconcurrences.md Estimates tau from the self similarity matrix. Call before calling the align method. Based on Fundamentals of Music Processing. ```APIDOC ## POST /estimate_settings_from_ssm ### Description Estimate tau from the self similarity matrix. Call before calling the align method. Based on Fundamentals of Music Processing. ### Method POST ### Endpoint /estimate_settings_from_ssm ### Parameters #### Request Body - **rho** (array) - Required - The self similarity matrix. - **set_penalty** (boolean) - Optional - Whether to set the penalty. - **set_gamma** (boolean) - Optional - Whether to set the gamma parameter. - **verbose** (boolean) - Optional - Whether to output verbose information. ### Request Example { "rho": [[1.0, 0.9], [0.9, 1.0]], "set_penalty": true } ### Response #### Success Response (200) - **settings** (object) - An object containing estimated settings. #### Response Example { "settings": { "tau": 0.2, "penalty": 0.1 } } ``` -------------------------------- ### Get Best Matches using Knee Detection (Python) Source: https://github.com/wannesm/dtaidistance/blob/master/docs/modules/subsequence/subsequencealignment.md Finds the best matches using a knee detection algorithm based on an exponentially moving average. This method is useful for identifying a series of good matches. ```python from dtaidistance.subsequence import subsequence_search import numpy as np query = np.array([1., 2, 0]) series = np.array([1., 0, 1, 2, 1, 0, 2, 0, 3, 0, 0]) sa = subsequence_search(query, series) for match in sa.best_matches_knee(alpha=0.3, overlap=0, minlength=2): print(match) ``` -------------------------------- ### KMeans Class Initialization for Time Series Clustering Source: https://github.com/wannesm/dtaidistance/blob/master/docs/modules/clustering/kmeans.md Initializes the KMeans class for time series clustering using Dynamic Barycenter Averaging. Allows configuration of parameters like the number of clusters (k), maximum iterations, convergence threshold, and initialization strategies (K-medoids or K-means++). ```python from dtaidistance.clustering.kmeans import KMeans # Example initialization kmeans_model = KMeans( k=5, max_it=20, max_dba_it=15, thr=0.001, drop_stddev=None, nb_prob_samples=None, dists_options=None, show_progress=True, initialize_with_kmedoids=False, initialize_with_kmeanspp=True, initialize_sample_size=None ) ``` -------------------------------- ### Get Warping Amount - dtaidistance.dtw Source: https://github.com/wannesm/dtaidistance/blob/master/docs/modules/dtw.md Returns the number of compressions and expansions performed to obtain the best warping path. This can serve as a metric for the degree of warping between two time series. It takes the computed path as input. ```python from dtaidistance.dtw import warping_amount # Assuming 'path' is a pre-computed warping path # path = [(0, 0), (1, 1), ...] # warping_val = warping_amount(path) ``` -------------------------------- ### estimate_settings_from_std Source: https://github.com/wannesm/dtaidistance/blob/master/docs/modules/subsequence/localconcurrences.md Estimates delta, tau and delta_factor from series, tau_std and gamma. ```APIDOC ## POST /estimate_settings_from_std ### Description Estimate delta, tau and delta_factor from series, tau_std and gamma. ### Method POST ### Endpoint /estimate_settings_from_std ### Parameters #### Request Body - **series** (array) - Required - The first time series. - **series2** (array) - Optional - The second time series. - **tau_std** (float) - Optional - Set tau to differences larger than tau_std time standard deviation of the given series (default is 0.33, or reject differences that are larger than the deviation wrt to the mean of 75% of the values in the series, assuming a normal distribution). ### Request Example { "series": [1.0, 2.0, 3.0, 4.0, 5.0], "tau_std": 0.5 } ### Response #### Success Response (200) - **settings** (object) - An object containing estimated settings. #### Response Example { "settings": { "tau": 0.4, "delta": -0.1, "delta_factor": 0.8 } } ``` -------------------------------- ### Configure DTW Computation Settings (Python) Source: https://context7.com/wannesm/dtaidistance/llms.txt Configures Dynamic Time Warping (DTW) computation parameters using `DTWSettings` objects for reusable configurations. This allows for consistent application of parameters like window size, pruning, distance thresholds, and different inner distance metrics across multiple DTW calculations. It also demonstrates how to check for available C libraries for performance enhancements. ```python from dtaidistance import dtw from dtaidistance.innerdistance import default, euclidean import numpy as np # Create a settings object settings = dtw.DTWSettings( window=5, # Sakoe-Chiba band width use_pruning=True, # Enable Euclidean pruning max_dist=10.0, # Early stopping threshold max_step=2.0, # Max difference between matched points max_length_diff=5, # Max length difference between series penalty=0.1, # Penalty for compression/expansion psi=2, # Relaxation at endpoints inner_dist=default, # Distance metric (squared euclidean) use_ndim=False, # Use multi-dimensional series use_c=True # Use C implementation ) # Use settings for distance calculation s1 = np.array([0, 0, 1, 2, 1, 0, 1, 0, 0], dtype=np.double) s2 = np.array([0.0, 1, 2, 0, 0, 0, 0, 0, 0]) # Apply settings via dictionary d = dtw.distance(s1, s2, **settings.__dict__) print(f"Distance with settings: {d}") # Different inner distance metrics d_euclidean = dtw.distance(s1, s2, inner_dist='euclidean') d_squared = dtw.distance(s1, s2, inner_dist='squared euclidean') print(f"Euclidean: {d_euclidean}, Squared: {d_squared}") # Psi relaxation for cyclical patterns # Psi as single value (applied to all endpoints) d_psi = dtw.distance(s1, s2, psi=2) # Psi as 4-tuple: (begin_s1, end_s1, begin_s2, end_s2) d_psi_asymmetric = dtw.distance(s1, s2, psi=(1, 2, 1, 3)) print(f"Symmetric psi: {d_psi}, Asymmetric psi: {d_psi_asymmetric}") # Check available C libraries try: dtw.try_import_c(verbose=True) print("C libraries available") except Exception as e: print(f"C libraries not available: {e}") ``` -------------------------------- ### Find Max Deviation from Line in Path Segment Source: https://github.com/wannesm/dtaidistance/blob/master/docs/modules/explain/explainpair.md Determines the point in a path segment that is furthest from the straight line connecting the segment's start and end points. This helps in identifying points that deviate most significantly from a linear approximation. ```python def max_deviation_from_line(points, i0, i1): """ Find the point in the path that is the furthest away from the line between the two indices. """ pass ``` -------------------------------- ### Simplify Path using Ramer-Douglas-Peucker Algorithm Source: https://github.com/wannesm/dtaidistance/blob/master/docs/modules/explain/explainpair.md Applies the Ramer-Douglas-Peucker algorithm to simplify a path within a Self-Similarity Matrix (SSM). Unlike standard RDP, it uses differences in cumulative cost along the path and allows simplification based on upper bounds or DTW distance differences. ```python def rdp_ssm(points): """ Ramer-Douglas-Peucker algorithm to simplify a path in a Self-Similarity Matrix (SSM). Instead of spatial distance to simplifying line, use difference in cumulative cost along path. Simplification is allowed based on an ub_m or difference on top of the current dtw distance. The type of relaxation is dependent on self.approx_type * **Parameters:** **points** – 2D numpy array (points x dimensions) """ pass ``` -------------------------------- ### Get Second Derivative of Points in Cost Matrix Source: https://github.com/wannesm/dtaidistance/blob/master/docs/modules/explain/explainpair.md Calculates the second derivative for points in a cost matrix, focusing on the magnitude of change. It uses centered difference approximations to identify areas with rapid changes, ignoring derivative direction. ```python def get_2ndderiv_in_path(inner_dist, points, h=1): """ Compute the second derivative of each point in the cost matrix (or self-similarity matrix). This method ignores the direction and computes the max absolute value of the derivative in the vertical and horizontal direction. The goal is to select points that have a rapidly changing point in the cost matrix. The centered difference approximations (along the diagonals) method is used. """ pass ``` -------------------------------- ### Get First Derivative of Points in Cost Matrix Source: https://github.com/wannesm/dtaidistance/blob/master/docs/modules/explain/explainpair.md Computes the first derivative for each point within a cost matrix or self-similarity matrix. This is essential for analyzing the rate of change across the matrix, often used in path optimization and analysis. ```python def get_1stderiv_in_path(inner_dist, points, h=1): """ Compute the first derivative of each point in the cost matrix (or self-similarity matrix). """ pass ``` -------------------------------- ### SubsequenceAlignment Class Initialization (Python) Source: https://github.com/wannesm/dtaidistance/blob/master/docs/modules/subsequence/subsequencealignment.md Illustrates the initialization of the SubsequenceAlignment class in Python. This class is used for finding a query subsequence within a longer series using DTW. ```python from dtaidistance.subsequence import SubsequenceAlignment query = [1., 2, 0] series = [1., 0, 1, 2, 1, 0, 2, 0, 3, 0, 0] sa = SubsequenceAlignment(query, series, penalty=0.1, use_c=False) ``` -------------------------------- ### K-means++ Initialization for Cluster Centers Source: https://github.com/wannesm/dtaidistance/blob/master/docs/modules/clustering/kmeans.md The kmeansplusplus_centers function implements the k-means++ algorithm for better initialization of cluster centers. This method selects initial centers probabilistically to improve the overall clustering quality compared to random initialization. ```python from dtaidistance.clustering.kmeans import kmeansplusplus_centers # Assuming 'series_data' is a list or array of time series initial_centers = kmeansplusplus_centers(series_data) print(f"K-means++ initial centers: {initial_centers}") ``` -------------------------------- ### Visualize DSW Explanation with dtaidistance Source: https://github.com/wannesm/dtaidistance/blob/master/docs/usage/explain.md This code snippet demonstrates how to generate and visualize the explanation of Dynamic Subsequence Warping (DSW) between two time series (ya, yb). It utilizes the ExplainPair class and allows for customization of warping parameters like delta_rel and delta_abs, as well as the split strategy. The output is saved to a specified file. ```python from dtaidistance.dtw import ExplainPair, SplitStrategy # Assuming ya and yb are your time series data ya = [1, 2, 3, 4, 5] yb = [1, 2, 4, 5, 6] ep = ExplainPair(ya, yb, delta_rel=2, delta_abs=0.5, split_strategy=SplitStrategy.DERIV_DIST) ep.plot_warping(filename="/path/to/figure.png") ```