Detecting spindles in your own data
This tutorial takes you from an EDF file recorded in your lab to a table of detected spindles: checking that your data resemble the training data, exporting one channel, reproducing the Portiloop preprocessing (in MATLAB or Python), running the pre-trained network, turning its output into events, and checking that the result is physiologically plausible. You can also try the detector on your own file directly in this page.
In this tutorial you will
- Check whether your montage, population and sleep stages match what the model was trained on
- Export one EEG channel from EDF with
pyedflib(or MNE) - Preprocess it exactly like the Portiloop, with the MATLAB script or a tested Python equivalent
- Run the pre-trained network with
run_offline_unlabelledand understand its output - Convert probabilities into spindle events and sanity-check density, duration and frequency
Will the model work on my data?
The pre-trained network was trained on a narrow, well-defined kind of data. The closer your recordings are to it, the more you can trust the detections. The repository's README is explicit: "note that the data must be collected in the same experimental setting as MODA for this to work".
What the network was trained on
The labels come from the MODA project (Massive Online Data Annotation), whose gold-standard spindles were scored by a median of 5 experts on recordings of the Montreal Archive of Sleep Studies (MASS) [2, 3]. From the MODA paper's methods [2]:
- "180 subjects were sampled from the SS1-SS5 subsets": 100 younger adults (phase 1, mean age 24.1 years) and 80 older adults (phase 2, mean age 62.0 years).
- "“Blocks” of 115 s were randomly extracted from artifact free Stage N2 sleep." Three blocks (about 6 minutes) per subject for most subjects, 10 blocks for 15 subjects of each phase.
- "C3 channel was reformatted to C3-A2 when possible otherwise the original reference “C3-Linked Ear” (C3-LE) was kept."
The authors' training files contained 162 of these subjects (98 from phase 1, 64 from phase 2). They are not distributed with these tutorials: the practice dataset of Tutorial 02 is synthetic, and Tutorial 02 lists real annotated databases you can request.
The dataset generator of this repository follows the same rules: it reads the C3 channel of each MASS EDF file, subtracts A2 for the subjects listed with a C3-A2 montage in MODA's channel table, and checks that the original sampling rate is 256 Hz (resampled to 250 Hz afterwards):
with pyedflib.EdfReader(filename) as edf_file:
# print(edf_file.getSignalLabels())
indices_C3 = [i for i, s in enumerate(edf_file.getSignalLabels()) if 'C3' in s]
signal = edf_file.readSignal(indices_C3[0])
assert edf_file.getSampleFrequency(indices_C3[0]) == fe
if 'C3-A2' in reference_list[reference_list["subject"] == filename[:-8] + ".edf"]["channel"].values:
indices_A2_CLE = [i for i, s in enumerate(edf_file.getSignalLabels()) if 'A2' in s]
ref = edf_file.readSignal(indices_A2_CLE[0])
assert edf_file.getSampleFrequency(indices_A2_CLE[0]) == fe
assert len(ref) == len(signal)
signal -= ref
Checklist
| Property | Training data | If yours differs |
|---|---|---|
| Channel | C3 | C4 is the closest alternative (untested here). Frontal or parietal sites see different spindle populations; expect lower agreement. |
| Reference | A2 (contralateral mastoid or earlobe) or linked ears | Re-reference to A2/M2 if possible. Average or Cz references change amplitude and shape. |
| Sleep stage | N2 only (annotated blocks) | Run on the whole night, but keep only events that fall in N2 (or N2 and N3) epochs of your hypnogram. Detections in wake or REM (alpha, sawtooth waves) are not meaningful. |
| Population | Adults of the MASS cohorts: a younger group (mean age 24.1) and an older group (mean age 62.0) | Children, patients, and medications that alter spindles (for example benzodiazepines) were not represented; validate on a hand-scored subset first. |
| Sampling rate | 256 Hz, resampled to 250 Hz | Any rate of at least 100 Hz is fine once properly resampled to 250 Hz (the chain removes everything above about 35 Hz anyway). |
| Amplitude units | µV | Irrelevant: the online standardization removes the scale (Tutorial 03). |
| Mains frequency | 60 Hz (Montreal) | Keep the 60 Hz notch anyway; the low-pass removes 50 Hz (Tutorial 03). |
| Amplifier and electrodes | Clinical PSG systems of the MASS cohorts | Dry electrodes, headbands or different hardware filters can change the signal; validate. |
Try it in your browser first
Before installing anything, you can run the real pre-trained network on one channel of your own recording in this page. The widget reproduces the Portiloop chain (resampling, FIR low-pass, 60 Hz notch, online standardization) and runs the same network as the Python code (its JavaScript port matches PyTorch to about 2 × 10−6; see validation).
- Resampling: a windowed-sinc (band-limited) resampler written for this page. On our test signals at 100, 256, 500 and 1000 Hz, it differed from
scipy.signal.resample_polyby 0.1 to 0.3% (relative RMS), and the standardized signals by at most 0.005. The library'sPL.resampleLinear, which is didactic only, differed by 20% from 100 Hz and 3% from 256 Hz, which is why it is not used here. - Network stride: to stay fast, the page runs the network every 5 samples with 8 interleaved hidden states (like the real-time simulation of Tutorial 08), whereas
run_offline_unlabelledruns it at every sample with 42 hidden states. On a 2-minute test, the two outputs differed by 0.01 on average (maximum 0.27), and 27 of 5500 compared positions fell on different sides of a 0.5 threshold. - Length: the first 10 minutes only (about 35 to 40 s of computation on our laptop).
- End result: on the 10-minute test file of the Python walkthrough, the code of this widget (run with Node.js) found 64 events and the Python pipeline 64; all matched, with a median onset difference of 8 ms.
- Timing: event times are corrected for the 40 ms filter delay and refer to the start of your file; detections in the first 15 s (warm-up) are discarded.
Step by step, with the Python package
For whole nights, many participants, or analyses you will publish, use the Python pipeline. The five steps below were run end to end on a synthetic 10-minute EDF file (C3 and A2 channels at 256 Hz, 66 spindles); the outputs shown are from that test.
- Export one EEG channel to a text file.
pyedflibis installed with the package (it is listed insetup.py). Adapt the file name and the channel labels: print the labels first, since every system names them differently (C3-M2,EEG C3-A2,C3...). If the C3 channel is already referenced to A2 or M2, do not subtract anything.
Expected output (our test file):import numpy as np import pyedflib edf_path = "night1.edf" with pyedflib.EdfReader(edf_path) as edf: labels = edf.getSignalLabels() print("channels:", labels) i_c3 = [i for i, s in enumerate(labels) if "C3" in s][0] i_a2 = [i for i, s in enumerate(labels) if "A2" in s][0] fs = edf.getSampleFrequency(i_c3) c3 = edf.readSignal(i_c3) # physical units, usually microvolts a2 = edf.readSignal(i_a2) assert edf.getSampleFrequency(i_a2) == fs eeg = c3 - a2 # C3-A2, as MODA used when possible np.savetxt("night1_C3-A2.txt", eeg, fmt="%.6g") print(f"{len(eeg)} samples at {fs} Hz = {len(eeg) / fs / 60:.1f} min")
With MNE instead (not a project dependency;channels: ['EEG C3-CLE', 'EEG A2-CLE'] 153600 samples at 256.0 Hz = 10.0 minpip install mne), the equivalent is below; on our test file both exports were identical.import numpy as np import mne raw = mne.io.read_raw_edf("night1.edf", preload=True, verbose="error") print(raw.ch_names, raw.info["sfreq"]) c3 = raw.get_data(picks=["EEG C3-CLE"], units="uV")[0] a2 = raw.get_data(picks=["EEG A2-CLE"], units="uV")[0] np.savetxt("night1_C3-A2_mne.txt", c3 - a2, fmt="%.6g")Whole night or N2 only?Export the whole night as one continuous signal and select N2 afterwards (step 5). Cutting N2 bouts first would create many junctions, each followed by a 15 s warm-up during which detections are unreliable (Tutorial 03). - Preprocess like the Portiloop. Choose one of the two options; they apply the same filters and the same standardization.
Option A: the MATLAB script
Open
portiloop_software/matlab/preprocess_unannotated_data.mand edit its first lines (explained line by line in Tutorial 03):path = "/data/mylab/exports/"; % folder that contains your text file (keep the final slash) dataset_filename = 'night1_C3-A2.txt'; % one sample per line, from step 1 final_dataset_filename = strcat('preprocessed_', dataset_filename); data_sampling_rate = 256; % the rate of YOUR recording (printed in step 1)Then run it from the
portiloop_software/matlabfolder (so that Simulink findsfilter_lp.slx). It needs Simulink, the Signal Processing Toolbox and the DSP System Toolbox. It writespreprocessed_night1_C3-A2.txtnext to your input file. A whole night may take a while in Simulink.Option B: the Python script (no MATLAB needed)
docs/tools/preprocess_like_portiloop.pyreproduces the same chain with NumPy and SciPy:scipy.signal.resample_polyto 250 Hz, the exact 21 FIR coefficients ofcoef30.coe, the notch coefficients ofiirnotch(60/125, 1/125, 1), and the standardization loop (vectorized). First, check it on your installation:python3 docs/tools/preprocess_like_portiloop.py --selftestFIR coefficients identical to coef30.coe: True 1.0 Hz FIR 0.20 dB notch -0.00 dB 13.0 Hz FIR -0.21 dB notch -0.00 dB 30.0 Hz FIR -0.99 dB notch -0.00 dB 35.0 Hz FIR -4.05 dB notch -0.00 dB 50.0 Hz FIR -35.92 dB notch -0.00 dB 59.5 Hz FIR -46.40 dB notch -1.00 dB 60.0 Hz FIR -43.31 dB notch -200.00 dB 60.5 Hz FIR -41.28 dB notch -1.00 dB vectorized vs loop standardization, max |difference| = 7.99e-15 SELFTEST OK(The script prints −200 dB when a frequency is removed completely, as the notch does at exactly 60 Hz.) Then preprocess the text file from step 1, giving its sampling rate, or read the EDF file directly:
python3 docs/tools/preprocess_like_portiloop.py night1_C3-A2.txt --fs 256 # or, straight from the EDF file (C3 minus A2; labels matched by substring): python3 docs/tools/preprocess_like_portiloop.py night1.edf --channel C3 --reference A2 -o preprocessed_night1_C3-A2.txtread 153600 samples at 256 Hz -> wrote 150000 samples at 250 Hz (10.00 min) to preprocessed_night1_C3-A2.txtOption Meaning --fsSampling rate of a text input (EDF files carry their own). --columnColumn to read in a multi-column text file (0 = first). --channel,--referenceEDF only: substrings of the channel labels; the reference is subtracted. --compensate-delayRemove the 10-sample FIR delay offline, like the MATLAB script. Off by default, so that the output is identical to the device and to the JavaScript in these pages. --no-notch,--alpha-avg,--alpha-varFor experiments only; changing them makes your data differ from the training data. -oOutput file (default preprocessed_<input name>.txt).Validation and remaining differences- Python versus the JavaScript of these pages: on 10 minutes of synthetic EEG at 250 Hz with 60 Hz noise, a DC offset and an electrode step, the Python output and
PL.preprocess(indocs/assets/js/portiloop.js, run with Node.js) differed by at most 7 × 10−14 (float64 rounding); after writing to text in single precision, by 5 × 10−6. - JavaScript network versus PyTorch: on 2 minutes of preprocessed signal, the JavaScript network run at every sample with 42 hidden states reproduced all 29,946 outputs of
run_offline_unlabelledto within 1.7 × 10−6, with no threshold crossing changed. - Python versus MATLAB: not compared numerically (we did not run MATLAB). By construction, two differences remain: (1) the MATLAB script removes the FIR delay offline (use
--compensate-delayto do the same; setFIR_DELAY = 0in step 4 in that case), and pads the end by repeating its last output samples; (2) MATLAB'sresampleand SciPy'sresample_polyboth use Kaiser-windowed anti-aliasing filters, but with slightly different designs, so resampled values differ slightly.
- Python versus the JavaScript of these pages: on 10 minutes of synthetic EEG at 250 Hz with 60 Hz noise, a DC offset and an electrode step, the Python output and
- Run the network. The package exposes
run_offline_unlabelled(config_dict, path_experiments, unlabelled_segment), which loads a checkpoint and runs it over a whole preprocessed signal. This is whatnotebooks/offline_inference.ipynbdoes.
Expected output. Computation time grows linearly with length: on the laptop used to write this page (Intel Core i7-1370P, CPU only, 14 PyTorch threads, other jobs running), 10, 30 and 60 minutes of signal took about 29 to 40 s, 90 s and 161 s, so an 8-hour night should take roughly 20 to 25 minutes.import numpy as np import torch from pathlib import Path import portiloop_software from portiloop_software import run_offline_unlabelled, get_final_model_config_dict config_dict = get_final_model_config_dict() # the published model (checkpoint pareto_search_15_35_v4_0) path_experiments = Path(portiloop_software.__file__).parent / "experiments" data = np.loadtxt("preprocessed_night1_C3-A2.txt", dtype=np.float32) output, true_idx = run_offline_unlabelled(config_dict=config_dict, path_experiments=path_experiments, unlabelled_segment=torch.from_numpy(data)) prob = output.numpy() # one probability per position, between 0 and 1 idx = true_idx.numpy() # index of the last (most recent) sample of each 54-sample window print(len(data), "samples ->", len(prob), "outputs, first index", idx[0], "last index", idx[-1]) np.savetxt("night1_probabilities.csv", np.c_[idx, prob], delimiter=",", fmt=["%d", "%.5f"], header="sample_index,probability", comments="")150000 samples -> 149940 outputs, first index 54 last index 149993What the outputs are. Reading
run_offline_unlabelledand the helpers it calls:- The parameters come from the configuration dictionary: window
int(0.218 × 250) = 54samples,seq_stride = int(0.170 × 250) = 42samples, andvalidation_network_stride = 1, so the network is evaluated at every sample. UnlabelledSignalDatasetSingleSegmentreturns single windowsfull_signal[i:i + 54](starting ati = 1) together with the index of the window's most recent sample, the same convention as the training labels:
The first output is therefore at index 54, and its probability refers to samples 1 to 54: it is what the network says once it has seen sample 54.signal_seq = self.full_signal[idx:idx + self.window_size].unfold(0, self.window_size, 1) true_idx = idx + self.window_size - 1 # index of the last (most recent) sample of the window, as for training labels return signal_seq, true_idxValidationSamplerarranges the windows in batches of 42 consecutive positions, and the GRU hidden state of batch element j is carried to element j of the next batch, i.e. to the window 42 samples later. In other words, 42 interleaved hidden states each see windows 42 samples (168 ms) apart, the same spacing as the training sequences.- The number of outputs is
42 × floor((N − 55) / 42), a whole number of batches: the last few samples (at most 42) get no output.
Which checkpoint is loadedget_final_model_config_dict()names the experiment'sanity_check_final_model_0'.run_offline_unlabelledloads the network throughget_trained_model, which falls back toportiloop_software/experiments/pareto_search_15_35_v4_0when no file of that name exists, so the published model is used. In older clones of the repository,run_offline_unlabelleddid not have this fallback and raisedFileNotFoundError: ... sanity_check_final_model_0; rungit pull, or addconfig_dict["experiment_name"] = "pareto_search_15_35_v4_0"after creating the dictionary.Older clones of the repositoryBefore the current version,run_offline_unlabelledhad three problems that are now fixed: it did not find the default checkpoint (see above); it raisedAssertionError: Index out of rangewhenever(N − 54)was a multiple of 42 (for example exactly 2 minutes, 30000 samples); and itstrue_idxpointed one sample after each window. If you see the assertion error or a first index of 55 instead of 54, rungit pull(and reinstall withpip install -e .if needed).On the hard drive- Reads: the preprocessed text file; the checkpoint
portiloop_software/experiments/pareto_search_15_35_v4_0(about 300 KB, included in the repository; nine other checkpoints_3to_18sit next to it). - Writes:
night1_probabilities.csvwith a header and two columns,sample_index(at 250 Hz, in the preprocessed file) andprobability.
- The parameters come from the configuration dictionary: window
- Threshold the output and convert it to events. A spindle event is a run of consecutive positions where the probability is at or above a threshold. Three choices shape the result:
- Threshold (default 0.5, as in the notebook): higher means fewer, more certain detections. Choose it on hand-scored data from your own lab (Tutorial 06).
- Minimum duration (default 0.3 s): very short runs are usually noise. MODA removed gold-standard events "longer than 2.5 s or shorter than 0.3 s" [2].
- Merge gap (default 0.1 s): two runs separated by a brief dip are counted as one spindle.
Expected output and the first lines of the file:import numpy as np FS = 250 FIR_DELAY = 10 # samples; set to 0 if you preprocessed with --compensate-delay or with the MATLAB script def probabilities_to_events(idx, prob, threshold=0.5, min_duration_s=0.3, merge_gap_s=0.1, warmup_s=15.0, fs=FS, delay=FIR_DELAY): """Threshold the network output; return a list of (onset_s, offset_s, peak_probability).""" above = prob >= threshold edges = np.diff(np.concatenate([[0], above.astype(int), [0]])) starts, stops = np.flatnonzero(edges == 1), np.flatnonzero(edges == -1) # stops are exclusive events = [] for a, b in zip(starts, stops): onset, offset = idx[a] - delay, idx[b - 1] + 1 - delay # in samples, offset exclusive peak = float(prob[a:b].max()) if events and onset - events[-1][1] <= merge_gap_s * fs: # close to the previous one: merge events[-1] = (events[-1][0], offset, max(events[-1][2], peak)) else: events.append((onset, offset, peak)) return [(on / fs, off / fs, p) for on, off, p in events if off - on >= min_duration_s * fs and on >= warmup_s * fs] table = np.loadtxt("night1_probabilities.csv", delimiter=",", skiprows=1) idx, prob = table[:, 0].astype(int), table[:, 1] events = probabilities_to_events(idx, prob, threshold=0.5) with open("night1_spindles.csv", "w") as fh: fh.write("onset_s,offset_s,duration_s,peak_probability\n") for on, off, p in events: fh.write(f"{on:.3f},{off:.3f},{off - on:.3f},{p:.3f}\n") print(len(events), "events written to night1_spindles.csv")
Times are in seconds from the start of the exported signal (resampling does not change time). If you exported only part of a night, add its start time.64 events written to night1_spindles.csv onset_s,offset_s,duration_s,peak_probability 17.836,18.580,0.744,0.988 26.824,27.620,0.796,0.986 35.428,36.232,0.804,0.987For neuroscientists: detected boundaries are lateAn event starts when the network has seen enough of the spindle to be confident, not at the physiological onset. The paper reports a detection delay of the network of about 250 ms (±100 ms) on top of the fixed delays [1]; on our synthetic test file, detected onsets were a median 0.32 s after the true onsets. Use the events to count spindles and to locate them; if you need precise onsets, durations or amplitudes, re-measure them on the raw signal around each detection (for example with a sigma-band envelope). - Sanity-check the result. A detector can fail silently on data unlike its training set. Compare three simple statistics with published values.
import numpy as np FS = 250 ev = np.loadtxt("night1_spindles.csv", delimiter=",", skiprows=1, ndmin=2) eeg = np.loadtxt("preprocessed_night1_C3-A2.txt") minutes = (len(eeg) / FS - 15) / 60 # exclude the 15 s warm-up dur = ev[:, 2] print(f"{len(ev)} spindles in {minutes:.1f} min -> {len(ev) / minutes:.2f} per minute") print(f"duration: median {np.median(dur):.2f} s, 10th to 90th percentile " f"{np.percentile(dur, 10):.2f} to {np.percentile(dur, 90):.2f} s") # dominant frequency inside each event (zero-padded spectrum of the preprocessed EEG) f = np.fft.rfftfreq(1024, 1 / FS) band = (f >= 5) & (f <= 25) peaks = [] for on, off in ev[:, :2]: seg = eeg[int(on * FS):int(off * FS)] seg = (seg - seg.mean()) * np.hanning(len(seg)) peaks.append(f[band][np.argmax(np.abs(np.fft.rfft(seg, 1024))[band])]) peaks = np.array(peaks) inside = np.mean((peaks >= 11) & (peaks <= 16)) * 100 print(f"peak frequency: median {np.median(peaks):.1f} Hz; {inside:.0f}% of events between 11 and 16 Hz")
Density is only meaningful per minute of N2. If you have a hypnogram with one label per epoch, keep the events that fall in N2 epochs:64 spindles in 9.8 min -> 6.56 per minute duration: median 0.72 s, 10th to 90th percentile 0.46 to 0.94 s peak frequency: median 13.7 Hz; 100% of events between 11 and 16 Hzimport numpy as np EPOCH_S = 30 # 30 s epochs (AASM); use 20 for R&K-scored files stages = np.loadtxt("night1_hypnogram.txt", dtype=str) # one label per line: W, N1, N2, N3, R ev = np.loadtxt("night1_spindles.csv", delimiter=",", skiprows=1, ndmin=2) epoch = np.minimum((ev[:, 0] // EPOCH_S).astype(int), len(stages) - 1) in_n2 = stages[epoch] == "N2" n2_minutes = np.sum(stages == "N2") * EPOCH_S / 60 print(f"{in_n2.sum()} of {len(ev)} events fall in N2; N2 density {in_n2.sum() / n2_minutes:.2f} per minute")What to compare with. The MODA gold standard, i.e. the very data the network learned from, reports per-subject medians (standard deviation across subjects) [2]:
MODA gold standard (C3, N2) Younger adults (phase 1) Older adults (phase 2) Density (spindles per minute) 4.2 (2.4) 2.6 (2.2) Duration (s) 0.79 (0.14) 0.75 (0.16) The AASM definition quoted by MODA describes a spindle as a train of distinct waves at 11 to 16 Hz lasting at least 0.5 s [2]. Red flags: a density far above 10 per minute or near 0 in N2; many events in wake or REM; median durations under 0.4 s or over 1.5 s; most peak frequencies outside 11 to 16 Hz (alpha around 8 to 12 Hz in wake, or muscle artifacts). Always look at a random sample of 20 to 30 detections in your EEG viewer.
From probabilities to events, interactively
The three post-processing parameters interact. This widget runs the network on 60 s of synthetic N2-like EEG with known spindles and scores the events with an event-level matching rule (a detection counts as correct if it overlaps a true spindle with an intersection over union of at least 0.2; see Tutorial 06).
Troubleshooting
| Symptom | Likely cause | What to do |
|---|---|---|
FileNotFoundError ... sanity_check_final_model_0 | Older clone of the repository, without the checkpoint fallback in run_offline_unlabelled | git pull, or set config_dict["experiment_name"] = "pareto_search_15_35_v4_0". |
AssertionError: Index out of range | Older clone of the repository (bug for some signal lengths) | git pull; or drop the last sample of the signal. |
ModuleNotFoundError: sklearn or wandb on import | The training module imports them even for inference | pip install -e . from the repository root installs them (Tutorial 02). |
| Probability high during the first seconds | Standardization warm-up | Expected; discard the first 15 s (done by probabilities_to_events). |
| Detections everywhere, density above 15 per minute | Not preprocessed, or preprocessed at the wrong rate; or wake/REM included | Check that the preprocessed file has (duration in s × 250) lines and values mostly between −3 and 3; restrict to N2. |
| Almost no detections | Different montage or very low spindle amplitude relative to background; or a hardware low-pass below 15 Hz | Inspect the raw signal for visible spindles; check the amplifier's filters; try a lower threshold and validate. |
| Event times shifted by 40 ms between two pipelines | One compensated the FIR delay (MATLAB, --compensate-delay), the other not | Set FIR_DELAY in step 4 accordingly. |
| The browser widget says the file has 0 samples | Wrong column, or a format with decimal commas | Use one value per line with a dot as decimal separator; set the column. |
| Inference on a whole night is slow | CPU inference at every sample (about 2.7 s per minute of signal on our laptop); in older clones, a quadratic slowdown on long signals | git pull; run it overnight, or on a GPU by setting config_dict["device_inference"] = "cuda" (untested here). |
Exercises
Density at different thresholds
In the first widget, use the demo recording. Note the number of detected spindles and the density at thresholds 0.3, 0.5 and 0.8. Then compare with the number of true spindles (purple bars after 15 s). Which threshold gives the most plausible count, and what does this tell you about reporting spindle density from an automatic detector?
Answer
The count changes with the threshold (lower thresholds add short or doubtful events, higher ones miss weak spindles), so "spindle density" is partly a property of the detector settings. Always report the threshold, minimum duration and merge gap, use the same settings for all participants and conditions, and, ideally, calibrate the threshold on hand-scored data from your own lab (Tutorial 06).
Which file did the network really see?
You preprocessed one recording with the MATLAB script and another with the Python script (default options), then ran events.py unchanged on both. Are the event times of the two recordings comparable?
Answer
Not exactly: the MATLAB output is already shifted 40 ms earlier, so with FIR_DELAY = 10 its events end up 40 ms too early. Set FIR_DELAY = 0 for files preprocessed with MATLAB or with --compensate-delay. The detections themselves (which spindles are found) are the same, because the network sees the same waveforms.
What next
To measure how good these detections are on your data, hand-score a subset and follow Tutorial 06. If performance is poor on your montage or population, consider retraining (Tutorial 05). To use the network for real-time stimulation, see Tutorial 08 and Tutorial 10.
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 and Table 2 from 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 (quotes from the Methods; densities and durations from Table 2 of the PMC version).
- 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