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.
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.mline 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.
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:
| Stage | Parameters | Source of truth in the repository |
|---|---|---|
| Resampling | to 250 Hz (MASS: from 256 Hz) | resample(data_256, fe, 256) in the dataset scripts |
| FIR low-pass | 21 taps, about 30 Hz | filter_lp.slx, identical to old_matlab/coef30.coe |
| Notch | 60 Hz, 1 Hz wide at −1 dB | filter_lp.slx (MATLAB iirnotch(60/125, 1/125, 1)) |
| Standardization | αav = 0.1, αvar = 0.001 | preprocess_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.
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:
- It is a smoother. The largest weights are in the middle and they sum to about 1, so slow activity passes unchanged while fast wiggles (muscle, mains) average out. Its gain is within ±0.3 dB from 0 to 25 Hz, −1 dB at 30 Hz, −4 dB at 35 Hz and −36 dB at 50 Hz (values computed from the coefficients; check them in the widget below). The Portiloop paper summarizes it as "An FIR filter of order 20 works reasonably well to remove frequencies above 30 Hz" [1].
- It is linear phase. The weights are symmetric (\(h_k = h_{20-k}\)). Mathematically, this means every frequency is delayed by the same amount, so the shape of a spindle is preserved: no frequency-dependent distortion of the waxing and waning envelope.
- It delays the signal by 10 samples = 40 ms. A symmetric filter of length 21 is centered on its 11th weight, so its output is aligned with the input sample 10 steps in the past. This is the "group delay", \((21-1)/2 = 10\) samples, or 40 ms at 250 Hz.
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.
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
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.1 | 9.49 samples | 10 samples | about 40 ms |
| Running variance σ² | 0.001 | 999.5 samples | 1000 samples | about 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:
- The mean tracker is a high-pass filter at about 4.7 Hz. With a 40 ms memory, μ follows everything slower than a few hertz, so subtracting it removes slow activity. Algebraically, \(x_n - \mu_n\) is a first-order high-pass filter, \(H(z) = (1-\alpha)(1-z^{-1})/(1-(1-\alpha)z^{-1})\), which is −3 dB at 4.7 Hz, −13 dB at 1 Hz and −19 dB at 0.5 Hz (tick "show mean-removal high-pass" in the first widget). The paper notes that this coefficient was chosen so that it "attenuates frequencies under 4 Hz" [1]. Slow oscillations, delta waves and the slow part of K-complexes are strongly attenuated in what the network sees; DC offsets and electrode drifts disappear entirely.
- The variance tracker is an automatic gain control with a 4 s memory. The network sees amplitude relative to the last few seconds. A spindle stands out because it is larger than the preceding background, not because it exceeds a fixed number of microvolts.
- The output is not exactly unit variance. Because \(\delta_n\) uses the mean before the update, \(x_n - \mu_n = (1-\alpha_{av})\,\delta_n\), so in steady state the output standard deviation is about \(1 - \alpha_{av} = 0.9\). The widget reports it.
Explore the standardization
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.
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.
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.
- 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);pathis the folder (relative to the folder MATLAB is running in),dataset_filenamea plain text file with one EEG sample per line, anddata_sampling_ratethe rate at which that file was recorded (100 Hz in this example; set it to your own). The output will be namedpreprocessed_followed by the input name.loadreads a numeric text file into a column vector. - 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. - Prepare the Simulink simulation.
The Simulink model reads a workspace variable that must be called exactly%% begin standardization signal = data_250_matlab; tot_time = length(data_250_matlab)/fe;signal(its "Signal From Workspace" block hasX = signaland a sample timeTs = 1/250), and the simulation stop time istot_timeseconds. Despite the comment, nothing is standardized yet. - 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);simrunsfilter_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 inout.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, so10:endskips 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_vectis not used afterwards. - Standardize. The loop quoted in Step 4, with
alpha_av = 0.1andalpha_var = 0.001. - Save.
The result is converted to single precision (about 7 significant digits, like the training files) and written as text, one value per line.%% save datasetupdate = single([lp_standard]); writematrix(datasetupdate, path + final_dataset_filename);
- Reads:
<path>/<dataset_filename>, one EEG sample per line, atdata_sampling_rate;filter_lp.slx(inportiloop_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 ofexample_data_not_annotated.txt(provided with the practice dataset, see Tutorial 02) and the input ofnotebooks/offline_inference.ipynb. - Leaves in the workspace:
out(Simulink output),sim_filtered_lp(filtered, before standardization),lp_standard(standardized, double precision).
Troubleshooting
| Symptom | Likely cause | What to do |
|---|---|---|
| Huge values (tens or hundreds) at the start of the preprocessed file | Warm-up of the variance estimate (σ² starts at 0) | Expected. Ignore the first 15 s. |
Undefined function or variable 'signal', or Simulink cannot find the source | The 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_lp | Current folder is not portiloop_software/matlab | cd into that folder or addpath it, and adapt path accordingly. |
| "Signal From Workspace" or "Digital Filter Design" blocks are unresolved | DSP System Toolbox not installed | Use the Python port in Tutorial 09. |
| Preprocessed file shorter or longer than expected | Wrong data_sampling_rate | Duration (samples ÷ 250) must equal the recording duration. |
| Strong 50 Hz noise visible after preprocessing | Very large mains interference; the chain notches 60 Hz only | See the 50 Hz box; improve electrode contact. |
| Values are NaN after a flat segment | A long run of identical samples (disconnected electrode, zero padding) makes σ² decay toward 0 | Cut 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
- 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.
- 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
- 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
- MathWorks documentation:
resample(Signal Processing Toolbox) andiirnotch(DSP System Toolbox).