usingNeuroAnalyzerusingDataFramesusingLinearAlgebraimportCairoMakie# Quarto sets a default figure size (672 × 480 px), which overrides the sizes of# NeuroAnalyzer figures: remove itdelete!(CairoMakie.Makie.CURRENT_DEFAULT_THEME, :resolution)
To compute the EEG or MEG produced by sources in the brain (the forward problem, see Brain electric model), the head must be described as a volume conductor: its geometry and the conductivities of its tissues. This description is the head model.
Types of head models
Spherical models:
Homogeneous sphere: one compartment; analytical solution (used in the Brain electric model tutorial).
Three-shell model: concentric spheres for the brain, skull and scalp with different conductivities; analytical solution (series of Legendre polynomials); the standard simple model for EEG.
Four-shell model: adds the CSF.
Spherical models fit the upper part of the head reasonably well but not the temporal and frontal regions; for MEG, a single sphere is often sufficient (the conductivities do not affect the field outside a spherically symmetric conductor).
Realistic models (from the individual MRI, or a template):
Boundary element method (BEM): the head is described by closed surfaces (e.g. brain, inner and outer skull, scalp) separating compartments of constant, isotropic conductivity; efficient, the standard realistic model for EEG and MEG.
Finite element method (FEM): the head is divided into a volume mesh (e.g. tetrahedra), each element with its own conductivity, which allows any geometry, holes in the skull and anisotropic conductivity (white matter, skull layers); most accurate, highest computational cost.
Finite difference method (FDM): a regular grid (e.g. the MRI voxels); simple, but geometry is represented only approximately.
The rest of this tutorial describes BEM models.
Boundary element models
A BEM model consists of nested closed surfaces, innermost first:
Surface
Compartment inside
Conductivity (S/m)
inner skull
brain (and CSF)
0.3
outer skull
skull
0.006
scalp
scalp
0.3
Outside the scalp is air (no current). The conductivities are the defaults of MNE-Python; the skull conductivity is the least known, ratios of the skull to brain conductivity between about 1/15 and 1/80 are used.
MEG: the magnetic field outside the head depends mainly on the currents inside the skull, so one surface (inner skull) is enough.
EEG: the scalp potentials are strongly attenuated and blurred by the poorly conducting skull, so all three surfaces are needed.
The BEM turns the volume conductor equations into equations for the potentials on the surfaces only. The surfaces are divided into triangles, and the potential is computed at the vertices (linear collocation, used by MNE-Python) or at the centres of the triangles (constant collocation). The result, the BEM solution, is a matrix that converts the potentials that a source would produce in an infinite homogeneous medium into the potentials on the surfaces; it depends only on the geometry and the conductivities, so it is computed once per subject.
BEM surfaces
The BEM surfaces are made from the MRI of the subject: FreeSurfer’s watershed algorithm (mne watershed_bem) or, better for the skull, FLASH MRI sequences (mne flash_bem). They are stored in the bem/ folder of the FreeSurfer subject as inner_skull.surf, outer_skull.surf and outer_skin.surf (FreeSurfer surfaces) or .tri files (MNE ASCII triangles). Each file holds one surface only (no conductivities, no solution), so it is loaded as a SURFACE.
The example is the sample subject of MNE-Python. The surfaces are loaded with import_surf() (or import_tri()) in the surface RAS (tkr) coordinates of FreeSurfer:
bem_dir ="files/bem/sample"srf = [import_surf(joinpath(bem_dir, "$f.surf"); tkr =true) for f in ("inner_skull", "outer_skull", "outer_skin")]srf[1]
All three surfaces together, colored by layer (red: inner skull, blue: outer skull, green: scalp), with the front-right quadrant of the outer skull and the scalp removed:
The surfaces must follow the anatomy: the inner skull must not cut into the brain, the outer skull must be outside the inner skull everywhere, and the scalp must follow the skin. The MRI of the subject (here downsampled to 3 mm voxels) is loaded in the same surface RAS coordinates (import_mgh(...; tkr = true)), and the vertices close to each slice are drawn on the slices of plot_slices() (red: inner skull, yellow: outer skull, blue: scalp):
t1 =import_mgh(joinpath(bem_dir, "T1.mgz"); tkr =true)pos = [0, 0, 40]fig =plot_slices(t1; pos = pos)ax =filter(c -> c isa CairoMakie.Axis, fig.content)# axes of the sagittal, coronal and axial slicesviews = ((1, 2, 3), (2, 1, 3), (3, 1, 2))for (s, col) inzip(srf, (:red, :gold, :deepskyblue)) v = s.verticesfor (a, (d, dx, dy)) inzip(ax, views) near =abs.(v[:, d] .- pos[d]) .<1.5 CairoMakie.scatter!(a, v[near, dx], v[near, dy]; color = col, markersize =4)endendfig
Creating a BEM model
import_bem() assembles a BEM object from the surface files of a bem/ folder (.surf, otherwise .tri): the surfaces are ordered by their names and, as the files hold no conductivities, the defaults of MNE-Python are used (or those given with conductivity):
:linear (potentials at the vertices) or :constant (potentials at the triangles)
frame
coordinate frame of the surfaces (:tkr: FreeSurfer surface RAS)
When a model is created, it is checked: each surface must be closed and consistently oriented, with the normals pointing outwards, and the surfaces must be ordered innermost first (increasing enclosed volume). For example, surfaces in the wrong order are rejected:
surfaces must be ordered innermost first (increasing enclosed volume).
MNE-Python models and solutions
MNE-Python stores BEM models (make_bem_model(), *-bem.fif) and solutions (make_bem_solution(), *-bem-sol.fif) in FIFF files, usually with decimated surfaces (e.g. 1280 or 5120 triangles per surface). import_bem() reads both; the surfaces (stored outermost first by MNE-Python) are ordered innermost first and the solution matrix is reordered accordingly:
With linear collocation, the solution has one row and one column per vertex of all surfaces (here 3 × 162 = 486). Its blocks show how the potentials on each surface depend on the infinite-medium potentials on each surface:
One-layer solutions (inner skull, for MEG) have a single block; the size of the matrix grows with the number of vertices (162 vertices for 320 triangles, 642 for 1280):
for f in ("sample-320-bem-sol.fif", "sample-1280-bem-sol.fif") b =import_bem(joinpath(bem_dir, f))println(rpad(f, 26), length(b.surfaces), " layer, solution ",join(size(b.solution), " × "))end
The surfaces of these examples are coarse. MNE-Python uses 5120 triangles per surface by default (ico = 4), or 1280 (ico = 3) for faster computations; the solution files are then much larger:
Solution file
Layers
Triangles per surface
Solution matrix
File size
sample-320-bem-sol.fif
1
320
162 × 162
0.1 MB
sample-320-320-320-bem-sol.fif
3
320
486 × 486
1 MB
sample-1280-bem-sol.fif
1
1280
642 × 642
1.7 MB
sample-1280-1280-1280-bem-sol.fif
3
1280
1926 × 1926
15 MB
sample-5120-bem-sol.fif
1
5120
2562 × 2562
26 MB
sample-5120-5120-5120-bem-sol.fif
3
5120
7686 × 7686
237 MB
Solutions with 5120 triangles are included in the subjects of the MNE-Python datasets (e.g. sample, spm, somato, bst_resting, OPM_sample). For recordings without an individual MRI, the template subject fsaverage (mne.datasets.fetch_fsaverage()) has a three-layer solution (fsaverage-5120-5120-5120-bem-sol.fif), and the infant templates of MNE-Python (mne.datasets.fetch_infant_template(), e.g. ANTS2-0Weeks3T, ANTS6-0Months3T, ANTS2-0Years3T) include three-layer solutions as well. All of them are loaded with import_bem().
Coregistration
BEM models and source spaces of FreeSurfer and MNE-Python are in the surface RAS (tkr) coordinates of the MRI of the subject. EEG electrodes and MEG sensors are in the head frame defined by the anatomical landmarks digitized during the recording (x axis from LPA through RPA, y axis through the nasion). Before a forward model can be computed, the two must be coregistered: the transform between the head frame and the MRI must be found.
The digitized points of a recording (landmarks, HPI coils, EEG electrodes and extra points on the scalp, the head shape) are loaded with import_dig():
coregister() finds the transform from the head frame to the MRI, as mne coreg:
the digitized landmarks are fitted to the landmarks of the MRI (the nasion with a 10× larger weight),
the head shape points are fitted to the scalp surface by the iterative closest point algorithm (ICP): each point is paired with the closest point of the scalp, the best rigid transform of the pairs is computed, and the two steps are repeated until the transform does not change,
optionally (omit), points farther from the scalp than a given distance (e.g. on the hair, or moved during the digitization) are omitted and ICP is repeated.
coreg_error() gives the distance of each digitized point to the scalp. A good coregistration has head shape points within 1–3 mm of the scalp on average; the landmarks are farther, as they are not exactly on the skin surface of the MRI:
The digitized points moved to the MRI (landmarks_transform()) on the scalp (red: EEG electrodes, blue: head shape points, green: HPI coils, black: landmarks):
dig_mri =landmarks_transform(dig, head_mri; frame =:tkr)fig =plot_surface(scalp; cam = (10, 60), gui =false)ax =filter(c -> c isa CairoMakie.Axis3, fig.content)[1]colors = ("eeg"=>:red, "extra"=>:blue, "hpi"=>:green,"cardinal"=>:black)for (k, col) in colors d = dig_mri[dig_mri.kind .== k, :] CairoMakie.scatter!(ax, d.x, d.y, d.z; color = col, markersize =10)endfig
The transform saved by MNE-Python (mne coreg) for this recording is loaded with import_trans(); the distances show how the two compare:
For a recording without an individual MRI, a template head (e.g. fsaverage) can be fitted to the digitized head shape with a uniform scaling (coregister(...; scale = true)).
Saving the transform
export_trans() saves the transform as a -trans.fif file of MNE-Python (e.g. for make_forward_solution()); import_trans() loads it:
Without digitized electrode positions, the positions of a standard montage (e.g. 10-20) can be placed on the scalp of the subject: the template positions are moved to the head frame of their landmarks (head_frame()), mapped to the MRI with the landmarks of the MRI and projected onto the scalp (locs_project(); :radial keeps the arrangement of the montage):
locs_tpl =import_locs("files/locs/standard_1020.elc")lm_tpl =import_landmarks("files/locs/standard_1020.elc")locs_tpl =locs_transform(locs_tpl, head_frame(lm_tpl))# head frame of the template → MRI of the subject (landmarks of the MRI)tpl_mri =inv(head_frame(lm_mri))locs_scalp =locs_project(locs_tpl, scalp, tpl_mri; method =:radial)p =locs_transform(locs_scalp, tpl_mri; unit ="mm")fig =plot_surface(scalp; cam = (10, 60), gui =false)ax =filter(c -> c isa CairoMakie.Axis3, fig.content)[1]CairoMakie.scatter!(ax, p.loc_x, p.loc_y, p.loc_z; color =:red, markersize =12)fig
locs_project!(obj, scalp, T) projects the EEG positions of a recording.
MEG: HPI coils
MEG sensors are fixed in the helmet (the device frame). The head position indicator (HPI) coils, digitized on the head and localized by the MEG sensors at the start of the recording, give the transform from the device to the head frame (import_hpi(), hpi_dev_head()); coils with a large localization error are rejected by the acquisition software:
r =hpi_dev_head(hpi)println("fit error of the coils (mm): ", round.(r.error; digits =2))dev_head =import_trans(joinpath(bem_dir, "sample-info.fif"); from =:device, to =:head)println("same as the stored transform: ", isapprox(r.T, dev_head; atol =1e-3))
fit error of the coils (mm): [0.89, 5.51, 1.69, 0.96]
same as the stored transform: true
Atlas labels
FreeSurfer divides the cortex of each subject into anatomical regions (parcellation) by fitting atlases to the folding pattern of the cortex. The regions are stored for each hemisphere as annotations in the label/ folder of the subject:
File
Atlas
?h.aparc.annot
Desikan-Killiany: 34 gyral regions per hemisphere
?h.aparc.a2009s.annot
Destrieux: 74 gyri and sulci per hemisphere
?h.aparc.DKTatlas.annot
Desikan-Killiany-Tourville: 31 regions per hemisphere
An annotation assigns a region to each vertex of the cortical surfaces of the same subject and hemisphere (?h.white, ?h.pial, ?h.inflated). import_annot() returns the region of each vertex and the table of regions (names, colors); surface_annot!() adds them to a surface. The example is the left hemisphere of fsaverage5, the average brain of FreeSurfer with 10242 vertices per hemisphere, on the inflated surface (which shows the sulci):
The vertices of a region, e.g. to average the source estimates in it:
regions = ctx.header[:regions][:aparc]r =findfirst(==("precentral"), regions.name)precentral =findall(==(r), vec(ctx.values[:aparc]))length(precentral)
675
Source spaces
The source space is the set of candidate locations of the sources: points on the cortical surface (the white matter surface, decimated, e.g. oct-5: 1026 points per hemisphere, about 10 mm apart) with the orientation normal to the cortex, or a grid of points inside the inner skull (volume source space). MNE-Python source spaces (setup_source_space(), setup_volume_source_space(), *-src.fif) are loaded with import_src():
source_space() creates a cortical source space of a FreeSurfer subject (folder with surf/?h.white and surf/?h.sphere), as setup_source_space() of MNE-Python: the points of a subdivided octahedron ("oct<n>") or icosahedron ("ico<n>") on the spherical registration of the subject are mapped to the closest vertices of the white matter surface, so that the sources are evenly spaced on the cortex:
source_space_volume() creates a grid of sources inside the inner skull, as setup_volume_source_space() (here 10 mm apart, at least 5 mm from the inner skull):
The forward solution (lead field, gain matrix) gives the signal at each channel produced by a dipole of unit moment (1 A·m) at each source. It is computed from the BEM model, the source space and the sensor positions coregistered with the MRI. MNE-Python forward solutions (make_forward_solution(), *-fwd.fif) are loaded with import_fwd(); the sources are moved to the head frame of the sensors:
Sources closer than 5 mm to the inner skull were excluded by MNE-Python (1884 of 2052 sources). With free orientation, each source has three columns (dipoles along x, y and z of the head frame), so the gain matrix has 59 rows (EEG channels) and 3 × 1884 columns. Units are V per A·m for EEG (T per A·m for magnetometers, T/m per A·m for gradiometers):
size(fwd.gain), unique(fwd.header[:units])
((59, 5652), ["V/Am"])
The sensitivity of the EEG to each source, the norm of its lead field (all channels, all three orientations), shows which sources produce the largest signals: the crowns of the gyri close to the skull; deep sources and sources in the sulci produce weaker signals:
forward() computes the MEG and EEG forward solution of a FIFF measurement (channel positions, MEG coil types, device → head transform) with a BEM model, as make_forward_solution() of MNE-Python (forward_eeg(): EEG electrodes given as positions). The MEG field is computed at the integration points of each coil (coil definitions of MNE-Python), the EEG potentials against the reference electrode of the recording. Here with the 3-layer BEM model with 320 triangles per surface (for speed; use 5120 triangles for real data):
MEG and EEG see different sources. For a dipole oriented along the normal of the cortex (the orientation of the pyramidal cells), the sensitivity of MEG decreases with the radial component of the orientation: radial sources (on the crowns of the gyri) produce almost no magnetic field outside the head, which is produced by tangential sources (in the walls of the sulci). The sensitivity of EEG hardly depends on the orientation:
# sensitivity to a dipole along the normal: gain projected on the normalfunctionsensitivity(fwd, type) ch = fwd.channel_type .==type n =size(fwd.src.pos, 1) [norm(fwd.gain[ch, (3i -2):3i] * fwd.src.normals[i, :]) for i in1:n]end# radial component: |normal · direction from the center of the sources|c =vec(sum(fwd_c.src.pos; dims =1)) ./size(fwd_c.src.pos, 1)rad = [abs(dot(fwd_c.src.normals[i, :],normalize(fwd_c.src.pos[i, :] .- c))) for i inaxes(fwd_c.src.pos, 1)]fig = CairoMakie.Figure(; size = (900, 400))for (k, (t, ty)) inenumerate((("MEG (magnetometers)", "mag"), ("EEG", "eeg"))) s =sensitivity(fwd_c, ty) ax = CairoMakie.Axis(fig[1, k]; title = t, xlabel ="radial component of the orientation", ylabel ="relative sensitivity") CairoMakie.scatter!(ax, rad, s ./maximum(s); markersize =4, color = (:black, 0.4))endfig
The forward solution is the input of source localization: dipole fitting, minimum norm estimates and beamformers.
Dipole fitting
dipole_fit() fits a single equivalent current dipole with the BEM model, as fit_dipole() of MNE-Python: the lead field is computed at any position inside the inner skull, the best position is searched on a grid and refined, and the dipole moment is fitted by least squares. Channels of different types (MEG, EEG) are combined by whitening the data and the lead field with the noise covariance (noise_cov()).
Here, data of a known dipole (20 nAm) with noise are simulated from the forward solution computed above (the column of a source and its normal) and fitted again:
k =1000# a source of the source spaceq = fwd_c.src.normals[k, :] .*20e-9# 20 nAm along the normal (A·m)# data in NeuroAnalyzer units: μV (EEG), fT (mag.), fT/cm (grad.)units =Dict("eeg"=>1e6, "mag"=>1e15, "grad"=>1e13)scale = [units[t] for t in fwd_c.channel_type]noise_sd = [t =="eeg" ? 0.5: t =="mag" ? 30.0:5.0 for t in fwd_c.channel_type]d = (fwd_c.gain[:, (3k -2):3k] * q) .* scaleimportRandomRandom.seed!(1)d = d .+ noise_sd .*randn(length(d), 10) # 10 time points# noise covariance (here: the simulated sensor noise)noise = NeuroAnalyzer.NOISECOV(Matrix(Diagonal(noise_sd .^2)), fwd_c.labels, fwd_c.channel_type)dip =dipole_fit(d, joinpath(bem_dir, "sample-info.fif"), bem_sol, head_mri_mne; ch = fwd_c.labels, noise = noise)
NeuroAnalyzer DIPOLE (fixed, frame: head)
position: [-24.9, 94.8, 35.0]
time points: 10
moment magnitude: 19.3–21.7
GOF: 0.677
sphere: center [-4.3, 19.5, 64.0], radius 72.3
true position (mm): [-24.9, 95.0, 34.8]
fitted position (mm): [-24.9, 94.8, 35.0]
error (mm): 0.3
With mode = :moving, a dipole is fitted at each time point. For real data, the noise covariance is estimated from the baseline (noise_cov()).
Noise covariance
Minimum norm estimates and beamformers weight the channels by the noise covariance: the covariance of the signals without the activity of interest, estimated from the baseline of the epochs (e.g. the pre-stimulus interval) or from an empty-room MEG recording. noise_cov() concatenates the samples of all epochs in the given time window and returns a NOISECOV object (export_cov() saves it as an MNE-Python -cov.fif file, import_cov() loads one):
With few samples or many channels, the empirical covariance is poorly conditioned; Ledoit-Wolf shrinkage pulls it towards a scaled identity matrix with the optimal amount of shrinkage (small here, with many samples), and regularization (reg) adds a fraction of the mean variance of each channel type to the diagonal:
nc_lw =noise_cov(e2; ch = ch, seg = (0, 0.5), method =:ledoit_wolf)nc_reg =noise_cov(e2; ch = ch, seg = (0, 0.5), reg =0.1)for (name, c) in (("empirical", nc), ("Ledoit-Wolf", nc_lw), ("reg = 0.1", nc_reg))println(rpad(name, 12), "condition number: ",round(cond(c.cov); sigdigits =3))end