You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
DIPFIT: reimplement the FieldTrip BEM forward model and make the MNI BEM the default #607
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.
Scope check: multi-module port + packaged asset + MATLAB parity suite, far above 100 lines, so analysis only. No PR opened.
Human review of the approach and open questions below
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.
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):
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.
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.
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).
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):
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).
ft_compute_leadfield for a fixed set of dipole positions (rtol ~1e-8).
Grid scan on sample_data/eeglab_data_epochs_ica.set with the EEGLAB default grid: same chosen grid point for every component.
Nonlinear fit from the same start: posxyz max error < 0.1 mm, and momxyz/rv close.
eLORETA and pop_dipfit_headmodel stay explicitly unsupported.
Location: a new plugins/fieldtrip/ package that mirrors FieldTrip's tree (forward/, private/), or keep everything under plugins/dipfit/?
Which optimizer does the reference MATLAB run use for dipole_fit (fminunc with the Optimization Toolbox, or fminsearch)? Do we match that one only?
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.
Activity
claude commentedon Nov 11, 2026
🤖 Plan:
Research
Every DIPFIT forward computation on
developgoes 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. SostandardBEMonly changes the metadata andcoord_transform, andvolis 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
src/eegprep/plugins/dipfit/_fitting.py#L210-L213-leadfield_matrix, the single forward entry pointsrc/eegprep/plugins/dipfit/_fitting.py#L369-L373- infinite-medium leadfieldsrc/eegprep/plugins/dipfit/_fitting.py#L147-L177-prepare_forward_data: spherical electrode projection,volignoredsrc/eegprep/plugins/dipfit/_utils.py#L42-L68-STANDARD_TEMPLATES(BESA first, which is the default)src/eegprep/plugins/dipfit/_fieldtrip_workflows.py#L345- "FieldTrip BEM fitting is still not bundled"Proposed approach (design, for review before implementation)
FieldTrip call path to port. EEGLAB
dipfit_gridsearch/dipfit_nonlinearbuild a cfg and callft_dipolefitting. That function callsft_prepare_vol_sensandft_prepare_sourcemodelfor the grid, andft_inside_headmodelfor the inner-skull test. Thendipole_fitruns, which callsft_compute_leadfield. For an EEG BEM (standard_vol.mat, typedipoli, with a precomputedvol.mat):ft_prepare_vol_sens: project electrodes onto the skinbnd(project_elec), build the barycentric interpolationtra(Nelec × Nvert_skin), then setvol.mat = tra * vol.mat(skin rows, :). That is the electrode transfer matrix.ft_compute_leadfieldfordipoli/bemcp: compute the infinite-medium potentials of the dipole at every boundary vertex (inf_medium_leadfield, with the conductivity scaling FieldTrip uses), thenlf = vol.mat * pot. Average reference is applied according tocfg.reducerank/avgref, as indipole_fit.ft_dipolefittinggridsearch branch).dipole_fitwithfminuncif the Optimization Toolbox exists, otherwisefminsearch. To get <1 mm parity we need to pin which optimizer the reference MATLAB uses. Forfminsearchwe would port it directly: same 5%/0.00025 initial simplex andTolX/TolFun/MaxIter. scipy's Nelder–Mead differs in stopping rules.Module layout. Add
src/eegprep/plugins/fieldtrip/(orplugins/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/ptriprojhelpers. Each FieldTrip leadfield type keeps its own module. Replaceleadfield_matrix/_unit_moment_leadfieldand the sphere projection in_fitting.pywith calls throughft_compute_leadfield, and drop the infinite-medium code. The spherical (#600) and BEM backends should both dispatch throughft_compute_leadfieldbyvol.type, so the two efforts converge.Asset. Package
standard_BEM/standard_vol.matas 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.matis a dense N×N matrix, so the wheel size needs checking (Q3). Then reorderSTANDARD_TEMPLATESso MNI BEM is the default, as in EEGLAB'spop_dipfit_settings.Verification, in order (the
@eeglab_test/--eeglab-backend=matlablane, with fixtures produced bytests/matlab/scripts):ft_prepare_vol_senstransfer matrix vs MATLAB forstandard_1005.elcand for theeeglab_data_epochs_ica.setchannels aftercoord_transform(rtol ~1e-10).ft_compute_leadfieldfor a fixed set of dipole positions (rtol ~1e-8).sample_data/eeglab_data_epochs_ica.setwith the EEGLAB default grid: same chosen grid point for every component.posxyzmax error < 0.1 mm, andmomxyz/rvclose.eLORETA and
pop_dipfit_headmodelstay explicitly unsupported.Suggested split into PRs: (a) asset +
ft_prepare_vol_sens+ft_compute_leadfieldwith leadfield parity; (b) grid scan +ft_inside_headmodel; (c)dipole_fitnonlinear + default switch + docs/help.Open questions
plugins/fieldtrip/package that mirrors FieldTrip's tree (forward/,private/), or keep everything underplugins/dipfit/?dipole_fit(fminuncwith the Optimization Toolbox, orfminsearch)? Do we match that one only?standard_vol.mat(densevol.mat) acceptable in the wheel, or should we ship onlybnd+condand recompute the dipoli system matrix? Recomputing means portingdipoli, which is a much larger scope.ft_compute_leadfielddispatch is already in place?EEGLAB_TESTS_EEGLAB_COMMIT?