Skip to content

DIPFIT: reimplement the FieldTrip BEM forward model and make the MNI BEM the default #607

Closed

Description

@suraj-ranganath

EEGLAB's DIPFIT default head model is the MNI boundary element model (BEM), computed with FieldTrip functions. eegprep has no BEM forward model, so #591 falls back to the BESA spherical template and reports FieldTrip BEM as a missing backend.

Arno's direction (Nov 11, 2026):

  • Reimplement in Python the FieldTrip functions that DIPFIT uses for the BEM forward model and dipole fit, with the same function names.
  • Make the MNI BEM the default model, as in EEGLAB.
  • Test against EEGLAB/FieldTrip with careful test cases. Dipole positions on the EEGLAB tutorial dataset (sample_data/eeglab_data_epochs_ica.set), with the same grid and starting positions, should match EEGLAB to well below 1 mm. Residual variance alone is not enough.

Scope notes:

  • Trace the call path from pop_dipfit_settings / pop_multifit with model='standardBEM' (standard_vol.mat) through ft_dipolefitting, ft_prepare_headmodel / ft_prepare_vol_sens, and ft_compute_leadfield, and port the functions used, including the BEM transfer-matrix step for EEG electrodes.
  • Compare leadfields to MATLAB first (same dipole positions, same electrodes), then the grid scan, then the nonlinear fit.
  • eLORETA and head-model creation can stay explicitly unsupported for this release, unless they come naturally from the ported FieldTrip functions.

Related: #553, #591, #600 (four-shell spherical model).

Activity

  1. claude commented on Nov 11, 2026

    @claude
    Contributor

    🤖 Plan:

    Research

    Every DIPFIT forward computation on develop goes through one leadfield: _unit_moment_leadfield, which is an infinite homogeneous medium potential (r_e - r_d)/|r_e - r_d|^3, average-referenced. It is not even a spherical model. Electrodes are also projected onto a sphere (_scale_or_project_to_head) whatever the template. So standardBEM only changes the metadata and coord_transform, and vol is never loaded. standard_BEM/ ships only the MRI for display (standard_mri_mni.npz, with a README saying it is "not a volume-conductor model"). The default template index is 1, which is BESA. #600's 21–42 mm error comes from the same leadfield.

    Relevant code

    Proposed approach (design, for review before implementation)

    FieldTrip call path to port. EEGLAB dipfit_gridsearch/dipfit_nonlinear build a cfg and call ft_dipolefitting. That function calls ft_prepare_vol_sens and ft_prepare_sourcemodel for the grid, and ft_inside_headmodel for the inner-skull test. Then dipole_fit runs, which calls ft_compute_leadfield. For an EEG BEM (standard_vol.mat, type dipoli, with a precomputed vol.mat):

    1. ft_prepare_vol_sens: project electrodes onto the skin bnd (project_elec), build the barycentric interpolation tra (Nelec × Nvert_skin), then set vol.mat = tra * vol.mat(skin rows, :). That is the electrode transfer matrix.
    2. ft_compute_leadfield for dipoli/bemcp: compute the infinite-medium potentials of the dipole at every boundary vertex (inf_medium_leadfield, with the conductivity scaling FieldTrip uses), then lf = vol.mat * pot. Average reference is applied according to cfg.reducerank/avgref, as in dipole_fit.
    3. Grid scan: compute the leadfield at each inside-grid point, fit the moment by pseudo-inverse, and choose the minimum residual variance (ft_dipolefitting gridsearch branch).
    4. Nonlinear fit: dipole_fit with fminunc if the Optimization Toolbox exists, otherwise fminsearch. To get <1 mm parity we need to pin which optimizer the reference MATLAB uses. For fminsearch we would port it directly: same 5%/0.00025 initial simplex and TolX/TolFun/MaxIter. scipy's Nelder–Mead differs in stopping rules.

    Module layout. Add src/eegprep/plugins/fieldtrip/ (or plugins/dipfit/private/, see Q1) with one module per FieldTrip function, keeping FieldTrip names: ft_prepare_vol_sens.py, ft_compute_leadfield.py, ft_inside_headmodel.py, ft_dipolefitting.py, dipole_fit.py, project_elec.py, inf_medium_leadfield.py, bounding_mesh/ptriproj helpers. Each FieldTrip leadfield type keeps its own module. Replace leadfield_matrix/_unit_moment_leadfield and the sphere projection in _fitting.py with calls through ft_compute_leadfield, and drop the infinite-medium code. The spherical (#600) and BEM backends should both dispatch through ft_compute_leadfield by vol.type, so the two efforts converge.

    Asset. Package standard_BEM/standard_vol.mat as an EEGPrep-owned resource (converted to .npz: bnd[3].pos/tri, cond, mat, type, unit) next to the existing MRI npz. Add provenance to the README. mat is a dense N×N matrix, so the wheel size needs checking (Q3). Then reorder STANDARD_TEMPLATES so MNI BEM is the default, as in EEGLAB's pop_dipfit_settings.

    Verification, in order (the @eeglab_test / --eeglab-backend=matlab lane, with fixtures produced by tests/matlab/ scripts):

    1. ft_prepare_vol_sens transfer matrix vs MATLAB for standard_1005.elc and for the eeglab_data_epochs_ica.set channels after coord_transform (rtol ~1e-10).
    2. ft_compute_leadfield for a fixed set of dipole positions (rtol ~1e-8).
    3. Grid scan on sample_data/eeglab_data_epochs_ica.set with the EEGLAB default grid: same chosen grid point for every component.
    4. Nonlinear fit from the same start: posxyz max error < 0.1 mm, and momxyz/rv close.
      eLORETA and pop_dipfit_headmodel stay explicitly unsupported.

    Suggested split into PRs: (a) asset + ft_prepare_vol_sens + ft_compute_leadfield with leadfield parity; (b) grid scan + ft_inside_headmodel; (c) dipole_fit nonlinear + default switch + docs/help.

    Open questions

    1. Location: a new plugins/fieldtrip/ package that mirrors FieldTrip's tree (forward/, private/), or keep everything under plugins/dipfit/?
    2. Which optimizer does the reference MATLAB run use for dipole_fit (fminunc with the Optimization Toolbox, or fminsearch)? Do we match that one only?
    3. Is the size of standard_vol.mat (dense vol.mat) acceptable in the wheel, or should we ship only bnd+cond and recompute the dipoli system matrix? Recomputing means porting dipoli, which is a much larger scope.
    4. Should DIPFIT standardBESA: eegprep and EEGLAB dipole positions differ by 21 to 42 mm #600 (four-shell spherical) land first, so ft_compute_leadfield dispatch is already in place?
    5. Which FieldTrip commit is the parity oracle: the one bundled with the pinned EEGLAB_TESTS_EEGLAB_COMMIT?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions