Dipole Fitting

Initialize NeuroAnalyzer
using NeuroAnalyzer
using LinearAlgebra
import CairoMakie
import Random
# 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)

Dipole fitting explains the EEG or MEG by one (or a few) equivalent current dipoles: the position, orientation and strength of a dipole whose field best explains the data (see Brain electric model for the physics and the other inverse methods). It suits focal activity: early sensory responses, epileptic spikes.

dipole_fit() fits a single dipole:

  1. the lead field (the signals of a dipole of unit moment) is computed at the candidate positions,
  2. the best position is searched on a grid and refined by non-linear optimization; for each position, the moment is found by linear least squares,
  3. the goodness of fit (GOF) is the fraction of the variance of the data explained by the dipole.

Two head models are available: a homogeneous sphere (channel locations only) and a realistic boundary element model of the MRI of the subject (see Head Models).

Spherical head model

Scalp potentials of a dipole in a homogeneous conducting sphere (radius 9 cm, conductivity 0.33 S/m) are simulated for the 47 electrodes of the 10-10 system: the dipole is 7 cm from the center of the head, under the electrode C3, with a moment of 20 nAm, either radial or tangential (pointing anteriorly), see Brain electric model:

locs = import_locs("files/locs/standard-10-10-cap47.ced")
xyz = Matrix(locs[:, [:loc_x, :loc_y, :loc_z]])
u = xyz ./ sqrt.(sum(abs2, xyz; dims = 2))        # unit vectors to electrodes
R = 0.09                                          # head radius [m]
σ = 0.33                                          # conductivity [S/m]

c3 = u[findfirst(==("C3"), locs.label), :]
r0 = 0.07 .* c3                                   # dipole position [m]
q_rad = 20e-9 .* c3                               # radial moment [A·m]
q_tan = 20e-9 .* normalize(cross(c3, [0, 0, 1]))  # tangential moment

L = NeuroAnalyzer._leadfield(r0, u, R, σ)         # lead field [V / A·m]
v_rad = L * q_rad .* 1e6                          # scalp potentials [μV]
v_tan = L * q_tan .* 1e6

dipole_fit() fits a single dipole in a homogeneous sphere to the simulated maps. The electrode positions are on a unit sphere; loc_scale = R converts them to meters. Without noise, the fit is exact (the data come from the same model); with noise (here 10% of the maximum amplitude of the map), the localization error depends on the depth and orientation of the source, the number and positions of the electrodes and the noise level:

Random.seed!(1)
# localization error (mm) and goodness of fit of a fitted map
function fit_map(v)
    d = dipole_fit(reshape(v, :, 1), locs; loc_scale = R)
    err = 1000 * R * norm(vec(d.pos) .- r0 ./ R)
    return round(err; digits = 1), round(d.gof[1]; digits = 3)
end
println(rpad("source", 12), rpad("noise", 7), rpad("error (mm)", 12), "GOF")
for (name, v) in (("radial", v_rad), ("tangential", v_tan)), noise in (0.0, 0.1)
    v_n = v .+ noise * maximum(abs.(v)) .* randn(length(v))
    err, gof = fit_map(v_n)
    println(rpad(name, 12), rpad("$(Int(100noise))%", 7),
            rpad(err, 12), gof)
end
source      noise  error (mm)  GOF
radial      0%     0.0         1.0
radial      10%    24.5        0.731
tangential  0%     0.0         1.0
tangential  10%    2.0         0.969

plot_dipole() draws the fitted dipole (dot) and its moment (arrow) in the ICBM152 template head: the positions of the spherical model (in the sphere of the fit, sphere_center and sphere_radius) are mapped to the template as the channel locations of plot_locs3d(). The cortex is semi-transparent (alpha), inside the scalp:

dip_sph = dipole_fit(reshape(v_tan, :, 1), locs; loc_scale = R)
plot_dipole(dip_sph; cam = (20, 200), gui = false)

type = :slices shows the dipole on the slices of the template MRI through its position (the moment projected onto each slice):

plot_dipole(dip_sph; type = :slices)

Realistic head model

With a boundary element model (BEM) of the head of the subject, dipole_fit() computes the lead field at any position inside the inner skull, as fit_dipole() of MNE-Python. Channels of different types (MEG, EEG) are combined by whitening the data and the lead field with the noise covariance (noise_cov(), see Noise Covariance).

The example is the sample subject of MNE-Python: the BEM solution (3 layers, 320 triangles per surface, for speed; use 5120 triangles for real data), the cortical source space, and the head → MRI transform of the coregistration (see Coregistration); forward() computes the forward solution (see Forward Solutions):

bem_dir = "files/bem/sample"
bem_sol = import_bem(joinpath(bem_dir, "sample-320-320-320-bem-sol.fif"))
src = import_src(joinpath(bem_dir, "sample-oct-5-src.fif"))
head_mri = import_trans(joinpath(bem_dir, "sample_audvis_raw-trans.fif");
                        from = :head, to = :tkr)
fwd = forward(joinpath(bem_dir, "sample-info.fif"), src, bem_sol, head_mri)
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

Data of a known dipole (20 nAm, along the normal of the cortex at a source of the source space) are simulated with noise from the forward solution and fitted again:

k = 1000                                  # a source of the source space
q = fwd.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.channel_type]
noise_sd = [t == "eeg" ? 0.5 : t == "mag" ? 30.0 : 5.0
            for t in fwd.channel_type]
d = (fwd.gain[:, (3k - 2):3k] * q) .* scale
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.labels, fwd.channel_type)
dip = dipole_fit(d, joinpath(bem_dir, "sample-info.fif"), bem_sol,
                 head_mri; ch = fwd.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

The dipole is in the head frame of the recording (dip.frame), in mm; the moment is in nAm:

println("true position (mm):   ", round.(fwd.src.pos[k, :]; digits = 1))
println("fitted position (mm): ", round.(dip.pos[1, :]; digits = 1))
err = norm(dip.pos[1, :] .- fwd.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()); MEG recordings with SSP projectors (e.g. of the environmental noise) need the projector as well (proj = generate_ssp_projectors(obj).ssp_projectors), which is applied to the data, the lead field and the noise covariance. For MEG, the radial component of the dipole moment produces almost no magnetic field outside the head and is omitted from the fit (as in MNE-Python).

Plotting dipoles

Dipoles are drawn on the MRI and the surfaces of the subject by plot_slices() and plot_surface() (dipole). The dipole is in the head frame of the recording, the MRI in its own coordinates: the head → MRI transform of the coregistration (trans) moves the dipole to the MRI.

On the MRI

The slices pass through the dipole (dot); the arrow is the moment projected onto each slice:

t1 = import_mgh(joinpath(bem_dir, "T1.mgz"); tkr = true)
plot_slices(t1; dipole = dip, trans = head_mri)

Without a coregistration, the anatomical landmarks of the MRI (landmarks) define the transform (inv(head_frame(landmarks)), see Coregistration); it is less accurate than the fit of the head shape:

lm_mri = import_landmarks(joinpath(bem_dir, "sample-fiducials.fif"))
plot_slices(t1; dipole = dip, landmarks = lm_mri)

On the cortical surface

The sources of the source space with their triangles form a (coarse) cortical surface of each hemisphere, in the coordinates of the MRI (:tkr); with a semi-transparent surface (alpha), the dipole in the sulcus is visible:

ctx = merge_surfaces([NeuroAnalyzer.SURFACE(src.pos[src.space .== h, :], src.triangles[h];
                                            frame = :tkr) for h in 1:2])
plot_surface(ctx; dipole = dip, trans = head_mri, alpha = 0.5, cam = (20, 150),
             gui = false)

Any surface of the subject in the coordinates of the MRI can be used, e.g. the pial or white matter surface of FreeSurfer (import_surf(file_name; tkr = true)) or the inner skull of the BEM model (bem_sol.surfaces[1]).

On a template head

Without the MRI of the subject, plot_dipole() draws the dipole in the ICBM152 template head, at its position in the head frame of the recording: the template approximates the anatomy of the subject, so the dipole is drawn only near its real anatomical location (here: the head of the subject is larger than the template, and the frontal dipole is at the front of the template brain):

plot_dipole(dip; gui = false)
plot_dipole(dip; type = :slices)

Tip: With t = 0, all time points of a moving dipole (mode = :moving) are shown, colored by the goodness of fit; t selects a single time point.

Tip: With gui = true (default), plot_dipole() and plot_surface() open an interactive window, where the view can be rotated and zoomed.