### Get Feature Configuration by Domain (Python) Source: https://tsfel.readthedocs.io/en/latest/_sources/descriptions/get_started.rst This code snippet demonstrates how to use the `tsfel.get_features_by_domain()` method to generate JSON configuration files for different feature domains. It shows how to extract all features or features specific to statistical, temporal, spectral, or fractal domains. No external dependencies are required beyond the TSFEL library. ```python import tsfel cfg_file = tsfel.get_features_by_domain() # All features will be extracted. cgf_file = tsfel.get_features_by_domain("statistical") # All statistical domain features will be extracted cgf_file = tsfel.get_features_by_domain("temporal") # All temporal domain features will be extracted cgf_file = tsfel.get_features_by_domain("spectral") # All spectral domain features will be extracted cgf_file = tsfel.get_features_by_domain("fractal") # All fractal domain features will be extracted ``` -------------------------------- ### Install TSFEL using pip Source: https://tsfel.readthedocs.io/en/latest/_sources/index.rst This command installs the TSFEL package using pip, the standard package installer for Python. Ensure you have Python and pip installed on your system. ```bash pip install tsfel ``` -------------------------------- ### Get Features by Domain Source: https://tsfel.readthedocs.io/en/latest/_modules/tsfel/feature_extraction/features_settings Retrieves a dictionary of feature settings filtered by specified domains. Supports individual domains, a list of domains, or 'all' domains. If no domain is specified, it defaults to 'statistical', 'temporal', and 'spectral'. ```python def get_features_by_domain(domain=None, json_path=None): """Creates a dictionary with the features settings by domain. Parameters ---------- domain : str, list of str, or None, default=None Specifies which feature domains to include in the dictionary. - 'statistical', 'temporal', 'spectral', 'fractal': Includes the corresponding feature domain. - 'all': Includes all available feature domains. - list of str: A combination of the above strings, e.g., ['statistical', 'temporal']. - None: By default, includes the 'statistical', 'temporal', and 'spectral' domains. json_path : string Directory of json file. Default: package features.json directory Returns ------- Dict Dictionary with the features settings """ valid_domains = ["statistical", "temporal", "spectral", "fractal", "all"] if json_path is None: json_path = tsfel.__path__[0] + "/feature_extraction/features.json" if isinstance(domain, str) and domain not in valid_domains: raise ValueError( f"Domain {domain} is invalid. Please choose from `statistical`, `temporal`, `spectral`, `fractal` or `all`.", ) elif isinstance(domain, list) and not np.all([d in valid_domains for d in domain]): raise ValueError( "At least one invalid domain was provided. Please choose from `statistical`, `temporal`, `spectral`, `fractal` or `all`.", ) elif not isinstance(domain, (str, list)) and domain is not None: raise TypeError( "The 'domain' argument must be a string or a list of strings.", ) dict_features = load_json(json_path) if domain is None: return dict_features else: if domain == "all": domain = ["statistical", "temporal", "spectral", "fractal"] if isinstance(domain, str): domain = [domain] d_feat = {} for d in domain: if d == "fractal": for k in dict_features[d]: dict_features[d][k]["use"] = "yes" d_feat.update({d: dict_features[d]}) return d_feat ``` -------------------------------- ### Get Features by Tag Source: https://tsfel.readthedocs.io/en/latest/_modules/tsfel/feature_extraction/features_settings Retrieves a dictionary of feature settings filtered by a specific tag (e.g., 'audio', 'inertial'). If no tag is provided, all available features are returned. It handles features associated with multiple tags. ```python def get_features_by_tag(tag=None, json_path=None): """Creates a dictionary with the features settings by tag. Parameters ---------- tag : string Available tags: "audio"; "inertial", "ecg"; "eeg"; "emg". If tag equals None then, all available features are returned. json_path : string Directory of json file. Default: package features.json directory Returns ------- Dict Dictionary with the features settings """ if json_path is None: json_path = tsfel.__path__[0] + "/feature_extraction/features.json" if tag not in ["audio", "inertial", "ecg", "eeg", "emg", None]: raise SystemExit( "No valid tag. Choose: audio, inertial, ecg, eeg, emg or None.", ) features_tag = {} dict_features = load_json(json_path) if tag is None: return dict_features else: for domain in dict_features: features_tag[domain] = {} for feat in dict_features[domain]: if dict_features[domain][feat]["use"] == "no": continue # Check if tag is defined try: js_tag = dict_features[domain][feat]["tag"] if isinstance(js_tag, list): if any(tag in js_t for js_t in js_tag): features_tag[domain].update( {feat: dict_features[domain][feat]}, ) elif js_tag == tag: features_tag[domain].update({feat: dict_features[domain][feat]}) except KeyError: continue # To remove empty dicts return {d: features_tag[d] for d in list(features_tag.keys()) if bool(features_tag[d])} ``` -------------------------------- ### Extract Features with Window Splitting Source: https://tsfel.readthedocs.io/en/latest/_sources/descriptions/get_started.rst Performs time series feature extraction with window splitting using TSFEL. This function divides the input data into equal-length windows before extracting features, allowing for analysis of time-varying patterns. The configuration is obtained using tsfel.get_features_by_domain(). ```python cfg = tsfel.get_features_by_domain() # Extracts the temporal, statistical and spectral feature sets. X = tsfel.time_series_feature_extractor(cfg, data, fs=100, window_size=100) # Performs window splitting before feature extraction X.shape # (10, 165) ``` -------------------------------- ### Load BiopluX ECG Dataset with TSFEL Source: https://tsfel.readthedocs.io/en/latest/_sources/descriptions/get_started.rst Loads a single-lead ECG time series dataset using tsfel.datasets.load_biopluxecg(). This function retrieves a time series recorded at 100 Hz for 10 seconds, suitable for initial testing and demonstration. ```python import tsfel import pandas as pd data = tsfel.datasets.load_biopluxecg() # A single-lead ECG collected during 10 s at 100 Hz. ``` -------------------------------- ### Extract Features from Dataset Files Source: https://tsfel.readthedocs.io/en/latest/_sources/descriptions/get_started.rst Extracts time series features from multiple files within a dataset directory using TSFEL. This function handles delimited files, synchronizes time series data through interpolation, and saves the extracted features to a specified output directory. It allows for flexible searching of files based on criteria and configuration of time units and resampling rates. ```python import tsfel main_directory = '/my_root_dataset_directory/' # The root directory of the dataset output_directory = '/my_output_feature_directory/' # The resulted file from the feature extraction will be saved on this directory data = tsfel.dataset_features_extractor( main_directory, tsfel.get_features_by_domain(), search_criteria="Accelerometer.txt", time_unit=1e-9, resample_rate=100, window_size=250, output_directory=output_directory ) ``` -------------------------------- ### Extract Features from Dataset Files Source: https://tsfel.readthedocs.io/en/latest/descriptions/get_started Extracts features from time series data stored in multiple files within a dataset directory using TSFEL. It crawls a specified directory, searches for files matching a pattern, and extracts features while handling potential time synchronization issues through resampling. Timestamps and resampling rate are configurable. ```python import tsfel main_directory = '/my_root_dataset_directory/' # The root directory of the dataset output_directory = '/my_output_feature_directory/' # The resulted file from the feature extraction will be saved on this directory data = tsfel.dataset_features_extractor( main_directory, tsfel.get_features_by_domain(), search_criteria="Accelerometer.txt", time_unit=1e-9, resample_rate=100, window_size=250, output_directory=output_directory ) ``` -------------------------------- ### tsfel.feature_extraction.features_settings Module Source: https://tsfel.readthedocs.io/en/latest/descriptions/modules/tsfel This module provides utilities for managing feature settings, including retrieving features by domain or tag, and loading feature configurations from JSON. ```APIDOC ## tsfel.feature_extraction.features_settings ### Description Utilities for managing feature extraction settings and configurations. ### Functions - `get_features_by_domain()`: Retrieves features based on their domain (e.g., time, frequency). - `get_features_by_tag()`: Retrieves features based on associated tags. - `get_number_features()`: Returns the total number of available features. - `load_json()`: Loads feature settings from a JSON file. ``` -------------------------------- ### tsfel.utils.progress_bar.progress_bar_notebook Source: https://tsfel.readthedocs.io/en/latest/descriptions/modules/tsfel.utils Generates a progress bar suitable for Jupyter notebooks. ```APIDOC ## tsfel.utils.progress_bar.progress_bar_notebook ### Description Progress bar for notebooks. ### Method Not specified (likely a Python function call) ### Endpoint Not applicable (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **iteration** (int) - Required - current iteration * **total** (int) - Optional, defaults to 100 - total iterations ### Request Example ```python # Example usage (assuming functions are imported) # for i in range(100): # progress_bar_notebook(i + 1, 100) ``` ### Response #### Success Response * **progress_bar** (Progress bar for notebooks) - The generated progress bar object. #### Response Example None (returns an object, not a simple JSON) ``` -------------------------------- ### Extract All Features from Time Series Data Source: https://tsfel.readthedocs.io/en/latest/_sources/descriptions/get_started.rst Extracts all available temporal, statistical, and spectral features from a given time series data using TSFEL. It utilizes a configuration obtained from tsfel.get_features_by_domain() and processes the input data with a specified sampling frequency (fs). ```python cfg = tsfel.get_features_by_domain() # Extracts the temporal, statistical and spectral feature sets. X = tsfel.time_series_feature_extractor(cfg, data, fs=100) X.shape # (1, 165) ``` -------------------------------- ### Compute Probability Density Function using KDE (Python) Source: https://tsfel.readthedocs.io/en/latest/_modules/tsfel/feature_extraction/features_utils Calculates the probability density function (PDF) of input features using a Gaussian Kernel Density Estimate (KDE). It utilizes the `create_xx` function for range calculation and `scipy.stats.gaussian_kde` for the estimation. Handles cases with constant feature values by adding small noise. ```python import numpy as np import scipy.stats def kde(features): """Computes the probability density function of the input signal using a Gaussian KDE (Kernel Density Estimate) Parameters ---------- features : nd-array Input from which probability density function is computed Returns ------- nd-array probability density values """ features_ = np.copy(features) xx = create_xx(features_) if min(features_) == max(features_): noise = np.random.randn(len(features_)) * 0.0001 features_ = np.copy(features_ + noise) kernel = scipy.stats.gaussian_kde(features_, bw_method="silverman") return np.array(kernel(xx) / np.sum(kernel(xx))) ``` -------------------------------- ### Notebook Progress Bar Functionality in Python Source: https://tsfel.readthedocs.io/en/latest/_modules/tsfel/utils/progress_bar Generates an HTML progress bar suitable for Jupyter notebooks. It takes the current and total iterations to calculate the completion percentage and formats it within HTML tags. ```python from IPython.display import HTML def progress_bar_notebook(iteration, total=100): """Progress bar for notebooks. Parameters ---------- iteration: int current iteration total: int total iterations Returns ------- Progress bar for notebooks """ result = int((iteration / total) * 100) return HTML( """

Progress: {result}% Complete

{value} """.format( value=iteration, max_value=total, result=result, ), ) ``` -------------------------------- ### tsfel.utils.progress_bar Module Source: https://tsfel.readthedocs.io/en/latest/descriptions/modules/tsfel This module provides utilities for displaying progress bars in different environments (notebook, terminal) during long-running computations. ```APIDOC ## tsfel.utils.progress_bar ### Description Utilities for displaying progress bars in various environments. ### Functions - `display_progress_bar()`: Generic function to display a progress bar. - `progress_bar_notebook()`: Displays a progress bar suitable for Jupyter notebooks. - `progress_bar_terminal()`: Displays a progress bar suitable for terminal applications. ``` -------------------------------- ### Load JSON Configuration Source: https://tsfel.readthedocs.io/en/latest/_modules/tsfel/feature_extraction/features_settings Loads feature configuration settings from a specified JSON file path. This function is useful for loading custom feature configurations. ```python import json import numpy as np import tsfel from tsfel.feature_extraction.features_utils import safe_eval_string def load_json(json_path): """A convenient method that wraps the built-in `json.load`. This method might be handy to load customized feature configuration files. Parameters ---------- json_path : file-like object, string, or pathlib.Path. The json file to read. Returns ------- dict Data stored in the file. """ with open(json_path) as f: out = json.load(f) return out ``` -------------------------------- ### Get Signal Templates - tsfel Source: https://tsfel.readthedocs.io/en/latest/descriptions/modules/tsfel.feature_extraction A helper function for sample entropy calculation that divides a signal into template vectors of a specified length (m). It's used to prepare the signal for further analysis. ```python tsfel.feature_extraction.features_utils.get_templates(signal, m=3) ``` -------------------------------- ### Split Signal into Windows (Python) Source: https://tsfel.readthedocs.io/en/latest/descriptions/modules/tsfel.utils Splits an input signal (ndarray or pandas DataFrame) into multiple windows. Users can specify the window size and the overlap percentage between consecutive windows. The overlap is defined as a float between 0 and 1 (exclusive). ```python import numpy as np import pandas as pd from typing import List def signal_window_splitter(_signal_ : np.ndarray | pd.DataFrame, _window_size_ : int, _overlap : float = 0) -> List: """ Splits the signal into windows. Parameters: * **signal** (_nd-array_ _or_ _pandas DataFrame_) – input signal * **window_size** (_int_) – number of points of window size * **overlap** (_float_) – percentage of overlap, value between 0 and 1 (exclusive) Default: 0 Returns: list of signal windows Return type: list """ # Implementation details would go here pass ``` -------------------------------- ### TSFEL Feature List Source: https://tsfel.readthedocs.io/en/latest/descriptions/feature_list This section provides an overview of the signal processing features available in the TSFEL library. Each feature is listed with a brief description of its computation. ```APIDOC ## TSFEL Features Overview ### Description This document lists and describes the signal processing features available in the TSFEL library. Each feature is presented with its function signature and a brief explanation of what it computes. ### Features - **`abs_energy`(signal)**: Computes the absolute energy of the signal. - **`auc`(signal, fs)**: Computes the area under the curve of the signal computed with the trapezoid rule. - **`autocorr`(signal)**: Calculates the first 1/e crossing of the autocorrelation function (ACF). - **`average_power`(signal, fs)**: Computes the average power of the signal. - **`calc_centroid`(signal, fs)**: Computes the centroid along the time axis. - **`calc_max`(signal)**: Computes the maximum value of the signal. - **`calc_mean`(signal)**: Computes the mean value of the signal. - **`calc_median`(signal)**: Computes the median of the signal. - **`calc_min`(signal)**: Computes the minimum value of the signal. - **`calc_std`(signal)**: Computes the standard deviation (std) of the signal. - **`calc_var`(signal)**: Computes the variance of the signal. - **`dfa`(signal)**: Computes the Detrended Fluctuation Analysis (DFA) of the signal. - **`distance`(signal)**: Computes the signal traveled distance. - **`ecdf`(signal[, d])**: Computes the values of ECDF (empirical cumulative distribution function) along the time axis. - **`ecdf_percentile`(signal[, percentile])**: Computes the percentile value of the ECDF. - **`ecdf_percentile_count`(signal[, percentile])**: Computes the cumulative sum of samples that are less than the percentile. - **`ecdf_slope`(signal[, p_init, p_end])**: Computes the slope of the ECDF between two percentiles. - **`entropy`(signal[, prob])**: Computes the entropy of the signal using the Shannon Entropy. - **`fundamental_frequency`(signal, fs)**: Computes the fundamental frequency of the signal. - **`higuchi_fractal_dimension`(signal)**: Computes the fractal dimension of a signal using Higuchi's method (HFD). - **`hist_mode`(signal[, nbins])**: Computes the mode of a histogram using a given number of (linearly spaced) bins. - **`human_range_energy`(signal, fs)**: Computes the human range energy ratio. - **`hurst_exponent`(signal)**: Computes the Hurst exponent of the signal through the Rescaled range (R/S) analysis. - **`interq_range`(signal)**: Computes the interquartile range of the signal. - **`kurtosis`(signal)**: Computes the kurtosis of the signal. - **`lempel_ziv`(signal[, threshold])**: Computes the Lempel-Ziv's (LZ) complexity index, normalized by the signal's length. - **`lpcc`(signal[, n_coeff])**: Computes the linear prediction cepstral coefficients. - **`max_frequency`(signal, fs)**: Computes the maximum frequency of the signal. - **`max_power_spectrum`(signal, fs)**: Computes the maximum power spectrum density of the signal. - **`maximum_fractal_length`(signal)**: Computes the Maximum Fractal Length (MFL) of the signal, which is the average length at the smallest scale, measured from the logarithmic plot determining FD. - **`mean_abs_deviation`(signal)**: Computes the mean absolute deviation of the signal. - **`mean_abs_diff`(signal)**: Computes the mean absolute differences of the signal. - **`mean_diff`(signal)**: Computes the mean of differences of the signal. - **`median_abs_deviation`(signal)**: Computes the median absolute deviation of the signal. - **`median_abs_diff`(signal)**: Computes the median absolute differences of the signal. - **`median_diff`(signal)**: Computes the median of differences of the signal. - **`median_frequency`(signal, fs)**: Computes the median frequency of the signal. - **`mfcc`(signal, fs[, pre_emphasis, nfft, ...])**: Computes the MEL cepstral coefficients. - **`mse`(signal[, m, maxscale, tolerance])**: Computes the Multiscale entropy (MSE) of the signal, which performs entropy analysis over multiple time scales. - **`negative_turning`(signal)**: Computes the number of negative turning points of the signal. - **`neighbourhood_peaks`(signal[, n])**: Computes the number of peaks from a defined neighborhood of the signal. - **`petrosian_fractal_dimension`(signal)**: Computes the Petrosian Fractal Dimension of a signal. - **`pk_pk_distance`(signal)**: Computes the peak-to-peak distance. - **`positive_turning`(signal)**: Computes the number of positive turning points of the signal. - **`power_bandwidth`(signal, fs)**: Computes the power spectrum density bandwidth of the signal. - **`rms`(signal)**: Computes the root mean square of the signal. - **`skewness`(signal)**: Computes the skewness of the signal. - **`slope`(signal)**: Computes the slope of the signal. - **`spectral_centroid`(signal, fs)**: Barycenter of the spectrum. - **`spectral_decrease`(signal, fs)**: Represents the amount of decrease in the spectra amplitude. - **`spectral_distance`(signal, fs)**: Computes the signal spectral distance. - **`spectral_entropy`(signal, fs)**: Computes the spectral entropy of the signal based on Fourier transform. - **`spectral_kurtosis`(signal, fs)**: Measures the flatness of a distribution around its mean value. - **`spectral_positive_turning`(signal, fs)**: Computes the number of positive turning points of the FFT magnitude signal. - **`spectral_roll_off`(signal, fs)**: Computes the spectral roll-off of the signal. ``` -------------------------------- ### tsfel.utils.add_personal_features.add_feature_json Source: https://tsfel.readthedocs.io/en/latest/descriptions/modules/tsfel.utils Adds new features to the features.json file. ```APIDOC ## tsfel.utils.add_personal_features.add_feature_json ### Description Adds new feature to features.json. ### Method Not specified (likely a Python function call) ### Endpoint Not applicable (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **features_path** (string) - Required - Personal Python module directory containing new features implementation. * **json_path** (string) - Required - Personal .json file directory containing existing features from TSFEL. New customised features will be added to file in this directory. ### Request Example ```python # Example usage (assuming functions are imported) # add_feature_json('/path/to/personal/features', '/path/to/tsfel/features.json') ``` ### Response #### Success Response None explicitly mentioned, likely modifies a file. #### Response Example None ``` -------------------------------- ### load_json Source: https://tsfel.readthedocs.io/en/latest/_modules/tsfel/feature_extraction/features_settings Loads feature configurations from a specified JSON file path. This function is useful for loading custom feature settings. ```APIDOC ## GET /load_json ### Description Loads feature configurations from a specified JSON file path. This function is useful for loading custom feature settings. ### Method GET ### Endpoint /load_json ### Parameters #### Query Parameters - **json_path** (string) - Required - The path to the JSON file to load. ### Response #### Success Response (200) - **dict** (dict) - A dictionary containing the data loaded from the JSON file. #### Response Example ```json { "example": "{\"statistical\": {\"mean\": {\"use\": \"yes\"}}}" } ``` ``` -------------------------------- ### Load TSFEL Feature Modules Source: https://tsfel.readthedocs.io/en/latest/descriptions/modules/tsfel.feature_extraction Loads feature functions from both the default TSFEL features module and an optional user-defined module. User-defined functions with the same name will override the default ones. ```python def load_combined_feature_modules(_features_path =None_): """Load feature functions from both the TSFEL features module and an optional user module. Parameters: features_path (str or None): Path to user-defined Python feature module (.py). If None, only the default TSFEL features module is used. Returns: dict: A dictionary mapping function names to function objects from both sources. User-defined functions override TSFEL ones with the same name. """ pass ``` -------------------------------- ### tsfel.utils.progress_bar.display_progress_bar Source: https://tsfel.readthedocs.io/en/latest/descriptions/modules/tsfel.utils Displays a progress bar according to the Python interface. ```APIDOC ## tsfel.utils.progress_bar.display_progress_bar ### Description Displays progress bar according to python interface. ### Method Not specified (likely a Python function call) ### Endpoint Not applicable (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **iteration** (int) - Required - current iteration * **total** (int) - Required - total iterations * **out** (progress bar notebook output) - Required - Output stream for the progress bar ### Request Example ```python # Example usage (assuming functions are imported) # for i in range(100): # display_progress_bar(i + 1, 100, out=sys.stdout) ``` ### Response #### Success Response None explicitly mentioned, modifies output stream. #### Response Example None ``` -------------------------------- ### Implement a Custom Time Series Feature in Python Source: https://tsfel.readthedocs.io/en/latest/descriptions/personal Demonstrates how to define a new time series feature using Python. It includes setting the feature's domain (statistical, temporal, spectral) and defining its parameters and return type. The `@set_domain` decorator is used for domain registration. ```python from tsfel.features_utils import set_domain @set_domain("domain", "temporal") def custom_feature(signal, parameters): """Description of your feature. Parameters ---------- signal: The time series to calculate the feature of. param: Parameters of your feature (optional) Returns ------- float Calculated feature """ # Feature implementation return feature ``` -------------------------------- ### Statistical and Wavelet Features Source: https://tsfel.readthedocs.io/en/latest/descriptions/feature_list Functions for computing statistical measures and wavelet-based features of an audio signal. ```APIDOC ## sum_abs_diff ### Description Computes sum of absolute differences of the signal. ### Method GET (Assumed, as no HTTP method is specified) ### Endpoint /features/sum_abs_diff ### Parameters #### Path Parameters - **signal** (array) - Required - The input audio signal. ### Response #### Success Response (200) - **sum_abs_diff** (float) - The computed sum of absolute differences. ## wavelet_abs_mean ### Description Computes CWT absolute mean value of each wavelet scale. ### Method GET (Assumed, as no HTTP method is specified) ### Endpoint /features/wavelet_abs_mean ### Parameters #### Path Parameters - **signal** (array) - Required - The input audio signal. - **fs** (int) - Required - The sampling frequency of the signal. - **wavelet** (string) - Optional - The type of wavelet to use. - **...** (any) - Optional - Additional parameters for wavelet transform. ### Response #### Success Response (200) - **wavelet_abs_mean** (array) - An array of absolute mean values for each wavelet scale. ## wavelet_energy ### Description Computes CWT energy of each wavelet scale. ### Method GET (Assumed, as no HTTP method is specified) ### Endpoint /features/wavelet_energy ### Parameters #### Path Parameters - **signal** (array) - Required - The input audio signal. - **fs** (int) - Required - The sampling frequency of the signal. - **wavelet** (string) - Optional - The type of wavelet to use. - **max_width** (int) - Optional - The maximum width of the wavelet. ### Response #### Success Response (200) - **wavelet_energy** (array) - An array of energy values for each wavelet scale. ## wavelet_entropy ### Description Computes CWT entropy of the signal. ### Method GET (Assumed, as no HTTP method is specified) ### Endpoint /features/wavelet_entropy ### Parameters #### Path Parameters - **signal** (array) - Required - The input audio signal. - **fs** (int) - Required - The sampling frequency of the signal. - **wavelet** (string) - Optional - The type of wavelet to use. - **max_width** (int) - Optional - The maximum width of the wavelet. ### Response #### Success Response (200) - **wavelet_entropy** (float) - The computed CWT entropy value. ## wavelet_std ### Description Computes CWT std value of each wavelet scale. ### Method GET (Assumed, as no HTTP method is specified) ### Endpoint /features/wavelet_std ### Parameters #### Path Parameters - **signal** (array) - Required - The input audio signal. - **fs** (int) - Required - The sampling frequency of the signal. - **wavelet** (string) - Optional - The type of wavelet to use. - **max_width** (int) - Optional - The maximum width of the wavelet. ### Response #### Success Response (200) - **wavelet_std** (array) - An array of standard deviation values for each wavelet scale. ## wavelet_var ### Description Computes CWT variance value of each wavelet scale. ### Method GET (Assumed, as no HTTP method is specified) ### Endpoint /features/wavelet_var ### Parameters #### Path Parameters - **signal** (array) - Required - The input audio signal. - **fs** (int) - Required - The sampling frequency of the signal. - **wavelet** (string) - Optional - The type of wavelet to use. - **max_width** (int) - Optional - The maximum width of the wavelet. ### Response #### Success Response (200) - **wavelet_var** (array) - An array of variance values for each wavelet scale. ## zero_cross ### Description Computes Zero-crossing rate of the signal. ### Method GET (Assumed, as no HTTP method is specified) ### Endpoint /features/zero_cross ### Parameters #### Path Parameters - **signal** (array) - Required - The input audio signal. ### Response #### Success Response (200) - **zero_cross** (float) - The computed zero-crossing rate. ``` -------------------------------- ### Global Warning Configuration in tsfel.feature_extraction.features Source: https://tsfel.readthedocs.io/en/latest/_modules/tsfel/feature_extraction/features This snippet defines global variables for managing warnings within the tsfel.feature_extraction.features module. It includes a boolean flag `warning_flag` and a descriptive string `warning_msg` that informs users when fractal features cannot be calculated due to insufficient signal length. ```python warning_flag = False warning_msg = ( "The fractal features will not be calculated and will be replaced with 'nan' because the length of the input signal is smaller than the required minimum of " + str(FEATURES_MIN_SIZE) + " data points." ) ``` -------------------------------- ### tsfel.utils.progress_bar.progress_bar_terminal Source: https://tsfel.readthedocs.io/en/latest/descriptions/modules/tsfel.utils Creates a terminal progress bar that can be updated in a loop. ```APIDOC ## tsfel.utils.progress_bar.progress_bar_terminal ### Description Call in a loop to create terminal progress bar. ### Method Not specified (likely a Python function call) ### Endpoint Not applicable (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **iteration** (int) - Required - current iteration * **total** (int) - Required - total iterations * **prefix** (str) - Optional, defaults to '' - prefix string * **suffix** (str) - Optional, defaults to '' - suffix string * **decimals** (int) - Optional, defaults to 0 - positive number of decimals in percent complete * **length** (int) - Optional, defaults to 100 - character length of bar * **fill** (str) - Optional, defaults to '█' - bar fill character * **printend** (str) - Optional, defaults to '\r' - end character (e.g. "\r", " ") ### Request Example ```python # Example usage (assuming functions are imported) # import time # for i in range(100): # progress_bar_terminal(i + 1, 100, prefix='Progress:', suffix='Complete', length=50) # time.sleep(0.1) ``` ### Response #### Success Response None explicitly mentioned, modifies terminal output. #### Response Example None ``` -------------------------------- ### Split Signal into Windows using Python Source: https://tsfel.readthedocs.io/en/latest/_modules/tsfel/utils/signal_processing Splits an input signal (ndarray or pandas DataFrame) into overlapping or non-overlapping windows of a specified size. It handles different overlap percentages and ensures valid window sizes and steps. Returns a list of signal windows. ```python from typing import List, Tuple, Union import numpy as np import pandas as pd from scipy.interpolate import interp1d def signal_window_splitter(signal, window_size, overlap=0): """Splits the signal into windows. Parameters ---------- signal : nd-array or pandas DataFrame input signal window_size : int number of points of window size overlap : float percentage of overlap, value between 0 and 1 (exclusive) Default: 0 Returns ------- list list of signal windows """ if not isinstance(window_size, int): raise SystemExit("window_size must be an integer.") step = int(round(window_size)) if overlap == 0 else int(round(window_size * (1 - overlap))) if step == 0: raise SystemExit( "Invalid overlap. " "Choose a lower overlap value.", ) if len(signal) % window_size == 0 and overlap == 0: return [signal[i : i + window_size] for i in range(0, len(signal), step)] else: return [signal[i : i + window_size] for i in range(0, len(signal) - window_size + 1, step)] ``` -------------------------------- ### Compute Power Bandwidth using Python Source: https://tsfel.readthedocs.io/en/latest/_modules/tsfel/feature_extraction/features Calculates the power spectrum density bandwidth of a signal, defined as the frequency band width where 95% of its power is located. It requires the signal and sampling frequency as input. Dependencies include numpy and `calc_fft`. ```python import numpy as np def calc_fft(signal, fs): # Placeholder for actual FFT calculation n = len(signal) yf = np.fft.fft(signal) xf = np.fft.fftfreq(n, 1 / fs) return xf[:n//2], np.abs(yf[:n//2]) def power_bandwidth(signal, fs): """Computes power spectrum density bandwidth of the signal. It corresponds to the width of the frequency band in which 95% of its power is located. Description in article: Power Spectrum and Bandwidth Ulf Henriksson, 2003 Translated by Mikael Olofsson, 2005 Feature computational cost: 1 Parameters ---------- signal : nd-array """ f, fmag = calc_fft(signal, fs) power_spectrum = fmag**2 total_power = np.sum(power_spectrum) cumulative_power = np.cumsum(power_spectrum) value = 0.95 * total_power # Find the indices where cumulative power exceeds the threshold indices = np.where(cumulative_power >= value)[0] if len(indices) == 0: # Handle cases where 95% power is not reached (e.g., very short signals or specific spectra) return 0.0 # Or np.nan, depending on desired behavior # The bandwidth is the difference between the frequency at the upper bound and the lower bound (assumed 0 for simplicity here) # A more precise calculation might consider the start of the band if needed. # For this definition, it's the frequency where 95% of power is contained. # If we interpret 'width' as the range from 0 to that frequency: bandwidth = f[indices[0]] # If 'width' implies a range, and we need both start and end: # This requires defining the start of the band, which is often implicitly 0 Hz. # If the definition implies the range of frequencies that *contain* 95% of the power, # a more complex calculation might be needed to find the start and end frequencies. # Assuming the definition implies the upper frequency limit for 95% of power: return bandwidth ``` -------------------------------- ### Implement Custom Time Series Feature in Python Source: https://tsfel.readthedocs.io/en/latest/_sources/descriptions/personal.rst Demonstrates how to define a new time series feature using Python. It requires importing `set_domain` from `tsfel.features_utils` and decorating the function with the desired domain. The function accepts the signal and optional parameters, returning the calculated feature. ```python from tsfel.features_utils import set_domain @set_domain("domain", "temporal") def custom_feature(signal, parameters): """Description of your feature. Parameters ---------- signal: The time series to calculate the feature of. param: Parameters of your feature (optional) Returns ------- float Calculated feature """ # Feature implementation return feature ``` -------------------------------- ### Calculate Feature Vector Size (Python) Source: https://tsfel.readthedocs.io/en/latest/_modules/tsfel/feature_extraction/features_settings Calculates the total number of features based on a dictionary of feature configurations. It handles integer feature counts and parameterized feature counts, including those defined by lists. ```python def calculate_feature_vector_size(dict_features): """ Calculate the size of the feature vector. Args: dict_features (dict): A dictionary containing feature configurations. Returns: int: The total number of features. """ number_features = 0 for domain in dict_features: for feat in dict_features[domain]: if dict_features[domain][feat]["use"] == "no": continue n_feat = dict_features[domain][feat]["n_features"] if isinstance(n_feat, int): number_features += n_feat else: n_feat_param = dict_features[domain][feat]["parameters"][n_feat] if isinstance(n_feat_param, int): number_features += n_feat_param else: n_feat_param_list = safe_eval_string(n_feat_param) number_features += len(n_feat_param_list) return number_features ``` -------------------------------- ### Set Domain Decorator for Functions Source: https://tsfel.readthedocs.io/en/latest/_modules/tsfel/feature_extraction/features_utils A decorator factory to attach arbitrary attributes (key-value pairs) to functions. This is useful for metadata or configuration associated with specific functions. ```python import numpy as np import pywt import scipy from sklearn.neighbors import KDTree [docs] def set_domain(key, value): def decorate_func(func): setattr(func, key, value) return func return decorate_func ``` -------------------------------- ### Calculate Sample Entropy with Dynamic Parameters (Python) Source: https://tsfel.readthedocs.io/en/latest/_modules/tsfel/feature_extraction/features Calculates the sample entropy of a signal using coarse-graining. It handles minimum signal size requirements, dynamically sets tolerance and maxscale if not provided, and computes the area under the entropy values using trapezoidal integration. Returns NaN for insufficient signal length. ```python def sample_entropy_with_dynamic_params(signal, m, tolerance=None, maxscale=None): """Calculates the sample entropy of a signal with dynamic parameter adjustment. Args: signal (np.ndarray): The input time series signal. m (int): The embedding dimension for sample entropy calculation. tolerance (float, optional): The tolerance for matching vectors. Defaults to 0.2 * np.std(signal). maxscale (int, optional): The maximum scale for coarse-graining. Defaults to n // (10 + 3). Returns: float: The calculated sample entropy area, or np.nan if the signal is too short. """ n = len(signal) if n < FEATURES_MIN_SIZE: if not warning_flag: warnings.warn(warning_msg, UserWarning) warning_flag = True return np.nan if tolerance is None: tolerance = 0.2 * np.std(signal) if maxscale is None: maxscale = n // (10 + 3) mse_values = np.array([sample_entropy(coarse_graining(signal, i + 1), m, tolerance) for i in np.arange(maxscale)]) mse_values_finite = mse_values[np.isfinite(mse_values)] mse_area = scipy.integrate.trapezoid(mse_values_finite) / len(mse_values_finite) return mse_area ``` -------------------------------- ### Generate Template Vectors for Sample Entropy - Python Source: https://tsfel.readthedocs.io/en/latest/_modules/tsfel/feature_extraction/features_utils A helper function for sample entropy calculation. It divides a signal into template vectors of a specified length (embedding dimension 'm'). This is a prerequisite for calculating sample entropy. ```python import numpy as np def get_templates(signal, m=3): """Helper function for the sample entropy calculation. Divides a signal into templates vectors of length m. Parameters ---------- signal : np.ndarray Input signal. m : int Embedding dimension that defines the length of the template vectors, defaults to 3. Returns ------- np.ndarray Array of template vectors. """ return np.array([signal[i : i + m] for i in np.arange(len(signal) - m + 1)]) ``` -------------------------------- ### Calculate Lempel-Ziv Complexity (Python) Source: https://tsfel.readthedocs.io/en/latest/_modules/tsfel/feature_extraction/features_utils Manually implements the Lempel-Ziv complexity, defined as the number of unique substrings in a binarized signal. It takes a string of binary characters as input and returns the LZ index. ```python def calc_lempel_ziv_complexity(sequence): """Manual implementation of the Lempel-Ziv complexity. It is defined as the number of different substrings encountered as the stream is viewed from begining to the end. Reference: https://github.com/Naereen/Lempel-Ziv_Complexity/blob/master/src/lempel_ziv_complexity.py Parameters ---------- sequence : string Binarised signal, as a string of characters Returns ------- LZ index """ sub_strings = set() ind = 0 inc = 1 while True: if ind + inc > len(sequence): break sub_str = sequence[ind : ind + inc] if sub_str in sub_strings: inc += 1 else: sub_strings.add(sub_str) ind += inc inc = 1 return len(sub_strings) / len(sequence) ``` -------------------------------- ### get_features_by_domain Source: https://tsfel.readthedocs.io/en/latest/_modules/tsfel/feature_extraction/features_settings Retrieves a dictionary of feature settings filtered by specified domains. Supports individual domains, 'all', or a list of domains. ```APIDOC ## GET /get_features_by_domain ### Description Retrieves a dictionary of feature settings filtered by specified domains. Supports individual domains, 'all', or a list of domains. ### Method GET ### Endpoint /get_features_by_domain ### Parameters #### Query Parameters - **domain** (string or list of strings) - Optional - Specifies which feature domains to include. Can be 'statistical', 'temporal', 'spectral', 'fractal', 'all', a list of these, or None (defaults to 'statistical', 'temporal', 'spectral'). - **json_path** (string) - Optional - Directory of the JSON file. Defaults to the package's features.json directory. ### Response #### Success Response (200) - **Dict** (dict) - A dictionary containing the feature settings for the specified domains. #### Response Example ```json { "example": "{\"statistical\": {\"mean\": {\"use\": \"yes\"}}}" } ``` ```