### Install EMGFlow and Run Unit Tests Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/testing.html Installs the EMGFlow package, clones the repository, navigates to the test directory, and runs all test cases using the unittest module. Ensure you have git and pip installed. ```bash # 1. Install EMGFlow package pip install EMGFlow # 2. Clone repo to local folder git clone git@github.com:WiIIson/EMGFlow-Python-Package.git . # 3. Navigate to test folder cd tests # 5. Run all test cases python -m unittest discover -v -s . -p 'test_*.py' ``` -------------------------------- ### Install EMGFlow via pip Source: https://wiiison.github.io/EMGFlow-Python-Package/guide/getting-started.html Use this command to install the package from PyPI. ```bash pip install EMGFlow ``` -------------------------------- ### Usage example for detect_spectral_outliers Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/preprocess-signals.html Example demonstrating how to call detect_spectral_outliers with specific signal parameters. ```python path_names = EMGFlow.make_paths() column_names = ['EMG_zyg', 'EMG_cor'] sampling_rate = 2000 window_ms = 120 outliers = EMGFlow.detect_spectral_outliers(path_names['Notch'], column_names, sampling_rate, window_ms) ``` -------------------------------- ### Apply Bandpass Filter Usage Example Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/preprocess-signals.html Example demonstrating how to apply a bandpass filter with a custom sampling rate and frequency range. ```python # Apply a bandpass filter below 20Hz, and above 250Hz. sampling_rate = 2000 band_Signal = EMGFlow.apply_bandpass_filter(Signal, 'EMG_zyg', sampling_rate, (20, 250)) ``` -------------------------------- ### Calculate Spectral Flux examples Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/extract-features.html Examples showing how to calculate spectral flux between two signals or by splitting a single signal. ```python # Calculate the Spectral Flux of two signals flux1 = EMGFlow.calc_spec_flux(Signal1, Signal2, 'EMG_zyg', 2000) # Calculate the Spectral Flux of one signal divided at the halfway point flux2 = EMGFlow.calc_spec_flux(Signal1, 0.5, 'EMG_zyg', 2000) ``` -------------------------------- ### Calculate Spectral Spread example Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/extract-features.html Example demonstrating the calculation of Spectral Spread from an EMG signal. ```python # Calculate the SS of Signal, for column 'EMG_zyg' psd = EMGFlow.emg_to_psd(Signal['EMG_zyg'], 2000) SS = EMGFlow.calc_ss(psd) ``` -------------------------------- ### Example: Extracting Features with Custom Parameters Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/extract-features.html Demonstrates how to use `extract_features` with specified column names and sampling rate. This example assumes sample data has been generated using `make_sample_data`. ```python path_names = EMGFlow.make_paths() EMGFlow.make_sample_data(path_names) column_names = ['EMG_zyg', 'EMG_cor'] sampling_rate = 2000 # Extracts all features from the files in the 'Bandpass' path and the 'Filled' # path. If the 'Filled' path was empty, it would use 'smoothed' instead. Assumes ``` -------------------------------- ### Execute clean_signals workflow Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/preprocess-signals.html Example usage showing how to initialize the path dictionary and invoke the signal cleaning process. ```python # Create path dictionary, then clean the signals. path_names = EMGFlow.make_paths() sampling_rate = 2000 EMGFlow.clean_signals(path_names, sampling_rate=sampling_rate) ``` -------------------------------- ### Apply Artefact Screening Example Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/preprocess-signals.html Usage example for reading a file and applying artefact screening to a signal column. ```python # Screen artefacts in a sample data file. pathNames = EMGFlow.make_paths() filePath = os.path.join(pathNames['raw'], '01', 'sample_data_01.csv') Signal = EMGFlow.read_file_type(filePath, 'csv') ASignal = EMGFlow.apply_screen_artefacts(Signal, 'EMG_zyg', 2000) ``` -------------------------------- ### Calculate Spectral Rolloff example Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/extract-features.html Example demonstrating the calculation of Spectral Rolloff from an EMG signal. ```python # Calculate the SR of Signal, for column 'EMG_zyg' psd = EMGFlow.emg_to_psd(Signal['EMG_zyg'], 2000) SR = EMGFlow.calc_sr(psd) ``` -------------------------------- ### Apply Boxcar Smooth Usage Example Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/preprocess-signals.html Example demonstrating the application of a boxcar smoothing filter with specified window size and sampling rate. ```python column_name='EMG_zyg' sampling_rate=2000.0 window_ms=100.0 boxcar_Signal = EMGFlow.apply_boxcar_smooth(Signal, column_name, sampling_rate, window_ms) ``` -------------------------------- ### Calculate MDF feature Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/extract-features.html Usage example for calculating the Median Frequency from a PSD object. ```python # Calculate the MDF of Signal, for column 'EMG_zyg' psd = EMGFlow.emg_to_psd(Signal['EMG_zyg'], 2000) MDF = EMGFlow.calc_mdf(psd) ``` -------------------------------- ### Apply RMS Smoothing Example Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/preprocess-signals.html Usage example for applying RMS smoothing to a specific signal column. ```python column_name='EMG_zyg' sampling_rate=2000.0 window_ms=100.0 rms_Signal = EMGFlow.apply_rms_smooth(Signal, column_name, sampling_rate, window_ms) ``` -------------------------------- ### Calculate WAMP feature Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/extract-features.html Usage example for calculating the WAMP of a specific signal column. ```python # Calculate the WAMP of Signal, for column 'EMG_zyg' WAMP = EMGFlow.calc_wamp(Signal, 'EMG_zyg', 55) ``` -------------------------------- ### Calculate Twitch Slope Example Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/extract-features.html Demonstrates how to convert an EMG signal to PSD and calculate the fast and slow twitch slopes. ```python # Calculate the Twitch Index of Signal, for column 'EMG_zyg' psd = EMGFlow.emg_to_psd(Signal['EMG_zyg'], 2000) fast_slope, slow_slope = EMGFlow.calc_twitch_slope(psd) ``` -------------------------------- ### Calculating Log Detector (LOG) Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/extract-features.html Function signature and usage example for calculating the Log Detector estimate of muscle force. ```python def calc_log(Signal:pd.DataFrame, column_name:str) ``` ```python # Calculate the LOG of Signal, for column 'EMG_zyg' LOG = EMGFlow.calc_log(Signal, 'EMG_zyg') ``` -------------------------------- ### Example Usage of fill_missing_signals Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/preprocess-signals.html Demonstrates how to use the fill_missing_signals function to interpolate missing data in signal files. Ensure 'raw' and 'filled' paths are correctly defined using EMGFlow.make_paths(). ```python # Fill missing values in all data from the 'raw' path, and put the output in # the 'filled' path. path_names = EMGFlow.make_paths() EMGFlow.fill_missing_signals(path_names['raw'], path_names['filled']) ``` -------------------------------- ### Calculate WL feature Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/extract-features.html Usage example for calculating the Waveform Length of a specific signal column. ```python # Calculate the WL of Signal, for column 'EMG_zyg' WL = EMGFlow.calc_wl(Signal, 'EMG_zyg') ``` -------------------------------- ### Calculate MNF feature Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/extract-features.html Usage example for calculating the Mean Frequency from a PSD object. ```python # Calculate the MNF of Signal, for column 'EMG_zyg' psd = EMGFlow.emg_to_psd(Signal['EMG_zyg'], 2000) MNF = EMGFlow.calc_mnf(psd) ``` -------------------------------- ### Read CSV File with EMGFlow Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/access-files.html Example of reading a CSV file using the `read_file_type` function from the EMGFlow package. Ensure the file path and extension are correctly specified. ```python # Read a csv file path = '/Data/1_raw/01/sample_data_01.csv' ext = 'csv' df = EMGFlow.read_file_type(path, ext) ``` -------------------------------- ### Calculating Average Power (AP) Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/extract-features.html Function signature and usage example for calculating the Average Power of a signal column. ```python def calc_ap(Signal:pd.DataFrame, column_name:str) ``` ```python # Calculate the AP of Signal, for column 'EMG_zyg' AP = EMGFlow.calc_ap(Signal, 'EMG_zyg') ``` -------------------------------- ### Screen Artefacts in Signal Data Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/preprocess-signals.html Use this example to screen artifacts in all data from a 'raw' path and direct the output to a 'screened' path, specifying a sampling rate of 2000 Hz. ```python # Screen artefacts in all data from the 'raw' path, and put the output in the # 'screened' path. path_names = EMGFlow.make_paths() EMGFlow.screen_artefact_signals(path_names['raw'], path_names['screened'], sampling_rate=2000) ``` -------------------------------- ### Calculating Integrated EMG (IEMG) Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/extract-features.html Function signature and usage example for calculating the Integrated EMG, which accounts for the sampling rate. ```python def calc_iemg(Signal:pd.DataFrame, column_name:str, sampling_rate:float) ``` ```python # Calculate the IEMG of Signal, for column 'EMG_zyg' IEMG = EMGFlow.calc_iemg(Signal, 'EMG_zyg', 2000) ``` -------------------------------- ### Example Usage of rectify_signals Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/preprocess-signals.html Rectifies all data from a 'raw' path and saves the output to an 'fwr' path. Assumes the existence of a make_paths function to generate path names. ```python # Rectify all data from the 'raw' path, and put the output in the 'fwr' path. pathNames = EMGFlow.make_paths() EMGFlow.rectify_signals(pathNames['raw'], pathNames['fwr']) ``` -------------------------------- ### Apply bandpass filtering to signal files Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/preprocess-signals.html Example usage of bandpass_filter_signals to process EMG data files with custom sampling rates and frequency edges. ```python path_names = EMGFlow.make_paths() EMGFlow.make_sample_data(path_names) column_names = ['EMG_zyg', 'EMG_cor'] sampling_rate = 2000 passband_edges = (20, 200) # Apply bandpass filters of below 20Hz and above 200Hz to the files in the # 'notch' path, and write the output to the 'bandpass' path. EMGFlow.bandpass_filter_signals(path_names['notch'], path_names['bandpass'], column_names, sampling_rate, passband_edges) ``` -------------------------------- ### Calculate PSD from EMG Signal Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/preprocess-signals.html Example of how to use the emg_to_psd function to calculate the Power Spectrum Density (PSD) from an EMG signal. Ensure the 'Signal' DataFrame and 'column_name' are defined, and specify the 'sampling_rate'. ```python column_name = 'EMG_zyg' sampling_rate = 2000 PSD = EMGFlow.emg_to_psd(Signal, column_name, sampling_rate) ``` -------------------------------- ### Custom Data Paths Configuration in Python Source: https://wiiison.github.io/EMGFlow-Python-Package/guide/examples.html Demonstrates constructing a custom path dictionary and using the high-level clean_signals method. ```python import os import EMGFlow as ef # Create sample data with custom raw location path_names = ef.make_paths(raw='workspace/sample_data_raw') ef.make_sample_data(path_names) # Preprocess signals ef.clean_signals(path_names, sampling_rate=2000, do_fill=False, do_smooth=False, notch_f0=50) # Plot data on the "EMG_zyg" column ef.plot_dashboard(path_names, 'EMG_zyg', 'mV') # Extract features and save results in "Features.csv" df = ef.extract_features(path_names, sampling_rate=2000) ``` -------------------------------- ### Individual File Preprocessing in Python Source: https://wiiison.github.io/EMGFlow-Python-Package/guide/examples.html Shows how to preprocess EMG data by loading a pandas DataFrame directly. ```python import EMGFlow import os import pandas as pd import numpy as np # Get path dictionary path_names = EMGFlow.make_paths() # Load sample data EMGFlow.make_sample_data(path_names) # Load dataframe from generated data root = os.getcwd() sample_data = pd.read_csv(os.path.join(root, 'Data', '1_raw', '01', 'sample_data_01.csv')) # Sampling rate sampling_rate = 2000 # Custom filter parameters notch_vals = [(50, 5)] passband_edges = (20, 140) smooth_window = 50 # Columns containing data for preprocessing column_names = ['EMG_zyg', 'EMG_cor'] # Preprocess first column of signals ('EMG_zyg') sample_data = EMGFlow.apply_notch_filters(sample_data, column_names[0], sampling_rate, notch_vals) sample_data = EMGFlow.apply_bandpass_filter(sample_data, column_names[0], sampling_rate, passband_edges) sample_data = EMGFlow.apply_rectify(sample_data, column_names[0]) # Preprocess second column of signals ('EMG_cor') sample_data = EMGFlow.apply_notch_filters(sample_data, column_names[1], sampling_rate, notch_vals) sample_data = EMGFlow.apply_bandpass_filter(sample_data, column_names[1], sampling_rate, passband_edges) sample_data = EMGFlow.apply_rectify(sample_data, column_names[1]) ``` -------------------------------- ### Process sEMG signals with EMGFlow Source: https://wiiison.github.io/EMGFlow-Python-Package/guide/getting-started.html This workflow demonstrates loading sample data, cleaning signals, visualizing a dashboard, and extracting features. ```python import EMGFlow as ef # Get path dictionary path_names = ef.make_paths() # Load sample data ef.make_sample_data(path_names) # Preprocess signals (sample data recorded at 50 Hz mains) 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', 'mV') # Extract features to disk "Features.csv" df = ef.extract_features(path_names, sampling_rate=2000) ``` -------------------------------- ### Standard Preprocessing Workflow in Python Source: https://wiiison.github.io/EMGFlow-Python-Package/guide/examples.html Outlines the full pipeline for EMG preprocessing and feature extraction using manual parameter selection. ```python import EMGFlow # Get path dictionary path_names = EMGFlow.make_paths() # Load sample data EMGFlow.make_sample_data(path_names) # Sampling rate sampling_rate = 2000 # Notch filter for mains hum (Hz, Q-score) notch_main = [(50, 5)] # Passband edges (low, high) passband_edges = [20, 450] # Columns containing data for preprocessing column_names = ['EMG_zyg', 'EMG_cor'] # 1. Apply notch filters EMGFlow.notch_filter_signals(path_names['raw'], path_names['notch'], column_names, sampling_rate, notch_main) # 2. Apply bandpass filter EMGFlow.bandpass_filter_signals(path_names['notch'], path_names['bandpass'], column_names, sampling_rate, passband_edges) # 3. Apply full wave rectifier EMGFlow.rectify_signals(path_names['bandpass'], path_names['fwr']) # 4. Apply artefact screening EMGFlow.screen_artefact_signals(path_names['fwr'], path_names['screened'], column_names, sampling_rate) # 5. Fill missing data EMGFlow.fill_missing_signals(path_names['screened'], path_names['filled'], column_names, sampling_rate) # 6. Apply smoothing filter EMGFlow.smooth_signals(path_names['filled'], path_names['smoothed'], column_names, sampling_rate) # 7. Extract features df = EMGFlow.extract_features(path_names, column_names, sampling_rate) ``` -------------------------------- ### Create EMG Workflow File Structure Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/access-files.html Generates a standard directory structure for EMG processing and returns a dictionary of file paths. Use when initializing a new EMG project. ```python path_names = EMGFlow.make_paths() ``` -------------------------------- ### make_sample_data - Generate Sample Data Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/access-files.html Generates sample sEMG data within the 'raw' folder of a provided file location dictionary. ```APIDOC ## make_sample_data ### Description Generates sample data in the 'raw' folder of a provided dictionary of file locations. Creates '01' and '02' folders, which each contain two sample data files ('01/sample_data_01.csv', '01/sample_data_02.csv', '02/sample_data_03.csv', '02/sample_data_04.csv') The sample data will not be written if it already exists in the folder. ### Method `make_sample_data(path_names:dict)` ### Parameters #### Path Parameters - **path_names** (dict-str) - A dictionary of file locations with keys for stage in the processing pipeline. ### Raises An exception is raised if 'raw' is not a key of the `path_names` dictionary provided. An exception is raised if the sample data cannot be loaded. ### Returns None. ### Example ```python # Create file paths, then create sample data path_names = EMGFlow.make_paths() EMGFlow.make_sample_data(path_names) ``` ``` -------------------------------- ### EMG Signal Preprocessing and Feature Extraction Source: https://wiiison.github.io/EMGFlow-Python-Package/guide/examples.html This script demonstrates a complete workflow for preprocessing EMG signals using EMGFlow, including setting up paths, applying notch and bandpass filters, rectifying signals, and extracting various time-series and spectral features. Ensure all necessary libraries like pandas and tqdm are imported. ```python import EMGFlow import pandas as pd import os import tqdm # Get path dictionary path_names = EMGFlow.make_paths() # Load sample data EMGFlow.make_sample_data(path_names) # Sampling rate sampling_rate = 2000 # Custom filter parameters notch_vals = [(50, 5)] passband_edges = (20, 140) smooth_window = 50 # Columns containing data for preprocessing column_names = ['EMG_zyg', 'EMG_cor'] # Preprocess signals EMGFlow.notch_filter_signals(path_names['raw'], path_names['notch'], column_names, sampling_rate, notch_vals) EMGFlow.bandpass_filter_signals(path_names['notch'], path_names['bandpass'], column_names, sampling_rate, passband_edges) EMGFlow.rectify_signals(path_names['bandpass'], path_names['smoothed'], column_names) # Map locations of files to process file_dirs_b = EMGFlow.map_files(path_names['bandpass']) file_dirs_s = EMGFlow.map_files(path_names['smoothed']) # List of measures to extract measureNames = [ 'IEMG', 'MAV', 'MMAV1', 'Spec_Centroid', # ... put column names for additional features here ] # Construct columns for each combination of data file column and features df_names = ['File_ID'] for col in column_names: for measure in measureNames: df_names.append(col + '_' + measure) SignalDF = pd.DataFrame(columns=df_names) filetype = 'csv' # Extract features for file in tqdm.tqdm(file_dirs_b): if (file[-len(filetype):] == filetype): data_B = pd.read_csv(file_dirs_b[file]) data_S = pd.read_csv(file_dirs_s[file]) df_vals = [file] # Make sure to make the same calculations as in measure_names for col in column_names: IEMG = EMGFlow.calc_iemg(data_S, col, sampling_rate) MAV = EMGFlow.calc_mav(data_S, col) MMAV1 = EMGFlow.calc_mmav1(data_S, col) # ... calculate additional time-series features here psd = EMGFlow.emg_to_psd(data_B, col, sampling_rate) specCentroid = EMGFlow.calc_sc(psd) # ... calculate additional spectral features here # Create list of measures (should match measure_names) col_vals = [ IEMG, MAV, MMAV1, specCentroid, # ... put additional features here ] # Combine values into list df_vals = df_vals + col_vals # Append to data frame SignalDF.loc[len(SignalDF.index)] = df_vals # Save results in "Features.csv" file SignalDF.to_csv(os.path.join(path_names['feature'], 'Features.csv'), index=False) ``` -------------------------------- ### make_paths - Generate File Structure Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/access-files.html Generates a standard file structure for an EMG workflow and returns a dictionary of file locations. ```APIDOC ## make_paths ### Description Generates a file structure for an EMG workflow, and returns a dictionary of the locations for these files for easy use with EMG processing functions. Creates '1_raw', '2_notch', '3_bandpass', '4_fwr', '5_screened', '6_filled', '7_smoothed', and '8_feature' subfolders at a given location. If no path is given, will create a 'Data' folder in the current working directory, with these subfolders inside. ### Method `make_paths(root:str=None, raw:str=None)` ### Parameters #### Path Parameters - **root** (str) - Optional - The root where the data is generated. The default is None. - **raw** (str) - Optional - The path for the raw data. The default is None, in which case a default location is generated. ### Returns - **path_names** (dict-str) - A dictionary of file locations with keys for stage in the processing pipeline. ### Example ```python # Create folders and get locations path_names = EMGFlow.make_paths() ``` ``` -------------------------------- ### Generate Sample EMG Data Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/access-files.html Populates the 'raw' directory within a given file path structure with sample sEMG data files. Ensures sample data is available for testing or demonstration. ```python path_names = EMGFlow.make_paths() EMGFlow.make_sample_data(path_names) ``` -------------------------------- ### map_files - Map Files in a Directory Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/access-files.html Generates a dictionary of file names and their corresponding locations from the subfiles of a given directory. ```APIDOC ## map_files ### Description Generate a dictionary of file names and locations (keys/values) from the subfiles of a folder. ### Method `map_files(in_path:str, file_ext:str='csv', expression:str=None, base:str=None)` ### Parameters #### Path Parameters - **in_path** (str) - The filepath to a directory to read files. - **file_ext** (str) - Optional - The file extension for files to read. Only reads files with this extension. The default is 'csv'. - **expression** (str) - Optional - A regular expression. If provided, will only count files whose relative paths from 'base' match the regular expression. The default is None. - **base** (str) - Optional - The path of the root folder the path keys should start from. Used to track the relative path during recursion. The default is None. ### Raises An exception is raised if `expression` is not None or a valid regular expression. ### Returns - **file_dirs** (dict-str) - Returns dictionary of file name keys and file path location values. ### Example ```python # Map all csv files in 'data' folder and subfolders file_loc_1 = EMGFlow.map_files('data') # Map all csv files in 'data' folder that start with 'DATA', # or in folders that start with 'DATA' file_loc_2 = EMGFlow.map_files('data', expression='^DATA') ``` ``` -------------------------------- ### Define Notch Filter Parameters Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/preprocess-signals.html Defines the parameters for applying notch filters to signal data. Includes basic and special case configurations. ```python path_names = EMGFlow.make_paths() EMGFlow.make_sample_data(path_names) sampling_rate = 2000 notch_vals = [(50,5), (150,25)] # Special case parameters notch_vals_spec = [(317,25)] expression = "^(08|11)" column_names = ['EMG_zyg', 'EMG_cor'] ``` -------------------------------- ### Native Feature Extraction Routines in Python Source: https://wiiison.github.io/EMGFlow-Python-Package/guide/examples.html Initializes imports for custom feature extraction routines. ```python import EMGFlow import os import pandas as pd import tqdm ``` -------------------------------- ### package_version - Print Package Version Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/access-files.html Prints the current version of the EMGFlow package. ```APIDOC ## package_version ### Description Prints the package version. ### Method `package_version()` ### Parameters None. ### Returns None. ### Example ```python EMGFlow.package_version() ``` ``` -------------------------------- ### Print Package Version Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/access-files.html Outputs the current version of the EMGflow package. Useful for checking compatibility or reporting issues. ```python EMGFlow.package_version() ``` -------------------------------- ### Apply Notch Filters to Signals Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/preprocess-signals.html Applies a list of notch filters to signal files in a specified directory. Writes filtered files to an output directory, preserving the input folder structure. ```python # Apply notch_vals filters to all files in the 'raw' path, and write them to # the 'notch' path. EMGFlow.notch_filter_signals(path_names['raw'], path_names['notch'], column_names, sampling_rate, notch_vals) ``` ```python # Apply an additional special case filter to files in the '08' or '11' folder EMGFlow.notch_filter_signals(path_names['notch'], path_names['notch'], column_names, sampling_rate, notch_vals_spec, expression=expression) ``` -------------------------------- ### Map Files in a Directory Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/access-files.html Recursively scans a directory for files with a specified extension and returns a dictionary mapping filenames to their full paths. Useful for collecting datasets. ```python # Map all csv files in 'data' folder and subfolders file_loc_1 = EMGFlow.map_files('data') # Map all csv files in 'data' folder that start with 'DATA', # or in folders that start with 'DATA' file_loc_2 = EMGFlow.map_files('data', expression='^DATA') ``` -------------------------------- ### package_citation - Print Package Citation Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/access-files.html Prints the citation information for the EMGFlow package. ```APIDOC ## package_citation ### Description Prints citation information. ### Method `package_citation(pkg:str='emgflow')` ### Parameters #### Path Parameters - **pkg** (str) - Optional - The package to print citation information for. The default is 'emgflow' ### Returns None. ### Example ```python EMGFlow.package_citation() ``` ``` -------------------------------- ### Cite EMGFlow via BibTeX Source: https://wiiison.github.io/EMGFlow-Python-Package/about/citation.html Use this BibTeX entry to reference the EMGFlow software package in academic publications. ```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}" } ``` -------------------------------- ### Calculate Spectral Bandwidth (SBW) Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/extract-features.html Calculates the Spectral Bandwidth (SBW) from a Power Spectral Density (PSD) DataFrame. Ignores NaN values. The parameter 'p' adjusts the order of the SBW calculation, with a default of 2 for standard deviation around the centroid. ```python def calc_sbw(psd:pd.DataFrame, p:int=2) ``` ```python # Calculate the SBW of Signal, for column 'EMG_zyg' psd = EMGFlow.emg_to_psd(Signal['EMG_zyg'], 2000) SBW = EMGFlow.calc_sbw(psd) ``` -------------------------------- ### calc_sflx Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/extract-features.html Calculate the Spectral Flux (SFlx) from a signal and either a second signal or a split percentage. ```APIDOC ## calc_sflx ### Description Calculate the Spectral Flux (SFlx) from Signal1 and diff. Spectral Flux measures the change in spectrums between two signals, or two sections of a signal. ### Parameters #### Request Body - **Signal1** (pd.DataFrame) - Required - A Pandas dataframe containing a 'Time' column and signal data. - **diff** (pd.DataFrame, float) - Required - The divisor of the calculation. If a float, it splits Signal1 into two parts. If a dataframe, it calculates flux between Signal1 and diff. - **column_name** (str) - Required - The column of Signal1 to calculate from. - **sampling_rate** (int/float) - Optional (1000.0) - The sampling rate of Signal1. - **diff_sr** (int/float) - Optional (None) - The sampling rate for diff if it is a dataframe. ### Response #### Success Response (200) - **flux** (float) - The Spectral Flux of Signal1 and diff. ``` -------------------------------- ### Print Package Citation Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/access-files.html Displays the citation information for the EMGflow package. Call this function to properly cite the software in publications. ```python EMGFlow.package_citation() ``` -------------------------------- ### Generate Shiny Dashboard for Signal Data Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/plot-signals.html Generates a Shiny dashboard to visualize different processing stages of signal data. Use this function to interactively explore raw signals or Power Spectrum Density plots for a specified column. It requires a filepath dictionary created by `make_paths`. ```python def plot_dashboard(path_names:dict, column_name:str, sampling_rate:float=1000.0, units:str='mV', file_ext:str='csv', use_mask:bool=False, show_legend:bool=True, auto_run:bool=True) ``` ```python # Create a plot of each stage path_names = EMGFlow.make_paths() EMGFlow.make_sample_data(path_names) EMGFlow.clean_signals(path_names, sampling_rate=2000) column_name = 'EMG_zyg' units = 'mV' EMGFlow.plot_dashboard(path_names, column_name, units) ``` -------------------------------- ### Define calc_wamp function Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/extract-features.html Function signature for calculating the Willison Amplitude from a signal column. ```python def calc_wamp(Signal:pd.DataFrame, column_name:str, threshold:float) ``` -------------------------------- ### calc_wamp Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/extract-features.html Calculates the Willison Amplitude (WAMP) from a signal column, measuring the number of times amplitude exceeds a threshold. ```APIDOC ## calc_wamp ### Description Calculate the Willison Amplitude (WAMP) from a column of Signal. Ignores NaNs. ### Parameters #### Request Body - **Signal** (pd.DataFrame) - Required - A Pandas dataframe containing a 'Time' column, and additional columns for signal data. - **column_name** (str) - Required - The column of Signal the feature is calculated from. - **threshold** (float) - Required - Threshold of the WAMP. ### Response - **WAMP** (int) - The calculated WAMP. ### Request Example EMGFlow.calc_wamp(Signal, 'EMG_zyg', 55) ``` -------------------------------- ### fill_missing_signals Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/preprocess-signals.html Applies an interpolation method to signal files in a folder, writing interpolated files to an output folder while maintaining the input structure. ```APIDOC ## fill_missing_signals ### Description Apply an interpolation method ('method') to all signal files in a folder. Writes interpolated signal files to an output folder, and generates a file structure matching the input structure. ### Method Python Function ### Endpoint N/A (Python Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **in_path** (str) - Required - Filepath to a directory to read signal files. - **out_path** (str) - Required - Filepath to a directory to write filtered signals. - **column_names** (list-str) - Optional (None) - List of columns of the signals to apply the interpolation to. The default is None, in which case the interpolation is applied to every column except for 'Time' and columns that start with 'mask_'. - **sampling_rate** (float) - Optional (1000.0) - The sampling rate of the signal files. The default is 1000.0. - **method** (str) - Optional ('pchip') - The interpolation method to use. Valid methods are 'pchip' and 'spline'. The default is 'pchip'. - **max_segment** (float) - Optional (500.0) - The maximum length (in ms) of NaN values to fill. If a length of invalid data is longer than this threshold, it will not be interpolated. The default is 500.0. - **expression** (str) - Optional (None) - A regular expression. If provided, will only apply the interpolation to files whose local paths inside of `in_path` match the regular expression. The default is None. - **copy_unmatched** (bool) - Optional (False) - If True, copies files that don't match the regular expression to the output folder without interpolating. The default is False, which ignores files that don't match. - **file_ext** (str) - Optional ('csv') - The file extension for files to read. Only interpolates files with this extension. The default is 'csv'. ### Raises A warning is raised if no files in `in_path` match with `expression`. An exception is raised if `expression` is not None or a valid regular expression. An exception is raised if a column from `column_names` is not a column of a signal file. An exception is raised if 'Time' is in `column_names`. An exception is raised if 'Time' is not a column of a signal file. An exception is raised if `sampling_rate` is less than or equal to 0. An exception is raised if `max_segment` results in a gap size less than or equal to 0. An exception is raised if `method` is an invalid interpolation method. An exception is raised if there aren't enough valid points to perform interpolation on a signal file. An exception is raised if a file could not be read. An exception is raised if an unsupported file format was provided for `file_ext`. ### Returns None. ### Example ```python # Fill missing values in all data from the 'raw' path, and put the output in # the 'filled' path. path_names = EMGFlow.make_paths() EMGFlow.fill_missing_signals(path_names["raw"], path_names["filled"]) ``` ``` -------------------------------- ### Conditional Filtering for Individual Files in Python Source: https://wiiison.github.io/EMGFlow-Python-Package/guide/examples.html Applies specific filter parameters based on file name patterns using regex expressions. ```python import EMGFlow # Get path dictionary path_names = EMGFlow.make_paths() # Load sample data EMGFlow.make_sample_data(path_names) # Sampling rate sampling_rate = 2000 # Filter parameters for all files notch_vals = [(50, 5)] passband_edges = (20, 140) smooth_window = 50 # Filter parameters for the "sample_data_01.csv" file notch_vals_s = [(45, 1), (60, 5)] expression = '^01' # Columns containing data for preprocessing column_names = ['EMG_zyg', 'EMG_cor'] # Preprocess signals EMGFlow.notch_filter_signals(path_names['raw'], path_names['notch'], column_names, sampling_rate, notch_vals) EMGFlow.notch_filter_signals(path_names['notch'], path_names['notch'], column_names, sampling_rate, notch_vals_s, expression=expression) EMGFlow.bandpass_filter_signals(path_names['notch'], path_names['bandpass'], column_names, sampling_rate, passband_edges) EMGFlow.rectify_signals(path_names['bandpass'], path_names['fwr'], column_names) # Extract features df = EMGFlow.extract_features(path_names, column_names, sampling_rate) ``` -------------------------------- ### rectify_signals Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/preprocess-signals.html Applies a Full Wave Rectifier to signal files in a directory and saves the output to a specified path. ```APIDOC ## rectify_signals ### Description Apply a Full Wave Rectifier (FWR) to all signal files in a folder and its subfolders. Writes filtered signal files to an output folder, and generates a file structure matching the input folder. ### Parameters - **in_path** (str) - Required - Filepath to a directory to read signal files. - **out_path** (str) - Required - Filepath to a directory to write filtered signals. - **column_names** (list-str) - Optional - List of columns of the signals to apply the filter to. Defaults to None (all columns except 'Time' and 'mask_'). - **expression** (str) - Optional - A regular expression to filter files by local path. Defaults to None. - **copy_unmatched** (bool) - Optional - If True, copies files that don't match the expression to the output folder. Defaults to False. - **file_ext** (str) - Optional - The file extension for files to read. Defaults to 'csv'. ### Returns - None ### Example ```python # Rectify all data from the 'raw' path, and put the output in the 'fwr' path. pathNames = EMGFlow.make_paths() EMGFlow.rectify_signals(pathNames['raw'], pathNames['fwr']) ``` ``` -------------------------------- ### calc_mdf Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/extract-features.html Calculates the Median Frequency (MDF) from a power spectral density dataframe. ```APIDOC ## calc_mdf ### Description Calculate the Median Frequency (MDF) from psd. Ignores NaNs. ### Parameters #### Request Body - **psd** (pd.DataFrame) - Required - A Pandas dataframe containing a 'Frequency' and 'Power' column. ### Response - **med_freq** (float) - The MDF of psd. ### Request Example psd = EMGFlow.emg_to_psd(Signal['EMG_zyg'], 2000) MDF = EMGFlow.calc_mdf(psd) ``` -------------------------------- ### plot_dashboard Function Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/plot-signals.html Generates a Shiny dashboard for visualizing signal data processing stages. ```APIDOC ## plot_dashboard Function ### Description Generate a Shiny dashboard of different processing stages for a given column of signal data. Uses a `path_names` filepath dictionary. Has a side bar menu to navigate the file and stage being displayed. There is an option to view the data as raw signals, or as a Power Spectrum Density plot. The function ignores the 'feature' filepath. The remaining filepaths are tested for files, and included if found. ### Method ```python def plot_dashboard(path_names:dict, column_name:str, sampling_rate:float=1000.0, units:str='mV', file_ext:str='csv', use_mask:bool=False, show_legend:bool=True, auto_run:bool=True) ``` ### Parameters #### Path Parameters - **path_names** (dict-str) - Required - A dictionary of file locations with keys for stage in the processing pipeline. The function will generate graphs for as many paths are provided in the dictionary. The dictionary can be created with the 'make_paths' function. - **column_name** (str) - Required - The column of the signals to display in the visualization. #### Query Parameters - **sampling_rate** (float) - Optional (default: 1000.0) - The sampling rate for all signal data being plotted. - **units** (str) - Optional (default: 'mV') - Units to use for the y axis of the plot, should be the same units used for the values in 'column_name'. - **file_ext** (str) - Optional (default: 'csv') - File extension for files to read. Only visualizes files with this extension. - **use_mask** (bool) - Optional (default: False) - An option to visualize the NaN mask. If True, it will set values to NaN based on the NaN mask. If False, it will use the unaltered values of the column ignoring the NaN mask. - **show_legend** (bool) - Optional (default: True) - An option to show the legend on the plot. If True, it will show the legend. If False, the legend will be hidden. - **auto_run** (bool) - Optional (default: True) - An option to automatically see the visualization. If True, it will run the visual and open it in the default browser. If False, it will return the visualization object. ### Raises - An exception is raised if `column_name` is not a column of a signal file. - An exception is raised if a file contained in the first file directory (`path_names[0]`) is not found in the other file directories. - An exception is raised if a file could not be read. - An exception is raised if an unsupported file format was provided for `file_ext`. ### Returns - **app** (None or shiny.app) - If `auto_run` is True, returns None. If False, returns a shiny.App instance. ### Request Example ```python # Create a plot of each stage path_names = EMGFlow.make_paths() EMGFlow.make_sample_data(path_names) EMGFlow.clean_signals(path_names, sampling_rate=2000) column_name = 'EMG_zyg' units = 'mV' EMGFlow.plot_dashboard(path_names, column_name, units) ``` ``` -------------------------------- ### calc_sbw Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/extract-features.html Calculate the Spectral Bandwidth (SBW) from a PSD dataframe. ```APIDOC ## calc_sbw ### Description Calculate the Spectral Bandwidth (SBW) from `psd`. Ignores NaNs. The SBW calculates the difference between the upper and lower frequencies in the frequency band. ### Parameters #### Request Body - **psd** (pd.DataFrame) - Required - A Pandas dataframe containing a 'Frequency' and 'Power' column. The 'Power' column should be normalized. - **p** (int) - Optional (default: 2) - Order of the SBW. ### Response #### Success Response (200) - **SBW** (float) - The SBW of `psd`. ``` -------------------------------- ### Calculate SSI Feature Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/extract-features.html Computes the Simple Square Integral of a signal column, accounting for sampling rate. Raises an exception if sampling_rate is non-positive. ```python def calc_ssi(Signal:pd.DataFrame, column_name:str, sampling_rate:float=1000.0) ``` ```python # Calculate the SSI of Signal, for column 'EMG_zyg' SSI = EMGFlow.calc_ssi(Signal, 'EMG_zyg', 2000) ``` -------------------------------- ### Define calc_mdf function Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/extract-features.html Function signature for calculating the Median Frequency from a power spectral density dataframe. ```python def calc_mdf(psd:pd.DataFrame) ``` -------------------------------- ### Define smooth_signals function signature Source: https://wiiison.github.io/EMGFlow-Python-Package/reference/preprocess-signals.html Defines the function signature for smoothing signal files. It takes input and output paths, with optional parameters for column names, sampling rate, smoothing method, window size, and more. ```python def smooth_signals(in_path:str, out_path:str, column_names=None, sampling_rate:float=1000.0, method:str='rms', window_ms:float=50.0, sigma:float=1.0, min_segment:float=30.0, expression:str=None, copy_unmatched:bool=False, file_ext:str='csv') ```