Coregistration

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)

The examples use the sample subject of MNE-Python: its MRI, scalp surface, anatomical landmarks and the digitization of an MEG/EEG recording:

bem_dir = "files/bem/sample"
"files/bem/sample"

Head frame and MRI

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.

Fitting the head shape

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

Transform from the landmarks only

Without a digitized head shape, the landmarks alone define the transform: the head frame is defined by the nasion and the preauricular points, so the head frame of the landmarks of the MRI (head_frame()) is the head frame of the recording, and its inverse moves the head frame to the MRI:

head_mri_lm = inv(head_frame(lm_mri))
err_lm = coreg_error(scalp, dig, head_mri_lm; kinds = ["hpi", "eeg", "extra"])
println("mean distance (mm), landmarks only: ", mean_mm(err_lm))
mean distance (mm), landmarks only: 8.59

The landmarks of the MRI are marked less precisely than the head shape is fitted, so this transform is less accurate; it is used when there is no digitization (e.g. template electrode positions, see below). Functions that draw sources on the MRI or its surfaces take either transform (trans) or the landmarks of the MRI (landmarks), e.g. the dipole plots of the Dipole Fitting tutorial.

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