Group-Level Analysis

Initialize NeuroAnalyzer
using NeuroAnalyzer
using CairoMakie
CairoMakie.activate!(type = "png")
# Quarto sets a default figure size (672 × 480 px), which overrides the sizes of
# NeuroAnalyzer figures: remove it
delete!(CairoMakie.Makie.CURRENT_DEFAULT_THEME, :resolution)
using DataFrames
NeuroAnalyzer.progress_bar = false

# Makie figure and axis settings matching NeuroAnalyzer plots
fig_size = (900, 450)
ax_style = (titlesize = 18,
            xlabelsize = 18,
            ylabelsize = 18,
            xticklabelsize = 12,
            yticklabelsize = 12,
            xticks = LinearTicks(10),
            xminorticksvisible = true,
            xminorticks = IntervalsBetween(10),
            xautolimitmargin = (0, 0),
            yautolimitmargin = (0.1, 0.1))

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)
group between-subject factor (e.g. "patient", "control")
file 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 in 1: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)
end
files
8-element Vector{String}:
 "sub-01_task-faces_eeg.hdf"
 "sub-02_task-faces_eeg.hdf"
 "sub-03_task-faces_eeg.hdf"
 "sub-04_task-faces_eeg.hdf"
 "sub-05_task-faces_eeg.hdf"
 "sub-06_task-faces_eeg.hdf"
 "sub-07_task-faces_eeg.hdf"
 "sub-08_task-faces_eeg.hdf"

Creating a study

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:

study_files(study)
8-element Vector{String}:
 "/tmp/jl_nzJniS/sub-01_task-faces_eeg.hdf"
 "/tmp/jl_nzJniS/sub-02_task-faces_eeg.hdf"
 "/tmp/jl_nzJniS/sub-03_task-faces_eeg.hdf"
 "/tmp/jl_nzJniS/sub-04_task-faces_eeg.hdf"
 "/tmp/jl_nzJniS/sub-05_task-faces_eeg.hdf"
 "/tmp/jl_nzJniS/sub-06_task-faces_eeg.hdf"
 "/tmp/jl_nzJniS/sub-07_task-faces_eeg.hdf"
 "/tmp/jl_nzJniS/sub-08_task-faces_eeg.hdf"

Checking the 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()):

chk = study_check(study)
chk[!, [:subject, :sr, :channels, :epoch_len, :ok, :issue]]
8×6 DataFrame
Row subject sr channels epoch_len ok issue
String Int64 Int64 Int64 Bool String
1 01 512 34 53249 true
2 02 512 34 52737 true
3 03 512 34 53249 true
4 04 512 34 52737 true
5 05 512 34 53249 true
6 06 512 34 53249 true
7 07 512 34 52737 true
8 08 512 34 53249 true

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

function preprocess(obj)
    NeuroAnalyzer.filter!(obj;
                          ch = "eeg",
                          fprototype = :butterworth,
                          ftype = :hp,
                          cutoff = 0.1,
                          order = 4)
    NeuroAnalyzer.filter!(obj;
                          ch = "eeg",
                          fprototype = :butterworth,
                          ftype = :lp,
                          cutoff = 30,
                          order = 8)
    reference_avg!(obj)
    return epoch(obj;
                 marker_value = ["s70", "s71"],
                 offset = 0.2,
                 ep_len = 1.2)
end

r = study_apply!(study, preprocess; out_dir = "derivatives")
8×5 DataFrame
Row subject session file ok error
String String String Bool String
1 01 1 derivatives/sub-01_task-faces_eeg.hdf true
2 02 1 derivatives/sub-02_task-faces_eeg.hdf true
3 03 1 derivatives/sub-03_task-faces_eeg.hdf true
4 04 1 derivatives/sub-04_task-faces_eeg.hdf true
5 05 1 derivatives/sub-05_task-faces_eeg.hdf true
6 06 1 derivatives/sub-06_task-faces_eeg.hdf true
7 07 1 derivatives/sub-07_task-faces_eeg.hdf true
8 08 1 derivatives/sub-08_task-faces_eeg.hdf true
study.design.file
8-element Vector{String}:
 "derivatives/sub-01_task-faces_eeg.hdf"
 "derivatives/sub-02_task-faces_eeg.hdf"
 "derivatives/sub-03_task-faces_eeg.hdf"
 "derivatives/sub-04_task-faces_eeg.hdf"
 "derivatives/sub-05_task-faces_eeg.hdf"
 "derivatives/sub-06_task-faces_eeg.hdf"
 "derivatives/sub-07_task-faces_eeg.hdf"
 "derivatives/sub-08_task-faces_eeg.hdf"

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()):

obj = load_neuro(study_files(study)[1])
obj.history[(end - 3):end]
4-element Vector{String}:
 "filter(obj; ch=\"eeg\", fprototyp" ⋯ 231 bytes ⋯ " 0.102 Hz; 0 Hz: -12306.106 dB"
 "filter(obj; ch=\"eeg\", fprototyp" ⋯ 226 bytes ⋯ "dB at 29.991 Hz; 0 Hz: -0.0 dB"
 "reference_avg(obj; exclude_fpo=" ⋯ 40 bytes ⋯ "ue, med=false, weighted=false)"
 "epoch(obj; marker_value=[\"s70\"," ⋯ 106 bytes ⋯ " reject=nothing, flat=nothing)"

The recordings are processed one after another: the processing functions use all threads.

After processing, all recordings have the same epochs and conditions:

chk = study_check(study)
chk[!, [:subject, :epochs, :conditions, :ok]]
8×4 DataFrame
Row subject epochs conditions ok
String Int64 String Bool
1 01 21 s71, s70 true
2 02 26 s70, s71 true
3 03 25 s71, s70 true
4 04 26 s70, s71 true
5 05 26 s71, s70 true
6 06 26 s70, s71 true
7 07 26 s71, s70 true
8 08 21 s71, s70 true

Measures

study_measure!() computes a measure of every included recording and condition:

Measure Description Shape
:erp average of the epochs (ERP/ERF) recording × condition × channel × time
:psd power spectral density averaged over epochs recording × condition × channel × frequency
:tf time-frequency power averaged over epochs recording × condition × channel × frequency × time

ERPs of the EEG channels with baseline correction (−200–0 ms):

study_measure!(study, :erp; ch = "eeg", bl = (-0.2, 0))
m = study.measures[:erp]
println("Data: ", size(m.data))
println("Conditions: ", m.conditions)
println("Time: ", m.t[1], " … ", round(m.t[end]; digits = 3), " s")
Data: (8, 2, 30, 614)
Conditions: ["s71", "s70"]
Time: -0.2 … 0.997 s

The number of epochs of each recording (rows) and condition (columns):

m.n_epochs
8×2 Matrix{Int64}:
 11  10
 13  13
  9  16
 14  12
 14  12
 10  16
 14  12
 12   9

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:

study_measure!(study, :erp; ch = "eeg", bl = (-0.2, 0))

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_measure!(study, :psd; ch = "eeg", flim = (1, 30))
study_measure!(study, :tf;
               ch = ["O1-avg", "O2-avg"],
               method = :mw,
               ncyc = (3, 10))
println("PSD: ", size(study.measures[:psd].data))
println("TF: ", size(study.measures[:tf].data))
PSD: (8, 2, 30, 30)
TF: (8, 2, 2, 257, 614)

Grand averages

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:

ga = study_average(study, :erp)
ga.levels
4×3 DataFrame
Row group condition n
String String Int64
1 A s71 4
2 A s70 4
3 B s71 4
4 B s70 4
println("Mean: ", size(ga.data), " (level × channel × time)")
Mean: (4, 30, 614) (level × channel × time)

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

plot_study_erp(study;
               ch = ["O1-avg", "Oz-avg", "O2-avg"],
               factor = :group,
               condition = "s71",
               subjects = true)

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) in enumerate(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")
end
axislegend(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:

  1. The statistic (t or F) is calculated at every point.
  2. 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.
  3. 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.
  4. 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:

factor Levels Test
:group (any design column) groups (between subjects) independent t-test (2 levels), ANOVA (more levels)
:condition conditions (within subjects) paired t-test (2 levels), repeated-measures ANOVA
:session sessions (within subjects) paired t-test (2 levels), repeated-measures ANOVA

correction is :cluster (default) or one of the p_adjust() methods (:none: uncorrected).

Channel adjacency from the channel locations (channels closer than 1.5 × the median distance to the nearest channel are neighbours):

adj = channel_adjacency(g; ch = "eeg")
println("Neighbours per channel: ", extrema(sum(adj; dims = 2) .- 1))
Neighbours per channel: (2, 6)

Conditions s71 and s70 (paired, within subjects), cluster-based permutation test (a random number generator with a seed makes the result reproducible):

using Random
st_cond = study_stats(study,
                      :erp;
                      factor = :condition,
                      ch_adj = adj,
                      nperm = 1000,
                      rng = Xoshiro(1))
println("Test: ", st_cond.test, ", subjects: ", st_cond.n[1])
first(st_cond.clusters, 5)
Test: ttest_paired, subjects: 8
5×5 DataFrame
Row id sign mass size p
Int64 Int64 Float64 Int64 Float64
1 40 -1 -6339.47 1404 0.012987
2 15 1 2935.42 750 0.03996
3 43 -1 -1194.57 343 0.0969031
4 45 -1 -1156.28 358 0.142857
5 39 -1 -1089.54 272 0.160839

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 in eachrow(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
Cluster 40 (s71 < s70): p = 0.013, 0.22–0.65 s, 17 channels
Cluster 15 (s71 > s70): p = 0.04, 0.19–0.48 s, 15 channels

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()):

plot_study_erp(study;
               ch = "Cz-avg",
               factor = :condition,
               levels = ["s70", "s71"],
               diff = true,
               stats = st_cond)

For comparison, the number of points significant without correction and after the FDR correction:

st_fdr = study_stats(study, :erp; factor = :condition, correction = :fdr)
println("p < 0.05 (uncorrected): ", count(<(0.05), filter(!isnan, st_fdr.p)))
println("FDR q < 0.05: ", count(st_fdr.mask))
println("Cluster test: ", count(st_cond.mask))
p < 0.05 (uncorrected): 4179
FDR q < 0.05: 937
Cluster test: 2154

Groups A and B (independent samples, condition s71). The groups are arbitrary, so no cluster should be significant:

st_grp = study_stats(study,
                     :erp;
                     factor = :group,
                     condition = "s71",
                     ch_adj = adj,
                     rng = Xoshiro(1))
println("Test: ", st_grp.test, ", subjects: ", st_grp.n)
first(st_grp.clusters, 3)
Test: ttest, subjects: [4, 4]
3×5 DataFrame
Row id sign mass size p
Int64 Int64 Float64 Int64 Float64
1 20 1 1222.98 359 0.0769231
2 22 1 430.03 114 0.422577
3 18 1 400.319 130 0.422577

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:

obj = load_neuro(study_files(study)[1])
chi = get_channel(obj; ch = "eeg")
ep70 = get_epochs(obj; condition = "s70")
ep71 = get_epochs(obj; condition = "s71")
# epochs × channels × time points
e70 = permutedims(obj.data[chi, :, ep70], (3, 1, 2))
e71 = permutedims(obj.data[chi, :, ep71], (3, 1, 2))
r = cluster_perm(e71, e70;
                 ch_adj = channel_adjacency(obj; ch = "eeg"),
                 rng = Xoshiro(1))
first(r.clusters, 3)
3×5 DataFrame
Row id sign mass size p
Int64 Int64 Float64 Int64 Float64
1 43 -1 -500.967 164 0.173826
2 11 1 335.263 109 0.418581
3 5 1 220.295 87 0.742258

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!():

study.design.include[8] = false
study_average(study, :erp; condition = "s71").levels
2×3 DataFrame
Row group condition n
String String Int64
1 A s71 4
2 B s71 3
study.design.include[8] = true

Saving and loading

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

study_file = joinpath(study_dir, "faces.hdf")
save_study(study; file_name = study_file)
study = load_study(study_file)
NeuroAnalyzer STUDY: faces
  root: /tmp/jl_nzJniS
  recordings: 8 (8 included), subjects: 8, sessions: 1
  groups: A (4), B (4)
  covariates: age
  measures: erp, psd, tf

The history of the study:

study.history
5-element Vector{String}:
 "study_create(design; root = \"/tmp/jl_nzJniS\", name = \"faces\")"
 "study_apply!(study, preprocess; out_dir = \"derivatives\", all = false)"
 "study_measure!(study, :erp; ch = \"eeg\", condition = nothing, bl = (-0.2, 0))"
 "study_measure!(study, :psd; ch = \"eeg\", condition = nothing, flim = (1, 30))"
 "study_measure!(study, :tf; ch =" ⋯ 43 bytes ⋯ " method = :mw, ncyc = (3, 10))"

References

  1. Maris E, Oostenveld R. Nonparametric statistical testing of EEG- and MEG-data. J Neurosci Methods. 2007;164(1):177-190.
  2. 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.
  3. 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.
  4. 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.