NeuroAnalyzer.NEURO

NeuroAnalyzer functions operate on NeuroAnalyzer objects. The main object is NeuroAnalyzer.NEURO, which holds a single recording of any type (e.g. EEG, MEG or NIRS) together with its metadata.

mutable struct NEURO
    header::NeuroAnalyzer.HEADER
    history::Vector{String}
    markers::DataFrame
    epochs::DataFrame
    locs::DataFrame
    time_pts::Vector{Float64}
    epoch_time::Vector{Float64}
    data::Array{Float64, 3}
end
Field Contents
header metadata: subject, recording and notes (see Header)
history list of the processing steps applied to the object, with their parameters
markers event markers (see Event markers)
epochs epoch metadata, one row per epoch (see Epoch metadata)
locs channel (electrode, magnetometer, gradiometer or optode) locations
time_pts time of each sample (in seconds) from the start of the recording
epoch_time time of each sample (in seconds) within an epoch; negative before the event onset
data the signal: channels × samples × epochs

A NEURO object is created by importing a recording (e.g. import_edf(), import_fiff(), import_snirf()), by loading a saved object (load_neuro()) or by creating an empty object (create_object()). Objects are saved with save_neuro().

using NeuroAnalyzer
eeg = import_edf("files/eeg/eeg-test-edf.edf")
println("data type:     ", datatype(eeg))
println("channels:      ", nchannels(eeg))
println("epochs:        ", nepochs(eeg))
println("sampling rate: ", sr(eeg), " Hz")
println("duration:      ", signal_duration(eeg), " s")
data type:     eeg
channels:      24
epochs:        1
sampling rate: 256 Hz
duration:      1205.0 s

info() prints a summary of the object:

info(eeg)
              Data type: EEG
            File format: EDF
            Source file: files/eeg/eeg-test-edf.edf
         File size [MB]: 14.13
       Memory size [MB]: 61.2
                Subject:  528004  SIT 52, 20220831-122227-{d589f756-53fc-4f1b-915d-6e3b8c1560ad}
              Recording: EEGDigiTrack EEG-1042 (42-channel EEG Amplifier) V0.5 Rev. 41
         Recording date: 31.08.22
         Recording time: 12:32:53
     Sampling rate (Hz): 256
Signal length [samples]: 308480
Signal length [seconds]: 1205.0
     Number of channels: 24
       Epoch conditions: none
       Number of epochs: 1
 Epoch length [samples]: 308480
 Epoch length [seconds]: 1205.0
         Reference type: physical
         Line frequency: 50 Hz
                Markers: no
      Channel locations: yes (unit unknown)
 Number of EEG channels: 19

Channels:
 ch     label           type        unit    bad     
 ------ --------------- ----------- ------- -------
 1      Fp1             EEG         μV      false   
 2      Fp2             EEG         μV      false   
 3      F3              EEG         μV      false   
 4      F4              EEG         μV      false   
 5      C3              EEG         μV      false   
 6      C4              EEG         μV      false   
 7      P3              EEG         μV      false   
 8      P4              EEG         μV      false   
 9      O1              EEG         μV      false   
 10     O2              EEG         μV      false   
 11     F7              EEG         μV      false   
 12     F8              EEG         μV      false   
 13     T3              EEG         μV      false   
 14     T4              EEG         μV      false   
 15     T5              EEG         μV      false   
 16     T6              EEG         μV      false   
 17     A1              REF         μV      false   
 18     A2              REF         μV      false   
 19     Fz              EEG         μV      false   
 20     Cz              EEG         μV      false   
 21     Pz              EEG         μV      false   
 22     EOG1            EOG         μV      false   
 23     EOG2            EOG         μV      false   
 24     ECG             ECG         μV      false   

Functions operating on NEURO objects take the object(s) as positional arguments and all other arguments as keyword arguments, e.g. delete_epoch!(eeg; ep = 12). Multiple dispatch is used wherever possible.

Most edit and process functions have a mutator variant (e.g. delete_epoch() and delete_epoch!()). Mutators modify the input object in place: delete_channel!(eeg; ch = "Fp1") instead of eeg = delete_channel(eeg; ch = "Fp1"). Functions without ! return a new object and leave the input unchanged.

Channels are selected with the ch keyword, by label (ch = "C4"), by several labels (ch = ["Fp1", "Fp2"]), by type (ch = "eeg", ch = ["eeg", "eog"]), with a regular expression (ch = r"^F"), or as ch = "all" or ch = "bad". See the Glossary.

Functions whose names start with _ (e.g. NeuroAnalyzer._band_power()) are private: they work on plain vectors and arrays, are used internally by the public functions, and may change without notice.

NeuroAnalyzer.STUDY

NeuroAnalyzer.STUDY describes a group of recordings for group-level analysis (see Group-Level Analysis):

mutable struct STUDY
    name::String
    notes::String
    root::String
    design::DataFrame
    measures::Dict{Symbol, Any}
    history::Vector{String}
end
Field Contents
name study name
notes free-text notes (e.g. the aim of the study, inclusion criteria); study_create(...; notes = "...") or study.notes = "..."
root base folder; relative file names are relative to it
design design table: one row per recording (subject, session, group, file, include, covariates)
measures cached measures (:erp, :psd, :tf) of all recordings and conditions, see study_measure!()
history processing history

The study holds the file names, not the signals: recordings are loaded one at a time. It is created with study_create() or from a BIDS dataset with study_bids(), and saved with save_study().

NeuroAnalyzer.DIPOLE

NeuroAnalyzer.DIPOLE holds an equivalent current dipole fitted with dipole_fit():

mutable struct DIPOLE
    pos::Matrix{Float64}
    q::Matrix{Float64}
    gof::Vector{Float64}
    sphere_center::Vector{Float64}
    sphere_radius::Float64
    frame::Symbol
    header::Dict{Symbol, Any}
end
Field Contents
pos dipole position(s): 1 × 3 (fixed dipole) or time points × 3 (moving dipole)
q dipole moments: 3 × time points
gof goodness of fit (0–1), one value per fit
sphere_center center of the fitted head sphere
sphere_radius radius of the fitted head sphere
frame coordinate frame of pos and q: :head (BEM model: head frame of the recording, mm, nAm) or :unknown (spherical model: units of the channel locations)
header head model, channels, units, time points

DIPOLE(pos, q) creates a single dipole in a unit sphere (without a fit, frame = :unknown), e.g. for simulations. Dipoles are plotted with plot_dipole() (ICBM152 template head) and with plot_slices(mri; dipole = d) and plot_surface(srf; dipole = d) (MRI and surfaces of the subject; a dipole in the head frame is moved to the MRI by the coregistration transform, trans, or the anatomical landmarks, landmarks), see Dipole Fitting.

NeuroAnalyzer.MRI

NeuroAnalyzer.MRI holds an MRI volume (or a series of volumes, e.g. fMRI or diffusion-weighted images):

mutable struct MRI
    data::Array{Float32, 4}
    affine::Matrix{Float64}
    frame::Symbol
    header::Dict{Symbol, Any}
    history::Vector{String}
end
Field Contents
data voxel values: x × y × z × volumes (1 volume for anatomical images, e.g. T1)
affine 4 × 4 transformation from voxel indices to coordinates in mm in frame
frame coordinate frame: :ras (scanner RAS), :tkr (FreeSurfer surface RAS), :mni (MNI space), :head (EEG/MEG head frame) or :unknown
header file name, modality and the original header fields
history processing history

The voxels are stored in the orientation of the file (they are not resampled); the orientation, voxel size and position of the volume in space are given by the affine. As in NIfTI and MGH files, the affine uses 0-based voxel indices \((i, j, k)\):

\[ \begin{bmatrix} x \\ y \\ z \\ 1 \end{bmatrix} = A \begin{bmatrix} i \\ j \\ k \\ 1 \end{bmatrix} \]

and voxel \((i, j, k)\) of volume \(v\) is data[i + 1, j + 1, k + 1, v]. The values are stored as Float32 (half the memory of Float64; label volumes, e.g. FreeSurfer aseg, are stored exactly). voxel_size() returns the size of the voxels in mm.

An MRI object is created from an array (3D data are one volume; default affine: 1 mm voxels, origin at the first voxel):

mri = NeuroAnalyzer.MRI(data;
                        affine = A,
                        frame = :ras)
voxel_size(mri)

NeuroAnalyzer.SURFACE

NeuroAnalyzer.SURFACE holds a triangulated surface (mesh), e.g. the scalp, skull or cortex:

mutable struct SURFACE
    vertices::Matrix{Float64}
    faces::Matrix{Int64}
    values::Dict{Symbol, Matrix{Float64}}
    frame::Symbol
    header::Dict{Symbol, Any}
    history::Vector{String}
end
Field Contents
vertices vertex coordinates in mm: vertices × 3 (x, y, z)
faces triangles: triangles × 3 (vertex numbers, counter-clockwise seen from outside, i.e. the normals point outwards)
values data defined at the vertices, by name: vertices × components (e.g. :thickness: n × 1, :E: n × 3 for the electric field vector)
frame coordinate frame (as for MRI)
header file name, surface type (e.g. pial, white, scalp) and the original header fields
history processing history
srf = NeuroAnalyzer.SURFACE(vertices, faces; frame = :tkr)

Values defined at the vertices (e.g. curvature or cortical thickness, source estimates, the electric field of a brain stimulation simulation) are stored in values; a vector is one component:

srf = NeuroAnalyzer.SURFACE(vertices, faces;
                            values = Dict(:magnE => magn_e,
                                          :E => e_xyz),
                            frame = :tkr)
srf.values[:magnE]

MRI volumes and surfaces are separate objects, not parts of the NEURO object: one MRI can be used with several recordings of the same subject. Their coordinates are related to the channel locations of a recording by the coordinate frame and a coregistration transformation (head frame ↔︎ MRI).

NeuroAnalyzer.BEM

NeuroAnalyzer.BEM holds a boundary element model of the head (see Head Models): nested closed surfaces separating compartments of constant conductivity, optionally with the BEM solution:

mutable struct BEM
    surfaces::Vector{SURFACE}
    conductivity::Vector{Float64}
    solution::Matrix{Float64}
    method::Symbol
    frame::Symbol
    header::Dict{Symbol, Any}
    history::Vector{String}
end
Field Contents
surfaces closed surfaces, innermost first (1 layer: inner skull; 3 layers: inner skull, outer skull, scalp), in the same frame
conductivity conductivity (S/m) of the compartment inside each surface; outside the outermost surface is air
solution BEM solution matrix (potentials at the collocation points of all surfaces); 0 × 0 if the model is not solved
method collocation: :linear (at the vertices) or :constant (at the triangles)
frame coordinate frame of the surfaces (as for MRI)
header file name, solver and the original fields
history processing history

The surfaces must be closed, with the normals pointing outwards, and nested. A model is created from surfaces and conductivities (the frame is taken from the surfaces), or loaded with import_bem():

bem = NeuroAnalyzer.BEM([inner_skull, outer_skull, scalp], [0.3, 0.006, 0.3])

NeuroAnalyzer.SOURCESPACE

NeuroAnalyzer.SOURCESPACE holds the candidate source (dipole) locations of one or more spaces, e.g. the two cortical surfaces, a volume grid inside the inner skull or discrete points (see Head Models):

mutable struct SOURCESPACE
    pos::Matrix{Float64}
    normals::Matrix{Float64}
    space::Vector{Int64}
    vertices::Vector{Int64}
    spaces::Vector{Symbol}
    kind::Vector{Symbol}
    triangles::Vector{Matrix{Int64}}
    frame::Symbol
    header::Dict{Symbol, Any}
    history::Vector{String}
end
Field Contents
pos source positions in mm: sources × 3 (x, y, z), ordered by space
normals unit vectors: sources × 3 (cortical surfaces: normal to the cortex)
space space of each source (index into spaces)
vertices index of each source in the full surface or grid of its space
spaces name of each space, e.g. :lh, :rh, :volume
kind kind of each space: :surface, :volume or :discrete
triangles per space: triangles between its sources (indices into the sources of that space); 0 × 3 if none
frame coordinate frame (as for MRI)
header file name and per-space information (e.g. the volume grid)
history processing history

Source spaces are loaded with import_src() or created with source_space_volume(); the columns of a forward solution follow the order of the sources.

NeuroAnalyzer.FORWARD

NeuroAnalyzer.FORWARD holds a forward solution (lead field): the signal at each channel produced by a dipole of unit moment (1 A·m) at each source (see Forward Solutions):

mutable struct FORWARD
    gain::Matrix{Float64}
    labels::Vector{String}
    channel_type::Vector{String}
    src::SOURCESPACE
    orientation::Symbol
    frame::Symbol
    header::Dict{Symbol, Any}
    history::Vector{String}
end
Field Contents
gain gain matrix: channels × (3 × sources) (free orientation: dipoles along x, y, z of frame) or channels × sources (fixed orientation: dipoles along the normals)
labels channel labels (rows of gain)
channel_type channel types: "eeg", "mag", "grad"
src sources (columns of gain), in frame
orientation :free or :fixed
frame coordinate frame of the sources and dipole orientations (as for MRI)
header file name, units (SI per A·m: V for EEG, T for magnetometers, T/m for gradiometers), transforms (mm), bad channels
history processing history

Forward solutions are loaded with import_fwd() or computed with forward() and forward_eeg().

NeuroAnalyzer.NOISECOV

NeuroAnalyzer.NOISECOV holds a noise covariance for source localization (see Noise Covariance):

mutable struct NOISECOV
    cov::Matrix{Float64}
    labels::Vector{String}
    channel_type::Vector{String}
    units::Vector{String}
    nfree::Int64
    method::Symbol
    shrinkage::Float64
    reg::Float64
    header::Dict{Symbol, Any}
    history::Vector{String}
end
Field Contents
cov covariance: channels × channels, symmetric, in the units of the channels (μV², fT², (fT/cm)²)
labels channel labels
channel_type channel types
units units of the channels
nfree degrees of freedom (number of samples - 1)
method :empirical, :ledoit_wolf, :imported or :unknown
shrinkage Ledoit-Wolf shrinkage (0: none)
reg regularization: fraction of the mean variance of each channel type added to the diagonal
header file name and the original fields
history processing history

The noise covariance is estimated with noise_cov(), loaded with import_cov(), or created from a matrix and the channels (e.g. a diagonal model of the sensor noise):

nc = NeuroAnalyzer.NOISECOV(cov, labels, channel_type)

NeuroAnalyzer.SOURCEESTIMATE

NeuroAnalyzer.SOURCEESTIMATE holds a source estimate: the activity of each source of a source space over time, the output of the inverse methods (as SourceEstimate and VectorSourceEstimate of MNE-Python):

mutable struct SOURCEESTIMATE
    data::Array{Float64, 3}
    src::SOURCESPACE
    time::Vector{Float64}
    measure::Symbol
    units::String
    header::Dict{Symbol, Any}
    history::Vector{String}
end
Field Contents
data sources × components × time points: 1 component (scalar: e.g. current along the normal, amplitude, dSPM, power) or 3 components (vector: along x, y, z of the frame of src)
src sources (rows of data), in their frame
time time points (s), e.g. the epoch time (0: stimulus)
measure what the values are: :current, :amplitude, :dspm, :sloreta, :eloreta, :power or :unknown
units units of the values, e.g. "nAm"; "" for unitless measures (dSPM, sLORETA)
header inverse method, regularization, channels, file name, subject
history processing history

A source estimate is created from a matrix (sources × time points: scalar) or an array (sources × 3 × time points: vector) and the source space:

stc = NeuroAnalyzer.SOURCEESTIMATE(data,
                                   src,
                                   time;
                                   measure = :current,
                                   units = "nAm")

Source estimates of MNE-Python (.stc, .w) are loaded with import_stc(), with their source space (the files contain the vertex numbers of the sources, not their positions):

src = import_src("sample-oct-6-src.fif")
stc = import_stc("sample_audvis-meg-lh.stc", src)

Scalar source estimates are saved as files of MNE-Python with export_stc() (cortical source spaces: <name>-lh.stc and <name>-rh.stc; volume: <name>-vl.stc). The sources of a cortical source space are vertices of the surfaces of the subject: stc_surface() returns the full surface of a hemisphere (?h.white, ?h.pial, ?h.inflated) with the values of a time point spread to all its vertices (values[:stc]; smoothing over the surface as MNE-Python, or nearest source), and plot_stc() plots them over time (time slider, time course of the peak source, animations; see Minimum-norm estimates):

export_stc("auditory.stc", stc)
lh = stc_surface(stc, import_surf("lh.white"; tkr = true); t = 10, smooth = 10)
plot_stc(stc, [import_inflated("lh.inflated"), import_inflated("rh.inflated")]; t = 10)
plot_stc(stc, import_inflated("lh.inflated"); t = 1:20, file_name = "auditory.mp4")

NeuroAnalyzer.INVERSE

NeuroAnalyzer.INVERSE holds an inverse operator of the minimum-norm methods (MNE, dSPM, sLORETA, eLORETA): the parts of the source estimate that do not depend on the data, computed once and applied to any data, method and regularization (as InverseOperator of MNE-Python):

mutable struct INVERSE
    labels::Vector{String}
    channel_type::Vector{String}
    src::SOURCESPACE
    orientation::Symbol
    loose::Float64
    depth::Float64
    source_nn::Matrix{Float64}
    source_cov::Vector{Float64}
    whitener::Matrix{Float64}
    eigen_fields::Matrix{Float64}
    sing::Vector{Float64}
    eigen_leads::Matrix{Float64}
    noise_cov::NOISECOV
    frame::Symbol
    header::Dict{Symbol, Any}
    history::Vector{String}
end
Field Contents
labels channels (columns of whitener)
channel_type channel types: "eeg", "mag", "grad"
src sources, in frame
orientation :fixed (one column per source, along the normal) or :free (three columns per source)
loose weight of the tangential components: 0 (fixed), 0–1 (loose), 1 (free)
depth exponent of the depth weighting (0: none; NaN: unknown, imported operators)
source_nn orientation of each column (columns × 3): normals, local surface frames (loose) or x, y, z (free)
source_cov source covariance R of each column: depth weighting × orientation prior, scaled
whitener whitener W (components × channels, units of NeuroAnalyzer signals; projectors included)
eigen_fields Uᵀ of the SVD of the whitened and weighted lead field W G R^(1/2) = U diag(s) Vᵀ
sing singular values s
eigen_leads V (columns × components)
noise_cov noise covariance of the channels
frame coordinate frame of the sources and orientations
header file name, depth and orientation priors, projectors, rank, transforms
history processing history

The minimum-norm estimate is K * data, with the kernel K = R^(1/2) V diag(s / (s² + λ)) Uᵀ W (A·m); dSPM and sLORETA divide it by its noise; eLORETA replaces R by source weights fitted iteratively (stored in header[:eloreta]). The inverse operator is computed from a forward solution and a noise covariance with inverse_operator(), or loaded with import_inv() (saved for MNE-Python with export_inv()); the source estimate (SOURCEESTIMATE) is computed with apply_inverse():

inv = inverse_operator(fwd, nc; loose = 0.2, depth = 0.8)
stc = apply_inverse(inv, erp; method = :dspm, λ = 1 / 9)