ERP Analysis

Preprocessing

  1. Filtering:
  • Apply a bandpass filter (e.g., 0.1–30 Hz) to remove high-frequency noise and low-frequency drifts.
  • Use a notch filter (e.g., 50/60 Hz) to remove power-line noise.
  1. Artifact Removal:
  • Use Independent Component Analysis (ICA) to remove eye blinks, muscle activity, and heartbeats.
  • Apply automated artifact rejection (e.g., thresholding, moving window).
  1. Baseline Correction:
  • Subtract the mean voltage from the pre-stimulus baseline (e.g., -200 ms to 0 ms).
  1. Epoch Selection:
  • Segment the data into epochs (e.g., -200 ms to 1000 ms relative to stimulus onset).
  • Exclude trials with artifacts or incorrect responses.

ERP Quantification

  1. Mean Amplitude:
  • Measure the average voltage over a time window (e.g., 300–500 ms for P300).
  • Example: \(\text{Mean Amplitude} = \frac{1}{t_2 - t_1} \int_{t_1}^{t_2} \text{ERP}(t) \, dt\)
  1. Peak Amplitude:
    • Measure the maximum or minimum voltage within a time window.
    • Example: \(\text{Peak Amplitude} = \max(\text{ERP}(t)) \quad \text{for} \quad t \in [t_1, t_2]\)
  2. Latency:
    • Measure the time-to-peak or time-to-trough for a component.
    • Example: \(\text{Latency} = \arg\max_t (\text{ERP}(t)) \quad \text{for} \quad t \in [t_1, t_2]\)
  3. Topographical Maps:
    • Visualize the spatial distribution of ERP components across the scalp (e.g., using topoplots).

Statistical Analysis

  1. Repeated Measures ANOVA:
  • Compare ERP amplitudes/latencies across conditions, groups, or time points.

e.g. amplitude ~ condition * group with subjects as a repeated factor (or a linear mixed model with subjects and items as random effects).

  1. Regression Analysis:
  • Model ERP amplitudes as a function of behavioral or demographic variables.
  1. Cluster-Based Permutation Testing:
  • Test for significant differences across time and space while correcting for multiple comparisons.

Applications of ERPs

Application Description
Cognitive Neuroscience Studying attention, memory, language, and decision-making.
Clinical Research Assessing neurodevelopmental disorders (e.g., ADHD, autism), schizophrenia, and depression.
Neurofeedback Training individuals to regulate their brain activity for therapeutic purposes.
Brain-Computer Interfaces (BCIs) Using ERPs for real-time neural decoding (e.g., P300 speller).
Psychopharmacology Evaluating drug effects on brain activity.
Sleep Research Monitoring brain responses to stimuli during sleep.
Marketing and Consumer Neuroscience Studying consumer preferences and decision-making.

Advantages of ERPs

Advantage Description
High Temporal Resolution Captures millisecond-level brain activity.
Non-Invasive Uses EEG, which is safe, portable, and cost-effective.
Direct Measure of Brain Activity Reflects postsynaptic potentials in large neuronal populations.
Task-Specific Can be time-locked to specific events or cognitive processes.
Well-Established Methods Decades of research have established standard paradigms (e.g., oddball, Stroop).

Limitations of ERPs

Limitation Description
Low Spatial Resolution Centimetre resolution: scalp potentials are blurred by volume conduction.
Susceptibility to Artifacts Sensitive to eye blinks, muscle activity, and movement artifacts.
Many Trials Required Tens to hundreds of trials per condition are needed for a clean average.
Interpretation Challenges Requires expertise to distinguish specific cognitive processes from general brain activity.
Individual Variability High inter-subject variability in ERP amplitudes and latencies.

ERP vs. Other Neuroimaging Modalities

Modality Temporal Resolution Spatial Resolution Invasiveness Cost Applications
ERP Milliseconds Centimetres Non-invasive Low Cognitive neuroscience, clinical research.
fMRI Seconds 1–3 mm Non-invasive High Structural-functional mapping.
MEG Milliseconds 5–10 mm Non-invasive High Epilepsy, cognitive neuroscience.
fNIRS Seconds 1–3 cm Non-invasive Low Cognitive neuroscience, clinical research.
PET Minutes 4–6 mm Radioactive tracer High Metabolic imaging.

Future Directions

  • High-Density EEG and Source Imaging: Larger electrode arrays and source localization for better spatial resolution.
  • Multi-Modal Integration: Combining ERPs with fMRI, MEG, or fNIRS for comprehensive analysis.
  • Machine Learning: Using AI to decode ERP patterns for BCIs and brain state prediction.
  • Closed-Loop Systems: Integration with neurofeedback or BCIs for real-time brain activity modulation.
  • Longitudinal Studies: Using ERPs to track brain development, aging, or disease progression.

Processing ERP Data

The example recording (34 channels, 512 Hz) was made during a visual experiment; the stimuli are marked with s70 and s71 (100 trials each). Before epoching, the signal was band-pass filtered (0.1–30 Hz) and re-referenced to the common average (see the setup code above).

The markers of the recording:

m = eeg.markers
println("Number of markers: ", nrow(m))
for v in ["s70", "s71", "s130"]
    println(v, ": ", count(==(v), m.value))
end
first(m[3:end, :], 5)
Number of markers: 406
s70: 100
s71: 100
s130: 200
5×5 DataFrame
Row id start length value channel
String Float64 Float64 String Int64
1 Stimulus 20.5605 0.00195312 s111 0
2 Stimulus 20.9785 0.00195312 s130 0
3 Stimulus 21.8242 0.00195312 s71 0
4 Stimulus 25.0098 0.00195312 s130 0
5 Stimulus 25.8711 0.00195312 s71 0

view_marker(eeg) prints the list of all markers.

Epoching and Averaging

Epochs time-locked to the marker s71, from 500 ms before to 2000 ms after the stimulus (offset is the time before the marker, ep_len the total epoch length, both in seconds):

e71 = epoch(eeg;
            marker = "s71",
            offset = 0.5,
            ep_len = 2.5)
println("Epochs: ", nepochs(e71))
NeuroAnalyzer.plot(e71;
                   ch = "eeg",
                   gui = false)
Epochs: 100

average_epochs() averages the epochs and creates an ERP object (datatype(obj) == "erp"): the first epoch is the average (the ERP), and the remaining epochs are the original trials. The baseline (in seconds) is subtracted from the average (or, with blfirst = true, from each epoch before averaging):

erp71 = average_epochs(e71; bl = (-0.2, 0))
println("Epochs: ", nepochs(erp71), " (ERP + ", nepochs(erp71) - 1, " trials)")
plot_erp(erp71; ch = "O2-avg")
Epochs: 101 (ERP + 100 trials)

plot_erp() detects and marks the largest positive and negative peaks and prints their latencies and amplitudes. The channel labels end with -avg after re-referencing to the common average.

Tip: many ERP studies plot negative voltages up; use yrev = true to reverse the Y axis:

plot_erp(erp71;
         ch = "O2-avg",
         yrev = true)

A response time (in seconds) can be marked with a vertical line:

plot_erp(erp71;
         ch = "O2-avg",
         rt = 0.4)

Detecting Peaks

erp_peaks() returns the positions (in samples) of the largest positive (first column) and negative (second column) peak of each channel’s ERP; their latencies are obtained from the time axis:

p = erp_peaks(erp71)
lat = erp71.epoch_time[p] .* 1000
first(DataFrame(channel = labels(erp71),
                positive_ms = lat[:, 1],
                negative_ms = lat[:, 2]), 5)
5×3 DataFrame
Row channel positive_ms negative_ms
String Float64 Float64
1 Fp1-avg 519.531 234.375
2 Fpz-avg 546.875 236.328
3 Fp2-avg 509.766 226.562
4 F7-avg 1765.62 445.312
5 F3-avg 1468.75 238.281

Visualization

Butterfly plot of several channels with their average (thick line):

plot_erp(erp71;
         ch = ["O1-avg", "O2-avg", "P7-avg", "P8-avg"],
         avg = true)

Butterfly plot of the single trials of one channel with their average:

plot_erp(erp71;
         ch = "O2-avg",
         avg = true)

Mean and 95% confidence interval over channels (here the posterior channels; with the common average reference, the mean over all channels is zero at every time point):

plot_erp(erp71;
         ch = ["P7-avg", "P8-avg", "POz-avg", "O1-avg", "Oz-avg", "O2-avg"],
         avg = false,
         ci95 = true,
         peaks = false)

Mean and 95% confidence interval over trials:

plot_erp(erp71;
         ch = "O2-avg",
         avg = false,
         ci95 = true,
         peaks = false)

ERPs at the electrode locations (gui = false returns a static figure; in the interactive window, clicking an ERP opens it enlarged):

plot_erp(erp71;
         ch = "eeg",
         type = :topo,
         gui = false)

The ERP of O2 has a small negative deflection at about 150 ms, a large positive peak at 234 ms and a slow negative wave peaking at about 820 ms. Topographical maps at 150 and 234 ms (the ERP, epoch 1, is plotted):

plot_topo(erp71;
          ch = "eeg",
          tpos = 0.15,
          title = "150 ms")
plot_topo(erp71;
          ch = "eeg",
          tpos = 0.234,
          title = "234 ms")

Stacked channels (the amplitude is coded by color):

plot_erp(erp71;
         ch = "eeg",
         type = :stack)

Stacked trials of one channel, with time markers (in ms) at the peaks:

plot_erp(erp71;
         ch = "O2-avg",
         type = :stack,
         tm = [150, 234])

Smoothed (smooth = true; ks is the size of the Gaussian kernel):

plot_erp(erp71;
         ch = "O2-avg",
         type = :stack,
         smooth = true,
         ks = 5)

Response times (in seconds, one per trial) are drawn over the stacked trials; here random values are used, as the recording has no responses:

rt = 0.4 .+ rand(-0.1:0.01:0.1, nepochs(erp71) - 1)
plot_erp(erp71;
         ch = "O2-avg",
         type = :stack,
         rt = rt)

With sort_epochs = true the trials are sorted by the response time:

plot_erp(erp71;
         ch = "O2-avg",
         type = :stack,
         rt = rt,
         sort_epochs = true)

ERP Measures

The amplitude at a time point, and the mean, minimum and maximum amplitude within a time window (in seconds) are calculated for each channel and epoch; for an ERP object the first column is the ERP:

w = (0.2, 0.3)
a = amp_at(erp71; t = 0.234)
m = avgamp_at(erp71; t = w)
mn = minamp_at(erp71; t = w)
mx = maxamp_at(erp71; t = w)
first(DataFrame(channel = labels(erp71),
                amp_234ms = a[:, 1],
                mean = m[:, 1],
                min = mn[:, 1],
                max = mx[:, 1]), 5)
5×5 DataFrame
Row channel amp_234ms mean min max
String Float64 Float64 Float64 Float64
1 Fp1-avg -8.42934 -6.5803 -8.42934 -4.28408
2 Fpz-avg -9.67389 -7.60485 -9.70902 -5.01557
3 Fp2-avg -9.11445 -7.64337 -9.35597 -4.28831
4 F7-avg -5.73018 -4.87535 -6.03114 -1.6878
5 F3-avg -11.9711 -9.21218 -12.0615 -4.53064

The non-phase-locked (induced) activity is the signal of each trial with the ERP subtracted:

erp71_npl = npl(erp71)

Comparing Conditions

ERP of the second condition (s70):

e70 = epoch(eeg;
            marker = "s70",
            offset = 0.5,
            ep_len = 2.5)
erp70 = average_epochs(e70; bl = (-0.2, 0))

Global Dissimilarity

The global dissimilarity (DISS) compares the topographies of two ERPs at each time point, independent of their strength: both topographies are normalized by their global field power, and DISS is the root mean square of their difference. It ranges from 0 (identical topographies) to 2 (inverted topographies); the spatial correlation is \(1 - DISS^2 / 2\). A change of the topography indicates that different generators are active. Before the stimulus, both ERPs are close to zero and their topographies are dominated by noise, so DISS is high and the spatial correlation low; after the stimulus, the two conditions have similar topographies (high spatial correlation).

d = diss(erp71, erp70; ch1 = "eeg", ch2 = "eeg")
t = erp71.epoch_time
fig = Figure(size = fig_size)
ax = Axis(fig[1, 1];
          ax_style...,
          xlabel = "Time [s]",
          title = "s71 vs s70")
lines!(ax, t, d.gd; label = "global dissimilarity")
lines!(ax, t, d.sc; label = "spatial correlation")
vlines!(ax, 0; color = :black, linestyle = :dash)
axislegend(ax; position = :rb)
fig

Topographical Variance

The topographical variance is the variance across channels at each time point of the ERP (with the average reference, it is the square of the global field power); peaks indicate strong, spatially structured responses:

fig = Figure(size = fig_size)
ax = Axis(fig[1, 1];
          ax_style...,
          xlabel = "Time [s]",
          ylabel = "Variance [μV²]",
          title = "Topographical variance")
lines!(ax, t, topo_var(erp71; ch = "eeg"); label = "s71")
lines!(ax, t, topo_var(erp70; ch = "eeg"); label = "s70")
vlines!(ax, 0; color = :black, linestyle = :dash)
axislegend(ax)
fig