Real-time simulation and stimulation
A detector that scores well offline is not yet a closed-loop device. In this tutorial you stream EEG through the real Portiloop network sample by sample, see why it keeps eight hidden states instead of one, add up every millisecond between a spindle's onset and the sound reaching the sleeper, and run the repository's simulation notebook with your own trained model.
In this tutorial you will
- Follow one EEG sample from the electrode to a stimulation decision, and name every source of delay
- Understand the eight interleaved hidden states (the "virtual parallel networks" of the paper) and why they are needed
- Watch a live closed loop: the published network, the Portiloop filters and the stimulation rule, running in your browser
- Read and modify
simulate_Portiloop_1_input_classification.ipynbto evaluate your own trained model as a stimulation device - Interpret the notebook's stimulation statistics and its Captum attribution plots
From offline scores to a closed loop
In tutorial 06 the network was judged sample by sample: is this 4 ms point inside a spindle or not? A stimulation experiment asks a different question: did one sound arrive while the spindle was still going on, and only one? The Portiloop paper makes this distinction explicitly [1]:
Valenchon et al. (2022), section 6.1"The performance measured in the previous section is not entirely representative of the performance on the final task. So far, we have only measured the capability of the model to annotate each data point of the signal individually. Yet, we want the ability to send one single stimulation per sleep spindle."
Between the brain and the speaker, the signal goes through a chain of stages. Coloured edges: purple for the acquisition and output hardware, blue for signal processing, orange for the network:
- Electrodes and ADCone sample every 4 ms (250 Hz)
- FIR lowpass, 21 taps40 ms group delay
- 60 Hz notchIIR, one biquad
- Online standardizationrunning mean and variance
- Window of 54 samples0.216 s of signal
- Network forward pass20 ms on the FPGA [1]
- Threshold and refractory ruleone stimulus per spindle
- Sound4 ms with a basic sound controller [1]
The filters were covered in tutorial 03 and the network in tutorial 04. Here we focus on what happens when these pieces run continuously, against the clock.
The sample stream and the 20 ms rhythm
The Portiloop samples the EEG at 250 Hz, so a new value arrives every 4 ms. The network cannot run that often: the paper reports "We measure the execution time of this architecture to be 20 ms per forward pass on the Portiloop" [1] (FPGA version). The simulation notebook encodes this as a number of samples:
FPGA_NN_EXEC_TIME = 5 # equivalent to 20 ms
ERROR_FPGA_EXEC_TIME = 0 # to be sure there is no overlap
Five samples at 4 ms each is 20 ms. ERROR_FPGA_EXEC_TIME is a safety margin (in samples) that you can add if your hardware's inference time fluctuates; it is 0 in the notebook. So at most one window can be evaluated every 5 samples. Each window is the last 54 standardized samples (int(0.218 * 250) = 54, about 0.22 s), ending at the newest sample. Consecutive windows therefore overlap by 49 samples: the network looks at almost the same stretch of signal, shifted by 20 ms.
Why eight hidden states?
The network ends with a GRU, a recurrent layer whose 7-number hidden state carries a memory of previous windows (tutorial 04). During training, the GRU was not fed overlapping windows 20 ms apart. It was fed sequences of 50 windows spaced by seq_stride_s = 0.17 s, that is int(0.17 * 250) = 42 samples or 168 ms. The paper calls this spacing time dilation: "the time-dilation (set to 168 ms by PMBO)" [1]. A sequence of 50 such windows covers about 8.4 s of EEG, which is what lets the network use context well beyond one window (the config entry 'time_in_past': 8.5).
The hidden state has therefore learned dynamics that assume 168 ms between updates. If we fed it a window every 20 ms, its memory would evolve about eight times too fast, a regime it never saw. The solution is to keep several independent copies of the hidden state and use them in turn (round robin):
$$n_\text{parallel} = \left\lfloor \frac{\text{seq\_stride}}{\text{FPGA\_NN\_EXEC\_TIME} + \text{ERROR\_FPGA\_EXEC\_TIME}} \right\rfloor = \left\lfloor \frac{42}{5} \right\rfloor = 8$$ nb_parallel_runs = seq_stride // (FPGA_NN_EXEC_TIME + ERROR_FPGA_EXEC_TIME)
print(f"seq_stride: {seq_stride}")
print(f"FPGA_NN_EXEC_TIME + ERROR_FPGA_EXEC_TIME: {FPGA_NN_EXEC_TIME + ERROR_FPGA_EXEC_TIME}")
print(f"nb_parallel_runs: {nb_parallel_runs}")
stride_between_runs = seq_stride // nb_parallel_runs
Hidden state 1 sees windows ending at samples 53, 95, 137, ... (42 apart); state 2 sees the windows 5 samples later; and so on. Each state lives in the 168 ms world it was trained in, yet together they produce a fresh output about every 20 ms. The paper calls these "decoupled virtual parallel networks" [1] and shows they matter: when the time dilation is shrunk to 20 ms so that a single state must be used, "the highly deteriorated results illustrate the importance of time-dilation" [1].
Three ways to fit 8 windows into 42 samples
Eight windows 5 samples apart span 40 samples, not 42, so the two extra samples must go somewhere. The code in the Portiloop ecosystem does this in three slightly different ways; all keep 8 hidden states:
| Where | Gaps between consecutive windows (samples) | Spacing seen by each hidden state |
|---|---|---|
Simulation notebook (ValidationSampler with network_stride = stride_between_runs = 5) | 5, 5, 5, 5, 5, 5, 5, 7 | exactly 42 |
Device software, portiloop-software (stride_counters) | 5, 5, 5, 6, 5, 5, 5, 6 | exactly 42 |
This website, PL.PortiloopModel.prototype.runStream | 5, 5, 5, 5, 5, 5, 5, 5 | 40 (an approximation) |
The device code computes its gaps from the same two numbers:
num_models_parallel = 8
window_size = 54
seq_stride = 42
...
self.stride_counters = [np.floor((self.seq_stride / self.num_models_parallel) * (i + 1)) for i in range(self.num_models_parallel)]
for idx in reversed(range(1, len(self.stride_counters))):
self.stride_counters[idx] -= self.stride_counters[idx-1]
assert sum(self.stride_counters) == self.seq_stride, f"{self.stride_counters} does not sum to {self.seq_stride}"
In the notebook, the extra 2 samples appear as the adder = 2 applied every 8th output (if (i+1)%nb_samp ==0) when outputs are mapped back to sample indices. The live oscilloscope below lets you switch between the three schedules.
Latency: where the milliseconds go
The paper measured each delay on the FPGA version of the Portiloop and summarized them in its Table 2 (reproduced here; "~" marks the variable part):
| Component | Hardware delay | Software delay |
|---|---|---|
| Electrodes + ADC | - | - |
| Filters | - | 40 ms |
| ANN | 20 ms | ~250 (± 100) ms |
| Stimulus | 4 ms | - |
| Total: ~314 ms | 24 ms | 290 (± 100) ms |
- Filters, 40 ms (constant). The 21-tap linear-phase FIR delays every frequency by half its length: 10 samples = 40 ms (tutorial 03). The paper designed both preprocessing branches "so that they introduce identical software delays to their respective outputs (i.e., 40 ms at 250 Hz sampling rate with FIR filters of order 20)" [1].
- ANN forward pass, 20 ms (constant). The time to compute one output once its window is complete.
- Stimulus, 4 ms (constant). "We measure an auditory stimulation delay of 4 ms when using a basic sound controller, for a total constant delay of 64 ms" [1].
- Detection delay, about 250 ms (variable). The network needs to see part of the spindle before its output crosses the threshold. This is the largest term, and the paper notes that "Training a faster model is thus a potential avenue for future work" [1].
The constant part is exactly the notebook's constant_delay_s:
seq_stride = int(config_dict["seq_stride_s"]*config_dict["fe"])
network_stride = 5
nb_samp = 8
window_size = int(config_dict["window_size_s"]*config_dict["fe"])
max_time_stimulate_s = 0.25
constant_delay_s = 0.064
print(f"seq_stride: {seq_stride}")
constant_delay_s = 0.064 is 40 + 20 + 4 ms. It is added in the notebook because the notebook's dataset was filtered offline with the FIR delay already compensated (tutorial 03), so the filter delay has to be put back by hand. max_time_stimulate_s = 0.25 is the tolerance used to call a stimulation "accurate" (see below). nb_samp = 8 repeats the number of hidden states for the bookkeeping loops.
The decision rule: threshold and refractory period
The network outputs a number between 0 and 1 every ~20 ms. Turning it into stimuli needs two choices.
A threshold. An output above the threshold means "spindle". The notebook uses THRESHOLD = 0.5 (from threshold_list = {'p1': 0.2, 'p2': 0.35, 'full': 0.5} with PHASE = 'full'). The device software uses a default of 0.75 ("threshold": 0.75 in DEFAULT_CONFIG_DICT, adjustable in its interface) and counts an output equal to the threshold as a detection (>=, where the notebook uses >). The paper found that, counting stimulations rather than samples, "the best such trade-off is attained at a threshold of 0.84 with our model, yielding a precision and a recall of 0.71 both", at the price of "slightly shifting the stimulation delay distribution to the right" [1].
A refractory rule. The output often flickers around the threshold at the beginning and end of a spindle, and the eight hidden states do not agree perfectly. Without a rule, one spindle would trigger a burst of sounds. The paper describes the rule [1]:
Valenchon et al. (2022), section 5"A stimulus is sent upon initial spindle detection. To avoid multiple stimuli of the same spindle, the subsequent stimulation may only occur 400 ms following the end of the spindle. If a spindle is detected again within this duration the timer is reset, and we consider it as being part of the previous spindle."
In the notebook it is implemented with two counters in samples (100 samples = 400 ms):
for i in range(len(output_test)):
adder = 0
label = output_test[i]
if (i+1)%nb_samp ==0:
adder = 2
if label > THRESHOLD and wait_stim == 0 and not in_spindle:
spindle_list_stimulate.append(cur_idx)
wait_stim = 100
in_spindle = True
if in_spindle and label > THRESHOLD:
wait_in_spindle = 100#42
if label <= THRESHOLD and wait_in_spindle <= 0:
in_spindle = False
cur_idx += network_stride+adder
wait_stim -=network_stride+adder
wait_in_spindle -=network_stride+adder
Read it as a small state machine: a stimulation is sent when the output crosses the threshold while we are not "in a spindle"; we stay "in the spindle" as long as above-threshold outputs keep coming less than 400 ms apart. The device software implements the same idea with a wall clock (self.wait_t = 0.4 # 400 ms and if ts - self.last_detected_ts > self.wait_t: in SleepSpindleRealTimeStimulator). The 400 ms value is a design choice, not a property of the network: you can change it for your experiment, for example to avoid stimulating spindle trains.
A live closed loop in your browser
The widget below is a complete software Portiloop. A synthetic NREM recording (tutorial 01, ground-truth spindles known) is played sample by sample through the exact Portiloop filters (21-tap FIR, 60 Hz notch, online standardization with αμ = 0.1 and ασ = 0.001), a 54-sample window is sent to the real published network (pareto_search_15_35_v4_0, 25,679 parameters) at the chosen schedule with 8 hidden states, and the notebook's stimulation rule decides when to "play a sound".
How the statistics are computed (paper definitions, section 6.1 [1]): a spindle is stimulated (true positive) if a stimulation falls inside its labelled duration, all delays included, and the delay is measured from the spindle onset to the first such stimulation; every other stimulation is false. "Within 250 ms" counts stimulated spindles whose delay is at most max_time_stimulate_s = 0.25, the notebook's tolerance. The first 5 s of each recording are not used for stimulation (see the note below).
PL.filters.FIR, PL.filters.Biquad with PL.filters.PORTILOOP_NOTCH, PL.OnlineStandardizer and model.step(window, h) from the site library. We checked offline that, with the uniform schedule, its outputs equal PL.preprocess followed by model.runStream on the same data (largest difference 3e-8, float rounding). Each model.step takes a few milliseconds in JavaScript; if your computer cannot keep up at 5x, the widget slows down rather than skipping samples and says so in the status line.Running the simulation notebook
The notebook notebooks/simulate_Portiloop_1_input_classification.ipynb does the same thing on the annotated dataset files (the synthetic practice dataset, or your own real data in the same format), offline but with every real-time constraint. It (1) runs the network on the test subjects with the interleaved schedule, (2) applies the stimulation rule, (3) measures stimulation delays, (4) shows an interactive plot and (5) explains individual decisions with Captum.
- Prepare the data and environment. Complete tutorial 02: the package installed with
pip install -e .and the dataset files inportiloop_software/dataset/. The notebook additionally importsipywidgets(interactive plot) and installscaptumitself in cell 15 (with%pip, which installs into the notebook's own environment; you can also install it beforehand, as below).pip install jupyter ipywidgets captum jupyter notebook notebooks/simulate_Portiloop_1_input_classification.ipynb - Cells 1 to 5: paths and definitions. Cell 1 prints the dataset, plots and experiments folders. Cell 5 is a copy of the training code (dataset, samplers,
PortiloopNetwork,run_inference,get_metrics,generate_dataloader) plusget_config_dict, which returns the configuration of the published architecture. - Cell 6:
simulate(c_dict, split_idx). Builds the test set for splitsplit_idx, loadsportiloop_software/experiments/<experiment_name>, and runs inference with 8 parallel hidden states (the batch dimension holds one hidden state per (segment, offset) pair, so each state sees windows 42 samples apart). It re-interleaves the outputs in time order and returnsf1_test, precision_test, recall_test, state, labels_portiloop, output_portiloop, test_loader, net.statecodes every output as 1 = true positive, 2 = false positive, 3 = true negative, 4 = false negative. - Cell 8: choose phase, threshold and models. This is the cell you edit (see below). As shipped it evaluates the first pre-trained model only: the loop over the 10 splits ends with
break. Expected printout:
with manyseq_stride: 42 FPGA_NN_EXEC_TIME + ERROR_FPGA_EXEC_TIME: 5 nb_parallel_runs: 8 output_segments.shape: (9, 5472)DEBUGlines (dataset sizes, subjects,f1_test,precision_test,recall_test). These sample-level scores are those of tutorial 06, computed on the interleaved stream. - Cells 10 to 12: stimulation analysis.
stimulation_analysis(THRESHOLD)walks through the outputs with the rule shown above, records each stimulation's sample index, finds spindle onsets and ends in the labels, and for each spindle keeps the stimulation closest to its onset:
It then reports, for a margin of 0.25 s and 0.5 s (for s in spindle_list_stimulate: delay = s - b if abs(delay) < abs(best): best = delay spindle_list_stimulate_delay_best.append(best) spindle_list_stimulate_delay_best = np.array(spindle_list_stimulate_delay_best) corrected_stimulation_delay = np.append(corrected_stimulation_delay, spindle_list_stimulate_delay_best/fe + constant_delay_s)i*max_time_stimulate_swithi= 1, 2), how many spindles were stimulated between 0 and the margin after their onset. Printout with the default synthetic dataset and the pre-trained model (split 0, 9 test segments):Split idx: 0 mean spindle length: 0.8278636363636364 For margin = 0.25 s accurate stimulation: 19 spindle not stimulated: 69 total stimulation: 113 ratio: 16.8141592920354 percentage stimulated spindles: 21.59090909090909 For margin = 0.5 s accurate stimulation: 74 spindle not stimulated: 14 total stimulation: 113 ratio: 65.48672566371681 percentage stimulated spindles: 84.0909090909091ratiois the percentage of all stimulations that were accurate (a precision);percentage stimulated spindlesis the percentage of spindles that received an accurate stimulation (a recall). Note that a stimulation that comes before the labelled onset (negative delay) counts as "not stimulated". In this example most stimulations arrive between 0.25 and 0.5 s after the labelled onset: 84% of the spindles are stimulated within 0.5 s, only 22% within 0.25 s. These are synthetic spindles; for real EEG, see the paper's figures above. - Cell 13: interactive plot. Two sliders (start time and width, in seconds) and a Print button. Colours of the EEG trace: green = true positive, red = false positive, blue = true negative, black = false negative; magenta = network output (drawn 5 units below the EEG, right axis); dotted cyan = labelled spindle onsets; dotted grey = stimulations; dashed grey = threshold. It is the notebook equivalent of the oscilloscope above.
Reads: portiloop_software/dataset/dataset_classification_full_big_250_matlab_standardized_envelope_pf.txt (signal, envelope, power ratio and label columns), subject_sequence_full_big.txt, subject_sequence_p1_big.txt, subject_sequence_p2_big.txt (which 115 s segments belong to which subject), and the checkpoints portiloop_software/experiments/pareto_search_15_35_v4_*.
Writes: portiloop_software/plots/stimulation_plot.pdf when you press Print in cell 13, and portiloop_software/plots/grad_explainer.pdf in cell 24. Nothing else is saved; results live in the notebook variables res, corrected_stimulation_delay, total_stim, spindle_list_stimulate.
Using your own trained model
After tutorial 05 you have a checkpoint named after your experiment. Change these things, all in the notebook:
| What | Where | Why |
|---|---|---|
Copy the checkpoint into portiloop_software/experiments/ | file system | run() saves to portiloop_software/dataset/<experiment_name>, but simulate() loads path_experiments / experiment_name. |
exp_name | cell 8 | List of checkpoint file names, one per split. Put your experiment name(s) here. |
split_idx pairing | cell 8 | Model exp_name[split_idx] is tested on the test subjects of split split_idx. Use the split your model was trained with (config_dict["split_idx"] in training), or you will test on training subjects. |
get_config_dict values | cell 5 | Must match the architecture you trained (nb_channel, hidden_size, window_size_s, seq_stride_s, nb_conv_layers, kernels...). A mismatch raises size mismatch in load_state_dict. |
FPGA_NN_EXEC_TIME, ERROR_FPGA_EXEC_TIME | cell 8 | Your hardware's inference time, in samples. This sets the number of hidden states. |
network_stride, nb_samp | cells 10 and 13 | Must equal stride_between_runs and nb_parallel_runs printed by simulate(). Cell 13 also hard-codes seq_stride = 42. |
THRESHOLD and the 100-sample counters | cells 8 and 11 | Detection threshold and refractory period of your protocol. |
constant_delay_s | cell 10 | Filter delay + forward pass + stimulus hardware of your setup. |
The break at the end of the loop | cell 8 | Remove it to evaluate all splits; stimulation_analysis loops over every entry of res. |
stimulation_analysis contains assert segment_state_size == 5472, which is 8 states × (28,750 // 42) cycles per 115 s segment. If you change the sequence stride, the network stride or LEN_SEGMENT, recompute this number (or replace the assertion) or the cell stops with an AssertionError.Which part of the signal drives a decision? (Captum)
The last section of the notebook ("Interpretation of the results with Captum") asks which samples of the input pushed the output up. It uses Integrated Gradients [3] from the Captum library [2]: the input is morphed gradually from a baseline (here, a sequence of windows taken elsewhere in the test set) to the real input, and the gradient of the output with respect to each input sample is accumulated along the way. Cell 19 rebuilds a sequence of seq_len = 20 consecutive windows of one hidden state (idx_batch selects the segment and offset, i_min = 98 the starting window; the comment suggests spindles at 97, 200, 281), cell 21 wraps the network so that it takes only the signal and starts from a zero hidden state, and cell 23 computes:
ig = IntegratedGradients(net_captum)
attributions, delta = ig.attribute(input, baselines=bl, return_convergence_delta=True)
Cell 24 draws the 20 windows in a grid, each coloured by the absolute attribution (red = strong influence), the last panel titled with the network's score, and saves grad_explainer.pdf. The convergence delta printed by cell 23 should be small compared with the output; if it is not, the attribution is not reliable (more integration steps are needed).
#FIXME: x axis is not correct here: the time axis of each small panel is approximate, so read the panels by their order, not their x values.Interpreting the results
- Sample-level F1 vs stimulation precision and recall. They measure different things. A detector can have a modest sample-level F1 (it marks the second half of each spindle) and still stimulate nearly every spindle once.
- The delay distribution is the key number for your protocol. If your hypothesis needs the sound during the first 300 ms of a spindle, count the stimulations inside that window, not the overall recall.
- Negative delays (stimulation before the labelled onset) happen; the paper counts them as false positives and notes that this "slightly harms our reported results" [1].
- Raising the threshold trades early stimulations for fewer false ones: precision goes up, the delay distribution shifts right.
Troubleshooting
| Symptom | Cause and fix |
|---|---|
FileNotFoundError on dataset_classification_full_big_250_...txt or subject_sequence_...txt | The dataset is not in portiloop_software/dataset/; see tutorial 02. |
ModuleNotFoundError: sklearn or ipywidgets | pip install -e . from the repository root installs scikit-learn; install ipywidgets separately. |
RuntimeError: Error(s) in loading state_dict ... size mismatch | get_config_dict in cell 5 does not match the checkpoint's architecture. |
AssertionError in stimulation_analysis | See the warning about segment_state_size == 5472 above. |
TypeError or FutureWarning about delim_whitespace | Older copies of the notebook pass delim_whitespace=True to read_csv, which recent pandas versions reject. The current notebook uses sep=r"\s+"; update your clone (git pull) or make the same replacement in generate_dataloader. |
| The oscilloscope runs slower than the selected speed | Your browser cannot run enough forward passes per second; the status line shows the effective speed. 1x always needs only 50 forward passes per second. |
Exercises
Why do we need a refractory rule?
In the oscilloscope, note the number of false stimuli after about one minute at the default settings. Restart, set the refractory period to 0 ms and run for the same time. What happens and why?
Answer
With 0 ms, the detector re-arms as soon as one output falls below the threshold, so every flicker of the output inside a spindle (and the disagreement between the eight hidden states) triggers a new sound. In our offline run of the widget's code on 3 minutes of recording 4 (the default) at threshold 0.5, 17 of 17 spindles were stimulated in both cases, but false stimuli went from 0 (400 ms) to 29 (0 ms): the extra sounds land on spindles that were already stimulated, or just after them, so they add no hits, only errors.
How much of a short spindle is left?
With the paper's values in the latency calculator, what fraction of a 0.5 s spindle remains when the sound starts? And of a 2 s spindle?
Answer
The total delay is 40 + 250 + 20 + 4 = 314 ms. For 0.5 s, 186 ms remain (37 %), about 2.4 cycles at 13 Hz; for 2 s, 1686 ms remain (84 %). Short spindles are the hard case for closed-loop stimulation, and the detection delay (not the hardware) is the main term to reduce.
Faster hardware, more hidden states
Suppose your hardware runs the network in 12 ms. With seq_stride unchanged, how many hidden states would simulate() use, and what do you change in the notebook?
Answer
12 ms is 3 samples, so set FPGA_NN_EXEC_TIME = 3: nb_parallel_runs = 42 // 3 = 14 and stride_between_runs = 42 // 14 = 3. Then set network_stride = 3 and nb_samp = 14 in cells 10 and 13, recompute the segment_state_size assertion (14 × 684 = 9576) and the adder (here 14 × 3 = 42, so adder must be 0). Also update constant_delay_s to 0.040 + 0.012 + your stimulus delay. You can check the schedule in the interleaved-states widget with a network stride of 3.
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 (preprint arXiv:2107.13473). Quotes are from the PLOS ONE version.
- Kokhlikyan N, Miglani V, Martin M, Wang E, Alsallakh B, Reynolds J, Melnikov A, Kliushkina N, Araya C, Yan S, Reblitz-Richardson O (2020). Captum: a unified and generic model interpretability library for PyTorch. arXiv:2009.07896. Library: captum.ai.
- Sundararajan M, Taly A, Yan Q (2017). Axiomatic attribution for deep networks. Proceedings of the 34th International Conference on Machine Learning, PMLR 70: 3319 to 3328. proceedings.mlr.press/v70/sundararajan17a.
- Portiloop device software: github.com/Portiloop/portiloop-software, files
portiloop/src/custom/custom_detectors.pyandportiloop/src/custom/custom_stimulators.py(RDK X5 version on therdkx5branch).