Head Models

Initialize NeuroAnalyzer
using NeuroAnalyzer
using DataFrames
using LinearAlgebra
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)

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:

  1. Homogeneous sphere: one compartment; analytical solution (used in the Brain electric model tutorial).
  2. 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.
  3. 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):

  1. 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.
  2. 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.
  3. 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]
NeuroAnalyzer SURFACE
  vertices: 2562, triangles: 5120
  values: none
  frame: tkr
  file: files/bem/sample/inner_skull.surf

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:

# keep the triangles outside the front-right quadrant (x > 0, y > 0)
function cutaway(s, layer; cut = true)
    v, f = s.vertices, s.faces
    c = (v[f[:, 1], :] .+ v[f[:, 2], :] .+ v[f[:, 3], :]) ./ 3
    keep = cut ? .!((c[:, 1] .> 0) .& (c[:, 2] .> 0)) : trues(size(f, 1))
    layer = fill(Float64(layer), size(v, 1))
    return NeuroAnalyzer.SURFACE(v, f[keep, :];
                                 values = Dict(:layer => layer))
end
layers = [cutaway(s, i; cut = i > 1) for (i, s) in enumerate(srf)]
plot_surface(merge_surfaces(layers);
             values = :layer,
             cmap = :Set1_3,
             cb = false,
             cam = (15, 30),
             gui = false)

Checking the surfaces on the MRI

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 slices
views = ((1, 2, 3), (2, 1, 3), (3, 1, 2))
for (s, col) in zip(srf, (:red, :gold, :deepskyblue))
    v = s.vertices
    for (a, (d, dx, dy)) in zip(ax, views)
        near = abs.(v[:, d] .- pos[d]) .< 1.5
        CairoMakie.scatter!(a, v[near, dx], v[near, dy];
                            color = col, markersize = 4)
    end
end
fig

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

bem = import_bem(bem_dir)
NeuroAnalyzer BEM
  layers: 3 (innermost first)
    inner_skull: 2562 vertices, 5120 triangles, σ = 0.3 S/m
    outer_skull: 2562 vertices, 5120 triangles, σ = 0.006 S/m
    scalp: 2562 vertices, 5120 triangles, σ = 0.3 S/m
  solution: not computed
  frame: tkr
  file: files/bem/sample

One layer (inner skull) for MEG:

import_bem(bem_dir; layers = 1)
NeuroAnalyzer BEM
  layers: 1 (innermost first)
    inner_skull: 2562 vertices, 5120 triangles, σ = 0.3 S/m
  solution: not computed
  frame: tkr
  file: files/bem/sample

A model can also be created from SURFACE objects (innermost first) with any conductivities, e.g. a skull to brain conductivity ratio of 1/80:

bem80 = NeuroAnalyzer.BEM(srf, [0.33, 0.0042, 0.33])
bem80.conductivity
3-element Vector{Float64}:
 0.33
 0.0042
 0.33

The BEM object holds:

Field Description
surfaces SURFACE objects, innermost first
conductivity conductivity (S/m) inside each surface
solution BEM solution matrix (empty: not computed)
method :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:

try
    NeuroAnalyzer.BEM(srf[[2, 1, 3]], [0.3, 0.006, 0.3])
catch err
    println(err.msg)
end
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:

import_bem(joinpath(bem_dir, "sample-1280-1280-1280-bem.fif"))
NeuroAnalyzer BEM
  layers: 3 (innermost first)
    inner_skull: 642 vertices, 1280 triangles, σ = 0.3 S/m
    outer_skull: 642 vertices, 1280 triangles, σ = 0.006 S/m
    scalp: 642 vertices, 1280 triangles, σ = 0.3 S/m
  solution: not computed
  frame: tkr
  file: files/bem/sample/sample-1280-1280-1280-bem.fif
bem_sol = import_bem(joinpath(bem_dir, "sample-320-320-320-bem-sol.fif"))
NeuroAnalyzer BEM
  layers: 3 (innermost first)
    inner_skull: 162 vertices, 320 triangles, σ = 0.3 S/m
    outer_skull: 162 vertices, 320 triangles, σ = 0.006 S/m
    scalp: 162 vertices, 320 triangles, σ = 0.3 S/m
  solution: 486 × 486 (linear collocation)
  frame: tkr
  file: files/bem/sample/sample-320-320-320-bem-sol.fif

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:

fig = CairoMakie.Figure(; size = (620, 520))
ax = CairoMakie.Axis(fig[1, 1];
                     aspect = 1,
                     yreversed = true,
                     xlabel = "column (vertex)",
                     ylabel = "row (vertex)",
                     title = "inner skull | outer skull | scalp")
hm = CairoMakie.heatmap!(ax, log10.(abs.(bem_sol.solution) .+ 1e-6)';
                         colormap = :viridis)
CairoMakie.Colorbar(fig[1, 2], hm; label = "log10 |value|")
fig

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
sample-320-bem-sol.fif    1 layer, solution 162 × 162
sample-1280-bem-sol.fif   1 layer, solution 642 × 642

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

dig = import_dig(joinpath(bem_dir, "sample-dig.fif"))
first(dig, 5)
5×5 DataFrame
Row label kind x y z
String String Float64 Float64 Float64
1 lpa cardinal -71.3766 0.0 5.12227e-6
2 nasion cardinal 3.72529e-6 102.606 4.19095e-6
3 rpa cardinal 75.2677 0.0 5.58794e-6
4 hpi_1 hpi 32.9227 98.9798 79.8433
5 hpi_2 hpi -69.9811 67.7165 68.8845

The anatomical landmarks of the MRI (here marked in MNE-Python and saved as sample-fiducials.fif) are loaded with import_landmarks():

lm_mri = import_landmarks(joinpath(bem_dir, "sample-fiducials.fif"))
3×4 DataFrame
Row label x y z
String Float64 Float64 Float64
1 nasion 2.18981 93.2951 36.7237
2 lpa -76.1461 1.31942 -6.72171
3 rpa 77.8654 -1.14449 -10.7582

coregister() finds the transform from the head frame to the MRI, as mne coreg:

  1. the digitized landmarks are fitted to the landmarks of the MRI (the nasion with a 10× larger weight),
  2. 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,
  3. 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.
scalp = import_surf(joinpath(bem_dir, "outer_skin.surf"); tkr = true)
head_mri = coregister(scalp, lm_mri, dig; omit = 5)
round.(head_mri; digits = 3)
4×4 Matrix{Float64}:
  0.995  0.068   0.072   -1.087
 -0.021  0.86   -0.51     6.769
 -0.097  0.506   0.857  -25.57
  0.0    0.0     0.0      1.0

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:

err = coreg_error(scalp, dig, head_mri)
combine(groupby(err, :kind),
        :distance => (d -> round(sum(d) / length(d); digits = 2)) => :mean_mm,
        :distance => (d -> round(maximum(d); digits = 2)) => :max_mm)
4×3 DataFrame
Row kind mean_mm max_mm
String Float64 Float64
1 cardinal 4.38 6.22
2 hpi 0.9 2.71
3 extra 2.08 26.43
4 eeg 1.64 4.67

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)
end
fig

The transform saved by MNE-Python (mne coreg) for this recording is loaded with import_trans(); the distances show how the two compare:

head_mri_mne = import_trans(joinpath(bem_dir, "sample_audvis_raw-trans.fif");
                            from = :head, to = :tkr)
err_mne = coreg_error(scalp, dig, head_mri_mne; kinds = ["hpi", "eeg", "extra"])
err_na = coreg_error(scalp, dig, head_mri; kinds = ["hpi", "eeg", "extra"])
mean_mm(e) = round(sum(e.distance) / nrow(e); digits = 2)
println("mean distance (mm), MNE-Python: ", mean_mm(err_mne),
        ", coregister(): ", mean_mm(err_na))
mean distance (mm), MNE-Python: 2.49, coregister(): 1.86

The inverse transform moves the MRI surfaces (surface_transform()), e.g. the BEM model, to the head frame of the sensors:

scalp_head = surface_transform(scalp, inv(head_mri); frame = :head)
NeuroAnalyzer SURFACE
  vertices: 2562, triangles: 5120
  values: none
  frame: head
  file: files/bem/sample/outer_skin.surf

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:

trans_file = joinpath(tempdir(), "sample-trans.fif")
export_trans(trans_file, head_mri; overwrite = true)
import_trans(trans_file) ≈ head_mri
false

Template electrode positions

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:

hpi = import_hpi(joinpath(bem_dir, "sample-info.fif"))
hpi[:, [:coil, :label, :goodness, :used]]
4×4 DataFrame
Row coil label goodness used
Int64 String Float64 Bool
1 1 hpi_2 0.987718 true
2 2 hpi_4 0.984717 false
3 3 hpi_3 0.995467 true
4 4 hpi_1 0.991041 true
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):

fs5 = "files/bem/fsaverage5"
ctx = import_surf(joinpath(fs5, "lh.inflated"); tkr = true)
surface_annot!(ctx, joinpath(fs5, "lh.aparc.annot"))
surface_annot!(ctx, joinpath(fs5, "lh.aparc.a2009s.annot"); name = :a2009s)
first(ctx.header[:regions][:aparc], 6)
6×5 DataFrame
Row name r g b n
String Int64 Int64 Int64 Int64
1 unknown 25 5 25 840
2 bankssts 25 100 40 126
3 caudalanteriorcingulate 125 100 160 67
4 caudalmiddlefrontal 100 25 0 232
5 corpuscallosum 120 70 50 198
6 cuneus 220 20 100 102

plot_surface() shows the regions in their colors:

plot_surface(ctx; values = :aparc, cam = (10, 180), gui = false)
plot_surface(ctx; values = :a2009s, cam = (10, 180), gui = false)

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

src = import_src(joinpath(bem_dir, "sample-oct-5-src.fif"))
NeuroAnalyzer SOURCESPACE
  sources: 2052
    lh (surface): 1026 sources, 2048 triangles
    rh (surface): 1026 sources, 2048 triangles
  frame: tkr
  file: files/bem/sample/sample-oct-5-src.fif

The SOURCESPACE object holds:

Field Description
pos positions of the sources (mm)
normals normals of the cortical surface at the sources
space space of each source (index of spaces)
spaces names of the spaces: :lh, :rh (cortical surfaces), :volume, :discrete
vertices index of each source in the full surface or grid
triangles triangles between the sources of each cortical surface
frame coordinate frame (:tkr)

The sources of the left hemisphere with their triangles form a (coarse) cortical surface:

lh = src.space .== 1
plot_surface(NeuroAnalyzer.SURFACE(src.pos[lh, :], src.triangles[1]);
             cam = (10, 180),
             gui = false)

Creating source spaces

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:

src_fs5 = source_space("files/bem/fsaverage5"; spacing = "oct5")
NeuroAnalyzer SOURCESPACE
  sources: 2052
    lh (surface): 1026 sources, 2048 triangles
    rh (surface): 1026 sources, 2048 triangles
  frame: tkr

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

inner = import_surf(joinpath(bem_dir, "inner_skull.surf"); tkr = true)
vol = source_space_volume(inner; pos = 10, mindist = 5)
NeuroAnalyzer SOURCESPACE
  sources: 1305
    volume (volume): 1305 sources
  frame: tkr

Forward solutions

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:

fwd = import_fwd(joinpath(bem_dir, "sample-eeg-oct-5-fwd.fif"))
NeuroAnalyzer FORWARD
  channels: 59 (eeg 59)
  sources: 1884 (lh, rh), free orientation
  gain: 59 × 5652
  frame: head
  file: files/bem/sample/sample-eeg-oct-5-fwd.fif

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:

n = size(fwd.src.pos, 1)
# μV per nAm: V/(A·m) × 10⁶ μV/V × 10⁻⁹ A·m/nAm
sens = [sqrt(sum(abs2, fwd.gain[:, (3i - 2):3i])) for i in 1:n] .* 1e-3
lh = fwd.src.space .== 1
ctx = NeuroAnalyzer.SURFACE(fwd.src.pos[lh, :], fwd.src.triangles[1];
                            values = Dict(:sens => sens[lh]))
plot_surface(ctx; values = :sens, cb_title = "μV / nAm", cam = (10, 180),
             gui = false)

Computing forward solutions

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

fwd_c = forward(joinpath(bem_dir, "sample-info.fif"),
                src,
                bem_sol,
                head_mri_mne)
NeuroAnalyzer FORWARD
  channels: 366 (grad 204, mag 102, eeg 60)
  sources: 2018 (lh, rh), free orientation
  gain: 366 × 6054
  frame: head
  file: files/bem/sample/sample-info.fif

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 normal
function sensitivity(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 in 1: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 in axes(fwd_c.src.pos, 1)]
fig = CairoMakie.Figure(; size = (900, 400))
for (k, (t, ty)) in enumerate((("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))
end
fig

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 space
q = 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) .* scale
import Random
Random.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
println("true position (mm):   ", round.(fwd_c.src.pos[k, :]; digits = 1))
println("fitted position (mm): ", round.(dip.pos[1, :]; digits = 1))
err = norm(dip.pos[1, :] .- fwd_c.src.pos[k, :])
println("error (mm): ", round(err; digits = 1))
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):

eeg = import_edf("files/eeg/eeg-test-edf.edf")
e2 = epoch(eeg; ep_len = 2)
ch = get_channel(e2; type = "eeg")
nc = noise_cov(e2; ch = ch, seg = (0, 0.5))
NeuroAnalyzer NOISECOV
  channels: 19 (eeg 19)
  degrees of freedom: 77657
  method: empirical

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
empirical   condition number: 194000.0
Ledoit-Wolf condition number: 161000.0
reg = 0.1   condition number: 170.0

Use plot_surface() to view any of the surfaces in an interactive window:

plot_surface(bem.surfaces[3])