### Install and Import EMGFlow Source: https://github.com/wiiison/emgflow-python-package/blob/main/README.md Instructions for installing the package via pip and importing it into a Python environment. ```bash pip install EMGFlow ``` ```python import EMGFlow ``` -------------------------------- ### Initialize EMGFlow Pipeline and Quick Start Source: https://context7.com/wiiison/emgflow-python-package/llms.txt Demonstrates the end-to-end workflow including workspace initialization, sample data loading, signal cleaning, feature extraction, and dashboard visualization. ```python import EMGFlow as ef path_names = ef.make_paths() ef.make_sample_data(path_names) ef.clean_signals(path_names, sampling_rate=2000, notch_f0=50) features_df = ef.extract_features(path_names, sampling_rate=2000) ef.plot_dashboard(path_names, 'EMG_zyg', sampling_rate=2000) ``` -------------------------------- ### Tailored Preprocessing Setup Source: https://github.com/wiiison/emgflow-python-package/blob/main/papers/JOSS/paper.md Shows how to initialize the workspace and set specific parameters for preprocessing, such as defining sampling rates and notch filter frequencies for AC mains interference removal. ```python import EMGFlow # Setup workspace path_names = EMGFlow.make_paths() EMGFlow.make_sample_data(path_names) # Data sampling rate sampling_rate = 2000 ``` -------------------------------- ### GET /package/citation Source: https://github.com/wiiison/emgflow-python-package/blob/main/README.md Retrieves the citation information for the currently installed version of the EMGFlow package. ```APIDOC ## GET /package/citation ### Description Returns the BibTeX citation string for the specific version of the EMGFlow package currently in use. ### Method GET ### Endpoint EMGFlow.package_citation() ### Parameters None ### Response #### Success Response (200) - **citation** (string) - The BibTeX formatted citation string. #### Response Example { "citation": "@software{Conley_EMGFlow_2026, ...}" } ``` -------------------------------- ### GET /plot_dashboard Source: https://context7.com/wiiison/emgflow-python-package/llms.txt Launches an interactive Shiny dashboard for visual inspection and comparison of EMG signal processing stages. ```APIDOC ## GET /plot_dashboard ### Description Launches an interactive Shiny dashboard to visualize raw vs. processed EMG signals. Supports time-domain and frequency-domain views, file inspection, and stage comparison. ### Method GET ### Endpoint ef.plot_dashboard(path_names, column_name, sampling_rate, auto_run=True) ### Parameters #### Query Parameters - **path_names** (list) - Required - List of file paths to visualize. - **column_name** (str) - Required - EMG column to plot. - **sampling_rate** (int) - Required - Signal sampling rate. - **auto_run** (bool) - Optional - Whether to launch the browser automatically. ### Response #### Success Response (200) - **app** (ShinyApp) - Returns an app object if auto_run is False, otherwise launches the UI. ``` -------------------------------- ### Launch Interactive EMG Visualization Dashboard Source: https://context7.com/wiiison/emgflow-python-package/llms.txt Starts a Shiny-based dashboard for inspecting EMG signals across different processing stages. Supports time-domain and frequency-domain views, file selection, and custom deployment. ```python ef.plot_dashboard(path_names, column_name='EMG_zyg', sampling_rate=2000, units='mV', use_mask=False, show_legend=True, auto_run=True) app = ef.plot_dashboard(path_names, column_name='EMG_zyg', sampling_rate=2000, auto_run=False) ``` -------------------------------- ### GET /package/version Source: https://github.com/wiiison/emgflow-python-package/blob/main/README.md Retrieves the current version number of the installed EMGFlow package. ```APIDOC ## GET /package/version ### Description Returns the semantic version string of the installed EMGFlow package. ### Method GET ### Endpoint EMGFlow.package_version() ### Parameters None ### Response #### Success Response (200) - **version** (string) - The current version of the package. #### Response Example { "version": "1.1.2" } ``` -------------------------------- ### Run EMGFlow Processing Pipeline Source: https://github.com/wiiison/emgflow-python-package/blob/main/README.md Demonstrates the end-to-end workflow including path initialization, sample data generation, signal cleaning, dashboard visualization, and feature extraction. ```python import EMGFlow as ef # Get path dictionary path_names = ef.make_paths() # Load sample data ef.make_sample_data(path_names) # Preprocess signals ef.clean_signals(path_names, sampling_rate=2000, notch_f0=50) # Plot data on the "EMG_zyg" column ef.plot_dashboard(path_names, 'EMG_zyg', sampling_rate=2000) # Extract features and save results in "Features.csv" in feature_path df = ef.extract_features(path_names, sampling_rate=2000) ``` -------------------------------- ### Perform Full EMGFlow Pipeline Source: https://github.com/wiiison/emgflow-python-package/blob/main/papers/JOSS/paper.md Demonstrates the end-to-end workflow including path creation, loading sample data, preprocessing signals with notch filtering, and extracting 33 statistical features to a CSV file. ```python import EMGFlow # Create project paths path_names = EMGFlow.make_paths() # Load sample data EMGFlow.make_sample_data(path_names) # Preprocess signals EMGFlow.clean_signals(path_names, sampling_rate=2000, notch_f0=50) # Extract features to disk "Features.csv" EMGFlow.extract_features(path_names, sampling_rate=2000) ``` -------------------------------- ### make_paths Source: https://context7.com/wiiison/emgflow-python-package/llms.txt Initializes the directory structure required for the EMGFlow processing pipeline. ```APIDOC ## make_paths ### Description Creates a standardized directory structure for the EMG processing pipeline. Returns a dictionary of path locations with keys corresponding to each processing stage. ### Parameters #### Optional Parameters - **root** (str) - Optional - The root directory for the project (default: './Data'). - **raw** (str) - Optional - Custom path for existing raw data. ### Response - **dict** - A dictionary mapping stage names (raw, notch, bandpass, fwr, screened, filled, smoothed, feature) to their respective directory paths. ``` -------------------------------- ### Create Standardized Directory Structure Source: https://context7.com/wiiison/emgflow-python-package/llms.txt Initializes the required directory structure for the EMG processing pipeline. It returns a dictionary mapping stage names to their respective file paths. ```python import EMGFlow as ef path_names = ef.make_paths() path_names_custom = ef.make_paths(root='/path/to/project/EMG_Data', raw='/path/to/existing/raw_signals') ``` -------------------------------- ### Retrieve EMGFlow Citation and Version Information Source: https://github.com/wiiison/emgflow-python-package/blob/main/README.md Demonstrates how to use the EMGFlow library functions to programmatically access citation details and the current package version. These functions ensure that users cite the exact version of the software they are utilizing. ```python import EMGFlow # Print the citation for the current version EMGFlow.package_citation() # Retrieve and print the current package version version = EMGFlow.package_version() print(f"Current EMGFlow version: {version}") ``` -------------------------------- ### Retrieve Package Metadata and Citations Source: https://context7.com/wiiison/emgflow-python-package/llms.txt Utility functions to display the current package version and generate BibTeX-formatted citations for EMGFlow or its dependencies. ```python ef.package_version() ef.package_citation() ef.package_citation(pkg='numpy') ``` -------------------------------- ### map_files Source: https://context7.com/wiiison/emgflow-python-package/llms.txt Utility to recursively scan directories and map files based on extensions and regex patterns. ```APIDOC ## map_files ### Description Generates a dictionary mapping file names to their full paths by recursively scanning a directory. ### Parameters #### Required Parameters - **directory** (str) - Required - The directory to scan. #### Optional Parameters - **file_ext** (str) - Optional - File extension to filter by (e.g., 'csv'). - **expression** (str) - Optional - Regular expression pattern for filtering file names. ### Response - **dict** - A dictionary where keys are relative file names and values are absolute file paths. ``` -------------------------------- ### Map Files with Filtering Source: https://context7.com/wiiison/emgflow-python-package/llms.txt Recursively scans a directory to map file names to full paths. Supports file extension filtering and regular expression matching for selective processing. ```python import EMGFlow as ef file_dirs = ef.map_files('./Data/1_raw', file_ext='csv', expression=r'01/.*\.csv') for file_name, file_path in file_dirs.items(): print(f"Processing: {file_name}") ``` -------------------------------- ### Batch Preprocess EMG Signals Source: https://context7.com/wiiison/emgflow-python-package/llms.txt Executes the complete preprocessing pipeline on signal files. Options include notch filtering, bandpass filtering, full-wave rectification, artefact screening, interpolation, and smoothing. ```python import EMGFlow as ef path_names = ef.make_paths() ef.clean_signals(path_names, column_names=['EMG_zyg', 'EMG_cor'], sampling_rate=2000, notch_f0=60.0, do_screen=True, do_fill=True, do_smooth=True) ``` -------------------------------- ### Plot EMG Data Dashboard with EMGFlow Source: https://github.com/wiiison/emgflow-python-package/blob/main/papers/JOSS/paper.md This code snippet demonstrates how to plot an interactive dashboard for EMG data using the EMGFlow library. It requires specifying the path names, the muscle to display, the sampling rate, and the desired units. ```python show_muscle = 'EMG_zyg' units = 'mV' EMGFlow.plot_dashboard(path_names, show_muscle, sampling_rate, units) ``` -------------------------------- ### Convert EMG to Power Spectral Density Source: https://context7.com/wiiison/emgflow-python-package/llms.txt Converts raw EMG signals into Power Spectral Density (PSD) using the Welch method, useful for spectral analysis. ```python import EMGFlow as ef import pandas as pd signal = pd.read_csv('./Data/3_bandpass/01/sample_data_01.csv') psd = ef.emg_to_psd(signal, column_name='EMG_zyg', sampling_rate=2000, max_segment=2.5, normalize=True) ``` -------------------------------- ### Apply Notch Filtering Source: https://context7.com/wiiison/emgflow-python-package/llms.txt Removes powerline interference and harmonics from signal files by applying notch filters. Supports multiple frequencies and configurable Q-factors. ```python import EMGFlow as ef ef.notch_filter_signals(in_path='./Data/1_raw', out_path='./Data/2_notch', sampling_rate=2000, notch_vals=[(60, 5)]) ``` -------------------------------- ### POST /detect_spectral_outliers Source: https://context7.com/wiiison/emgflow-python-package/llms.txt Identifies files with anomalous spectral peaks by comparing signal power against a fitted rational function envelope. ```APIDOC ## POST /detect_spectral_outliers ### Description Detects files containing spectral outliers by evaluating the power spectrum against a fitted rational function envelope. Useful for identifying corrupted or noisy EMG recordings. ### Method POST ### Endpoint ef.detect_spectral_outliers(in_path, sampling_rate, threshold, low, high, ...) ### Parameters #### Query Parameters - **in_path** (str) - Required - Directory path containing the processed signals. - **sampling_rate** (int) - Required - Sampling rate of the signals. - **threshold** (float) - Required - Multiplier for median-based outlier detection. - **low** (float) - Required - Lower frequency bound for analysis. - **high** (float) - Required - Upper frequency bound for analysis. ### Response #### Success Response (200) - **outliers** (dict) - A dictionary mapping file names to their respective paths for identified outliers. ``` -------------------------------- ### Apply Custom Notch Filter to Subfolder Source: https://github.com/wiiison/emgflow-python-package/blob/main/papers/JOSS/paper.md Applies a custom notch filter (e.g., at 150 Hz for the 3rd harmonic) to specific files within a subfolder. This function uses a regular expression to target files, allowing for selective filtering. It reads from and writes to the same directory, useful for iterative processing. ```python # Custom notch settings notch_custom = [(150, 25)] path_pattern = '^01/' # Step 1b. Apply custom notch filter all to files in subfolder "/01" EMGFlow.notch_filter_signals(path_names['notch'], path_names['notch'], muscles, sampling_rate, notch_custom, expression=path_pattern) ``` -------------------------------- ### BibTeX Citation Format Source: https://github.com/wiiison/emgflow-python-package/blob/main/README.md The standard BibTeX entry for referencing the EMGFlow package in academic publications. Users should update the version field to match the specific release used in their research. ```bibtex @software{Conley_EMGFlow_2026, author = {Conley, William and Livingstone, Steven R}, month = {02}, title = {{EMGFlow Package}}, url = {https://github.com/WiIIson/EMGFlow-Python-Package}, version = {1.1.2}, year = {2026}, note = "{\tt william@cconley.ca}" } ``` -------------------------------- ### clean_signals Source: https://context7.com/wiiison/emgflow-python-package/llms.txt Applies the complete EMG preprocessing pipeline to all signal files in batch. ```APIDOC ## clean_signals ### Description Executes the full preprocessing pipeline including notch filtering, bandpass filtering, and full-wave rectification. ### Parameters #### Required Parameters - **path_names** (dict) - Required - Dictionary returned by make_paths. - **sampling_rate** (int) - Required - Sampling rate of the signals in Hz. #### Optional Parameters - **notch_f0** (float) - Optional - Powerline frequency (50 or 60 Hz). - **column_names** (list) - Optional - Specific columns to process. - **do_screen** (bool) - Optional - Enable artefact screening (Hampel filter). - **do_fill** (bool) - Optional - Enable missing value interpolation (PCHIP). - **do_smooth** (bool) - Optional - Enable RMS smoothing. ``` -------------------------------- ### Fill Missing Data and Apply Smoothing Source: https://github.com/wiiison/emgflow-python-package/blob/main/papers/JOSS/paper.md Handles missing data points (gaps or NaNs) by interpolating using the Piecewise Cubic Hermite Interpolating Polynomial (PCHIP) method, which preserves signal shape and monotonicity. Subsequently, it applies an optional smoothing filter (e.g., RMS) to reduce residual high-frequency noise before feature extraction. ```python # Step 5. Fill missing data EMGFlow.fill_missing_signals(path_names['screened'], path_names['filled'], muscles, sampling_rate) # Step 6. Apply smoothing filter EMGFlow.smooth_signals(path_names['filled'], path_names['smooth'], muscles, sampling_rate) ``` -------------------------------- ### Signal Smoothing API Source: https://context7.com/wiiison/emgflow-python-package/llms.txt Provides methods for smoothing EMG signals using Gaussian or LOESS techniques. Allows specifying input/output paths, column names, sampling rate, and smoothing parameters. ```APIDOC ## Gaussian smoothing with custom sigma ef.smooth_signals( in_path='./Data/6_filled', out_path='./Data/7_smoothed', column_names=['EMG_zyg'], sampling_rate=2000, method='gauss', window_ms=50.0, sigma=1.5 # Gaussian kernel width ) ## LOESS smoothing ef.smooth_signals( in_path='./Data/6_filled', out_path='./Data/7_smoothed', sampling_rate=1000, method='loess', window_ms=75.0, min_segment=30.0 ) ``` -------------------------------- ### Apply Band-Pass and Rectification Filters Source: https://github.com/wiiison/emgflow-python-package/blob/main/papers/JOSS/paper.md Performs two sequential signal processing steps: band-pass filtering to isolate the frequency spectrum of muscle activity (e.g., 20-450 Hz) and full-wave rectification to convert negative signal values to positive. These steps are crucial for preparing sEMG data for feature extraction. ```python # Passband edges (low, high) passband_edges = [20, 450] # Step 2. Apply band-pass filter EMGFlow.bandpass_filter_signals(path_names['notch'], path_names['bandpass'], muscles, sampling_rate, passband_edges) # Step 3. Apply full-wave rectifier EMGFlow.rectify_signals(path_names['bandpass'], path_names['fwr'], muscles) ``` -------------------------------- ### Smooth EMG Signals with EMGFlow Source: https://context7.com/wiiison/emgflow-python-package/llms.txt Applies smoothing techniques to EMG signals. Supports Gaussian smoothing with custom sigma or LOESS smoothing based on window size and segment parameters. ```python ef.smooth_signals(in_path='./Data/6_filled', out_path='./Data/7_smoothed', column_names=['EMG_zyg'], sampling_rate=2000, method='gauss', window_ms=50.0, sigma=1.5) ef.smooth_signals(in_path='./Data/6_filled', out_path='./Data/7_smoothed', sampling_rate=1000, method='loess', window_ms=75.0, min_segment=30.0) ``` -------------------------------- ### Generate Power Spectral Density (PSD) for EMG Signals Source: https://context7.com/wiiison/emgflow-python-package/llms.txt Calculates the Power Spectral Density of EMG signals. Supports optional normalization and custom NaN masking to handle signal artifacts. ```python psd_raw = ef.emg_to_psd(signal, column_name='EMG_zyg', sampling_rate=2000, normalize=False) mask = signal['mask_EMG_zyg'] if 'mask_EMG_zyg' in signal.columns else None psd_masked = ef.emg_to_psd(signal, column_name='EMG_zyg', sampling_rate=2000, nan_mask=mask) ``` -------------------------------- ### Calculate Frequency-Domain Features Source: https://context7.com/wiiison/emgflow-python-package/llms.txt Computes spectral features like Median Frequency, Spectral Centroid, and Twitch Ratios from a Power Spectral Density (PSD) array. ```python import EMGFlow as ef import pandas as pd signal = pd.read_csv('./Data/3_bandpass/01/sample_data_01.csv') psd = ef.emg_to_psd(signal, 'EMG_zyg', sampling_rate=2000, normalize=True) mdf = ef.calc_mdf(psd) twitch_ratio = ef.calc_twitch_ratio(psd, freq=60.0) ``` -------------------------------- ### POST /emg_to_psd Source: https://context7.com/wiiison/emgflow-python-package/llms.txt Calculates the Power Spectral Density (PSD) of an EMG signal, supporting normalization and NaN masking for robust power measurements. ```APIDOC ## POST /emg_to_psd ### Description Calculates the Power Spectral Density (PSD) of an EMG signal. This function allows for raw or normalized power output and supports custom NaN masking for handling signal artifacts. ### Method POST ### Endpoint ef.emg_to_psd(signal, column_name, sampling_rate, normalize=True, nan_mask=None) ### Parameters #### Path Parameters - **signal** (DataFrame) - Required - The input signal containing EMG data. - **column_name** (str) - Required - The specific column to process. - **sampling_rate** (int) - Required - The sampling frequency in Hz. #### Request Body - **normalize** (bool) - Optional - Whether to normalize the PSD output. - **nan_mask** (array) - Optional - Mask to exclude specific data points. ### Response #### Success Response (200) - **psd** (DataFrame) - A DataFrame containing 'Frequency' and 'Power' columns. ``` -------------------------------- ### Extract and Inspect EMG Features with EMGFlow Source: https://github.com/wiiison/emgflow-python-package/blob/main/papers/JOSS/paper.md This code snippet shows how to extract temporal and spectral features from EMG data using EMGFlow. It saves the extracted features to a CSV file and provides a preview of the first few rows of the resulting DataFrame. The package version can also be retrieved. ```python # Step 7. Extract features and save results in "Features.csv" df = EMGFlow.extract_features(path_names, muscles, sampling_rate) # Inspect features df.round(4).head() # Get package version EMGFlow.package_version() ``` -------------------------------- ### Screen Artefacts using Hampel or Wiener Filter Source: https://context7.com/wiiison/emgflow-python-package/llms.txt Applies artefact detection and removal using either the Hampel filter (outlier detection) or Wiener filter (noise reduction). Parameters include method, window size, outlier threshold (n_sigma), and minimum segment length. Dependencies include the EMGFlow library. ```python import EMGFlow as ef # Hampel filter for outlier detection (default) ef.screen_artefact_signals( in_path='./Data/4_fwr', out_path='./Data/5_screened', sampling_rate=2000, method='hampel', window_ms=100.0, # Detection window size n_sigma=10.0, # Outlier threshold (standard deviations) min_segment=30.0 # Minimum valid segment length ) # Wiener filter for noise reduction ef.screen_artefact_signals( in_path='./Data/4_fwr', out_path='./Data/5_screened', column_names=['EMG_zyg'], sampling_rate=2000, method='wiener', window_ms=50.0 ) # More aggressive outlier detection ef.screen_artefact_signals( in_path='./Data/4_fwr', out_path='./Data/5_screened', sampling_rate=1000, method='hampel', window_ms=200.0, n_sigma=5.0 # Lower threshold = more aggressive ) ``` -------------------------------- ### Fill Missing Signal Values with Interpolation Source: https://context7.com/wiiison/emgflow-python-package/llms.txt Interpolates missing values (NaN) in signals using PCHIP or cubic spline interpolation. Users can specify the interpolation method, maximum gap size to fill, and target columns. Dependencies include the EMGFlow library. ```python import EMGFlow as ef # PCHIP interpolation (default, shape-preserving) ef.fill_missing_signals( in_path='./Data/5_screened', out_path='./Data/6_filled', sampling_rate=2000, method='pchip', max_segment=500.0 # Max gap to fill in ms ) # Cubic spline interpolation ef.fill_missing_signals( in_path='./Data/5_screened', out_path='./Data/6_filled', column_names=['EMG_zyg', 'EMG_cor'], sampling_rate=2000, method='spline', max_segment=250.0 # Shorter max gap for more conservative fill ) # Fill missing in FWR output (skip screening step) ef.fill_missing_signals( in_path='./Data/4_fwr', out_path='./Data/6_filled', sampling_rate=1000, method='pchip', max_segment=1000.0 ) ``` -------------------------------- ### Apply Notch Filter for Mains Hum Source: https://github.com/wiiison/emgflow-python-package/blob/main/papers/JOSS/paper.md Applies a notch filter to remove mains hum (e.g., 50 Hz) from sEMG signals. This function processes all files in a specified input directory and writes the filtered output to a new directory, preserving the original directory structure. It targets specific muscle channels. ```python # Columns names containing sEMG (Zygomaticus major, Corrugator supercilii) muscles = ['EMG_zyg', 'EMG_cor'] # Notch filter for mains hum (Hz, Q-score) notch_main = [(50, 5)] # Step 1. Apply notch filter to all files in 1_raw, writing output to 2_notch EMGFlow.notch_filter_signals(path_names['raw'], path_names['notch'], muscles, sampling_rate, notch_main) ``` -------------------------------- ### Detect Spectral Outliers in EMG Data Source: https://context7.com/wiiison/emgflow-python-package/llms.txt Identifies files containing anomalous spectral peaks by comparing signal power spectra against a rational function envelope. Allows configuration of thresholds and frequency limits for sensitive detection. ```python outliers = ef.detect_spectral_outliers(in_path='./Data/3_bandpass', sampling_rate=2000, window_ms=50.0, threshold=5.0, metric=np.median, low=20.0, high=450.0) outliers = ef.detect_spectral_outliers(in_path='./Data/3_bandpass', column_names=['EMG_zyg', 'EMG_cor'], sampling_rate=2000, window_ms=100.0, threshold=3.0, expression=r'session_01/.*') ``` -------------------------------- ### Individual Time-Domain Feature Functions Source: https://context7.com/wiiison/emgflow-python-package/llms.txt Calculate individual time-domain features from signal DataFrames. ```APIDOC ## Individual Feature Functions Calculate individual time-domain features from signal DataFrames. ### Method POST ### Endpoint /api/features/time-domain ### Parameters #### Request Body - **signal** (DataFrame) - Required - DataFrame containing the EMG signal. - **column_name** (str) - Required - The name of the EMG column to process. - **sampling_rate** (int) - Optional - The sampling rate of the signal (required for some features like IEMG, SSI). - **threshold** (float) - Optional - Threshold for Willison Amplitude calculation. ### Request Example ```python import EMGFlow as ef import pandas as pd # Load a signal file signal = pd.read_csv('./Data/7_smoothed/01/sample_data_01.csv') # Time-domain features iemg = ef.calc_iemg(signal, 'EMG_zyg', sampling_rate=2000) mav = ef.calc_mav(signal, 'EMG_zyg') mmav1 = ef.calc_mmav1(signal, 'EMG_zyg') mmav2 = ef.calc_mmav2(signal, 'EMG_zyg') ssi = ef.calc_ssi(signal, 'EMG_zyg', sampling_rate=2000) var = ef.calc_var(signal, 'EMG_zyg') vorder = ef.calc_vorder(signal, 'EMG_zyg') rms = ef.calc_rms(signal, 'EMG_zyg') wl = ef.calc_wl(signal, 'EMG_zyg') wamp = ef.calc_wamp(signal, 'EMG_zyg', threshold=0.05) log_det = ef.calc_log(signal, 'EMG_zyg') mfl = ef.calc_mfl(signal, 'EMG_zyg') ap = ef.calc_ap(signal, 'EMG_zyg') print(f"MAV: {mav:.4f}, RMS: {rms:.4f}, WL: {wl:.4f}") ``` ### Response #### Success Response (200) - **feature_value** (float) - The calculated value for the requested time-domain feature. ``` -------------------------------- ### notch_filter_signals Source: https://context7.com/wiiison/emgflow-python-package/llms.txt Applies notch filters to remove powerline interference. ```APIDOC ## notch_filter_signals ### Description Applies notch filters to remove powerline interference (50/60 Hz) and harmonics from all signal files in a directory. ### Parameters #### Required Parameters - **in_path** (str) - Required - Input directory path. - **out_path** (str) - Required - Output directory path. - **sampling_rate** (int) - Required - Sampling rate in Hz. - **notch_vals** (list) - Required - List of tuples containing (frequency_Hz, Q_factor). ``` -------------------------------- ### Frequency-Domain Feature Functions Source: https://context7.com/wiiison/emgflow-python-package/llms.txt Calculate spectral features from the Power Spectral Density (PSD) of EMG signals. ```APIDOC ## Frequency-Domain Feature Functions Calculate spectral features from the Power Spectral Density (PSD) of EMG signals. ### Method POST ### Endpoint /api/features/frequency-domain ### Parameters #### Request Body - **psd** (DataFrame) - Required - DataFrame containing the Power Spectral Density with 'Frequency' and 'Power' columns. - **sampling_rate** (int) - Optional - The sampling rate of the original signal (used for some calculations). - **freq** (float) - Optional - Frequency cutoff for twitch ratio and index calculations. - **p** (int) - Optional - Parameter for Spectral Bandwidth calculation. - **signal** (DataFrame) - Required for SFLX - DataFrame containing the raw EMG signal. - **duration_ratio** (float) - Required for SFLX - Ratio to split the signal into two halves. - **column_name** (str) - Required for SFLX - The name of the EMG column to process. ### Request Example ```python import EMGFlow as ef import pandas as pd # Load bandpass-filtered signal for spectral analysis signal = pd.read_csv('./Data/3_bandpass/01/sample_data_01.csv') # Generate Power Spectral Density psd = ef.emg_to_psd(signal, 'EMG_zyg', sampling_rate=2000, normalize=True) # Frequency-domain features mdf = ef.calc_mdf(psd) mnf = ef.calc_mnf(psd) sc = ef.calc_sc(psd) sflt = ef.calc_sflt(psd) ss = ef.calc_ss(psd) sdec = ef.calc_sdec(psd) se = ef.calc_se(psd) srbw = ef.calc_sbw(psd, p=2) # Corrected from sbw to srbw for Spectral Bandwidth # Twitch ratio features twitch_ratio = ef.calc_twitch_ratio(psd, freq=60.0) twitch_index = ef.calc_twitch_index(psd, freq=60.0) fast_slope, slow_slope = ef.calc_twitch_slope(psd, freq=60.0) # Spectral flux sflx = ef.calc_sflx(signal, 0.5, 'EMG_zyg', sampling_rate=2000) print(f"MDF: {mdf:.2f} Hz, MNF: {mnf:.2f} Hz, Twitch Ratio: {twitch_ratio:.4f}") ``` ### Response #### Success Response (200) - **feature_value** (float or tuple) - The calculated value for the requested frequency-domain feature. Returns a tuple for `calc_twitch_slope`. ``` -------------------------------- ### emg_to_psd API Source: https://context7.com/wiiison/emgflow-python-package/llms.txt Converts an EMG signal to its Power Spectral Density (PSD) using the Welch method. This Long Term Average Spectrum (LTAS) representation is used for frequency-domain feature extraction. ```APIDOC ## emg_to_psd Converts an EMG signal to its Power Spectral Density (PSD) using the Welch method. ### Method POST ### Endpoint /api/emg_to_psd ### Parameters #### Request Body - **signal** (DataFrame) - Required - DataFrame containing the EMG signal. - **column_name** (str) - Required - The name of the EMG column to process. - **sampling_rate** (int) - Required - The sampling rate of the EMG signal. - **max_segment** (float) - Optional - Maximum NaN gap (in ms) to interpolate. - **normalize** (bool) - Optional - If True, normalize power to [0, 1]. Defaults to False. ### Request Example ```python import EMGFlow as ef import pandas as pd # Load signal data signal = pd.read_csv('./Data/3_bandpass/01/sample_data_01.csv') # Generate normalized PSD psd = ef.emg_to_psd( signal, column_name='EMG_zyg', sampling_rate=2000, max_segment=2.5, normalize=True ) ``` ### Response #### Success Response (200) - **psd** (DataFrame) - DataFrame with 'Frequency' and 'Power' columns representing the PSD. ``` -------------------------------- ### Apply multiple notch filters (60 Hz + harmonics) Source: https://context7.com/wiiison/emgflow-python-package/llms.txt Applies notch filters to remove power line noise (60 Hz and its harmonics) from EMG signals. It can process all signals in a directory or a subset based on a regex expression. ```APIDOC ## POST /emgflow/notch_filter_signals ### Description Applies notch filters to remove power line noise (60 Hz and its harmonics) from EMG signals. It can process all signals in a directory or a subset based on a regex expression. ### Method POST ### Endpoint /emgflow/notch_filter_signals ### Parameters #### Query Parameters - **in_path** (string) - Required - Path to the input directory containing raw EMG data. - **out_path** (string) - Required - Path to the output directory for processed signals. - **column_names** (list of strings) - Optional - Specific columns to process. If not provided, all columns are processed. - **sampling_rate** (integer) - Required - The sampling rate of the EMG signals in Hz. - **notch_vals** (list of tuples) - Required - A list of tuples, where each tuple contains the frequency (Hz) and bandwidth (Hz) for a notch filter. Example: `[(60, 5), (120, 5)]` for 60 Hz and 120 Hz. - **min_segment** (float) - Optional - Minimum valid segment length in milliseconds. Segments shorter than this will be discarded. - **expression** (string) - Optional - A regex expression to filter which files in the `in_path` should be processed. ### Request Example ```json { "in_path": "./Data/1_raw", "out_path": "./Data/2_notch", "column_names": ["EMG_zyg", "EMG_cor"], "sampling_rate": 2000, "notch_vals": [(60, 5), (120, 5), (180, 5)], "min_segment": 30.0 } ``` ### Request Example (Regex) ```json { "in_path": "./Data/1_raw", "out_path": "./Data/2_notch", "sampling_rate": 2000, "notch_vals": [(50, 5)], "expression": "participant_0[1-5]/.*" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates successful processing. - **message** (string) - Confirmation message. #### Response Example ```json { "status": "success", "message": "Notch filtering applied successfully." } ``` ``` -------------------------------- ### Extract EMG Features Source: https://context7.com/wiiison/emgflow-python-package/llms.txt Extracts 33 time-domain and frequency-domain features from preprocessed EMG signals. It returns a DataFrame and saves the results to a CSV file. ```python import EMGFlow as ef path_names = ef.make_paths() features_df = ef.extract_features(path_names, sampling_rate=2000) features_df = ef.extract_features(path_names, column_names=['EMG_zyg', 'EMG_cor'], sampling_rate=2000, expression=r'session_\d+/.*', short_name=True) ``` -------------------------------- ### Screen Artefact Signals Source: https://context7.com/wiiison/emgflow-python-package/llms.txt Applies artefact detection and removal using Hampel filter (outlier detection) or Wiener filter (noise reduction) to identify and handle signal artifacts. Allows configuration of detection window and thresholds. ```APIDOC ## POST /emgflow/screen_artefact_signals ### Description Applies artefact detection and removal using Hampel filter (outlier detection) or Wiener filter (noise reduction) to identify and handle signal artifacts. Allows configuration of detection window and thresholds. ### Method POST ### Endpoint /emgflow/screen_artefact_signals ### Parameters #### Query Parameters - **in_path** (string) - Required - Path to the input directory containing signals (e.g., after rectification). - **out_path** (string) - Required - Path to the output directory for artefact-screened signals. - **column_names** (list of strings) - Optional - Specific columns to process. If not provided, all columns are processed. - **sampling_rate** (integer) - Required - The sampling rate of the EMG signals in Hz. - **method** (string) - Optional - The artefact detection/removal method. Options: 'hampel' (default) or 'wiener'. - **window_ms** (float) - Optional - The size of the detection window in milliseconds. - **n_sigma** (float) - Optional - For 'hampel' method, the outlier threshold in standard deviations. Higher values are less aggressive. - **min_segment** (float) - Optional - Minimum valid segment length in milliseconds. Segments shorter than this will be discarded. ### Request Example (Hampel Filter) ```json { "in_path": "./Data/4_fwr", "out_path": "./Data/5_screened", "sampling_rate": 2000, "method": "hampel", "window_ms": 100.0, "n_sigma": 10.0, "min_segment": 30.0 } ``` ### Request Example (Wiener Filter) ```json { "in_path": "./Data/4_fwr", "out_path": "./Data/5_screened", "column_names": ["EMG_zyg"], "sampling_rate": 2000, "method": "wiener", "window_ms": 50.0 } ``` ### Request Example (Aggressive Hampel) ```json { "in_path": "./Data/4_fwr", "out_path": "./Data/5_screened", "sampling_rate": 1000, "method": "hampel", "window_ms": 200.0, "n_sigma": 5.0 } ``` ### Response #### Success Response (200) - **status** (string) - Indicates successful processing. - **message** (string) - Confirmation message. #### Response Example ```json { "status": "success", "message": "Artefact screening applied successfully." } ``` ``` -------------------------------- ### Apply Multiple Notch Filters to EMG Signals Source: https://context7.com/wiiison/emgflow-python-package/llms.txt Applies notch filters to remove specific frequencies and their harmonics from EMG signals. It can process all signals in a directory or a subset based on a regex expression. Dependencies include the EMGFlow library. ```python import EMGFlow as ef # Apply multiple notch filters (60 Hz + harmonics) ef.notch_filter_signals( in_path='./Data/1_raw', out_path='./Data/2_notch', column_names=['EMG_zyg', 'EMG_cor'], sampling_rate=2000, notch_vals=[(60, 5), (120, 5), (180, 5)], # 60 Hz and harmonics min_segment=30.0 # Minimum valid segment length in ms ) # Process only specific files using regex ef.notch_filter_signals( in_path='./Data/1_raw', out_path='./Data/2_notch', sampling_rate=2000, notch_vals=[(50, 5)], expression=r'participant_0[1-5]/.*' # Only participants 1-5 ) ``` -------------------------------- ### extract_features API Source: https://context7.com/wiiison/emgflow-python-package/llms.txt Extracts a comprehensive set of 33 time-domain and frequency-domain features from preprocessed EMG signals. Saves results to a Features.csv file and returns a DataFrame. ```APIDOC ## extract_features Extracts a comprehensive set of 33 time-domain and frequency-domain features from preprocessed EMG signals. Saves results to a Features.csv file and returns a DataFrame. ### Method POST ### Endpoint /api/extract_features ### Parameters #### Query Parameters - **sampling_rate** (int) - Required - The sampling rate of the EMG signal. - **column_names** (list[str]) - Optional - List of column names to extract features from. Defaults to all EMG columns. - **expression** (str) - Optional - Regex expression to filter files. - **short_name** (bool) - Optional - If True, use relative paths as identifiers. ### Request Example ```python import EMGFlow as ef path_names = ef.make_paths() # Extract all features from preprocessed signals features_df = ef.extract_features( path_names, sampling_rate=2000 ) # Extract features for specific columns features_df = ef.extract_features( path_names, column_names=['EMG_zyg', 'EMG_cor'], sampling_rate=2000, expression=r'session_\\d+/.*', # Filter files short_name=True # Use relative paths as identifiers ) ``` ### Response #### Success Response (200) - **features_df** (DataFrame) - DataFrame containing extracted features. Columns include file path and feature names (e.g., EMG_zyg_Mean, EMG_zyg_RMS). #### Response Example ```python # Example DataFrame structure: # File_Path, EMG_zyg_Min, EMG_zyg_Max, EMG_zyg_Mean, EMG_zyg_SD, ... ``` ### Features Extracted: - **Time-domain**: Min, Max, Mean, SD, Skew, Kurtosis, IEMG, MAV, MMAV1, MMAV2, SSI, VAR, VOrder, RMS, WL, LOG, MFL, AP - **Frequency-domain**: Max_Freq, MDF, MNF, Twitch_Ratio, Twitch_Index, Twitch_Slope_Fast, Twitch_Slope_Slow, SC, SFlt, SFlx, SS, SDec, SE, SR, SB ``` -------------------------------- ### Calculate Individual Time-Domain Features Source: https://context7.com/wiiison/emgflow-python-package/llms.txt Computes specific time-domain metrics such as Mean Absolute Value, RMS, and Willison Amplitude from an EMG signal DataFrame. ```python import EMGFlow as ef import pandas as pd signal = pd.read_csv('./Data/7_smoothed/01/sample_data_01.csv') iemg = ef.calc_iemg(signal, 'EMG_zyg', sampling_rate=2000) rms = ef.calc_rms(signal, 'EMG_zyg') wamp = ef.calc_wamp(signal, 'EMG_zyg', threshold=0.05) ``` -------------------------------- ### Smooth EMG Signals for Envelope Extraction Source: https://context7.com/wiiison/emgflow-python-package/llms.txt Applies smoothing filters to extract the EMG envelope. Supports RMS, boxcar (moving average), Gaussian, and LOESS smoothing methods. Users can specify the method, window size, and target columns. Dependencies include the EMGFlow library. ```python import EMGFlow as ef # RMS smoothing (default, commonly used for EMG) ef.smooth_signals( in_path='./Data/6_filled', out_path='./Data/7_smoothed', sampling_rate=2000, method='rms', window_ms=50.0 # Smoothing window size ) # Boxcar (moving average) smoothing ef.smooth_signals( in_path='./Data/6_filled', out_path='./Data/7_smoothed', sampling_rate=2000, method='boxcar', window_ms=100.0 ) ``` -------------------------------- ### Fill Missing Signals Source: https://context7.com/wiiison/emgflow-python-package/llms.txt Interpolates missing values (NaN) in signals using PCHIP or cubic spline interpolation, with a maximum gap limit. Useful for handling gaps after artefact removal. ```APIDOC ## POST /emgflow/fill_missing_signals ### Description Interpolates missing values (NaN) in signals using PCHIP (Piecewise Cubic Hermite Interpolating Polynomial) or cubic spline interpolation, with a maximum gap limit. Useful for handling gaps after artefact removal. ### Method POST ### Endpoint /emgflow/fill_missing_signals ### Parameters #### Query Parameters - **in_path** (string) - Required - Path to the input directory containing signals (e.g., after artefact screening). - **out_path** (string) - Required - Path to the output directory for signals with missing values filled. - **column_names** (list of strings) - Optional - Specific columns to process. If not provided, all columns are processed. - **sampling_rate** (integer) - Required - The sampling rate of the EMG signals in Hz. - **method** (string) - Optional - The interpolation method. Options: 'pchip' (default, shape-preserving) or 'spline' (cubic spline). - **max_segment** (float) - Optional - The maximum gap length in milliseconds to interpolate. Gaps larger than this will not be filled. ### Request Example (PCHIP Interpolation) ```json { "in_path": "./Data/5_screened", "out_path": "./Data/6_filled", "sampling_rate": 2000, "method": "pchip", "max_segment": 500.0 } ``` ### Request Example (Spline Interpolation) ```json { "in_path": "./Data/5_screened", "out_path": "./Data/6_filled", "column_names": ["EMG_zyg", "EMG_cor"], "sampling_rate": 2000, "method": "spline", "max_segment": 250.0 } ``` ### Request Example (From FWR Output) ```json { "in_path": "./Data/4_fwr", "out_path": "./Data/6_filled", "sampling_rate": 1000, "method": "pchip", "max_segment": 1000.0 } ``` ### Response #### Success Response (200) - **status** (string) - Indicates successful processing. - **message** (string) - Confirmation message. #### Response Example ```json { "status": "success", "message": "Missing values filled successfully." } ``` ``` -------------------------------- ### Apply Bandpass Filter to EMG Signals Source: https://context7.com/wiiison/emgflow-python-package/llms.txt Applies a Butterworth bandpass filter to isolate the frequency range of interest for EMG signals. It supports standard ranges (e.g., 20-450 Hz) and custom ranges, with options to specify columns, sampling rate, and copy unmatched files. Dependencies include the EMGFlow library. ```python import EMGFlow as ef # Standard EMG bandpass filter (20-450 Hz) ef.bandpass_filter_signals( in_path='./Data/2_notch', out_path='./Data/3_bandpass', sampling_rate=2000, passband_edges=(20.0, 450.0) # (low_Hz, high_Hz) ) # Custom frequency range for specific application ef.bandpass_filter_signals( in_path='./Data/2_notch', out_path='./Data/3_bandpass', column_names=['EMG_zyg'], sampling_rate=1000, passband_edges=(10.0, 200.0), # Different frequency range min_segment=50.0 # Minimum segment length in ms ) # Copy unmatched files to output ef.bandpass_filter_signals( in_path='./Data/2_notch', out_path='./Data/3_bandpass', sampling_rate=2000, passband_edges=(20.0, 450.0), expression=r'trial_\d+\.csv', copy_unmatched=True # Copy files not matching regex unchanged ) ```