Most experiments record many subjects, often in several groups (e.g. patients and controls) and sessions (e.g. before and after treatment). A study describes such a set of recordings and analyzes them together, similar to the STUDY of EEGLAB:
recordings (.hdf files) study_create() design table
sub-01.hdf sub-02.hdf ... ─────────────────► subject, session,
group, covariates
│
│ study_apply!() batch processing (filtering, referencing,
▼ epoching, ...) of every recording
derivatives/sub-01.hdf ...
│
│ study_measure!() ERPs, spectra, time-frequency power of
▼ every recording and condition (cached)
study.measures
│
│ study_average() grand averages over subjects
▼ study_erp() (by group, session, covariate)
plots, statistics
The study does not hold the signals: it stores the file names and loads one recording at a time, so its memory use does not depend on the number of subjects. What it keeps in memory are the measures, e.g. one ERP per subject and condition, which are small.
The design table has one row per recording:
Column
Description
subject
subject identifier
session
session identifier (e.g. "1", "2"; repeated measures of one subject)
file name, relative to the study folder (root) or absolute
include
false excludes the recording from the analyses (without deleting it)
…
covariates (e.g. age, sex, scores)
The conditions (within-subject factor) are not part of the design: they are the conditions of the epochs of each recording (epoch metadata, see epoch() in the ERP tutorial).
Example data
The example data are a single recording (s1_faces.vhdr, see the ERP tutorial). To demonstrate the study functions, it is cut into eight parts of about 100 s (9–16 trials per condition), which play the role of eight subjects. They are assigned to two groups (A and B) and given an age. The groups are arbitrary: all differences between them are noise.
eeg =import_recording("files/eeg/s1_faces.vhdr")load_locs!(eeg; file_name ="files/locs/standard-10-20-cap81.locs")# study folder (temporary)study_dir =mktempdir()files =String[]# borders of the parts (s)edges =round.(Int, range(0, 829; length =9))for k in1:8 seg = (edges[k], edges[k +1]) part =trim(eeg; seg = seg, keep =true) f ="sub-0$(k)_task-faces_eeg.hdf"save_neuro(part; file_name =joinpath(study_dir, f))push!(files, f)endfiles
study_create() takes a list of files. Subjects and sessions are read from BIDS-style names (sub-<label>, ses-<label>); otherwise the subject is the file name and the session is "1". They can also be given explicitly (subject, session), as well as groups and covariates:
study =study_create(files; group =repeat(["A", "B"], 4), covariates = (; age = [25, 31, 28, 35,22, 40, 33, 29]), root = study_dir, name ="faces")
NeuroAnalyzer STUDY: faces
root: /tmp/jl_nzJniS
recordings: 8 (8 included), subjects: 8, sessions: 1
groups: A (4), B (4)
covariates: age
measures: none
study.design
8×6 DataFrame
Row
subject
session
group
file
include
age
String
String
String
String
Bool
Int64
1
01
1
A
sub-01_task-faces_eeg.hdf
true
25
2
02
1
B
sub-02_task-faces_eeg.hdf
true
31
3
03
1
A
sub-03_task-faces_eeg.hdf
true
28
4
04
1
B
sub-04_task-faces_eeg.hdf
true
35
5
05
1
A
sub-05_task-faces_eeg.hdf
true
22
6
06
1
B
sub-06_task-faces_eeg.hdf
true
40
7
07
1
A
sub-07_task-faces_eeg.hdf
true
33
8
08
1
B
sub-08_task-faces_eeg.hdf
true
29
A study can also be created from an existing design table (e.g. participants.tsv of a BIDS dataset read with CSV.jl), with the columns subject, session, group and file: study_create(design; root).
study_files() returns the full paths of the included recordings:
Measures of several recordings can be combined only if the recordings are compatible: the same data type, sampling rate and channels (in the same order) and, for epoched data, the same epoch time axis. study_check() loads every recording and compares it with the first one; issue describes the differences and the function to correct them (e.g. resample(), reorder_channel(), epoch()):
The continuous recordings differ in length, which is allowed. The measures (below) check the compatibility again and stop with an error naming the recording.
Batch processing
study_apply!() processes every included recording with a function: the recording is loaded, processed and saved to an output folder (out_dir, relative to the study folder), and the design table then points to the new files. The function either modifies the object in-place or returns a new object (e.g. epoch() returns the epoched object).
Here the recordings are filtered (0.1–30 Hz), re-referenced to the common average and epoched (200 ms before to 1000 ms after the markers s70 and s71, which become the epoch conditions):
The original files are not changed. An error in one recording does not stop the processing of the others: the error is reported in the returned table (ok, error) and the design table keeps the previous file of that recording.
The processing is recorded in the history of each recording (and can be exported as a script with export_history()):
Rejected epochs (see epoch_reject!()) are not used. Channels marked as bad in a recording are NaN in its measure, so that they are left out of the averages (only of that subject).
The measures are cached in the study (and saved with it, see below). study_measure!() with the same parameters does not compute the measure again, unless the included recordings or their files have changed (e.g. after another study_apply!()) or force = true:
Spectra and time-frequency power take the arguments of psd() and spectrogram(). The powers are stored in linear units (the conversion to dB is done when averaging):
study_average() averages a measure over subjects for each level of the design factor(s) by (default: :group) and each condition. The recordings of one subject (e.g. several sessions) are averaged first, unless :session is one of the factors, so each subject counts once. The result contains the mean, the standard deviation and the number of subjects:
by = Symbol[] averages all subjects together; by = [:group, :session] keeps the sessions apart; any column of the design table (e.g. a covariate category) can be used.
ERPs
study_erp() returns the grand average ERP as a NEURO object: epoch 1 is the grand average and the following epochs are the subjects, as after average_epochs(). It can be plotted with plot_erp() and plot_topo():
g =study_erp(study; condition ="s71")g.epochs
9×4 DataFrame
Row
condition
source
reject
onset
String
String
Bool
Float64
1
s71
grand average
false
NaN
2
s71
01
false
NaN
3
s71
02
false
NaN
4
s71
03
false
NaN
5
s71
04
false
NaN
6
s71
05
false
NaN
7
s71
06
false
NaN
8
s71
07
false
NaN
9
s71
08
false
NaN
plot_erp(g; ch ="O2-avg")
The subjects (type = :stack, one row per subject):
plot_erp(g; ch ="O2-avg", type=:stack)
Topographical map of the grand average at the positive peak (234 ms):
plot_topo(g; ch ="eeg", tpos =0.234)
Group ERPs are plotted with plot_study_erp(): the grand average of each level of a factor (factor: :condition, :session or a design column such as :group) with its 95% confidence interval across subjects (band = :ci95, t distribution; :se: ± standard error). subjects = true draws the ERPs of the subjects behind the grand averages, diff = true adds the difference wave of two levels (within subjects: the mean of the differences of the subjects; between groups: the difference of the grand averages with the Welch standard error). Several channels are averaged (region of interest):
The confidence interval of plot_erp(g; ci95 = true) is calculated over the epochs of g, here the subjects (with several channels, ci_over = :epochs averages the channels of each subject first; ci_over = :channels, the default, calculates it over the channels of the grand average):
plot_erp(g; ch ="O2-avg", ci95 =true, peaks =false)
Group averages (mean ± SD over subjects) as arrays, from study_average():
ga =study_average(study, :erp; condition ="s71")ch =findfirst(==("O2-avg"), ga.labels)fig =Figure(size = fig_size)ax =Axis(fig[1, 1]; xlabel ="Time [s]", ylabel ="Amplitude [μV]", title ="O2, condition s71 (mean ± SD)", ax_style...)for (k, grp) inenumerate(ga.levels.group) mu = ga.data[k, ch, :] sd = ga.sd[k, ch, :]band!(ax, ga.t, mu .- sd, mu .+ sd; alpha =0.3)lines!(ax, ga.t, mu; label ="group $grp")endaxislegend(ax; position =:rt)fig
Spectra
For powers (:psd, :tf), the power of each subject is converted to dB before averaging (db = true, default), as the distribution of dB values is closer to normal:
gp =study_average(study, :psd; by =Symbol[], condition ="s70")plot_psd(gp.f, gp.data[1, :, :]; clabels = gp.labels, xlabel ="Frequency [Hz]", ylabel ="Power [dB]")
Time-frequency power
Grand average time-frequency power of O2 (frequencies 2–30 Hz):
gt =study_average(study, :tf; by =Symbol[], condition ="s71")fi =findall(f ->2<= f <=30, gt.f)plot_spectrogram(gt.t, gt.f[fi], gt.data[1, 2, fi, :]; db =false, xlabel ="Time [s]", ylabel ="Frequency [Hz]", cb_title ="Power [dB]")
Power increases at 4–8 Hz at about 150–300 ms after the stimulus (the evoked response, see the ERP above). Wavelet power near the epoch edges is affected by edge effects.
Group statistics
Mass-univariate tests and multiple comparisons
ERPs, spectra and time-frequency maps are compared at every point: channel × time point (e.g. 30 × 614 = 18,420 tests), channel × frequency or channel × frequency × time point. This is a mass-univariate analysis: a t-test or an ANOVA at each point.
Function
Test
mass_ttest()
one-sample, paired or independent (Student or Welch) t-test
mass_anova()
one-way ANOVA between groups
mass_anova_rm()
one-way repeated-measures ANOVA (within subjects)
The functions take arrays with observations (subjects, epochs) along the first dimension, e.g. subjects × channels × time points, and return the statistics and the p-values of every point. Missing values (NaN, e.g. bad channels) are left out of the test of their point.
With thousands of tests, many points are “significant” by chance: at α = 0.05, 5% of the points of data without any effect. The p-values must be corrected for multiple comparisons, e.g. with p_adjust():
Method
Controls
Notes
:bonferroni
family-wise error rate
p × number of tests; very conservative
:holm
family-wise error rate
step-down Bonferroni; always at least as powerful
:fdr
false discovery rate
Benjamini-Hochberg; independent or positively dependent tests
:by
false discovery rate
Benjamini-Yekutieli; any dependence, conservative
The family-wise error rate (FWER) is the probability of any false positive; the false discovery rate (FDR) is the expected proportion of false positives among the significant points.
Cluster-based permutation tests
EEG effects are extended in time, frequency and space: neighbouring points are strongly correlated, so Bonferroni-type corrections are far too conservative. The cluster-based permutation test (Maris & Oostenveld 2007, cluster_perm()) uses this structure:
The statistic (t or F) is calculated at every point.
Points exceeding a threshold (the critical value at cluster_alpha, e.g. p < 0.05) form clusters of adjacent points: neighbouring time points and frequencies, and neighbouring channels (channel_adjacency()). The cluster mass is the sum of the statistic over its points.
The data are permuted many times (e.g. 1000): the signs of the subject differences are flipped (paired tests), the group labels are shuffled (independent samples) or the conditions are shuffled within subjects (repeated measures). The largest cluster mass of each permutation forms the null distribution.
The p-value of a cluster is the proportion of permutations with a larger maximal cluster mass.
The test controls the FWER: the probability that any cluster is significant when there is no effect is α. It does not need any assumption about the distribution of the data or the dependence of the points.
What a significant cluster does and does not show: the conditions differ (somewhere). Its extent (first and last time point, channels) is a description, not a statistical result: the test does not establish when or where the effect starts (Sassenhagen & Draschkow 2019).
The number of distinct permutations is limited by the number of subjects: with paired data of \(n\) subjects there are \(2^n\) sign flips, so the smallest possible p-value is \(1/2^n\) (with 4 subjects 1/16 = 0.0625: no cluster can be significant).
Testing study measures
study_stats() tests a study measure with the subjects as observations:
Conditions s71 and s70 (paired, within subjects), cluster-based permutation test (a random number generator with a seed makes the result reproducible):
stat is the t statistic at every point (s71 − s70), cluster_id the cluster of every point and mask the points of the significant clusters. The extent of the significant clusters:
for c ineachrow(st_cond.clusters[st_cond.clusters.p .<0.05, :]) pts =findall(==(c.id), st_cond.cluster_id) t1, t2 =extrema(st_cond.t[[p[2] for p in pts]]) chs =unique(st_cond.labels[[p[1] for p in pts]])println("Cluster ", c.id," (", c.sign >0 ? "s71 > s70":"s71 < s70", ")",": p = ", round(c.p; digits =3),", ", round(t1; digits =2), "–", round(t2; digits =2)," s, ", length(chs), " channels")end
After the stimulus, s71 is more negative than s70 at frontocentral channels from about 220 ms and more positive at posterior and temporal channels. With the average reference, the two clusters are probably the two poles of one effect.
The t statistic of all channels and time points (plot_study_stats()); the significant clusters are outlined and the channels are ordered by region (frontal → occipital, left → right):
plot_study_stats(st_cond)
The non-significant points can also be dimmed (sig = :dim or :both), and the p-values plotted instead of the statistic (value = :p or :p_adj, as −log₁₀ p):
plot_study_stats(st_cond; value =:p, sig =:both)
The ERPs of both conditions at Cz, their difference wave (s70 − s71) and the significant time points of Cz (bars below the waveforms; stats is the result of study_stats()):
Spectra are tested in dB (db = true), e.g. study_stats(study, :psd; factor = :condition); for time-frequency maps the clusters extend over channels, frequencies and time points.
The mass-univariate functions and cluster_perm() can also be used directly, e.g. to compare the epochs of two conditions of one recording (epochs as observations, independent samples), here the first subject:
With 9–13 epochs per condition, no cluster is significant in one subject: the effect is found by combining the subjects.
Excluding recordings
Setting include to false excludes a recording from the measures and averages (and from study_apply!()), without removing it from the study. A cached measure still contains the excluded recording, so it does not have to be computed again; recordings included after the measure was computed require study_measure!():
save_study() saves the design table, the cached measures and the history of the study (not the recordings) in a .hdf file; load_study() loads it (if the study folder was moved, its new location is given by root):
Maris E, Oostenveld R. Nonparametric statistical testing of EEG- and MEG-data. J Neurosci Methods. 2007;164(1):177-190.
Sassenhagen J, Draschkow D. Cluster-based permutation tests of MEG/EEG data do not establish significance of effect latency or location. Psychophysiology. 2019;56(6):e13335.
Benjamini Y, Hochberg Y. Controlling the false discovery rate: a practical and powerful approach to multiple testing. J R Stat Soc B. 1995;57(1):289-300.
Delorme A, Makeig S. EEGLAB: an open source toolbox for analysis of single-trial EEG dynamics including independent component analysis. J Neurosci Methods. 2004;134(1):9-21.