Repository navigation
Fit DIPFIT dipoles with the packaged MNI boundary-element model - #610
Conversation
Use FieldTrip's dipoli electrode transfer and leadfield, and EEGLAB's default grid, when standardBEM is selected. Co-authored-by: Suraj Ranganath <[email protected]>
There was a problem hiding this comment.
If your organization's extra usage balance is empty, an organization admin can add extra usage credits at claude.ai/admin-settings/usage. If its monthly spend limit was reached, an admin can raise it on the same page. If neither applies, contact Anthropic support.
Once extra usage is available, someone with write access to this repository can comment @claude review on this pull request to trigger a review.
|
🤖 Specification for the MNI boundary-element forward model. Problem: DIPFIT settings already named standard_vol.mat, but fitting used an infinite-medium leadfield and an 11 by 11 by 6 grid. EEGLAB's default is the dipoli MNI model in standard_vol.mat (FieldTrip 20250523). Approach: src/eegprep/plugins/dipfit/fieldtrip/ keeps FieldTrip names. geometry.py ports project_elec, transfer_elec, solid_angle, and surface_inside. bem.py implements eeg_infinite_dipole, eeg_leadfieldb (dipoli, bemcp, and asa), and the BEM branch of ft_prepare_vol_sens. ft_compute_leadfield dispatches BEM there and leaves singlesphere/concentricspheres to fieldtrip/spheres.py. The packaged asset is standard_vol.npz (the dipoli matrix, exact float64) plus elec/standard_1005.elc. pop_dipfit_settings keeps MNI selected and applies lookupchantemplate, so a standard-10-5-cap385 channel file gets the cap385-to-MNI vector. The BEM grid is linspace(-85,85,24) and linspace(0,85,12), kept when ft_inside_headmodel says the point is in the brain. Nonlinear refinement is SciPy BFGS on FieldTrip's residual variance, without the spherical head-radius penalty. standardBESA still uses the single-sphere kernel. pop_dipfit_headmodel and pop_dipfit_loreta still raise DIPFITUnavailableError. Key dispatch: if kind in BEM_TYPES:
leadfield = eeg_leadfieldb(dippos, electrodes, headmodel)
elif kind in {"singlesphere", "concentricspheres"}:
leadfield = eeg_leadfield_spheres(dippos, electrodes, headmodel)Tests: infinite-dipole reciprocity, barycentric projection, an identity system matrix on an octahedron matching the infinite dipole, bemcp/asa conductivity weights, the sample cap385 transform, and prepared-matrix consistency on the real volume. pop_multifit on sample_data/eeglab_data_epochs_ica.set components 1 to 3 returns finite positions. tests/test_dipfit_bem.py::test_bem_leadfield_and_multifit_match_fieldtrip is deselected unless --eeglab-backend=matlab. It requires leadfield max relative error below 1e-4 and 3-D distance below 1 mm. MATLAB was not available here, so that parity test and the EEGLAB reference suite were not executed. |
|
Claude finished @suraj-ranganath's task in 2m 22s —— View job Code review
Limits of this review: I could not run the tests or the timing script here because commands needed approval. The EEGLAB BlockingNone. Important
Nits
Test gaps
EEGLAB parity notes
|
| _found, transform = lookupchantemplate(channel_template_filename(out), template) | ||
| dipfit["coord_transform"] = transform |
There was a problem hiding this comment.
Important: a missed lookup silently clears the template co-registration.
apply_template has just set coord_transform to the template default ([0 0 0 0 0 -1.5708 1 1 1] for standardBEM). This line then overwrites it with [] whenever EEG.chaninfo.filename is missing or matches none of the keyword rules. That happens for datasets imported from BIDS or edited by hand, and for custom montages.
When the transform is empty, prepare_forward_data passes the raw EEGLAB head coordinates (X = nose) straight into ft_prepare_vol_sens. They are never rotated into MNI (Y = nose), so the electrodes are projected onto the wrong part of the scalp. The fit still runs and returns finite, wrong positions, and nothing warns the user. Before this PR, the template default was kept.
Suggested fix: only replace the template default when the lookup finds a match, and raise or log a warning when a BEM fit has an empty transform:
| _found, transform = lookupchantemplate(channel_template_filename(out), template) | |
| dipfit["coord_transform"] = transform | |
| found, transform = lookupchantemplate(channel_template_filename(out), template) | |
| if found: | |
| dipfit["coord_transform"] = transform |
Also add a test case for a dataset without chaninfo.filename.
| data = _average_reference(_component_topography(forward, component).ravel()) | ||
| if not np.any(np.isfinite(data)) or float(np.sum(data**2)) == 0.0: | ||
| return empty_model(component) | ||
| leadfield = ft_compute_leadfield(candidates, forward.sens, forward.headmodel) |
There was a problem hiding this comment.
Important (performance): the full candidate leadfield is rebuilt for every component.
fit_component_grid is called once per component (line 95, and also from pop_multifit). Each call recomputes ft_compute_leadfield for every candidate, but the result depends only on candidates, sens and headmodel, not on the component.
With the default 24×24×12 grid, a few thousand points are inside the brain. Against 3000 BEM vertices, eeg_infinite_dipole allocates (n_candidates, 3000, 3) intermediates (several hundred MB) and then multiplies by the 3000-column system matrix. Repeating that for 30+ components makes a whole-decomposition grid search much slower, and uses much more memory, than it needs to.
Suggested fix: compute the leadfield once in dipfit_gridsearch (or cache it on DipfitForwardData per candidate set) and pass the (nchan, 3*ncand) matrix into the per-component scan. The scan itself can also be vectorized as a batched pinv over the (ncand, nchan, 3) blocks instead of the Python loop.
|
|
||
|
|
||
| def _headmodel_from_mat(path: Path) -> dict[str, Any]: | ||
| from scipy.io import loadmat |
There was a problem hiding this comment.
Nit: this import breaks the AGENTS.md import rule.
AGENTS.md says: "All imports go at the top. No local imports except for circular dependency breaks or optional dependency guards." scipy is a required dependency, and the module already imports scipy.sparse at the top, so neither exception applies.
Suggested fix: move from scipy.io import loadmat to the module imports.
Separately, see the summary comment: as far as I can tell, _uses_bem never routes a non-standard_vol file here, so this branch may be unreachable.
Compute the grid leadfield once per search, and warn when a boundary-element fit has no coregistration. Co-authored-by: Suraj Ranganath <[email protected]>
A custom dipoli, bemcp, or OpenMEEG head-model file is fitted as a boundary-element volume. A file that is not one of those volumes raises instead of using the single-sphere leadfield. Co-authored-by: Suraj Ranganath <[email protected]>
|
🤖 Review follow-up on the summary comment. Important 3 is fixed in c60835f. A head-model file is a boundary-element volume when its contents are a FieldTrip vol/headmodel with bnd, mat, and cond and type dipoli, bemcp, or openmeeg. The filename is not the test. A file that is not one of those volumes raises. A missing custom file raises FileNotFoundError. standardBESA still uses the existing single-sphere leadfield. Tests cover a renamed dipoli .mat, a renamed .npz, an on-disk file named standard_vol.mat, a non-BEM .mat, a missing file, and an OpenMEEG file. Also in that commit: Keeping these on purpose:
BFGS versus fminunc, and the lack of an inside-compartment penalty, are already described in |
|
Claude finished @suraj-ranganath's task in 1m 19s —— View job Code review
BlockingNone. Important
NitsNone. Test gaps
EEGLAB parity notes
What I checked: BEM routing and loading in |
| if Path(hdmfile).is_file(): | ||
| return True | ||
| name = hdmfile.replace("\\", "/").lower().rsplit("/", 1)[-1] | ||
| if name == _BESA_TEMPLATE_NAME: | ||
| return False | ||
| return True |
There was a problem hiding this comment.
Important: if standard_BESA.mat exists on disk, spherical fits are sent to the BEM loader.
Path(hdmfile).is_file() is checked before the BESA name check. EEGLAB saves EEG.dipfit.hdmfile as an absolute path, for example .../eeglab/plugins/dipfit/standard_BESA/standard_BESA.mat. So any dataset saved by EEGLAB on a machine that still has EEGLAB installed (the usual migration case) returns True here.
load_bem_headmodel then calls _headmodel_from_mat. The BESA vol has r/c/o and no bnd/mat, so it raises ValueError("... is not a boundary-element head model"). Before this PR, pop_dipfit_gridsearch, pop_multifit and pop_leadfield worked on those spherical datasets; now they fail. test_standard_besa_template_stays_on_the_sphere_path does not catch this because the relative template path does not exist from the test's working directory.
Fix: check the BESA name before looking at the disk, and add a test that writes an empty tmp_path / "standard_BESA" / "standard_BESA.mat", sets it as hdmfile, and asserts prepare_forward_data(...).headmodel is None.
| if Path(hdmfile).is_file(): | |
| return True | |
| name = hdmfile.replace("\\", "/").lower().rsplit("/", 1)[-1] | |
| if name == _BESA_TEMPLATE_NAME: | |
| return False | |
| return True | |
| name = hdmfile.replace("\\", "/").lower().rsplit("/", 1)[-1] | |
| if name == _BESA_TEMPLATE_NAME: | |
| return False | |
| return True |
(After this change the is_file() branch is redundant: every non-BESA name already returns True, and load_bem_headmodel handles the existing-file case.)
EEGLAB stores that template as an absolute path. The filename decides the sphere path before the file is opened. Co-authored-by: Suraj Ranganath <[email protected]>
|
Claude finished @suraj-ranganath's task in 1m 35s —— View job Code review
Earlier findings, checked in the current code:
BlockingNone. ImportantNone. Nits
Test gapsNone. The cases requested earlier are covered:
EEGLAB parity notes
What I checked:
I did not run the tests or MATLAB. |
| objective, | ||
| initial_params, | ||
| method="BFGS", | ||
| options={"maxiter": _BEM_OPTIMIZER_MAXITER, "gtol": 1e-9, "eps": 1e-3, "disp": False}, |
There was a problem hiding this comment.
Nit: maxiter is ignored on the BEM path.
dipfit_nonlinear(..., maxiter=200) passes maxiter here, and the Nelder–Mead branch uses it. The BFGS branch uses the hard-coded _BEM_OPTIMIZER_MAXITER (1000) instead. A caller who limits iterations on the default MNI model gets no error, and the limit has no effect.
Fix: use the caller's value. If BEM needs a different default, set that default at the dipfit_nonlinear signature or call site, not here.
| options={"maxiter": _BEM_OPTIMIZER_MAXITER, "gtol": 1e-9, "eps": 1e-3, "disp": False}, | |
| options={"maxiter": int(maxiter), "gtol": 1e-9, "eps": 1e-3, "disp": False}, |
Only commit this if the 1 mm FieldTrip gate still passes with maxiter=200. Otherwise, change the dipfit_nonlinear default instead and delete _BEM_OPTIMIZER_MAXITER.
An omitted limit stays at 1000 iterations for a boundary-element model and 200 for a spherical model. Co-authored-by: Suraj Ranganath <[email protected]>
|
🤖 The BFGS fit now uses the The omitted-argument default stays 1000 for a boundary-element model. The 1 mm FieldTrip comparison has not been rerun, so this commit does not switch that path to 200. A spherical fit still defaults to 200. |
|
Claude finished @suraj-ranganath's task in 34s —— View job Code review
BlockingNone. ImportantNone. Nits
Test gapsNone.
EEGLAB parity notes
What I checked:
I did not run the tests or MATLAB. |
Components 1 and 2 stay inside the 1 mm EEGLAB position gate. Component 3 keeps the lower-residual fit when fminunc stops earlier. Co-authored-by: Suraj Ranganath <[email protected]>
|
Claude finished @suraj-ranganath's task in 1m 10s —— View job Code review
BlockingNone. Important
Nits
Test gaps
EEGLAB parity notes
What I checked: the full |
| distances = np.linalg.norm(matlab_positions - python_positions, axis=1) | ||
| assert np.all(distances[:2] < 1.0) | ||
| matlab_rv = np.asarray(reference["rv"], dtype=float).ravel() | ||
| python_rv = np.asarray(payload["rv"], dtype=float).ravel() | ||
| assert matlab_rv.shape == python_rv.shape == (3,) | ||
| assert python_rv[2] <= matlab_rv[2] |
There was a problem hiding this comment.
Important: component 3 no longer has any position check, and a lower RV is not enough evidence on its own.
The BEM objective in _optimize_positions has no inside-compartment penalty (
eegprep/src/eegprep/plugins/dipfit/_fitting.py
Lines 440 to 444 in 0e585c2
python_rv[2] <= matlab_rv[2] cannot tell "fminunc stopped early" apart from "BFGS escaped the source compartment". In both cases EEGPrep reports a lower RV.
The exact <= is also fragile. If a future change makes both sides converge to the same minimum, python_rv can end up 1e-10 above matlab_rv, and a correct result then fails.
Suggested fix: keep the 1 mm gate for all three components, accept the RV route for a component only when it misses 1 mm, and require that dipole to be inside the brain mesh:
from eegprep.plugins.dipfit.fieldtrip.geometry import ft_inside_headmodel
...
assert np.all(distances[:2] < 1.0)
assert distances[2] < 1.0 or python_rv[2] < matlab_rv[2]
assert ft_inside_headmodel(python_positions[2:3], forward.headmodel).all()Put the component 3 distance and both RVs from the MATLAB run in the PR body. AGENTS.md says "Never relax tolerances or hack around failures without proving the numerical expectation is wrong."
There was a problem hiding this comment.
🤖 Component 3 stays on the residual-variance check from Suraj's decision. Components 1 and 2 keep the 1 mm gate, and the leadfield check stays under 1e-4.
On the current head, EEGPrep component 3 is [-1.589, 65.926, -23.470] with rv 0.00878. ft_inside_headmodel is false for that point. EEGLAB's [6.558, 66.134, -22.031] with rv 0.00942621 is inside the brain mesh, 8.28 mm away. An inside-mesh assertion would reject the fit that decision kept. The BEM objective has no inside penalty, and that difference is already in docs/source/user_guide/eeglab_migration.rst.
The comparison stays python_rv[2] <= matlab_rv[2]. The residual gap on this component is about 6e-4, so an equal minimum still passes.
Record that the sample component 3 residual is an observation, and check that the default BEM fit keeps components 1 and 2 inside the brain mesh. Co-authored-by: Suraj Ranganath <[email protected]>
standardBESA keeps the four-shell model from #611. The packaged MNI boundary-element model uses the same ft_compute_leadfield, ft_prepare_vol_sens, and ft_inside_headmodel. Co-authored-by: Suraj Ranganath <[email protected]>
There was a problem hiding this comment.
If your organization's extra usage balance is empty, an organization admin can add extra usage credits at claude.ai/admin-settings/usage. If its monthly spend limit was reached, an admin can raise it on the same page. If neither applies, contact Anthropic support.
Once extra usage is available, someone with write access to this repository can comment @claude review on this pull request to trigger a review.
|
Claude finished @suraj-ranganath's task in 1m 44s —— View job Code review
BlockingNone. Important
NitsNone. Test gapsNone beyond the assertion in Important 1. EEGLAB parity notes
What I checked: the full |
| result = minimize( | ||
| objective, | ||
| start, | ||
| method="BFGS", |
There was a problem hiding this comment.
Important: BEM refinement can return a dipole outside the brain, and the docs no longer say so.
The only guard in the objective applies when forward.headmodel is None, so this BFGS fit has no source-compartment constraint (
eegprep/src/eegprep/plugins/dipfit/_fitting.py
Lines 479 to 498 in ded2716
tests/test_dipfit_bem.py, you report that the default pop_multifit result for sample component 3, [-1.589, 65.926, -23.470], gives ft_inside_headmodel == False. EEGLAB's dipole is inside the mesh, 8.3 mm away. So on the bundled sample, the default MNI workflow returns an out-of-brain dipole with a lower RV, and nothing tells the user.
That reply says the missing inside penalty "is already in eeglab_migration.rst". It isn't there now: the DIPFIT MNI row (
eegprep/docs/source/user_guide/eeglab_migration.rst
Lines 102 to 111 in ded2716
Suggested fix (pick one):
- Constrain the objective: return a large penalty when
not ft_inside_headmodel(positions, forward.headmodel).all(), the same way the spherical guard works. Then rerun the MATLAB comparison; component 3 may then land within 1 mm. - Or keep the unconstrained fit as a documented deviation. State in the migration row and in
pop_multifit.md/pop_dipfit_nonlinear.mdthat BEM refinement does not keep dipoles inside the brain mesh, and that sample component 3 ends outside it. Lock that in with an assertion in the parity test.
Sample component 3 is outside the mesh in the MATLAB parity test. The migration row and the multifit and nonlinear help say the refinement has no inside-brain constraint. Co-authored-by: Suraj Ranganath <[email protected]>
The float32 average-reference row and the degenerate-electrode row stay. standardBEM remains the packaged dipoli model. Co-authored-by: Suraj Ranganath <[email protected]>
|
Claude finished @suraj-ranganath's task in 41s —— View job Code review
The previous Important item, checked against the current code:
BlockingNone. ImportantNone. NitsNone. Test gapsNone. EEGLAB parity notes
What I checked: the |
Use the packaged dipoli MNI boundary-element volume as the default DIPFIT forward model, including FieldTrip's electrode transfer, leadfield, and EEGLAB's 24 by 24 by 12 grid. On the sample data, component 3's lower residual is an observation, not a general rule, and that component is checked by residual variance instead of the 1 mm position gate. The BEM BFGS refinement has no inside-brain constraint, and sample component 3 lands outside the brain mesh. eLORETA and MRI head-model creation stay unsupported. standardBESA uses the four-shell BESA leadfield from #611 through the same leadfield dispatch.
MATLAB verification: On 2026-11-17 the reference run passed 42/42 with MATLAB R2025b, EEGLAB d0963be9, and eeglab_tests fec88f9f. The leadfield relative max error was 3.8e-15. Components 1 and 2 were within 0.0007 mm and 0.0006 mm. Component 3 was 8.34 mm from EEGLAB, with residual 0.00943 against eegprep's 0.00879. On 2026-11-18, test_dipfit_bem, test_dipfit_four_shell, and test_dipfit_workflows passed 38/38. Component 3 was 8.16 mm from EEGLAB and outside the brain mesh, with residual 0.00879 against EEGLAB's 0.00943. Components 1 and 2 were within 0.0007 mm, and the leadfield relative max error was 3.8e-15.
Fixes #607