> For the complete documentation index, see [llms.txt](https://help.imotions.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://help.imotions.com/lab/analysis/biosensor-analysis/r-notebook-emg-processing.md).

# R Notebook: EMG Processing

Run the EMG R notebook to filter, smooth and normalize EMG signals, then compute AUC, average activity and muscle contraction events per stimulus.

The **EMG R-notebook** runs a complete signal processing protocol for filtering and smoothing raw EMG data. The notebook subsequently allows the normalization of a smoothed signal to maximum voluntary contraction stimuli. You can automatically compute the area under the curve (AUC) and average EMG activity, for comparing EMG activity across people or conditions. You can also define threshold criteria to count and measure contraction events. This notebook can be used on data from Shimmer, BIOPAC, BIOPAC Bionomadix and devices that support lab streaming layer (LSL) such as Biosignals Plux.

You can find more information about EMG signal processing here: [EMG Study Design: Normalization](https://help.imotions.com/lab/sensor-setup/shimmer/emg-study-design-normalization.md)

## Prerequisites

Supported stimulus types: All

Supported sensors: Shimmer EMG, Biopac MP150 and MP160 (EMG100C), Biopac Bionomadix, and lab streaming layer (LSL) compatible devices such as Biosignals Plux.

## How to Analyze in iMotions Desktop

To run the **EMG R Notebook**, the following steps need to be followed:

1\. Create a new analysis for the study for which you wish to run the EMG R-Notebook:

![1.png](https://286068319-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNLNBWkNpljDaAj5rQtNa%2Fuploads%2Fgit-blob-8e5e5f3dc60424e150905ba955ee99b8296c0c57%2Fed278d0b15_1-7-.png?alt=media)

2\. Advance through the steps "Segmentation settings" with your preferred selections and "Segmentation criteria" until you reach the step "Signal processing".

![22.png](https://286068319-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNLNBWkNpljDaAj5rQtNa%2Fuploads%2Fgit-blob-64e970cd42490f0b1fd7302a162f3a77b90adc0f%2Fb729e619ef_22-1-.webp?alt=media)

3.By clicking "+" next to "Active flows" you can select the algorithms you want to use for signal processing. Select the sensor for which you want to apply the EMG R-Notebook in the drop-down "Device" menu. Select "EMG Processing" in the drop-down “Algorithm” menu.

***Note***: you can run the notebook on multiple sensors of the same kind. E.g., you can run the notebook on two Shimmer devices here by adding two Active flows, choosing each Shimmer via the "Devices" field.

![](https://286068319-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNLNBWkNpljDaAj5rQtNa%2Fuploads%2Fgit-blob-23d4ff7d214610462db26c499f41f3d77cf38ee7%2F208ff86fe7_EMG-add-an-active-flow.webp?alt=media)

4\. Name the analysis in the "Flow name" menu. Alter the parameters to suit your research needs, then click on “Next”. The parameters will be described in detail in the next section of this article below: Algorithm Introduction. Click the "Next" button to continue.

![](https://286068319-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNLNBWkNpljDaAj5rQtNa%2Fuploads%2Fgit-blob-f166a80ae62f5afa024f50d32b0e84ae9d6c829a%2F2d9290feb0_image-1694708581477.webp?alt=media)

5\. Select the stimulus to be included in the analysis. Then click the "Add" button to add the analysis and close the dialog.

![mceclip1.png](https://286068319-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNLNBWkNpljDaAj5rQtNa%2Fuploads%2Fgit-blob-805bb3c6f9da6ce3cfeb0790116effdf58ef5e7a%2F012c6b3f8c_92kfvegkhuqwekamh8l1vw.webp?alt=media)

## Algorithm Introduction

Surface EMG signals are an aggregate of the individual action potentials coming from the motor units within a muscle. Raw EMG has the following characteristics:

* **Bipolar:** Because raw EMG has both negative and positive components, if you simply took the average of the raw EMG signal to determine amplitude, the signal would average out to zero.
* **Oscillatory:** Raw EMG consists of the aggregation of many neurons firing at different frequencies. This results in a "spiky" signal that is very difficult to quantify on its own.
* **Prone to noise:** EMG can range in frequencies from 10-500Hz, and can range in amplitude from a few microvolts for facial muscles to several millivolts for large muscles. The required sensitivity of EMG electrodes to pick up these signals means that there often are sources of noise (electrical, environmental, mechanical, etc) that contaminate the signal.

Therefore, EMG data requires some filtering and post-processing to remove sources of electrical noise and obtain useful metrics like EMG amplitude (Fridlund & Cacioppo, 1986). It is **very difficult** to get anything useful out of raw EMG data without some kind of filtering.

### (1) Signal Processing

1. **\[Name of the first EMG Signal (EMG 1)]**: Defines the channel of the first EMG signal. If there is only one channel of EMG recorded, you can leave this blank. If you use more than one EMG channel, please specify the name of the channel you want to use. For example, Shimmer EMG channels are named "EMG CH1 CAL" and "EMG CH2 CAL". If you use a different brand, you can always find the specific channel name in the EMG section in the individual replay as the picture below shows (the example below is for Shimmer but it applies similarly to other brands):
2. ![EMG HC article.png](https://286068319-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNLNBWkNpljDaAj5rQtNa%2Fuploads%2Fgit-blob-933ed5b0c4e6cfda686d5fff1abd4fa663d2a85a%2F904865463c_EMG-HC-article.webp?alt=media)
3. **\[Use a second EMG channel?]**: If recording two muscles, check off this option.
4. **\[Name of the second EMG Signal (EMG 2)]:** If recording one muscle, leave this field blank. If recording two muscles (relevant only with Shimmer devices), you can define which channels are designated Channel 1 and Channel 2. If still left blank, iMotions will autodetect and designate these for you.
5. **\[Bandpass filter: Low cutoff frequency \[Hz]:** EMG frequencies tend to fall between 10-500Hz, with the majority of frequencies falling below 300Hz. The distribution of these frequencies can depend on the muscle being studied. Extraneous frequencies (from amplifiers, etc) must be filtered out, but not without compromising signal quality. A zero-phase-lag [Butterworth](https://en.wikipedia.org/wiki/Butterworth_filter) band-pass filter with a total order of 4 is applied to isolate frequency bands specific to EMG. The high-pass filter is set to 20Hz by default, based on recommendations for facial muscles including corrugator and zygomaticus (van Boxtel, 2001). The low-pass cutoff is automatically calculated as half of the sampling rate in accordance with Nyquist theorem.
6. **\[Notch filtering?]:** A fourth-order, zero-phase-lag bandstop butterworth filter can be applied to remove line noise from the surrounding environment (Lajante et al., 2017). Line noise is at the frequency of the local mains electricity: 60 Hz in most of the Americas, South Korea, Taiwan, Saudi Arabia and western Japan, and 50 Hz in most of the rest of the world, including all countries in the European Union, Argentina, Chile and eastern Japan. Check the mains frequency where the data was recorded.
7. The signal is then full-wave rectified (Lajante et al, 2017). Given the bipolar nature of raw EMG, the signal must be rectified in order to study its absolute value.
8. **\[Method used for smoothing]:** Following rectification, smoothing and linear envelopes are used to remove high-frequency components and look at the general shape of muscle activation. The shorter the expected expression (i.e. microexpressions), the higher the threshold frequency has to be, but the higher you go the greater the risk of introducing noise. You will be able to choose from two different smoothing options.
   1. **Lowpass filter**: The EMG signal is smoothed using a fourth-order, zero-phase-lag low-pass filter to isolate the linear envelope of the signal.
      1. Cutoff frequency for low-pass filter \[Hz]: While the default cutoff frequency is 10 Hz, you can modify this value to meet your research goals.
   2. **Root mean square:** *It is another procedure to obtain the EMG linear envelope.* The root mean square (RMS) is calculated for the rectified data (Farfán, Politti, and Felice 2010). The two parameters are:
      1. Window length for RMS smoothing \[ms]: The recommended size of this sliding window is between 120ms to 300ms (Farfán, Politti, and Felice 2010), hence the default value is set to 150ms.
      2. Window overlap percentage for RMS smoothing \[%]: The percentage of window overlap has no standard value as some use 0% (no overlapping) and others use x% where 0 < x < 100 (some overlapping) (Stegeman and Hermens 1998). The default value is set to 10%.

### (2) Contraction Threshold

In this part of the notebook, you can define a threshold to determine periods of contraction, which can be represented in the replay and marker data. This method is also explained in detail in a video below.

1. **\[Method used to define the contraction threshold for EMG signal]:** Defines the criteria used to count muscle contractions. There are two options:
   1. Standard Deviation: Uses a defined threshold based on the standard deviation of the smoothed EMG signal. Please note that the SD is calculated on the entirety of the smoothed EMG signal, and not on a separate baseline stimulus. Choose this option if you have no intention of normalizing your data (See 3, Optional Normalization, below). The default value is 1.5x standard deviation, but this threshold value can be modified.

      ![](https://286068319-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNLNBWkNpljDaAj5rQtNa%2Fuploads%2Fgit-blob-5e1a10ab556ca3c0652e90d1671ba2b10d7fdb1d%2F548bb3e0fe_sd.webp?alt=media)
   2. MVC Percentage: Uses a defined threshold based on a percentage of maximum voluntary contraction (MVC), run on normalized EMG data. This method can only be used if you have MVC stimuli in your study for the purposes of normalizing your data (see 3, Optional Normalization, below). The default value is 20% MVC, but this threshold should be modified depending on the specific muscles and tasks you are doing.

      ![](https://286068319-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNLNBWkNpljDaAj5rQtNa%2Fuploads%2Fgit-blob-2d88a73a9414e2670d7f707b1add418841e226a3%2F49912c18fb_image-1694709126682.webp?alt=media)
2. **\[Minimum contraction duration (ms)]:** Determines a minimum contraction duration to avoid any false positives due to noisy signal. By default, any detected contractions less than 50ms of duration are discarded from the analysis.

### (3) Optional Normalization

If you are interested in comparing EMG amplitude across groups or conditions, normalization is a necessary step in that it allows for the standardization of EMG activity across different days, or in different individuals, or to compare EMG activity between muscles. (Halaki & Ginn, 2012). The most common method of normalizing EMG signals is to compare the signal to the signal generated by a maximal voluntary contraction (MVC). For facial EMG, MVC tests can include making big smiles (zygomaticus) or intentionally furrowing your brow (corrugator) as hard as you can. Given the variability of raw EMG signals, academic standards recommend at least 3 max trials per muscle, with 100% MVC calculated from the average peak of each of these three trials (Halaki & Ginn, 2012).

The current EMG notebook allows for the averaging of **two** max trials. These trials **must** be set up as separate stimuli within iMotions.

1. **\[Normalize signal?]**: Check this box off to enable Normalization.
2. **\[Name of the 1st Maximum Voluntary Contraction stimulus (EMG1)] (Mandatory if enabled):** Input the name of the first stimulus to be used as an MVC trial for the muscle designated as Channel 1.
3. **\[Name of the 2nd Maximum Voluntary Contraction stimulus (EMG1)] (Optional):** Input the name of the second stimulus to be used as an MVC trial for the muscle designated as Channel 1, if applicable.
4. **\[Name of the 1st Maximum Voluntary Contraction stimulus (EMG2)] (Mandatory if second channel present and normalization is enabled):** If measuring two muscles, input the name of the first stimulus to be used as an MVC trial for the muscle designated as Channel 2.
5. **\[Name of the 2nd Maximum Voluntary Contraction stimulus (EMG2)] (Optional):** If measuring two muscles, input the name of the second stimulus to be used as an MVC trial for the muscle designated as Channel 2, if applicable.

If Normalization is enabled, stimuli that have been labeled as MVC will be filtered and smoothed, and the peak of the signal will be extracted. These peak values are averaged together to establish a value representing 100% MVC per channel per respondent.

Filtered and smoothed data for each stimulus are divided by the 100% MVC value for that respondent and multiplied by 100, generating a new normalized dataset expressed as a percentage of MVC. Because 100% is the average of the MVC peaks, values above 100% are possible.

## The Outputs

#### (1) Desktop replay:

In the individual replays of data, the calculated signals are displayed as follows.

**EMG Processing:**

* **\[Smoothed Signal]**: The smoothed EMG as a product of the Signal Processing algorithms. Units are in mV.
* **\[Normalized Signal] (optional):** Normalized graphs will appear if the Normalization function has been enabled. Units are %MVC, where 100 is the maximum voluntary contraction. Values above 100 are possible.
* **\[Contraction Detection]**: Binarized representation of the EMG data based on whether the signal exceeded the defined threshold.
* **\[Contraction Occurrences]**: Binarized representation of EMG contraction events, timelocked to the peak of the contraction.

  You will also find the following EMG metrics for both smoothed and, if applicable, normalized data:
* **\[Average smoothed]**: Averaged EMG activity of the smoothed EMG signal. Units are in mV.
* **\[AUC smoothed]**: Area under the curve of the smoothed EMG signal. Units are in mV\*s.
* **\[Average normalized] (optional)**: Averaged EMG activity of the normalized EMG signal. Units are in % of MVC.
* **\[AUC normalized] (optional):** Area under the curve of the normalized EMG signal. Units are in % of MVC × s.
* **\[Contraction count]**: The number of contraction events as calculated from the chosen contraction detection threshold.
* **\[Contractions per minute]**: The number of contraction events per minute.
* **\[Average contraction amplitude]**: Averaged EMG activity of EMG contractions. Units are in mV.
* **\[Average AUC contraction]**: Averaged area under the curve of EMG contractions. Units are in mV\*s.

In addition, the contraction detection feature also produces [event markers](https://help.imotions.com/lab/analysis/signal-processing-r-notebooks/my-library/respondent-replay.md) for the following:

* **Contraction Onset**
* **Contraction Offset**
* **Peak**

These can be viewed in the "Markers" panel and toggled in the "Markers" menu on the left.

![](https://286068319-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNLNBWkNpljDaAj5rQtNa%2Fuploads%2Fgit-blob-1e6f4501c95c8a0e83ac275258685bb94b8d06f1%2F5f41661767_Screenshot-2023-09-19-105857.webp?alt=media)

#### (2) Exported files:

**There are two types of files you can access: Sensor Data file and files from R processing called internally Summary exports.**

* **Sensor Data file:** raw sensor data export. Can also include R-processed signals by ticking "Processed and imported data". To obtain these exports, follow the instructions in the next 2 figures:

![](https://286068319-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNLNBWkNpljDaAj5rQtNa%2Fuploads%2Fgit-blob-595e78bdd0a2f5f9bc318740ae4b32e5285ce8a6%2Fbe2a8aa658_Sensor-exports-A.webp?alt=media)

![](https://286068319-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNLNBWkNpljDaAj5rQtNa%2Fuploads%2Fgit-blob-a0b137c0f636c9c15cd47b5e95e89917792b744c%2Fe677a202fc_Sensor-exports-B.webp?alt=media)

As a result of those steps, you will obtain a csv file with the raw EMG signals along with the smoothed and, if applicable, normalized EMG time series signals.

* **Summary export file:** To obtain the EMG metrics (average EMG data, area under the curve, and contraction-related metrics: contraction count, contractions per minute, average peak amplitude, average area under the curve of contractions), click on R PROCESSING, select either "Individual metrics exports" or, particularly useful when you use more than one type of sensor, "Single multi-modal export". Then, select the "EMG Metrics Export" button on the image below to finally export the results by clicking on the "Export individual files". As a result of that last step, you will be prompted to select a folder where you would like to store the results.

  ![](https://286068319-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNLNBWkNpljDaAj5rQtNa%2Fuploads%2Fgit-blob-5f608b0e8a823be7cf773bd137012594f2f0050a%2F1eed297e2f_Exporting-EMG-metrics-out-of-iMotions-1-.webp?alt=media)

  Finally, when opening the Summary export file for example in Microsoft Excel or other relevant software, you will visualize every respondent's EMG metrics. A brief description of the Summary export is shown as follows.

  ![](https://286068319-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNLNBWkNpljDaAj5rQtNa%2Fuploads%2Fgit-blob-330974cfea814f5b51e1bcf41c5ac758afac64e9%2Fc4e7a6e017_EMGMetrics-exports.webp?alt=media)

  There is also a separate export entitled "EMG Contraction Table" that can give you information on each individual contraction as detected from the threshold criteria:

  ![](https://286068319-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNLNBWkNpljDaAj5rQtNa%2Fuploads%2Fgit-blob-adb92e3034d0a75566d82487e11282fa87742303%2F3c1e03200e_EMGContractionTable.webp?alt=media)

#### (3) Reports:

A one-page readout is generated, along with the descriptions of each of the analysis steps, EMG plots, the actual R Code used to calculate the results, and links to the articles that were referred to when writing the algorithm’s script. You can find the Reports by clicking on the Reports button as shown below.

![](https://286068319-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNLNBWkNpljDaAj5rQtNa%2Fuploads%2Fgit-blob-91883c03fdb28c7b420368a10149fd03183fa8cf%2F137d11d317_Reports-button-1-.webp?alt=media)

## References

Halaki, Mark, and Karen Ginn. 2012.*Normalization of EMG Signals’:’ To Normalize or Not to Normalize and What to Normalize to?* <https://doi.org/10.5772/49957>.

Lajante, Mathieu MP, Olivier Droulers, and David Amaranti. 2017. “How Reliable Are ‘State-of-the-Art’ Facial EMG Processing Methods? Guidelines for Improving the Assessment of Emotional Valence in Advertising Research.” *Journal of Advertising Research*, no. 1 (March): 28–37. <https://doi.org/10.2501/JAR-2017-011>.

Merletti, Roberto, and Di Torino Politecnico. 1999. “Standards for Reporting EMG Data.” *Journal Electromyogr Kinesio*, no. 1 (March): 3–4.

van Boxtel, Anton. 2001. “Optimal Signal Bandwidth for the Recording of Surface EMG Activity of Facial, Jaw, Oral, and Neck Muscles.” *Psychophysiology*, no. 1 (February): 22–34. <https://doi.org/10.1017/S004857720199016X>.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://help.imotions.com/lab/analysis/biosensor-analysis/r-notebook-emg-processing.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
