Tutorial 09 · Using your model

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.

Time
45 minutes (plus computing time)
Level
Intermediate
You need
The installation of Tutorial 02; an EDF recording; Tutorial 03 recommended
Runs in browser
Yes, both widgets (your file never leaves your computer)

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_unlabelled and 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]:

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

PropertyTraining dataIf yours differs
ChannelC3C4 is the closest alternative (untested here). Frontal or parietal sites see different spindle populations; expect lower agreement.
ReferenceA2 (contralateral mastoid or earlobe) or linked earsRe-reference to A2/M2 if possible. Average or Cz references change amplitude and shape.
Sleep stageN2 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.
PopulationAdults 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 rate256 Hz, resampled to 250 HzAny 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µVIrrelevant: the online standardization removes the scale (Tutorial 03).
Mains frequency60 Hz (Montreal)Keep the 60 Hz notch anyway; the low-pass removes 50 Hz (Tutorial 03).
Amplifier and electrodesClinical PSG systems of the MASS cohortsDry electrodes, headbands or different hardware filters can change the signal; validate.
Be honest about generalizationThe Portiloop paper itself lists this limitation: "all our experiments are based on the MODA dataset rather than actual nights spent wearing the Portiloop device", and recommends caution "because the EEG acquisition and signal may differ somewhat from the training data or between individuals" [1]. It also notes that "The MODA dataset is relatively small (∼24 h of annotated data) and heterogeneous." If your montage, population or hardware differs, hand-score a few minutes of N2 from several participants and compute precision and recall as in Tutorial 06 before you interpret detections.

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).

Try it on your own recording

Load a text file with one EEG sample per line (a single channel, for example C3-A2 exported as in step 1), choose its sampling rate, and the page detects spindles in the first 10 minutes. Without a file, the demo uses 2 minutes of synthetic NREM EEG at 256 Hz with known spindles (purple bars just above the network output); the gray band is the 15 s warm-up. What to try: scroll through the recording, move the threshold, and compare the density with the expected ranges.

Drop a .txt or .csv file here, or choose one:

Your file is read by your browser with the File API and processed in this tab. Nothing is uploaded: this site has no server-side code.

Loading the model…
Analyzed
…
Spindles
…
Density (/min)
…
Median duration
…
How the widget differs from the Python pipeline
  • 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_poly by 0.1 to 0.3% (relative RMS), and the standardized signals by at most 0.005. The library's PL.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_unlabelled runs 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.

  1. Export one EEG channel to a text file. pyedflib is installed with the package (it is listed in setup.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.
    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")
    Expected output (our test file):
    channels: ['EEG C3-CLE', 'EEG A2-CLE']
    153600 samples at 256.0 Hz = 10.0 min
    With MNE instead (not a project dependency; pip 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).
  2. 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.m and 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/matlab folder (so that Simulink finds filter_lp.slx). It needs Simulink, the Signal Processing Toolbox and the DSP System Toolbox. It writes preprocessed_night1_C3-A2.txt next 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.py reproduces the same chain with NumPy and SciPy: scipy.signal.resample_poly to 250 Hz, the exact 21 FIR coefficients of coef30.coe, the notch coefficients of iirnotch(60/125, 1/125, 1), and the standardization loop (vectorized). First, check it on your installation:

    python3 docs/tools/preprocess_like_portiloop.py --selftest
    FIR 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.txt
    read 153600 samples at 256 Hz -> wrote 150000 samples at 250 Hz (10.00 min) to preprocessed_night1_C3-A2.txt
    OptionMeaning
    --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 (in docs/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_unlabelled to 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-delay to do the same; set FIR_DELAY = 0 in step 4 in that case), and pads the end by repeating its last output samples; (2) MATLAB's resample and SciPy's resample_poly both use Kaiser-windowed anti-aliasing filters, but with slightly different designs, so resampled values differ slightly.
  3. 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 what notebooks/offline_inference.ipynb does.
    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="")
    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.
    150000 samples -> 149940 outputs, first index 54 last index 149993

    What the outputs are. Reading run_offline_unlabelled and the helpers it calls:

    • The parameters come from the configuration dictionary: window int(0.218 × 250) = 54 samples, seq_stride = int(0.170 × 250) = 42 samples, and validation_network_stride = 1, so the network is evaluated at every sample.
    • UnlabelledSignalDatasetSingleSegment returns single windows full_signal[i:i + 54] (starting at i = 1) together with the index of the window's most recent sample, the same convention as the training labels:
              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_idx
      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.
    • ValidationSampler arranges 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_unlabelled loads the network through get_trained_model, which falls back to portiloop_software/experiments/pareto_search_15_35_v4_0 when no file of that name exists, so the published model is used. In older clones of the repository, run_offline_unlabelled did not have this fallback and raised FileNotFoundError: ... sanity_check_final_model_0; run git pull, or add config_dict["experiment_name"] = "pareto_search_15_35_v4_0" after creating the dictionary.
    Older clones of the repositoryBefore the current version, run_offline_unlabelled had three problems that are now fixed: it did not find the default checkpoint (see above); it raised AssertionError: Index out of range whenever (N − 54) was a multiple of 42 (for example exactly 2 minutes, 30000 samples); and its true_idx pointed one sample after each window. If you see the assertion error or a first index of 55 instead of 54, run git pull (and reinstall with pip 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 _3 to _18 sit next to it).
    • Writes: night1_probabilities.csv with a header and two columns, sample_index (at 250 Hz, in the preprocessed file) and probability.
  4. 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.
    The function also removes the 10-sample filter delay (if you used the causal Python preprocessing) and drops detections in the first 15 s (warm-up).
    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")
    Expected output and the first lines of the file:
    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.987
    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.
    For 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).
  5. 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")
    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 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:
    import 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).

Post-processing: threshold, minimum duration, merge gap

Shaded: detected events; purple bars (just above the network output): true spindles. The first 15 s are grayed out (warm-up, excluded from scoring). What to try: (1) set the minimum duration to 0 and lower the threshold: count the short false alarms; (2) raise the threshold to 0.8 and increase the merge gap to recover fragmented spindles; (3) change the recording to see how stable your choice is.

True spindles
…
Detections
…
Precision
…
Recall
…
F1
…
Waiting for the model…

Troubleshooting

SymptomLikely causeWhat to do
FileNotFoundError ... sanity_check_final_model_0Older clone of the repository, without the checkpoint fallback in run_offline_unlabelledgit pull, or set config_dict["experiment_name"] = "pareto_search_15_35_v4_0".
AssertionError: Index out of rangeOlder clone of the repository (bug for some signal lengths)git pull; or drop the last sample of the signal.
ModuleNotFoundError: sklearn or wandb on importThe training module imports them even for inferencepip install -e . from the repository root installs them (Tutorial 02).
Probability high during the first secondsStandardization warm-upExpected; discard the first 15 s (done by probabilities_to_events).
Detections everywhere, density above 15 per minuteNot preprocessed, or preprocessed at the wrong rate; or wake/REM includedCheck that the preprocessed file has (duration in s × 250) lines and values mostly between −3 and 3; restrict to N2.
Almost no detectionsDifferent montage or very low spindle amplitude relative to background; or a hardware low-pass below 15 HzInspect 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 pipelinesOne compensated the FIR delay (MATLAB, --compensate-delay), the other notSet FIR_DELAY in step 4 accordingly.
The browser widget says the file has 0 samplesWrong column, or a format with decimal commasUse one value per line with a dot as decimal separator; set the column.
Inference on a whole night is slowCPU inference at every sample (about 2.7 s per minute of signal on our laptop); in older clones, a quadratic slowdown on long signalsgit 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

  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 and Table 2 from 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 (quotes from the Methods; densities and durations from Table 2 of the PMC version).
  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