/yasa

YASA (Yet Another Spindle Algorithm) : fast and robust detection of spindles, slow-waves, and REMs from sleep EEG recordings.

Primary LanguagePythonBSD 3-Clause "New" or "Revised" LicenseBSD-3-Clause


https://travis-ci.org/raphaelvallat/yasa.svg?branch=master https://pepy.tech/badge/yasa
/docs/pictures/yasa_logo.png

YASA (Yet Another Spindle Algorithm) is a sleep analysis toolbox in Python. YASA includes several fast and convenient command-line functions to:

  • Automatically detect sleep spindles, slow-waves, and rapid eye movements on single and multi-channel EEG data
  • Automatically reject major artifacts on single or multi-channel EEG data
  • Perform advanced spectral analyses: spectral bandpower, phase-amplitude coupling, event-locked analyses, 1/f, and more!
  • Manipulate hypnogram and calculate sleep statistics

For more details, check out the API documentation or try the tutorial (Jupyter notebooks).

Installation

To install YASA, simply open a terminal or Anaconda command prompt and enter:

pip install --upgrade yasa

What are the prerequisites for using YASA?

To use YASA, all you need is:

  • Some basic knowledge of Python, especially the NumPy, Pandas and MNE packages.
  • A Python editor: YASA works best with Jupyter Lab, a web-based interactive user interface.
  • Some sleep EEG data and optionally a sleep staging file (hypnogram) to perform calculations on specific sleep stages. To facilitate masking and indexing operations, the data and hypnogram must have the same sampling frequency and number of samples. YASA provide some convenient functions to load and upsample hypnogram data to the desired shape.

I have sleep EEG data in European Data Format (.edf), how do I load the data in Python?

If you have sleep EEG data in standard formats (e.g. EDF or BrainVision), you can use the excellent MNE package to load and preprocess your data in Python. A simple preprocessing pipeline using MNE is shown below:

import mne
# Load the EDF file, excluding the EOGs and EKG channels
raw = mne.io.read_raw_edf('MYEDFFILE.edf', preload=True, exclude=['EOG1', 'EOG2', 'EKG'])
raw.resample(100)                      # Downsample the data to 100 Hz
raw.filter(0.1, 40)                    # Apply a bandpass filter from 0.1 to 40 Hz
raw.pick_channels(['C4-A1', 'C3-A2'])  # Select a subset of EEG channels

How do I get started with YASA?

If you want to dive right in, you can simply go to the documentation and try to apply YASA's functions on your own EEG data. However, for most users, we strongly recommend that you first try running the examples Jupyter notebooks to get a sense of how YASA works and what it can do! The advantage is that the notebooks also come with example datasets so they should work right out of the box as long as you've installed YASA first. The notebooks and datasets can be found on GitHub (make sure that you download the whole notebooks/ folder). A short description of all notebooks is provided below:

Spindles

Slow-waves

  • 05_sw_detection: single-channel slow-waves detection and step-by-step description of the slow-waves detection algorithm.
  • 06_sw_detection_multi: multi-channel slow-waves detection.

Rapid Eye Movements (REMs)

Spectral analysis

  • 08_bandpower: calculate spectral band power, optionally averaged across channels and sleep stages.
  • 09_IRASA: separate the aperiodic (= fractal = 1/f) components of the EEG power spectrum using the IRASA method.
  • 10_spectrogram: plot a multi-taper full-night spectrogram on single-channel EEG data with the hypnogram on top.
  • 11_nonlinear_features: calculate non-linear EEG features on 30-seconds epochs and perform sleep stage classification.
  • 12_spindles-SO_coupling: slow-oscillations/spindles phase-amplitude coupling and data-driven comodulogram.

Artifact rejection

Typical use: spindles detection

import yasa

# 1) Single-channel spindles detection, in its simplest form.
# There are many optional arguments that you can change to customize the detection.
sp = yasa.spindles_detect(data, sf)
# The output of the the detection (`sp`) is a class that has several attributes and methods.
# For instance, to get the full detection dataframe, one can simply use:
sp.summary()
# To plot an average template of all the detected spindles,
# centered around the most prominent peak (+/- 1 second)
sp.plot_average(center='Peak', time_before=1, time_after=1)

# 2) Multi-channels spindles detection limited to N2/N3 sleep, with automatic outlier rejection
sp = yasa.spindles_detect(data, sf, ch_names, hypno=hypno, include=(2, 3), remove_outliers=True)
# Return spindles count / density and parameters averaged across channels and sleep stages
sp.summary(grp_stage=True, grp_chan=True)

The output of sp.summary() is a pandas DataFrame where each row is a detected spindle and each column a parameter of this event, including the start and end timestamps (in seconds from the beginning of the data), duration, amplitude, etc.

Start End Duration Amplitude RMS AbsPower RelPower Frequency Oscillations Symmetry
3.32 4.06 0.74 81.80 19.65 2.72 0.49 12.85 10 0.67
13.26 13.85 0.59 99.30 24.49 2.82 0.24 12.15 7 0.25

In turn, the detection dataframe can be easily used to plot the events.

/docs/pictures/detection.png

Interactive visualization with Visbrain

YASA can also be used in combination with the Sleep module of the Visbrain visualization package. The result of the detection can then easily be displayed and checked in an interactive graphical user interface. To do so, load Visbrain using the following python file (make sure to update 'PATH/TO/EEGFILE').

from visbrain.gui import Sleep
from yasa import spindles_detect

sl = Sleep(data='PATH/TO/EEGFILE')

def fcn_spindle(data, sf, time, hypno):
    """Replace Visbrain built-in spindles detection by YASA algorithm.
    See http://visbrain.org/sleep.html#use-your-own-detections-in-sleep
    """
    # Apply on the full recording...
    # sp = spindles_detect(data, sf).summary()
    # ...or on NREM sleep only
    sp = spindles_detect(data, sf, hypno=hypno).summary()
    return (sp[['Start', 'End']].values * sf).astype(int)

sl.replace_detections('spindle', fcn_spindle)
sl.show()

Then navigate to the Detection tab and click on Apply to run the YASA algorithm on the specified channel.

/docs/pictures/visbrain.PNG

Outlier rejection

YASA incorporates an optional post-processing step to identify and remove pseudo (fake) events. The method is based on a machine-learning algorithm (the Isolation Forest, implemented in the scikit-learn package), which uses the events parameters (e.g. amplitude, duration, frequency, etc) as input features to identify aberrant spindles / slow-waves / REMs.

To activate this post-processing step, simply use:

import yasa
yasa.spindles_detect(data, sf, remove_outliers=True)  # Spindles
yasa.sw_detect(data, sf, remove_outliers=True)        # Slow-waves
yasa.rem_detect(loc, roc, sf, remove_outliers=True)   # REMs

Gallery

Below some plots demonstrating the functionalities of YASA. To reproduce these, check out the tutorial (Jupyter notebooks).

/docs/pictures/gallery.png

The two top plots show an overlay of the detected spindles (blue) and slow-waves (red) on real EEG data. The middle right panel shows a time-frequency representation of the whole-night recording (spectrogram), plotted with the hypnogram (sleep stages) on top. The middle right panel shows the sleep stage probability transition matrix, calculated across the entire night. The left and right plots of the bottom row show the average template of all detected slow-waves and spindles across the entire night, stratified by channels. The middle bottom plot shows a phase-amplitude coupling comodulogram between slower (0.2-4Hz) and faster (7.5-25Hz) frequency ranges.

Development

YASA was created and is maintained by Raphael Vallat. Contributions are more than welcome so feel free to contact me, open an issue or submit a pull request!

To see the code or report a bug, please visit the GitHub repository.

Note that this program is provided with NO WARRANTY OF ANY KIND.

Citation

To cite YASA, please use the Zenodo DOI: