2. Sleep


2.1. Description

Sleep is a flexible graphical user interface for visualization, analysis and scoring of polysomnographic sleep data.


2.1.1. Help

If you need help with the Sleep module, ask your questions in the dedicated gitter Sleep chat

2.1.2. Main features

  • Graphical User Interface (GUI)
    • Modular and responsive GUI
    • Take screenshot with controllable dpi
    • Save the GUI state (buttons, sliders, checkbox…)
  • Load standard electro-physiological files
    • Default supported files : .vhdr (BrainVision V1 and V2), .edf (European Data Format), .trc (Micromed), .eeg (ELAN)
    • Pass raw data, or use MNE-python to load other non natively supported files
    • Supported extensions for hypnogram files : .txt, .csv, .hyp or raw data.
  • Display
    • Polysomnographic data (e.g. EEG, EOG, EMG)
    • Time-frequency (a.k.a. spectrogram)
    • Hypnogram
    • Topographic map
  • Hypnogram
    • Load, edit and save
    • Real-time computation of sleep statistics
    • Export high-quality hypnogram figure
  • Signal processing
    • De-meaning / de-trending
    • Filtering
    • Re-referencing to a reference channel or common average
    • Bipolarization
  • Semi-automatic events detections
    • Spindles, K-complexes, slow waves, rapid eye movements, muscle twitches and peaks (each detection comes with additional and controllable parameters)
    • Can be performed either on single or multiple channels
    • Detections are reported on the hypnogram and inside a table

2.1.3. Import and use sleep

The Sleep module can be imported as follow :

from visbrain import Sleep

2.1.4. Examples and datasets

To try out in the absence of sleep data, please check out some sleep example scripts and datasets on Google drive

2.1.5. GUI description Components

The Sleep interface is divided into N parts :

  • Menu : load and save files (GUI configuration, screenshot…), control which object to display / hide, open the documentation…
  • Canvas :
    • One individual canvas per channel
    • One canvas for the time-frequency
    • One canvas for the hypnogram
    • One canvas for the time axis
    • One canvas for the topoplot (hidden by default)
  • Ruler :
    • Go to : go to the time location of your choice
    • Window : length of the displayed time window
    • Slider step : step between each consecutive window
    • Rule : display unit in second, minute or hours
    • Grid : display the grid on the hypnogram and channel plot
    • Magnify : apply a zoom on the signal (e.g. useful to examine short events such as spindles). Alternatively, you can use CTRL + click at any time to zoom on a specific signal and time point.
  • Settings panel : for all setting controls, functions to run… See the section Settings panel tabs for a description of each tab. Settings panel tabs

Sleep provide five settings tabs :

  • Panels : manage channel, time-frequency, hypnogram and topographic map
  • Tools : signal processing tools (e.g filtering, re-referencing)
  • Infos : sleep statistics and basic infos on the EEG recording
  • Scoring : a scoring table that can be used to edit the hypnogram
  • Detections : automatic events detections
  • Annotations : manage annotations Panels

Manage channel, time-frequency, hypnogram and topographic map


The Settings panel: topoplot properties

  • Channels
    • Show / hide channels :
      • Select channels of your choice by clicking on the corresponding checkbox
      • Display / hide all channels
    • Control the amplitude :
      • Per channel
      • By setting all amplitudes at once
      • Use symmetric amplitudes (-M, +M)
      • Use automatic amplitude (each amplitude fit to the (minimum, maximum) of the current displayed window)
  • Time-frequency
    • Manage the time-frequency of the full recording
      • Channel on which to compute the time-frequency
      • Computation method (see Time-frequency)
      • Starting and ending frequencies
      • Time length window and overlap
      • Colormap
  • Hypnogram
    • Manage the hypnogram
      • Width and color of hypnogram line
      • Reset to an empty one
  • Topoplot
    • Manage the topographic map (topoplot) of the current window
      • Show / hide topoplot
      • Display either the filtered signal, the amplitude or the power in specific frequency band
      • Colormap control Tools

Signal processing and re-referencing tools.


Bandpass filter (12-14 Hz) applied on all channels.

  • Signal processing (apply in real time)
    • Apply de-meaning and de-trending
    • filtering* and re-referencing which are applied directly on the signal and spectrogram (see image below).
  • Re-referencing
    • Common average
    • Bipolarization (for intra-cranial EEG data) Infos

The Infos panel displays the recording infos (e.g. name and downsampling frequency) as well as the main sleep statistics computed with the hypnogram (see specs below). These values are adjusted in real-time when you edit the hypnogram. Sleep statistics can be exported to .csv or .txt file.


The Infos panel: sleep statistics and basic infos of the current recording.

  • File properties
    • Filename
    • Sampling frequency
    • Down-sampling frequency
  • Sleep statistics (All values are expressed in minutes):
    • Time in Bed (TIB) : total duration of the hypnogram.
    • Total Dark Time (TDT) : duration of the hypnogram from beginning to last period of sleep.
    • Sleep Period Time (SPT) : duration from first to last period of sleep.
    • Wake After Sleep Onset (WASO) : duration of wake periods within SPT
    • Sleep Efficiency (SE) : TST / TDT * 100 (%).
    • Total Sleep Time (TST) : SPT - WASO.
    • W, N1, N2, N3 and REM : sleep stages duration.
    • Latencies : latencies of sleep stages from the beginning of the record. Scoring

This tab contains the scoring table, i.e. where each stage start and finish. For further informations about how to score your hypnogram see Hypnogram scoring Detections

Perform semi-automatic detection. For a full tutorial see Apply semi-automatic detection Annotations

Add and edit annotations (annotations are defined by a start and end point, as well as an optional text marker). To quickly add annotations:

  • Use the Annotate button in the ruler to annotate the entire window
  • Double click (with left mouse button) on a canvas to add an annotation starting and finishing at the mouse cursor location.

If you want to import / export annotations, see the Import, add and save annotations Shortcuts

Sleep comes with a bundle of shortcuts that can be used to speed up your productivity. If shortcuts do not work, simply left click on a canvas.

Keys Description
mouse wheel Move the current window
double left click Add annotation under mouse cursor
- Decrease amplitude
+ Increase amplitude
a Score the current epoch as Artefact
w Score the current epoch as Wake
1 Score the current epoch as N1
2 Score the current epoch as N2
3 Score the current epoch as N3
r Score the current epoch as REM
b Previous window
n Next window
s Display / hide spectrogram
t Display / hide topoplot
h Display / hide hypnogram
p Display / hide navigation bar
x Display / hide time axis
g Display / hide grid
z Enable / disable zoom
i Enable / disable indicators
CTRL + Num Display / hide the channel Num [0, 9]
CTRL + left click On a channel canvas, magnify signal under mouse location
CTRL + d Display quick settings panel
CTRL + s Save hypnogram
CTRL + n Screenshot window
CTRL + e Display documentation
CTRL + t Display shortcuts window
CTRL + q Close the window

2.2. Tutorial

2.2.1. Supported files and format

Sleep support by default several data formats for both electrophysiological and hypnogram data. Data files

Here’s the list of natively supported file formats :

  • .vhdr (BrainVision version 1 and 2)
  • .edf (European Data Format)
  • .trc (Micromed version 4)
  • .eeg (ELAN)

If MNE-python is installed, this list is extended to (see also):

  • .bdf
  • .gdf
  • .egi
  • .mff
  • .set (EEGLAB)
  • .cnt
  • .vhdr (BrainVision files can be loaded using either the native library of Sleep or using MNE)


If MNE-python is installed on your computer, the loading of these file formats is transparent for users. It means that you can load these file formats directly using Sleep graphical user interface or command-line, without any additional steps. We therefore strongly recommand to install MNE-python.


If you have a file format that is currently not supported, Sleep also provide the ability to directly pass raw data (NumPy array). Please click see this example of how to to load a Matlab file and then pass the data directly to Sleep.


Sleep applies an automatic downsampling to (100 Hz by default) upon loading. You can change this value with the “downsample” argument of Sleep. Hypnogram

Here’s the list of supported extensions for hypnogram files :

  • .txt
  • .csv
  • .hyp (ELAN)


There is no international gold standard for the hypnogram format yet and each lab can have its own format. To overcome problems caused by different sampling rate of hypnogram files and/or different values assigned to each sleep stages, Sleep requires that you specify these parameters in a .txt file. This text file should be in the same directory as the original hypnogram file and be named: HYPNOFILENAME_description.txt. Checkout this example.

This text file should contain the following information :

Parameters Values Description
Time 1 Hypnogram file contains one value per second
Wake 0 The value assigned to Wake in the hypnogram is 0
N1 1 The value assigned to N1 sleep in the hypnogram is 1
N2 2 The value assigned to N2 sleep in the hypnogram is 2
N3 3 The value assigned to N3 sleep in the hypnogram is 3
REM 4 The value assigned to REM in the hypnogram is 4
Artefact -1 The value assigned to Artefact in the hypnogram is -1

Please note that Sleep uses the guidelines of Iber et al. 2007 for sleep stage nomenclature, i.e. Wake, N1, N2, N3, REM and Artefact. If your hypnogram includes both NREM-S3 and NREM-S4 sleep stages you can add “N4” categories with the corresponding values in the description file. However, keep in mind that S3 and S4 will be merged into N3 during the import to the Sleep module. That also means that if you load and then save your hypnogram in Sleep, you will loose differentiation between S3 and S4 so be sure not to overwrite your original file! Save hypnogram

By default, Sleep will save your hypnogram with a sampling rate of 1 value per second, and with the following values assigned to each sleep stages:

Stage Value
Wake 0
N1 1
N2 2
N3 3
Art -1 (optional) Elan .hyp format

Sleep will create a single .hyp file with 4 header rows and the values presented above for the sleep stages, with the exception that the value assigned to REM sleep will be 5 for compatibility with Elan hypnogram reader. .txt format

Sleep will automatically create a HYPNOFILENAME_description.txt with the appropriate parameters (time, sleep stages values), therefore making it easy to reload it later.

2.2.2. Load your files

There are four ways to load datasets into Sleep: Load file from the GUI

Don’t send anything, just open the interface and you will have a popup window asking for the filename of your data and hypnogram. If you do not have a hypnogram for your data and/or wish to display only the data, just press Cancel when the hypnogram popup opens.

# Import the Sleep module from visbrain :
from visbrain import Sleep
# Run the interface :

Popup window for loading your files. Load file from path

Instead of leaving inputs arguments empty, send the path to the data :

# Import the Sleep module from visbrain :
from visbrain import Sleep
# Define where the data are located :
dfile = '/home/perso/myfile.eeg'
# File for the hypogram :
hfile = '/home/perso/hypno.hyp'
# If you prefer to start with an empty hypnogram, just pass :
# hfile = None
Sleep(data=dfile, hypno=hfile).show() Load file using MNE-Python

Finally, it is possible to load several other file formats using MNE Python package. The code below shows how to load either BDF, EGI or EEGLab files and pass them to Sleep.

# Import the Sleep module:
from visbrain import Sleep
# - Biosemi Data Format (BDF)
data = 'mybdffile.bdf'
# - EGI format
# data = 'myegifile.egi'
# - EEGLab
# data = 'myeeglabfile.set'
# Now, pass all the arguments to the Sleep module :
Sleep(data=data).show() Load file from raw data

It is possible to manually load raw data and pass them as inputs arguments Sleep. The code below show how to extract raw data from a Matlab .mat file (using SciPy):

    from scipy.io import loadmat
# Import the Sleep module from visbrain:
from visbrain import Sleep
# Load your dataset :
mat = loadmat('testing_database.mat')
# Get the data, sampling frequency and channel names:
raw_data, raw_sf, raw_channels = mat['data'], mat['sf'], mat['channels']
# For the hypnogram :
raw_hypno = mat['hypno']
# As before, if you prefer to start from a fresh empty one, use:
# raw_hypno = None or ignore passing this argument.
# Now, pass all the arguments to the Sleep module:
Sleep(data=raw_data, sf=raw_sf, channels=raw_channels,


Data must be an array with shape (channels, samples). The number of channels must be the same as in channels variable. If you load an hypnogram this way, it must have the same number of point (i.e same sampling rate) as the data. If your hypnogram comes with a different time base, the simplest way is to export it into a simple txt file and follow the procedure described above.

2.2.3. Time-frequency

There are currently three methods implemented in Sleep to compute the time-frequency (i.e. spectrogram) of the recording.

Name Method Dependency
Fourier transform Fourier-based spectrogram (default) SciPy
Wavelet Morlet’s wavelet None
Multitaper Multitaper-based Wigner spectrogram lspopt

Comparison of the 3 methods on a 50 minutes recording (C3 electrode, 0.5-20 Hz).


In most cases, the multitaper method is the one that gives the best results. To enable it, you must first install the lspopt package.

2.2.4. Hypnogram scoring

Sleep offers two possibilities to score the hypnogram, i.e. during the Navigation using shortcuts or using the Scoring table.


Hypnogram scoring. Scoring table

The Scoring panel can be used to manually edit the hypnogram values. It contains three columns:

  • From : specify where the stage start (in minutes)
  • To : specify where the stage finish (in minutes)
  • Stage : the stage type (use Art, Wake, N1, N2, N3 or REM. Can be lowercase)

At the end of the hypnogram, you can Add line or Remove line when a line is selected. An other interesting option is that the table is sortable (by clicking on the arrow inside the column name).


You can export either the raw hypnogram values, the hypnogram scoring table, or a high-quality figure of the hypnogram using the Files > Save contextual menu.

2.2.5. Apply semi-automatic detection

The Detection panel offers several semi-automatic algorithms for the detection of sleep features such as sleep spindles, K-complexes, rapid eyes movements, slow waves, muscle twitches and peaks. All detection types shared the following parameters :

  • Apply on : choose on which channel to perform the detection
    • Selected : apply detection on selected channel
    • Visible : apply detection on all visible channels
    • All : apply detection on all channels (even those that are hidden)


After performing one of the detection, go to the Location tab to see infos about each detected events (starting and ending points, duration, sleep stage). Select the event to jump to it. Finally, you can export the location table using the File > Save contextual menu.

Two examples of automatic event detection are shown below. Spindles detection

This algorithm perform a semi-automatic detection of sleep spindles which are an essential feature of N2 sleep. Sleep spindles are defined as bursts of 12-14 Hz waves that occur for at least 0.5 seconds. They are maximally visible on central electrodes.


Spindles detection on channel Cz.


  • Parameters
    • Fmin : Highpass frequency, default 12 Hz
    • Fmax : Lowpass frequency, default 14 Hz
    • Tmin : Minimum duration, default 0.5 second
    • Tmax : Maximum duration, default 2 seconds
    • Threshold : defined as Mean + X * standard deviation of the signal. A higher threshold will results in a more conservative detection.
    • Perform detection only for NREM sleep : if True and a hypnogram is loaded, then the detection will only be performed on NREM sleep epochs. Peaks detection

Perform a peak detection.


Peaks detection on ECG channel.


  • Parameters
    • Lookahead : minimum distance between two peaks.
    • Display : display either maximum / minimum / maximum & minimum

2.2.6. Load and save the GUI configuration

From the Files > Save contextual menu, you can save the GUI configuration. This will save the state of all buttons and properties inside Sleep. Then, you can recharge the GUI configuration using Files > Load > GUI config. Alternatively, if you want to use a configuration when running Sleep, you can use the config_file argument to directly pass the path to a configuration file.

from mne import io
# Import the Sleep module:
from visbrain import Sleep


2.2.7. Import, add and save annotations

Sleep provides a table for annotations. In this table, specify where the event start, finish and the associated text. Selecting a row of this table center the window around the selected time-code. This allow to quickly navigate even in large files.


Annotations in Sleep. All annotations are referenced in a table in the quick settings panel (left). Each annotation is then reported in the time axis as a green triangle. Import annotations

If the interface is opened, load annotations from the menu Files > Load > Annotations. Otherwise, you can use the input variable annotations to set the path to an existing annotation file that need to be loaded. There is several ways to define annotations : Annotations in a text file

Annotations can be defined in a csv file or in a txt file file.

from mne import io
# Import the Sleep module:
from visbrain import Sleep

Sleep(annotations='pathto/myannotations.txt') Using MNE-Python annotations

Alternatively, you can use annotations from MNE-python and pass your annotations to the annotations variable :

import numpy as np
from mne import Annotations
from visbrain import Sleep

# Define the onset, duration and description :
onset = np.array([117., 256., 312.])
durations = np.array([5, 10, 4])
description = np.array(['First event', 'Second event', 'Third event'])
annot = Annotations(onset, durations, description)

Sleep(annotations=annot) Define only markers

Annotations can be seen as the combination of a time-code and a label. If you don’t need a label to your event, you can only specify the time-code in seconds:

import numpy as np
from visbrain import Sleep

# Define the onset :
onset = np.array([117., 256., 312.])

Sleep(annotations=onset) Add new annotations

To add new annotations :

  • From the ruler or from the Annotations tab of the quick settings panel, use the Annotate button to annotate the currently displayed window
  • Double clicking on a canvas is an other way to quickly add annotations. Save annotations

The list of annotations can be exported (either in .txt or .csv) or loaded from the Files contextual menu.

2.3. API

2.3.1. Sleep class

Here is the list of default Sleep inputs :

class visbrain.Sleep(data=None, hypno=None, config_file=None, annotations=None, channels=None, sf=None, downsample=100.0, axis=True, href=['art', 'wake', 'rem', 'n1', 'n2', 'n3'], preload=True, use_mne=False, kwargs_mne={}, verbose=None)[source][source]

Visualize and edit sleep data.

Use this module to :

  • Load and visualize polysomnographic data and spectrogram.
  • Load, edit and save hypnogram from the interface
  • Perform automatic events detection
  • Further signal processing tools (de-mean, de-trend and filtering)
  • Topographic data visualization

Sleep has been developped in collaboration with Raphael Vallat.


data : string, array_like | None

Polysomnographic data. Must either be a path to a supported file (see notes) or an array of raw data of shape (n_channels, n_pts). If None, a dialog window to load the file should appear.

hypno : array_like | None

Hypnogram data. Should be a raw vector of shape (n_pts,)

config_file : string | None

Path to the configuration file (.txt)

annotations : string | None

Path to the annotation file (.txt, .csv). Alternatively, you can pass an annotation instance of MNE or simply an (N,) array describing the onset.

channels : list | None

List of channel names. The length of this list must be n_channels.

sf : float | None

The sampling frequency of raw data.

downsample : float | 100.

The downsampling frequency for the data and hypnogram raw data.

axis : bool | False

Specify if each axis have to contains its own axis. Be carefull with this option, the rendering can be much slower.

href : list | [‘art’, ‘wake’, ‘rem’, ‘n1’, ‘n2’, ‘n3’]

List of sleep stages. This list can be used to changed the display order into the GUI.

preload : bool | True

Preload data into memory. For large datasets, turn this parameter to True.

use_mne : bool | False

Force to load the file using mne.io functions.

kwargs_mne : dict | {}

Dictionary to pass to the mne.io loading function.



  • Supported polysomnographic files : by default, Sleep support .vhdr (BrainVision), .eeg (Elan), .trc (Micromed) and .edf (European Data Format). If mne-python is installed, this default list of supported files is extended to .cnt, .egi, .mff, .edf, .bdf, .gdf, .set, .vhdr.
  • Supported hypnogram files : by default, Sleep support .txt, .csv and .hyp hypnogram files.

Deprecated since version 0.3.4: Input arguments file and hypno_file has been deprecated in 0.3.4 release. Use instead the data and hypno inputs.


show() Display the graphical user interface.

Display the graphical user interface.

2.3.2. Command line

In addition to using Python script, you can also use the following command-lines from a terminal :

  • visbrain_sleep : open the graphical user interface of Sleep.
  • visbrain_fig_hyp : export a hypnogram file (.txt, .csv or .hyp) into a high definition colored or black and white image.
  • visbrain_sleep_stats : Compute sleep statistics from hypnogram file and export them in csv. visbrain_sleep

Open the graphical user interface of Sleep.

visbrain_sleep [OPTIONS]


-d, --data <data>

Name of the polysomnographic file to load.

-h, --hypno <hypno>

Name of the hypnogram file to load.

-c, --config_file <config_file>

Path to a configuration file.

-a, --annotations <annotations>

Path to an annotation file.

--downsample <downsample>

Down-sampling frequency. Default is 100.

--use_mne <use_mne>

Load your file using MNE-python. Default is False.

--preload <preload>

Preload data in memory. Default is True

--show <show>

Display GUI. Default is True visbrain_fig_hyp

Create hypnogram figure from hypnogram file.

visbrain_fig_hyp [OPTIONS]


-h, --hypno <hypno>

Name of the hypnogram file to load (with extension).

-g, --grid <grid>

Add X and Y grids to figure. Default is False.

-c, --color <color>

Get colored figure. Default is False (black and white).

-o, --outfile <outfile>

Output filename (with extension).

--dpi <dpi>

Dots per inches (resolution). Default is 300. visbrain_sleep_stats

Compute sleep statistics from hypnogram file and export them in csv.

Sleep statistics specifications:

  • Time in Bed (TIB) : total duration of the hypnogram.
  • Total Dark Time (TDT) : duration of the hypnogram from beginning to last period of sleep.
  • Sleep Period Time (SPT) : duration from first to last period of sleep.
  • Wake After Sleep Onset (WASO) : duration of wake periods within SPT
  • Sleep Efficiency (SE) : TST / TDT * 100 (%).
  • Total Sleep Time (TST) : SPT - WASO.
  • W, N1, N2, N3 and REM: sleep stages duration.
  • % (W, … REM) : sleep stages duration expressed in percentages of TDT.
  • Latencies: latencies of sleep stages from the beginning of the record.

(All values except SE and percentages are expressed in minutes)

visbrain_sleep_stats [OPTIONS]


-h, --hypno <hypno>

Name of the hypnogram file to load (with extension).

-o, --outfile <outfile>

Output filename (with extension - *.csv). If None, sleep statistics will only be displayed and not saved into a file

2.4. Collaborators

Sleep is developed in collaboration with Raphael Vallat and Christian O Reilly.

2.5. Publications

Please reference Sleep using its dedicated article in Frontiers in Neuroinformatics. Please let us know if you used or plan to use Sleep in any upcoming publications !

Bibtex entry :

 AUTHOR={Combrisson, Etienne and Vallat, Raphael and Eichenlaub, Jean-Baptiste and O'Reilly, Christian and Lajnef, Tarek and Guillot, Aymeric and Ruby, Perrine M. and Jerbi, Karim},
 TITLE={Sleep: An Open-Source Python Software for Visualization, Analysis, and Staging of Sleep Data},
 JOURNAL={Frontiers in Neuroinformatics},
 ABSTRACT={We introduce Sleep, a new Python open-source graphical user interface (GUI) dedicated to visualization, scoring and analyses of sleep data. Among its most prominent features are: 1) Dynamic display of polysomnographic data, spectrogram, hypnogram and topographic maps with several customizable parameters, 2) Implementation of several automatic detection of sleep features such as spindles, K-complexes, slow waves and rapid eye movements, 3) Implementation of practical signal processing tools such as re-referencing or filtering, and 4) Display of main descriptive statistics including publication-ready tables and figures.  The software package supports loading and reading raw EEG data from a standard file formats such as European Data Format, in addition to a range of commercial data formats. Most importantly, Sleep is built on top of the VisPy library, which provides GPU-based fast and high-level visualization. As a result, it is capable of efficiently handling and displaying large sleep datasets. Sleep is freely available (http://visbrain.org/sleep) and comes with sample datasets and an extensive documentation. Novel functionalities will continue to be added and open-science community efforts are expected to enhance the capacities of this module.}