Sleep spindles and closed-loop stimulation
Why would anyone want to play a sound to a sleeping brain exactly when a sleep spindle starts, why is that so difficult, and how does the Portiloop solve it with a small neural network? This page sets the scene for the whole tutorial series.
In this tutorial you will
- Review what a sleep spindle is (frequency, duration, sleep stage, generators, function) and play with a synthetic one.
- Understand what closed-loop stimulation is and why real-time detection is much harder than offline scoring.
- Watch the real pre-trained Portiloop network process a synthetic recording, seeing only the past, and compare it with an offline detector that sees the future.
- Get an overview of the Portiloop pipeline, of the ten tutorials, and of how to cite the work.
What is a sleep spindle?
Sleep spindles are short bursts of oscillatory activity in the sigma band that appear in the EEG during non-rapid eye movement (NREM) sleep. They are most characteristic of stage N2 (where they are part of the scoring criteria) but are also present in N3. The MODA paper, whose annotations are used to train the Portiloop detector, describes them as follows:
"Spindles follow a characteristic waxing and waning profile, and generally last 0.5 to 1.0 seconds in duration."
Lacourse et al. (2020), Scientific Data, Introduction [2]
Definitions of the frequency band vary slightly between sources. The definition of the American Academy of Sleep Medicine (AASM), as quoted in the MODA paper [2], is a train of distinct waves with frequency 11 to 16 Hz with a duration of at least 0.5 seconds, usually maximal in amplitude using central derivations. The MODA introduction itself speaks of 10 to 16 Hz bursts, and the Portiloop paper of a "high frequency (∼12 to 16 Hz) and rapid evolution (<2.5 s)" [3]. In these tutorials we call 11 to 16 Hz the sigma band.
How big and how frequent are they? On the MODA data (central channel C3, stage N2), the authors report:
"[...] the average spindle density for a young cohort was 4.2 spm with an average duration of 0.8 s, average maximum peak-to-peak amplitude of 33 µV and average dominant oscillation frequency of 13.3 Hz [...]. The aggregated average spindle activity for older sleepers was 2.5 spm with an average duration of 0.75 s, average amplitude of 27 µV and average frequency of 13.2 Hz"
Lacourse et al. (2020), Scientific Data, Discussion [2]; spm = spindles per minute
Where do they come from?
Spindles are generated by the thalamus and relayed to the cortex. In the classical picture, GABAergic neurons of the thalamic reticular nucleus rhythmically inhibit thalamocortical relay neurons; these rebound with bursts of action potentials that entrain cortical networks, and the scalp EEG picks up the resulting synchronized cortical activity. The review by Fernandez and Lüthi [1] summarizes this in its first sentence:
"Sleep spindles are burstlike signals in the electroencephalogram (EEG) of the sleeping mammalian brain and electrical surface correlates of neuronal oscillations in thalamus. As one of the most inheritable sleep EEG signatures, sleep spindles probably reflect the strength and malleability of thalamocortical circuits that underlie individual cognitive profiles."
Fernandez and Lüthi (2020), Physiological Reviews, Abstract [1]
Why do neuroscientists care?
Spindles are linked to memory consolidation, sensory gating and plasticity. The same review proposes that spindles "enable a selective reactivation and routing of wake-instated neuronal traces between brain areas such as hippocampus and cortex" [1]. The Portiloop paper motivates its choice of spindles as a target in the same way:
"Their role in memory consolidation is supported by increases in spindle density following learning [...], and the observation that age-related changes in sleep spindles are correlated with differences in overnight performance gains [...]. If it were possible to influence spindles with sound, as it is to enhance slow oscillations, researchers could explore their functional role in healthy adults as well as characterize their involvement in cognitive aging, and even perhaps restore degraded function."
Valenchon et al. (2022), PLOS ONE, Section 2.2 [3]
Anatomy of a spindle (interactive)
The widget below builds a synthetic 8 second stretch of NREM EEG with one spindle starting at 3 s. The lower panel shows what a classical (non deep learning) detector would look at: the signal band-pass filtered in the sigma band and its envelope, the slowly varying amplitude of the oscillation.
filtfilt or the default filters of EEGLAB and MNE-Python, runs forward and then backward in time: no delay, but it uses future samples. Offline analysis can afford zero-phase filters; a device that must act during the recording cannot. Tutorial 03 covers the filters of the Portiloop in detail.What is closed-loop stimulation?
In an open-loop experiment, stimuli are delivered on a fixed schedule regardless of the brain state. In a closed-loop experiment the recorded signal decides when to stimulate: the system measures the EEG, detects a target event (a slow oscillation up-state, a spindle, a theta burst) and triggers a stimulus (a sound, a light, a current) timed to that event. Because the brain responds to the stimulus, which changes the next measurements, the loop is closed.
The best known example in sleep research targets slow oscillations:
"Using auditory stimulation to SO up-states, when neural tissue is partly depolarized and more excitable, Ngo et al. enhanced the amplitude of SOs and reported an overnight improvement in memory performance, a result that has now been replicated multiple times"
Valenchon et al. (2022), PLOS ONE, Introduction [3], referring to Ngo et al. (2013) [5]
Slow oscillations are slow (0.5 to 1.5 Hz according to [3]) and large, so detecting their up-state in time is feasible with simple filters and thresholds. Spindles are a much harder target: they are faster, shorter, and lower in amplitude.
Why is real-time spindle detection hard?
When an expert scores a recording, or a detector runs on a finished file, the whole signal is available. A closed-loop device must decide during the spindle, using only what it has already recorded. Three difficulties follow.
1. Causality: you only have the past
"Online detectors (i.e., detectors that act during signal acquisition) face more challenging conditions than offline detectors, due to the unavailability of “future” data points. For example, if we aim to detect and stimulate a spindle before it ends, the duration of the spindle is not yet known by definition, yet it is one of the identifying criteria for spindles commonly used by experts."
Valenchon et al. (2022), PLOS ONE, Section 2.4 [3]
An offline detector can measure the whole burst, check that it lasts at least 0.5 s, and then place the onset back in time. A real-time detector has to bet on a spindle after seeing only its first few cycles.
2. Latency: every stage adds delay
A spindle lasts less than a second, so delays matter. The Portiloop paper measured the delays of its own spindle configuration (Table 2 of [3], reproduced here):
| Component | Hardware delay | Software delay |
|---|---|---|
| Electrodes + ADC | (none reported) | (none reported) |
| Filters | (none reported) | 40 ms |
| Neural network (ANN) | 20 ms | ∼250 (± 100) ms |
| Stimulus | 4 ms | (none reported) |
| Total: ∼314 ms | 24 ms | 290 (± 100) ms |
"Software delay" means time spent waiting for enough data: the 21-tap filter needs 10 samples (40 ms at 250 Hz) of the future of each sample before its output is "centered" on it, and the network needs to see a few cycles of a spindle before its output rises. As the paper puts it, "the most significant source of delay is the detection delay of our ANN" [3].
3. False alarms cost stimulations
The network outputs a number between 0 and 1 for each new window of signal; a stimulus is sent when that number crosses a threshold. A low threshold detects spindles early but also fires on alpha bursts, artifacts or noise; a high threshold is more selective but later. In a stimulation experiment, every false alarm is a sound played at the wrong moment, which may disturb sleep or dilute the effect you are trying to measure.
"A threshold of 0.84 yields the optimal trade-off; however, researchers may wish to select different parameters according to experimental objectives. [...] Increasing the threshold yields longer delays."
Valenchon et al. (2022), PLOS ONE, Fig 6 caption [3]
See it for yourself: online versus offline (interactive)
The widget below streams a 40 s synthetic NREM recording through the real pre-trained Portiloop network (the same weights as the checkpoint pareto_search_15_35_v4_0, running in your browser). The upper panel is what the device knows at each instant: the past. The lower panel is what an offline analysis sees: the whole recording at once. The offline detector is a deliberately simple one (zero-phase sigma envelope, a detection threshold, then boundaries extended backward and forward along the envelope); it is not how the MODA labels were made (those come from human scorers), but it shows what access to the future buys.
How to read the widget. Shaded green bands are the true spindles of the synthetic signal (they are revealed as the playhead passes them, as an expert would score them afterwards). A pink vertical line is a stimulus: here, one stimulus is sent each time the output crosses the threshold upward. Delays are measured from the true spindle onset to the first stimulus inside the spindle, in "wall-clock" time, so they include the 40 ms filter delay. Online counts and delays cover the part of the recording to the left of the playhead, after the warm-up; the offline error covers every spindle after the warm-up, since the offline detector sees everything at once. Extra stimuli inside an already stimulated spindle are counted in "stimuli sent" but not in the two other boxes; the paper counts them as false positives.
PL.synth.nrem: colored noise, slow waves and waxing and waning sigma bursts). Delays and counts on this signal illustrate the concepts; they are not the performance of the Portiloop on human EEG. For the published numbers, see the paper [3] and Tutorial 06.What is the Portiloop?
The Portiloop is an open-source, low-cost device for closed-loop EEG stimulation, developed by the MIST Lab (Polytechnique Montréal) and the CL:ASP lab (Concordia University), the affiliations of the authors of [3]. In the words of the paper:
"In this article, we propose the Portiloop, a deep learning-based, portable and low-cost closed-loop stimulation system able to target specific brain oscillations. [...] Software and plans are available to the community as an open science initiative to encourage further development and advance closed-loop neuroscience research"
Valenchon et al. (2022), PLOS ONE, Abstract [3]
The paper describes two hardware implementations, "one using the Xilinx Pynq FPGA together with the HackEEG board and one using a custom board and a Google Coral System-on-Module neural accelerator" [3]. This repository, portiloop-training, contains the software side: building the training dataset, training and selecting the spindle detector, simulating it offline, and exporting it for a device. Its headline result:
"Our resulting system is the first portable device to be able to detect and stimulate sleep spindles in real time with an f1-score of 0.71, measured on MODA, a dataset renowned for the reliability of its labels."
Valenchon et al. (2022), PLOS ONE, Section 7 [3]
For comparison, "The experts annotating the MODA dataset had an average performance of 0.72 on the whole cohort in term of the f1-score of their individual annotations with respect to the final labels" [3]. Note what this comparison means: the reference labels are a consensus of several human scorers, so even individual experts do not reach an F1 of 1.
The pipeline at a glance
Every new EEG sample travels through the same chain, on the device and in the offline simulations of this repository. Click a box to jump to the tutorial that explains it.
portiloop_software/matlab/; network sizes from get_final_model_config_dict(); delays from Table 2 of the paper [3]. The notch frequency must match the mains frequency of your country.The numbers in the diagram are those of the published model, read from the code:
'fe': 250,
...
'nb_conv_layers': 3,
'seq_len': 50,
'nb_channel': 31,
'hidden_size': 7,
'seq_stride_s': 0.170,
'nb_rnn_layers': 1,
'RNN': True,
'envelope_input': False,
...
'window_size_s': 0.218,
...
'kernel_conv': 7,
'kernel_pool': 7,
...
'time_in_past': 8.5,
Reading it as a neuroscientist: the sampling rate fe is 250 Hz; the network looks at windows of window_size_s = 0.218 s, which the code turns into int(0.218 * 250) = 54 samples; three convolutional layers with 31 channels and kernels of 7 samples extract features from each window; a recurrent unit (GRU) with 7 hidden units remembers the last seq_len = 50 windows taken 0.17 s apart, which is the 8.5 s of time_in_past. The whole network has 25,679 trainable parameters, small enough to run on embedded hardware.
How this tutorial series is organized
The tutorials follow the life of a detector, from data to device. Each page has interactive widgets that run in your browser; pages that need Python say so in their header.
| # | Tutorial | What it covers |
|---|---|---|
| 01 | Sleep spindles and closed-loop stimulation | This page: the scientific context and the pipeline. |
| 02 | Installation and data | Installing the code, downloading the dataset and pre-trained models, file formats, how subjects are split, a first sanity check. |
| 03 | Signal preprocessing | The low-pass FIR, the notch, the online standardization, and the delays they introduce. |
| 04 | Inside the network | The convolutional and recurrent layers of the detector, step by step. |
| 05 | Training a new model | Running the training script, its options, and monitoring a run. |
| 06 | Evaluating a detector | Precision, recall, F1, thresholds, and sample-level versus event-level scoring. |
| 07 | Hyperparameter search | How the architecture was chosen under hardware constraints. |
| 08 | Real-time simulation and stimulation | Simulating the device offline: when would it have stimulated, and how late. |
| 09 | Detecting spindles in your own data | Preparing your recordings and running the pre-trained detector on them. |
| 10 | Exporting and deploying | Exporting a trained model (ONNX, parameter files) for a device. |
Exercises
How narrow is the sigma band of the widget?
In the "Anatomy of a spindle" widget, keep the duration at 1 s and the amplitude at 35 µV, set the background to 0, and read the envelope peak at 13 Hz, then at 9, 11, 16 and 18 Hz. By what factor does the envelope shrink at each frequency? What does this tell you about using a fixed 11 to 16 Hz band for subjects whose spindles are slower (for example, frontal "slow spindles" around 11 to 12 Hz)?
Answer
The didactic filter is two cascaded resonators centered on 13.5 Hz. Its gain, computed with PL.filters.freqz, is about −0.3 dB at 13 Hz, −5.3 dB at 11 Hz (amplitude factor ≈ 0.54), −4.0 dB at 16 Hz (≈ 0.63), −13 dB at 9 Hz (≈ 0.22) and −8.7 dB at 18 Hz (≈ 0.37). The readout will differ slightly from these factors because the envelope is a running RMS over 0.2 s and the spindle is short. A slow spindle at 11 Hz therefore looks about half as large as an identical 13.5 Hz spindle: a fixed-band, fixed-threshold detector is biased against slow spindles. A learned detector like the Portiloop network can in principle adapt its filters, but only to what is in its training labels.
Short events and the duration rule
Set the duration to 0.4 s. Does the event satisfy the AASM definition? Would it survive the MODA duration rule? Now think about the online detector: at what moment can a real-time system know that an event will last at least 0.5 s?
Answer
A 0.4 s event fails the AASM criterion (at least 0.5 s) but passes the MODA post-processing, which removes consensus events shorter than 0.3 s or longer than 2.5 s ("spindle longer than 2.5 s or shorter than 0.3 s were filtered out of the GC" [2]). Such short events do occur in the training labels: the very first 115 s block of the released dataset contains a labelled spindle of about 0.39 s (see Tutorial 02). An online detector can only know that an event lasted 0.5 s after 0.5 s have passed, which is already most of an average 0.8 s spindle. This is why the Portiloop network must learn to bet on spindles from their first cycles, and why it sometimes stimulates events that turn out to be too short.
The price of a high threshold
In the online versus offline widget, run recording 4 to the end with threshold 0.5, then with 0.84. Write down the number of stimuli outside spindles, the number of spindles stimulated, and the median delay. Which setting would you choose for (a) an experiment where any stimulus outside a spindle may wake the participant, (b) an experiment that needs the stimulus as early as possible in the spindle?
Answer
On this synthetic recording, the higher threshold sends fewer stimuli outside spindles, but it also misses some spindles and stimulates later in the ones it catches: exactly the trend the paper reports ("Increasing the threshold yields longer delays" [3]). For (a), favor precision: a high threshold, accepting later and fewer stimuli. For (b), favor timing: a lower threshold, accepting more false alarms, or train a model that is faster to react. The paper's choice of 0.84 maximizes the F1 of stimulation, a compromise between the two; Tutorials 06 and 08 show how to choose a threshold on your own criteria.
How to cite
If you use the Portiloop software, the pre-trained models or these tutorials in your work, cite the Portiloop paper [3]. If you use the pre-trained models or MASS data, also cite MODA [2] and MASS [4], as required by their maintainers (MASS asks users to state which subsets they used).
@article{valenchon2022portiloop,
author = {Valenchon, Nicolas and Bouteiller, Yann and Jourde, Hugo R. and L'Heureux, Xavier and Sobral, Milo and Coffey, Emily B. J. and Beltrame, Giovanni},
title = {The Portiloop: A deep learning-based open science tool for closed-loop brain stimulation},
journal = {PLOS ONE},
year = {2022},
volume = {17},
number = {8},
pages = {e0270696},
doi = {10.1371/journal.pone.0270696}
}
@article{lacourse2020moda,
author = {Lacourse, Karine and Yetton, Ben and Mednick, Sara and Warby, Simon C.},
title = {Massive online data annotation, crowdsourcing to generate high quality sleep spindle annotations from {EEG} data},
journal = {Scientific Data},
year = {2020},
volume = {7},
pages = {190},
doi = {10.1038/s41597-020-0533-4}
}
@article{oreilly2014mass,
author = {O'Reilly, Christian and Gosselin, Nadia and Carrier, Julie and Nielsen, Tore},
title = {Montreal Archive of Sleep Studies: an open-access resource for instrument benchmarking and exploratory research},
journal = {Journal of Sleep Research},
year = {2014},
volume = {23},
number = {6},
pages = {628--635},
doi = {10.1111/jsr.12169}
}
The paper is also available as a preprint: arXiv:2107.13473. The code is released under the MIT License.
References
- Fernandez LMJ, Lüthi A (2020). Sleep spindles: mechanisms and functions. Physiological Reviews 100(2): 805 to 868. doi:10.1152/physrev.00042.2018
- Lacourse K, Yetton B, Mednick S, Warby SC (2020). Massive online data annotation, crowdsourcing to generate high quality sleep spindle annotations from EEG data. Scientific Data 7: 190. doi:10.1038/s41597-020-0533-4 (open access, also on PubMed Central)
- Valenchon N, Bouteiller Y, Jourde HR, L'Heureux X, Sobral M, Coffey EBJ, Beltrame G (2022). The Portiloop: a deep learning-based open science tool for closed-loop brain stimulation. PLOS ONE 17(8): e0270696. doi:10.1371/journal.pone.0270696; preprint arXiv:2107.13473
- O'Reilly C, Gosselin N, Carrier J, Nielsen T (2014). Montreal Archive of Sleep Studies: an open-access resource for instrument benchmarking and exploratory research. Journal of Sleep Research 23(6): 628 to 635. doi:10.1111/jsr.12169
- Ngo HVV, Martinetz T, Born J, Mölle M (2013). Auditory closed-loop stimulation of the sleep slow oscillation enhances memory. Neuron 78(3): 545 to 553. doi:10.1016/j.neuron.2013.03.006