Tutorial 03 · Understanding the pipeline

Signal preprocessing

Before the network sees a single sample, the Portiloop resamples the EEG to 250 Hz, removes fast activity with a short low-pass filter, removes 60 Hz mains noise, and rescales the signal with a running mean and variance. All of this happens causally, one sample at a time. This tutorial explains each stage, lets you manipulate each one in your browser, and walks through the MATLAB script that reproduces the chain offline.

Time
40 minutes
Level
Beginner (no signal processing background needed)
You need
Tutorial 01; MATLAB only for the last section
Runs in browser
Yes, all three widgets

In this tutorial you will

  • Understand why the network must receive exactly the same preprocessing during training and on the device
  • See what the 21-tap FIR low-pass filter and the 60 Hz notch do to EEG, and what a lab on 50 Hz mains should do
  • Explore the online standardization, its two time constants (40 ms and 4 s) and its warm-up transient
  • Measure the 40 ms delay that a real-time filter cannot avoid
  • Read preprocess_unannotated_data.m line by line, so you can preprocess your own recordings (Tutorial 09)

Why the preprocessing must be identical

The Portiloop network does not know what a microvolt is. It was trained on numbers that had passed through a specific chain of operations, and it learned what a spindle looks like after that chain. If the numbers it receives at inference time went through a different chain (a different low-pass, no standardization, a different sampling rate), the waveforms it sees are distorted in ways it has never encountered, and its output becomes unreliable without any error message.

For neuroscientistsThink of a trained sleep scorer who has always scored on a C3-A2 derivation displayed with a 0.3 to 30 Hz bandpass at 7 µV/mm. Show the same scorer an unfiltered, differently scaled trace and their accuracy drops, although the brain activity is identical. The network is a scorer with a single display setting, frozen at training time. Preprocessing is that display setting.

In this repository the training data and the device share the same building blocks. The original training files were built with a MATLAB script that resamples the MASS recordings, runs them through the Simulink model filter_lp.slx (the FIR low-pass and the notch), then applies the standardization loop:

data_256 = load(path+"dataset_"+phase+"_"+size_data+"_at_256_to_resample.txt");
%% resample
fe = 250;
data_250_matlab = resample(data_256, fe, 256);
...
%% filter
out = sim('filter_lp',tot_time);
sim_filtered_lp = [out.filtered_simulink(10:end); out.filtered_simulink(end-7:end)];
...
%% standardize
lp_standard = sim_filtered_lp;
moving_average = lp_standard(1);
moving_variance = 0;
alpha_av = 0.1;
alpha_var = 0.001;

The same filter_lp.slx and the same loop appear in preprocess_unannotated_data.m, the script the README asks you to run on your own data. The complete chain is:

Raw EEGany rate, µV Resampleto 250 Hz FIR low-pass21 taps, 40 ms delay Notch60 Hz, 1 Hz wide Standardizeα = 0.1 and 0.001 Network54-sample windows offline only on the device and in training same loop everywhere
The preprocessing chain. Blue stages run causally on the Portiloop and were reproduced offline to build the training set.
StageParametersSource of truth in the repository
Resamplingto 250 Hz (MASS: from 256 Hz)resample(data_256, fe, 256) in the dataset scripts
FIR low-pass21 taps, about 30 Hzfilter_lp.slx, identical to old_matlab/coef30.coe
Notch60 Hz, 1 Hz wide at −1 dBfilter_lp.slx (MATLAB iirnotch(60/125, 1/125, 1))
Standardizationαav = 0.1, αvar = 0.001preprocess_unannotated_data.m

Step 1: resampling to 250 Hz

The Portiloop runs at 250 samples per second, so every number inside the network is defined in samples at 250 Hz: the input window is int(0.218 × 250) = 54 samples (216 ms), the filter coefficients below assume 250 Hz, and the standardization time constants are counted in samples. Feeding the network 500 Hz data would make every spindle look half as fast to it.

The MASS recordings used for training were sampled at 256 Hz (the dataset generator checks it with assert edf_file.getSampleFrequency(indices_C3[0]) == fe, where fe = 256). MATLAB's resample(x, 250, 256) converted them. According to the MathWorks documentation, resample "applies an FIR Antialiasing Lowpass Filter to x and compensates for the delay introduced by the filter" [MathWorks]. This step is offline only: the device digitizes directly at 250 Hz.

TipNever resample by simply keeping every k-th sample or by linear interpolation. Both let fast activity fold back into lower frequencies (aliasing) or smear the waveform. Use resample in MATLAB or scipy.signal.resample_poly in Python; Tutorial 09 gives a tested Python version and quantifies the error of linear interpolation.

Step 2: the 21-tap FIR low-pass filter

A finite impulse response (FIR) filter computes each output sample as a weighted sum of the most recent input samples. The Portiloop's filter uses the current sample and the 20 previous ones (21 "taps"):

$$y_n = \sum_{k=0}^{20} h_k \, x_{n-k}$$

The 21 weights \(h_k\) are stored in coef30.coe:

0.001624, 0.014989, 0.021288, 0.007350, -0.025128, -0.052211, -0.039274, 0.033022, 0.147607, 0.254000,
0.297331,
0.254000, 0.147607, 0.033022, -0.039274, -0.052211, -0.025128, 0.007350, 0.021288, 0.014989, 0.001624

Three properties matter for EEG:

For neuroscientistsThe FIR filter is like a very short smoothing kernel slid along the trace. The analog filters of a classic EEG amplifier also delay the signal, but by different amounts at different frequencies (non-linear phase), which can distort waveform shape. A linear-phase FIR delays everything equally: the spindle arrives intact, just 40 ms late.

Step 3: the 60 Hz notch

A notch filter removes a narrow band around one frequency, here the North American mains frequency. It is an infinite impulse response (IIR) filter: besides the last inputs, it also reuses its own previous outputs (feedback), which lets a filter with only 5 coefficients carve a 1 Hz wide hole:

$$y_n = g\,x_n - 2g\cos\omega_0\,x_{n-1} + g\,x_{n-2} + 2g\cos\omega_0\,y_{n-1} - (2g-1)\,y_{n-2}$$

with \(\omega_0 = \pi \cdot 60/125\) and \(g = 0.9936459\) (stored in filter_lp.slx). These are the coefficients of MATLAB's iirnotch(60/125, 1/125, 1): notch at 60 Hz (normalized by the Nyquist frequency, 125 Hz), bandwidth 1 Hz (also normalized), measured at −1 dB because of the third argument. The MathWorks documentation states that with the third argument "the filter's bandwidth, bw, is specified at a level of −ab decibels" [MathWorks]. The resulting filter is −1 dB at 59.5 and 60.5 Hz and essentially transparent elsewhere; its delay at spindle frequencies is under 0.01 sample.

Labs on 50 Hz mains (Europe, most of Asia, Africa, Australia)

The published filter notches 60 Hz only. The training data (MASS, recorded in Montreal) went through this 60 Hz notch, and filter_lp.slx in this repository contains no 50 Hz option. The Portiloop paper says the device applies "a notch filter whose frequency depends on the geographical area (50 Hz in Europe, 60 Hz in North America)" [1], but that choice is not part of the training code documented here; check the configuration of your own device firmware.

What this means in practice:

  • The FIR low-pass alone already attenuates 50 Hz by about 36 dB (a factor of about 60): 20 µV of mains noise becomes about 0.3 µV. Verify it in the widget below by choosing 50 Hz noise.
  • Keep the 60 Hz notch exactly as it is when you preprocess data for this network, so that your data stay identical to the training data in the 0 to 45 Hz range.
  • If your 50 Hz noise is very large (hundreds of µV, typically bad electrode contact), fix the recording first. As a fallback you can add an extra 50 Hz notch before the chain; this changes very little below 45 Hz, but we have not validated detection performance with it.

Explore the filter chain

Filter chain: frequency response and effect on EEG

Top: how much each stage lets through at each frequency (0 dB = unchanged, −20 dB = amplitude divided by 10). Bottom: 3 s of synthetic NREM EEG with added mains noise, before and after the FIR and notch. What to try: (1) select 50 Hz noise and read the residual; (2) turn off the notch with 60 Hz noise; (3) show the standardization's high-pass curve and look at what happens below 4 Hz.

Gain at 13 Hz
…
Gain at mains freq.
…
Residual mains (µV)
…
Group delay
40 ms

Step 4: online standardization

The last stage rescales the filtered EEG so that the network always receives numbers of roughly unit size, whatever the amplifier gain, electrode impedance or individual amplitude. A standard z-score would need the mean and standard deviation of the whole recording, which a real-time device does not have. The Portiloop therefore keeps a running estimate of both, updated at every sample with an exponential moving average (EMA). Here is the loop from preprocess_unannotated_data.m:

lp_standard = sim_filtered_lp;
moving_average = lp_standard(1);
moving_variance = 0;
alpha_av = 0.1;
alpha_var = 0.001;
for i=2:size(lp_standard,1)
    delta = lp_standard(i) - moving_average;
    moving_average = moving_average + alpha_av*delta;
    moving_variance = (1-alpha_var)*(moving_variance + alpha_var*delta.^2);
    moving_std = sqrt(moving_variance);
    lp_standard(i) = (lp_standard(i) - moving_average)./moving_std;
end

In equations, for each new filtered sample \(x_n\):

$$\delta_n = x_n - \mu_{n-1}$$ $$\mu_n = \mu_{n-1} + \alpha_{av}\,\delta_n$$ $$\sigma^2_n = (1-\alpha_{var})\left(\sigma^2_{n-1} + \alpha_{var}\,\delta_n^2\right)$$ $$y_n = \frac{x_n - \mu_n}{\sigma_n}$$

with \(\alpha_{av} = 0.1\), \(\alpha_{var} = 0.001\), \(\mu_1 = x_1\) and \(\sigma^2_1 = 0\). The first sample is passed through unchanged.

Time constants: 40 ms for the mean, 4 s for the variance

The update \(\mu_n = (1-\alpha)\mu_{n-1} + \alpha x_n\) means that a sample \(k\) steps in the past still contributes with weight \(\alpha(1-\alpha)^k\). The memory fades exponentially, and the number of samples after which it has fallen to \(1/e\) (37%) is the time constant:

$$\tau = \frac{-1}{\ln(1-\alpha)} \approx \frac{1}{\alpha}\ \text{samples}\quad(\text{for small }\alpha)$$
Estimateατ (exact)τ ≈ 1/αIn time at 250 Hz
Running mean μ0.19.49 samples10 samplesabout 40 ms
Running variance σ²0.001999.5 samples1000 samplesabout 4 s

The widget below measures these two time constants by running the actual update equations (the readouts "measured τ"), so you can check the approximation for any α.

These two numbers have important, and not obvious, consequences:

For neuroscientistsThe variance tracker behaves like sensory adaptation: a sustained change in amplitude (a louder subject, a drop in impedance) is "adapted away" within a few seconds, while transient events of a second or less (spindles) remain salient. An abrupt artifact, conversely, leaves an after-effect: once it ends, the background looks tiny for a few seconds until the variance estimate recovers.

Explore the standardization

Online standardization explorer

30 s of synthetic NREM EEG (filtered with the Portiloop FIR and notch) with a perturbation at 15 s. Top: the filtered signal, the running mean μ, and the running standard deviation σ drawn as ±σ around zero. Bottom: what the network receives. What to try: (1) with the Portiloop values, look at the first second (warm-up) and at the 15 s perturbation; (2) increase αvar tenfold and see the adaptation speed up (and spindles shrink); (3) decrease αav and watch slow waves leak into the output; (4) compare measured and theoretical τ.

τ mean (theory)
…
τ mean (measured)
…
τ variance (theory)
…
τ variance (measured)
…
Output SD, 8 to 14 s
…
Theory: τ = −1/ln(1 − α) samples. Measured τ: number of samples for μ to cover 63.2% (1 − 1/e) of a unit step, and for σ² to cover 63.2% of a fourfold step in variance, obtained by running the update equations above.

The warm-up transient and the 15 s lead-in of the dataset

At the start, \(\sigma^2\) begins at 0 and grows slowly (4 s time constant), so the first outputs are divided by a tiny number and are huge (bottom plot of the widget, first second). The variance estimate needs several time constants to settle: after 15 s, that is 3750 samples, its initial error has decayed to \(0.999^{3750} \approx 2.3\%\).

The training dataset is built accordingly. The generator cuts each 115 s MODA block with 15 s of extra signal before it and after it, and marks those extra samples with negative labels:

pre_sequence_length_s = 15
...
pre_sequence_length = pre_sequence_length_s * new_fe
post_sequence_length = pre_sequence_length_s * new_fe
...
            lenSignal = post_sequence_length+pre_sequence_length + 115*new_fe
            ...
            spindle_seq_list[i][index][:pre_sequence_length] = -1
            spindle_seq_list[i][index][-post_sequence_length:] = -2

Each segment in the dataset files is therefore 145 s long: 15 s unlabeled lead-in (label −1), 115 s annotated, 15 s unlabeled tail (label −2). The segments come from different parts of different nights and are concatenated, so every junction is a discontinuity that the filters and the standardization must recover from. The training code never uses a window that ends in the unlabeled zones, and also requires enough past signal to build its input sequence:

        self.past_signal_len = self.seq_len * self.idx_stride

        # list of indices that can be sampled:
        self.indices = [idx for idx in range(len(self.data[0]) - self.window_size)  # all possible idxs in the dataset
                        if not (self.data[3][idx + self.window_size - 1] < 0  # that are not ending in an unlabeled zone
                                or idx < self.past_signal_len)]  # and far enough from the beginning to build a sequence up to here

For the published model, seq_len = 50 windows spaced seq_stride = 42 samples apart, that is 2100 samples (8.4 s) of history per training example (see Tutorial 04). The 15 s lead-in thus serves two purposes: it lets the standardization settle after a junction, and it provides the 8.4 s of past windows that the recurrent part of the network is trained with. The code does not state the reason in a comment; this is our reading of it.

Practical ruleWhen you run the detector on your own data, ignore detections in the first 15 s of a recording and in the 15 s after any gap, discontinuity or large artifact. Tutorial 09 does this automatically.

The cost of causality: the 40 ms delay

Offline, you can filter without any delay: run the filter forward, then backward (MATLAB/SciPy filtfilt), or, for a linear-phase FIR, simply shift the output 10 samples earlier. Both use samples from the future. A real-time device cannot: at time \(n\) it only has \(x_n\) and the past. The Portiloop paper lists the filters as a constant 40 ms software delay, part of "a total constant delay of 64 ms" once the 20 ms network computation and the 4 ms stimulus hardware are added; the network's own detection delay (about 250 ms, highly variable) comes on top [1]. Shortening the filter reduces the delay but weakens the attenuation of 50 and 60 Hz noise. The widget lets you explore that trade-off.

The cost of causality

A single synthetic spindle (gray) filtered causally, as on the device (orange), and with the delay removed offline, as in the MATLAB script (blue, dashed). The vertical line marks the true spindle onset; in the lower plot, the green line marks the spindle frequency. What to try: (1) zoom on the onset and read the lag; (2) choose "windowed-sinc" and change the number of taps: the lag is always (taps − 1)/2 samples, but short filters let 50 Hz through.

Group delay
…
Measured lag
…
Gain at spindle freq.
…
Gain at 50 Hz
…

Reproducing the chain offline with MATLAB

The README asks users to preprocess their own recordings with portiloop_software/matlab/preprocess_unannotated_data.m, which simulates the Portiloop filters with the Simulink model filter_lp.slx and then applies the standardization. You need MATLAB with Simulink, the Signal Processing Toolbox (resample) and the DSP System Toolbox (the model uses its "Signal From Workspace" and "Digital Filter Design" blocks). If you do not have MATLAB, Tutorial 09 provides a Python equivalent validated against this page's JavaScript implementation.

  1. Choose the input file and its sampling rate.
    path = "../dataset/";
    dataset_filename = 'potiloop_sleep_age_young11.txt';
    final_dataset_filename = strcat('preprocessed_', dataset_filename);
    data_sampling_rate = 100;
    raw_data = load(path + dataset_filename);
    path is the folder (relative to the folder MATLAB is running in), dataset_filename a plain text file with one EEG sample per line, and data_sampling_rate the rate at which that file was recorded (100 Hz in this example; set it to your own). The output will be named preprocessed_ followed by the input name. load reads a numeric text file into a column vector.
  2. Resample to 250 Hz.
    %% resample
    fe = 250;
    data_250_matlab = resample(raw_data, fe, data_sampling_rate);
    %% generate vector
    data_250_matlab = [data_250_matlab];
    resample(x, 250, 100) multiplies the rate by 250/100 with an anti-aliasing filter. The second statement does nothing (it wraps the vector in brackets); it is a leftover of the dataset scripts, where extra columns were concatenated here.
  3. Prepare the Simulink simulation.
    %% begin standardization
    signal = data_250_matlab;
    tot_time = length(data_250_matlab)/fe;
    The Simulink model reads a workspace variable that must be called exactly signal (its "Signal From Workspace" block has X = signal and a sample time Ts = 1/250), and the simulation stop time is tot_time seconds. Despite the comment, nothing is standardized yet.
  4. Run the Portiloop filters.
    %% filter
    out = sim('filter_lp',tot_time);
    sim_filtered_lp = [out.filtered_simulink(10:end); out.filtered_simulink(end-7:end)];
    time_vect = out.tout(2:end);
    sim runs filter_lp.slx (which must be in the current folder or on the MATLAB path): the 21-tap FIR, then the 60 Hz notch, exactly as on the device. The "To Workspace" block stores the result in out.filtered_simulink. The second line is the important difference with the device: it drops the first samples of the output (MATLAB indices start at 1, so 10:end skips 9 samples), which moves the filtered signal earlier in time and removes the FIR group delay offline, then appends the last 8 output samples again so that the vector keeps the input length. Simulink also logs a sample at time 0, which affects how many samples must be dropped; we could not run Simulink to confirm whether the net shift is exactly 10 samples, but it is within one sample (4 ms) of the 40 ms group delay either way. time_vect is not used afterwards.
  5. Standardize. The loop quoted in Step 4, with alpha_av = 0.1 and alpha_var = 0.001.
  6. Save.
    %% save
    
    datasetupdate = single([lp_standard]);
    
    writematrix(datasetupdate, path + final_dataset_filename);
    The result is converted to single precision (about 7 significant digits, like the training files) and written as text, one value per line.
On the hard drive
  • Reads: <path>/<dataset_filename>, one EEG sample per line, at data_sampling_rate; filter_lp.slx (in portiloop_software/matlab/, next to the script).
  • Writes: <path>/preprocessed_<dataset_filename>, one preprocessed sample per line at 250 Hz, same duration as the input. This is the format of example_data_not_annotated.txt (provided with the practice dataset, see Tutorial 02) and the input of notebooks/offline_inference.ipynb.
  • Leaves in the workspace: out (Simulink output), sim_filtered_lp (filtered, before standardization), lp_standard (standardized, double precision).
Offline versus device: what differsThe MATLAB script and the device apply the same filters and the same standardization. The only systematic difference is the alignment: offline, the 40 ms filter delay is removed; on the device, it is not. The network's input waveforms are the same in both cases (shifted by 40 ms), so its outputs are the same, but timestamps computed from offline-preprocessed files are 40 ms earlier than those of the device. The training data were built with the offline (delay-compensated) version, so spindle labels are aligned with the filtered signal the network saw.

Troubleshooting

SymptomLikely causeWhat to do
Huge values (tens or hundreds) at the start of the preprocessed fileWarm-up of the variance estimate (σ² starts at 0)Expected. Ignore the first 15 s.
Undefined function or variable 'signal', or Simulink cannot find the sourceThe workspace variable was renamed, or the script was turned into a function (Simulink reads the base workspace)Keep the name signal and run the file as a script.
sim cannot find filter_lpCurrent folder is not portiloop_software/matlabcd into that folder or addpath it, and adapt path accordingly.
"Signal From Workspace" or "Digital Filter Design" blocks are unresolvedDSP System Toolbox not installedUse the Python port in Tutorial 09.
Preprocessed file shorter or longer than expectedWrong data_sampling_rateDuration (samples ÷ 250) must equal the recording duration.
Strong 50 Hz noise visible after preprocessingVery large mains interference; the chain notches 60 Hz onlySee the 50 Hz box; improve electrode contact.
Values are NaN after a flat segmentA long run of identical samples (disconnected electrode, zero padding) makes σ² decay toward 0Cut flat segments before preprocessing, or treat them as gaps.

Exercises

How long is the memory of the variance tracker?

In the standardization widget, choose "amplitude triples" and keep the Portiloop values. Roughly how many seconds after 15 s does the output return to its usual size? Relate your answer to τvar. Then set αvar to 0.01 (slider at −2) and repeat.

Answer

With αvar = 0.001 (τ ≈ 4 s), the output is visibly too large for several seconds and is close to normal after roughly 3τ, about 12 s. With αvar = 0.01 (τ ≈ 0.4 s), it adapts within about a second, but then the variance estimate also adapts during a 1 s spindle, so spindles are partially normalized away. The value 0.001 is a compromise: slow enough to keep spindles salient, fast enough to follow changes in amplitude across the night.

A lab with 50 Hz mains

In the filter-chain widget, set 50 Hz noise at 100 µV with the notch on, then off. Does the 60 Hz notch matter for this lab? What residual amplitude remains, and how does it compare with a 30 µV spindle?

Answer

The notch makes no difference at 50 Hz (its gain there is 0 dB). The FIR alone brings 100 µV down to about 1.6 µV (−36 dB), small compared with a 30 µV spindle, and the network then sees a signal very close to what it was trained on. The real risk for such a lab is not the residual 50 Hz, but changing the chain (for instance replacing the 60 Hz notch with a 50 Hz one) without retraining.

Why can the device not use filtfilt?

In the causality widget, select the Portiloop filter and zoom on the onset. The dashed curve starts with the spindle; the orange one starts 40 ms later. Which samples would the device need to produce the dashed curve at the moment the spindle starts?

Answer

The dashed output at time n is the causal output at time n + 10, which depends on inputs up to n + 10, i.e. 40 ms in the future. The device would have to wait 40 ms to compute it, which is exactly the delay we wanted to remove. Delay can be traded for filter quality (fewer taps), but never eliminated by a causal filter.

What next

You now know exactly what the network receives. Tutorial 04 opens the network itself: how 54-sample windows go through convolutions and a recurrent unit. To apply this preprocessing to your own recordings, jump to Tutorial 09.

References

  1. 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. Quotes are from Sections 5.1 and 6.1 and Table 2 of the PMC version.
  2. 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
  3. 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
  4. MathWorks documentation: resample (Signal Processing Toolbox) and iirnotch (DSP System Toolbox).