Initialize NeuroAnalyzer
using NeuroAnalyzer
import CairoMakie
# 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 NeuroAnalyzer
import CairoMakie
# 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)Source imaging (source localization, source reconstruction) estimates the activity of the brain sources that generated the EEG or MEG: where the activity comes from, and its time course at each location. EEG and MEG measure the activity with a millisecond resolution, but at the sensors: each channel records a mixture of many sources, spread by volume conduction (EEG) or by the distance to the sensors (MEG). A model of the head and of the sensors is used to go back from the sensors to the sources.
| Concept | Description |
|---|---|
| Source model | where the sources can be: a few equivalent current dipoles, or thousands of dipoles on the cortex (source space) |
| Head model | geometry and conductivities of the head tissues (spheres, or realistic models from the MRI: BEM, FEM) |
| Coregistration | transform between the head frame of the sensors and the MRI |
| Forward solution | lead field: the signal of each sensor for a unit dipole at each source location and orientation |
| Noise covariance | covariance of the signals without the activity of interest: weights and combines the channels |
| Inverse solution | the estimate of the sources from the data, the forward solution and the noise covariance |
The physics of the sources and of volume conduction, and the forward problem in a spherical head, are described in the Brain electric model tutorial.
The measured data are a linear combination of the activity of the sources:
\[ \mathbf{m}(t) = \mathbf{L} \mathbf{j}(t) + \mathbf{n}(t) \]
where \(\mathbf{m}\) are the signals of the \(N\) channels, \(\mathbf{L}\) is the \(N \times M\) lead field (forward solution) of \(M\) source components, \(\mathbf{j}\) the source strengths and \(\mathbf{n}\) the noise. The forward problem (computing \(\mathbf{L}\)) has a unique solution. The inverse problem (estimating \(\mathbf{j}\) from \(\mathbf{m}\)) is ill-posed:
The inverse methods differ in their assumptions about the sources.
| Aspect | Forward problem | Inverse problem |
|---|---|---|
| Definition | calculate the EEG/MEG from known sources | estimate the sources from the EEG/MEG |
| Uniqueness | unique solution | infinitely many solutions; constraints needed |
| Input | sources and head model | measured data, forward solution, noise covariance |
| Output | potentials or fields at the sensors | source locations, orientations and strengths |
| Methods | analytical (spheres) and numerical (BEM, FEM, FDM) solutions | dipole fitting, minimum-norm methods, beamformers, Bayesian and machine-learning methods |
| Main difficulties | accuracy of geometry and conductivities, computational cost | non-uniqueness, noise, model errors, choice of constraints and regularization |
Assumption: the data are generated by a small number of focal sources (equivalent current dipoles).
Suited for focal activity (early sensory responses, epileptic spikes); the number of dipoles must be known, and the fit can end in local minima. See the Dipole fitting tutorial.
Assumption: the activity is distributed over many sources (e.g. thousands of dipoles on the cortical surface); the number of sources is much larger than the number of sensors, so constraints are added:
\[ \hat{\mathbf{j}} = \arg\min_{\mathbf{j}} \left( \|\mathbf{m} - \mathbf{L}\mathbf{j}\|^2 + \lambda \|\mathbf{j}\|^2 \right) = \mathbf{L}^T (\mathbf{L}\mathbf{L}^T + \lambda \mathbf{I})^{-1} \mathbf{m} \]
where \(\lambda\) is the regularization parameter, balancing the fit to the data and the stability of the solution (it depends on the noise level; the noise covariance is used instead of \(\mathbf{I}\) in practice). The two equivalent forms \((\mathbf{L}^T\mathbf{L} + \lambda \mathbf{I})^{-1} \mathbf{L}^T \mathbf{m}\) and \(\mathbf{L}^T (\mathbf{L}\mathbf{L}^T + \lambda \mathbf{I})^{-1} \mathbf{m}\) give the same result; the second inverts only an \(N \times N\) matrix (sensors). MNE favours superficial sources (they explain the data with smaller strengths).
Distributed models need no assumption about the number of sources and capture extended activity, but the estimates are blurred and depend on the regularization.
Beamformers (e.g. LCMV in the time domain, DICS in the frequency domain) construct a spatial filter for each location that passes the activity from that location and suppresses the activity from elsewhere (minimizing the output variance under the constraint of unit gain at the location); the brain is scanned location by location.
They give a good spatial resolution for well-separated sources and are robust to noise, but they assume that the sources are uncorrelated: correlated sources (e.g. both auditory cortices) are suppressed. They need a good estimate of the data covariance (enough data).
Deep neural networks (e.g. convolutional networks) can be trained on simulated data (from forward models) to map scalp topographies to source distributions; they depend on the realism of the training simulations.
| Method | Assumption | Data | Output | Limitations | NeuroAnalyzer |
|---|---|---|---|---|---|
| Dipole fitting | few focal sources | averaged responses, spikes (high SNR) | position, orientation, moment, GOF | number of dipoles must be known; local minima | dipole_fit() |
| MNE, wMNE | distributed, smallest total power | averaged responses, continuous data | current at every source | blurred; bias to superficial sources (MNE) | inverse_operator(), apply_inverse() (wMNE: depth) |
| dSPM, sLORETA, eLORETA | as MNE, normalized by noise | as MNE | statistical or standardized maps | blurred; values are not currents | apply_inverse() (dSPM, sLORETA); eLORETA planned |
| LCMV, DICS | uncorrelated sources | long segments: data covariance (LCMV), cross-spectra (DICS) | power or time course at each location | correlated sources are suppressed | planned |
See the Minimum-Norm Estimates tutorial, and the roadmap for the planned methods.
Source imaging joins three branches: the anatomy (the MRI of the subject, or a template head), the sensors (their positions on the head) and the data. They meet in the forward solution and in the inverse solution:
anatomy sensors data
MRI (or template) landmarks, electrodes, EEG/MEG recording
│ head shape, HPI coils │
▼ │ ▼
surfaces, BEM model, │ preprocessing
source space │ (filters, bad channels,
│ ▼ artifacts, reference)
├───────────────────► coregistration │
│ (head → MRI) ▼
▼ │ epochs, averaging
forward solution ◄────────────┘ │ │
(lead field) ▼ │
│ baseline: │
│ noise covariance │
▼ │ │
inverse solution ◄─────────────────────────────────┴────────────┘
│ noise covariance,
▼ active window
sources on the MRI, the cortex, atlas regions
| Step | What | NeuroAnalyzer | Tutorial |
|---|---|---|---|
| 1. Anatomy | MRI segmentation, surfaces, BEM surfaces (FreeSurfer recon-all, mne watershed_bem) |
import_mgh(), import_surf(), import_bem(); templates (fsaverage, ICBM152, Colin27) |
MRI, BEM |
| 2. Head model | BEM model and solution | import_bem(), BEM |
BEM |
| 3. Source space | sources on the cortex or in a volume grid | source_space(), source_space_volume(), import_src() |
BEM |
| 4. Coregistration | transform from the head frame of the sensors to the MRI | import_dig(), coregister(), import_trans() |
Coregistration |
| 5. Forward solution | lead field of the channels of the recording | forward(), forward_eeg(), import_fwd() |
Forward solutions |
| 6. Data | preprocessing, epochs, averaging | filter(), reference_avg(), ica_decompose(), generate_ssp_projectors(), maxwell_filter(), epoch(), average_epochs() |
ERP |
| 7. Noise covariance | from the baseline or an empty-room recording | noise_cov(), import_cov() |
Noise covariance |
| 8. Inverse solution | dipoles or distributed sources | dipole_fit(), whitener(), inverse_operator(), apply_inverse(), import_inv() |
Dipole fitting, Minimum-norm estimates |
| 9. Results | sources on the MRI, the cortex and a template head | plot_dipole(), plot_slices(), plot_surface(), import_annot(), import_stc() |
Dipole fitting, Minimum-norm estimates |
Steps 1–5 depend only on the subject and the sensor positions: they are done once per subject (and session, for MEG, where the head moves in the helmet), and can be reused for all recordings of the session.
The data enter the workflow at three points: the sensor positions (coregistration and forward solution), the baseline (noise covariance) and the signals of interest (inverse solution).
locs_project()). Electrode position errors of a few millimeters cause localization errors of similar size.import_hpi(), hpi_dev_head()).The inverse solution assumes that the data contain the activity of the brain and noise described by the noise covariance:
generate_ssp_projectors()); MEG: Maxwell filtering (signal space separation, maxwell_filter()).proj of dipole_fit()). Projectors and Maxwell filtering reduce the rank of the data (fewer independent channels than channels), which the whitening must take into account.epoch()) are averaged (average_epochs()): the noise decreases with the square root of the number of epochs, so the averaged response (ERP, ERF) has a high signal-to-noise ratio and suits dipole fitting and minimum-norm estimates. The noise covariance of an average is the noise covariance of single epochs divided by the number of epochs.noise_cov(obj; seg = (-0.2, 0))); for MEG, an empty-room recording (with the same preprocessing) can be used instead.ch of dipole_fit()).The whole workflow for an evoked response (the sample recording of MNE-Python: auditory stimuli, MEG and EEG), with the functions of NeuroAnalyzer. The files of the anatomy are made with FreeSurfer and MNE-Python; for speed, the example uses a coarse BEM model (320 triangles per surface) and source space (source_space() of the FreeSurfer surfaces of the subject, surf/?h.white and surf/?h.sphere: oct5, about 1000 sources per hemisphere; oct6 is the default of MNE-Python).
The anatomy and the sensors (once per subject and session): the head shape digitized in the recording is fitted to the scalp of the MRI (coregistration), and the forward solution is computed for the channels of the recording without the bad channels:
bem_dir = "files/bem/sample"
raw_file = "files/meg/sample_audvis_raw.fif"
bem_file = joinpath(bem_dir, "sample-320-320-320-bem-sol.fif")
bem_sol = import_bem(bem_file)
src = source_space(bem_dir; spacing = "oct5")
scalp = import_surf(joinpath(bem_dir, "outer_skin.surf"); tkr = true)
dig = import_dig(raw_file)
lm_mri = import_landmarks(joinpath(bem_dir, "sample-fiducials.fif"))
head_mri = coregister(scalp, lm_mri, dig; omit = 5)
fwd = forward(raw_file, src, bem_sol, head_mri; exclude_bads = true)NeuroAnalyzer FORWARD
channels: 364 (grad 203, mag 102, eeg 59)
sources: 2018 (lh, rh), free orientation
gain: 364 × 6054
frame: head
file: files/meg/sample_audvis_raw.fif
The data: low-pass filter, SSP projectors of the recording (environmental noise), epochs of the left-ear tones (marker "1"), noise covariance of the baseline and the average:
obj = import_fiff(raw_file)
ch = fwd.labels
obj = NeuroAnalyzer.filter(obj;
ch = ch,
fprototype = :butterworth,
ftype = :lp,
cutoff = 40,
order = 4,
report = false)
apply_ssp_projectors!(obj)
ep = epoch(obj; marker_value = "1", offset = 0.2, ep_len = 0.7)
nc = noise_cov(ep; ch = ch, seg = (-0.2, 0.0))
# noise of the average: noise of single epochs / number of epochs
nc.cov ./= nepochs(ep)
erp = average_epochs(ep; bl = (-0.2, 0.0))A dipole fitted at the peak of the auditory N100 (90–110 ms), with the MEG and EEG channels combined by the noise covariance:
idx = [findfirst(==(l), labels(erp)) for l in ch]
t = findall(x -> 0.09 <= x <= 0.11, erp.epoch_time)
dip = dipole_fit(erp.data[idx, t, 1],
raw_file,
bem_sol,
head_mri;
ch = ch,
noise = nc)NeuroAnalyzer DIPOLE (fixed, frame: head)
position: [-61.1, -1.61, 59.5]
time points: 12
moment magnitude: 28.6–34.7
GOF: 0.434
sphere: center [-4.24, 16.6, 61.5], radius 72.3
The dipole is in the auditory cortex of the left hemisphere (here drawn in the template head; see Dipole fitting for the MRI of the subject). The N100 is generated in both hemispheres, so a single dipole explains only a part of the data (goodness of fit):
plot_dipole(dip; type = :slices)| Application | Description |
|---|---|
| Source localization | epileptic foci, eloquent cortex, generators of ERP components |
| Source-space analysis | power and connectivity of brain regions instead of channels (less affected by volume conduction) |
| Simulations | generating realistic test data with known sources, e.g. to evaluate analysis methods |
| Brain-computer interfaces | source estimates as features for decoding (e.g. motor imagery) |
| Brain stimulation | modelling the electric fields of transcranial electric (tDCS, tACS) and magnetic stimulation (TMS) |