Skip to content

Fit DIPFIT dipoles with the packaged MNI boundary-element model - #610

Merged
suraj-ranganath merged 10 commits into
developfrom
cursor/dipfit-mni-bem-e231
Nov 18, 2026
Merged

suraj-ranganath merged 10 commits into
developfrom
cursor/dipfit-mni-bem-e231

Conversation

@suraj-ranganath

@suraj-ranganath suraj-ranganath commented Nov 11, 2026 •

Copy link
Copy Markdown
Member

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

Open in Web Open in Cursor 

Use FieldTrip's dipoli electrode transfer and leadfield, and EEGLAB's default grid, when standardBEM is selected.

Co-authored-by: Suraj Ranganath <[email protected]>

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Code review skipped — your organization has no extra usage available to pay for this review.

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.

@cursor

cursor Bot commented Nov 11, 2026

Copy link
Copy Markdown

🤖 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

claude Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @suraj-ranganath's task in 2m 22s —— View job


Code review

  • Overall assessment: Needs changes. I compared the BEM forward chain (eeg_infinite_dipole, eeg_leadfieldb, the BEM branch of ft_prepare_vol_sens, ft_compute_leadfield) with FieldTrip. The electrode projection, the transfer, the average reference of mat, and the dipoli conductivity handling look consistent. The main problems are how the co-registration is chosen and how much work the grid search does.
  • Highest-risk area: How coord_transform is chosen for standardBEM in pop_dipfit_settings._apply_settings.
  • Merge recommendation: Needs changes.

Limits of this review: I could not run the tests or the timing script here because commands needed approval. The EEGLAB .m reference files are not in this checkout, so I could not check parity line by line. This PR changes core DIPFIT numerics, so per AGENTS.md it still needs the MATLAB reference-suite run (eeglab-reference.yml), with its results in the PR body, before merging.

Blocking

None.

Important

  1. A missed lookup clears the co-registration and BEM fits go silently wrong, at pop_dipfit_settings.py:170, in _apply_settings.

    • lookupchantemplate returns [] when EEG.chaninfo.filename is missing or matches no rule, and that [] overwrites the template default [0 0 0 0 0 -1.5708 1 1 1] that apply_template just set.
    • The BEM path then passes unrotated EEGLAB head coordinates (X = nose) into ft_prepare_vol_sens, so the electrodes are projected onto the wrong part of the MNI scalp.
    • The fit still produces finite positions, with no warning. Before this PR, the default transform was kept.
    • Fix: only overwrite the default when found is true, and warn or raise when a BEM fit has an empty transform. (inline)
  2. The grid-search leadfield is rebuilt for every component, at _fitting.py:457, in _fit_bem_component_grid.

    • ft_compute_leadfield(candidates, …) depends only on the grid and the head model, but it is recomputed for every component. That builds (ncand, 3000, 3) intermediates each time.
    • Grid-searching a full decomposition will be very slow and memory-heavy.
    • Fix: compute it once per dipfit_gridsearch or pop_multifit call and pass it in. (inline)
  3. Custom BEM head-model files are never used as BEM.

    • _uses_bem returns true only for an in-memory dipfit["vol"], or when is_bem_hdmfile finds a name ending in standard_vol.mat or .npz.
    • A user who picks "Custom files" with their own dipoli .mat file therefore gets the single-sphere leadfield, with no message.
    • The code meant for that case is then unreachable: _headmodel_from_mat, the .npz branch, and the FileNotFoundError branch in load_bem_headmodel.
    • Fix (either):
      • route any existing .mat/.npz hdmfile through load_bem_headmodel, letting it raise its clear "not a dipoli/bemcp model" error; or
      • delete the unreachable loaders and make an unsupported hdmfile fail loudly instead of falling back to the sphere.

Nits

  • Speculative scaffolding (fieldtrip/spheres.py, sphere and infinite branches of ft_compute_leadfield, ft_headmodeltype(desired=…), the openmeeg case in _check_system_rows):
    • spheres.py only raises NotImplementedError("Plug … into …"). DIPFIT never takes the sphere or infinite branches, because the spherical path uses leadfield_matrix.
    • AGENTS.md says "Do not add features beyond what was asked. No speculative configurability, future-proofing…".
    • Fix: drop these pieces, and the fieldtrip/__init__.py __all__ re-exports, until a caller exists.
  • _BEM_TYPES duplicates bem.BEM_TYPES (_fitting.py). Fix: import the existing constant.
  • Local loadmat import in bem.py:220. Fix: move it to the top of the module. (inline)

Test gaps

  • No test where chaninfo.filename is missing or unmatched.
    • All the new BEM tests use eeglab_data_epochs_ica.set, whose cap385 file name always matches.
    • Fix: add a case where pop_dipfit_settings(EEG, model="standardBEM") runs on a dataset with chaninfo = {}, and assert the documented outcome (template rotation kept, or a clear error). This would catch Important refactor for packaging and test distribution #1.
  • Tests import from scripts/.
    • tests/test_dipfit_bem.py imports bem_parity_payload from scripts.dipfit_standard_bem_parity, so the unit tests depend on a developer script.
    • test_pop_multifit_default_bem_returns_finite_positions runs a full BEM pop_multifit and is not marked slow.
    • Fix: move the small payload helper into the test file (or tests/) and mark the multifit test slow.

EEGLAB parity notes

  • Nonlinear refinement uses a different optimizer. The BEM path uses BFGS (gtol=1e-9, eps=1e-3), while the spherical path keeps Nelder–Mead. Unlike the spherical path, the BEM objective has no inside-compartment penalty. Please confirm against the FieldTrip ft_dipolefitting / dipole_fit behaviour that EEGLAB's dipfit_nonlinear uses, and record the agreement (the < 1 mm assertion in test_bem_leadfield_and_multifit_match_fieldtrip) in the PR body once the reference run has passed.

Comment on lines +170 to +171
_found, transform = lookupchantemplate(channel_template_filename(out), template)
dipfit["coord_transform"] = transform

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Suggested change
_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.

Comment thread src/eegprep/plugins/dipfit/_fitting.py Outdated
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

cursoragent and others added 2 commits November 11, 2026 21:24
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]>
@cursor

cursor Bot commented Nov 11, 2026

Copy link
Copy Markdown

🤖 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: _BEM_TYPES now uses bem.BEM_TYPES; bem_parity_payload lives in the package so the tests do not import scripts/; the unused ft_headmodeltype(desired=) argument, the infinite-medium arm of ft_compute_leadfield, and the OpenMEEG system-matrix size skip are gone. OpenMEEG is recognized and then rejected. Important 1, Important 2, the missing chaninfo.filename test, and the top-level loadmat import were already in 7577608.

Keeping these on purpose:

  • fieldtrip/spheres.py and the singlesphere/concentricspheres arms of ft_prepare_vol_sens and ft_compute_leadfield stay. They are the hook for the four-shell model on Fit standardBESA dipoles with the four-shell BESA leadfield #611. Deleting them would mean a second sphere implementation when that branch merges. They raise NotImplementedError until then. standardBESA does not call them yet; it still uses the existing single-sphere kernel. After Fit standardBESA dipoles with the four-shell BESA leadfield #611 is on develop, this branch will take that implementation so there is one dispatch and no duplicate sphere code.
  • fieldtrip/__init__.py keeps the FieldTrip names this fit path calls. eeg_infinite_dipole is the kernel inside the dipoli/bemcp leadfield, not a separate DIPFIT model.

test_pop_multifit_default_bem_returns_finite_positions stays in the default run. It is a few seconds and is the check that the packaged model returns positions without MATLAB. The 1e-4 and 1 mm gates are unchanged.

BFGS versus fminunc, and the lack of an inside-compartment penalty, are already described in docs/source/user_guide/eeglab_migration.rst. The MATLAB reference result is not in the PR body yet.

@suraj-ranganath
suraj-ranganath marked this pull request as draft November 11, 2026 21:33
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 11, 2026 21:33
@claude

claude Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @suraj-ranganath's task in 1m 19s —— View job


Code review

  • Overall assessment: Needs changes.
    • The fixes in 7577608 and c60835f resolve the earlier review items:
      • The template transform is kept when the channel-template lookup misses, and an empty transform logs a warning.
      • The grid-search leadfield is computed once and shared across components, with a batched pinv.
      • Head-model files are recognized as BEM volumes from their contents, not their names.
      • loadmat is now imported at the top of the module.
      • Tests no longer import from scripts/.
    • The new head-model routing in c60835f brings one regression.
  • Highest-risk area: _uses_bem in src/eegprep/plugins/dipfit/_fitting.py. It decides whether a fit uses the BEM path or the sphere.
  • Merge recommendation: Needs changes.

Blocking

None.

Important

  1. Spherical BESA datasets fail when standard_BESA.mat exists on disk (_fitting.py:521-526, _uses_bem).
    • Why it breaks: Path(hdmfile).is_file() is checked before the BESA name.
      • EEGLAB saves EEG.dipfit.hdmfile as an absolute path.
      • A dataset saved by EEGLAB, opened on a machine that still has EEGLAB installed, is therefore routed to load_bem_headmodel.
      • The BESA vol has r/c/o and no bnd/mat, so loading raises ValueError("... is not a boundary-element head model").
    • Effect: gridsearch, multifit and leadfield all worked on these datasets before this PR, and now they fail.
    • Fix: check the BESA name first; the is_file() branch is then redundant. Add a test that writes a dummy tmp_path/standard_BESA/standard_BESA.mat, sets it as hdmfile, and asserts prepare_forward_data(...).headmodel is None. (inline)

Nits

None.

Test gaps

  • No test for standardBESA with an absolute, existing hdmfile. test_standard_besa_template_stays_on_the_sphere_path only covers the relative template path, which does not resolve from the test's working directory. This is the test described in Important 1.

EEGLAB parity notes

  • The MATLAB reference evidence required before merging is still missing.
    • This PR changes core DIPFIT numerics: the BEM leadfield, the default grid, and the optimizer.
    • AGENTS.md requires one eeglab-reference.yml run, or a local --eeglab-backend=matlab run, recorded in the PR body. That record should include:
      • the EEGLAB and eeglab_tests commits
      • pass/fail/skip counts
      • the result of test_bem_leadfield_and_multifit_match_fieldtrip (gates: leadfield relative error < 1e-4, position difference < 1 mm)
    • The PR also needs human approval. The documented deviation (BFGS instead of fminunc, no inside-compartment penalty) depends on that 1 mm agreement to be accepted.

What I checked: BEM routing and loading in bem.py and _fitting.py; the lookupchantemplate rules and how the transform is chosen in pop_dipfit_settings; the shared grid leadfield; the order of candidate grid points; _template_index; and the history defaults in pop_dipfit_gridsearch. I did not run tests or MATLAB here.

Comment thread src/eegprep/plugins/dipfit/_fitting.py Outdated
Comment on lines +521 to +526
if Path(hdmfile).is_file():
return True
name = hdmfile.replace("\\", "/").lower().rsplit("/", 1)[-1]
if name == _BESA_TEMPLATE_NAME:
return False
return True

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
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]>
@suraj-ranganath
suraj-ranganath marked this pull request as draft November 11, 2026 21:37
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 11, 2026 21:37
@claude

claude Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @suraj-ranganath's task in 1m 35s —— View job


Code review

  • Overall assessment: Needs more context. The code problems from the two earlier reviews are fixed as of 01dccca, and I found no new correctness bug. What's missing is evidence: the MATLAB reference run and human approval.
  • Highest-risk area: The numerics of BEM nonlinear refinement (_optimize_positions in _fitting.py), which uses BFGS with no inside-compartment penalty. Nothing has been compared against FieldTrip yet.
  • Merge recommendation: Needs more context. Code changes are only nits; the remaining gap is evidence.

Earlier findings, checked in the current code:

  • Template transform: kept when lookupchantemplate misses; an empty transform logs a warning (pop_dipfit_settings.py:188-190, _fitting.py:212-218).
  • Grid leadfield: computed once per dipfit_gridsearch and scanned with a batched pinv (_fitting.py:98-103).
  • Head-model files: detected by content; non-BEM, missing and OpenMEEG files raise clear errors (bem.py load_bem_headmodel / _validate_bem_volume).
  • On-disk standard_BESA.mat: stays on the sphere path, because the BESA name is checked before the file is opened. It has a regression test.
  • loadmat: now imported at the top of bem.py.
  • Tests: no longer import from scripts/.

Blocking

None.

Important

None.

Nits

  • dipfit_nonlinear(maxiter=...) is ignored on the BEM path (_fitting.py:450).
    • BFGS always uses _BEM_OPTIMIZER_MAXITER = 1000; only the sphere path honors maxiter.
    • Fix: pass int(maxiter) through, or change the default where dipfit_nonlinear is called. (inline)
  • Test-only code is in the runtime plugin package (src/eegprep/plugins/dipfit/_bem_parity.py).
    • It builds the parity payload (pop_loadset → pop_dipfit_settings → pop_multifit) and is used only by tests/test_dipfit_bem.py and scripts/dipfit_standard_bem_parity.py.
    • AGENTS.md: "src/eegprep/utils/: Python-only test/development support."
    • Fix: move it to src/eegprep/utils/ (or tests/) so the shipped plugins/dipfit holds only ported DIPFIT code.

Test gaps

None. The cases requested earlier are covered:

  • missing chaninfo.filename
  • renamed dipoli .mat and .npz files
  • a non-BEM .mat file
  • a missing file
  • an OpenMEEG file
  • an on-disk standard_BESA.mat

EEGLAB parity notes

  • The merge-gate evidence is still missing. This PR changes core DIPFIT numerics: the default forward model, the 24×24×12 grid, the optimizer, and the co-registration lookup. Per AGENTS.md, before merge it needs:
    • one eeglab-reference.yml run, or a local --eeglab-backend=matlab run, recorded in the PR body with the EEGLAB and eeglab_tests commits, pass/fail/skip counts, and runtime;
    • the result of test_bem_leadfield_and_multifit_match_fieldtrip, with leadfield max relative error < 1e-4 and position difference < 1 mm;
    • human approval.
  • The documented optimizer difference rests on that 1 mm gate. The difference is BFGS instead of fminunc, with no inside-brain penalty (described in eeglab_migration.rst). Until the gate passes, nothing shows that BEM refinement converges to FieldTrip's positions.

What I checked:

  • the latest commit 01dccca;
  • _uses_bem, _load_bem_volume and load_bem_headmodel routing;
  • _headmodel_from_mat and _validate_bem_volume;
  • the BEM branch of ft_prepare_vol_sens (skin transfer, average reference) and ft_compute_leadfield;
  • grid order (F-order, like MATLAB ndgrid) and the ft_inside_headmodel filter;
  • how lookupchantemplate and _template_index choose the transform;
  • callers of prepare_forward_data, fit_component_grid and run_nonlinear;
  • package-data entries for .npz and .elc.

I did not run the tests or MATLAB.

Comment thread src/eegprep/plugins/dipfit/_fitting.py Outdated
objective,
initial_params,
method="BFGS",
options={"maxiter": _BEM_OPTIMIZER_MAXITER, "gtol": 1e-9, "eps": 1e-3, "disp": False},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
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]>
@cursor

cursor Bot commented Nov 11, 2026

Copy link
Copy Markdown

🤖 The BFGS fit now uses the maxiter argument. An explicit dipfit_nonlinear(..., maxiter=200) limits the MNI model to 200 iterations.

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. test_bem_nonlinear_uses_the_callers_maxiter checks that maxiter=1 stops short of the 1000-iteration result and that the default matches 1000.

@suraj-ranganath
suraj-ranganath marked this pull request as draft November 11, 2026 21:42
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 11, 2026 21:42
@claude

claude Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @suraj-ranganath's task in 34s —— View job


Code review

  • Overall assessment: Needs more context.
    • The latest commit (a48a212) correctly fixes the maxiter nit:
      • The caller's maxiter now reaches both optimizers.
      • _BEM_OPTIMIZER_MAXITER is gone.
      • When maxiter is omitted, it defaults to 1000 for a BEM model and 200 for a sphere, set at the dipfit_nonlinear signature.
    • The two callers (pop_dipfit_nonlinear and pop_multifit in _fieldtrip_workflows.py) leave maxiter unset, so their behavior is the same as before.
    • I found no new correctness bug.
  • Highest-risk area: The numerics of BEM nonlinear refinement (_optimize_positions: BFGS with no inside-brain penalty). Nothing has compared them with FieldTrip yet.
  • Merge recommendation: Needs more context. The remaining gap is merge-gate evidence, not code.

Blocking

None.

Important

None.

Nits

  • Test-only helper still ships in the runtime plugin (src/eegprep/plugins/dipfit/_bem_parity.py). This was raised in the last review and is still open.
    • Only tests/test_dipfit_bem.py and scripts/dipfit_standard_bem_parity.py import it.
    • AGENTS.md says src/eegprep/utils/ is for "Python-only test/development support".
    • Fix: move it to src/eegprep/utils/ and update the two imports.

Test gaps

None. test_bem_nonlinear_uses_the_callers_maxiter checks three things:

  • an explicit limit cuts the fit short;
  • an omitted limit matches the 1000-iteration result;
  • an on-disk standard_BESA.mat stays on the sphere path, along with the other routing cases.

EEGLAB parity notes

  • Merge-gate evidence is still missing. This PR changes core DIPFIT numerics: the default forward model, the 24×24×12 grid, the optimizer, and the co-registration lookup. Per AGENTS.md, it needs the following before merge:
    • one eeglab-reference.yml run, or a local --eeglab-backend=matlab run, recorded in the PR body with:
      • the EEGLAB and eeglab_tests commits
      • pass/fail/skip counts
      • runtime
    • the result of test_bem_leadfield_and_multifit_match_fieldtrip: leadfield max relative error < 1e-4 and position difference < 1 mm
    • human approval
  • The 1 mm FieldTrip gate supports a documented difference. The BFGS-instead-of-fminunc change and the missing inside-brain penalty are described in eeglab_migration.rst. That gate is also the only evidence that the 1000-iteration BEM default is enough.

What I checked:

  • the a48a212 diff
  • every caller of dipfit_nonlinear / run_nonlinear, for how maxiter is passed through
  • that the removed constant has no remaining references
  • the new test's determinism and what it asserts

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]>
@suraj-ranganath
suraj-ranganath marked this pull request as draft November 12, 2026 05:19
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 12, 2026 05:19
@claude

claude Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @suraj-ranganath's task in 1m 10s —— View job


Code review

  • Overall assessment: Needs more context.
    • The fixes from earlier reviews are still in place: template transform kept on lookup miss, shared grid leadfield, content-based BEM detection, the BESA name checked first, maxiter passed through.
    • The new commit 0e585c2 loosens the FieldTrip parity gate for sample component 3, and nothing recorded in the PR backs that change yet.
  • Highest-risk area: test_bem_leadfield_and_multifit_match_fieldtrip, which is the only evidence for the BFGS-without-inside-penalty deviation, now accepts any component 3 position as long as its RV is lower.
  • Merge recommendation: Needs more context.

Blocking

None.

Important

  1. The component 3 gate changed from a 1 mm position check to python_rv <= matlab_rv, with no position or inside-brain check (tests/test_dipfit_bem.py:356-361).
    • Why it matters: The BEM objective in _optimize_positions (_fitting.py:440-444) has no inside-compartment penalty. A lower RV there may come from BFGS leaving the brain mesh, not from fminunc stopping early, and the new assertion cannot tell these apart. The exact <= also fails when both sides reach the same minimum and differ by about 1e-10.
    • Missing evidence: The PR body says fminunc "stops at a higher-residual local minimum", and also says MATLAB was not run. The numbers behind that claim are not recorded anywhere. AGENTS.md: "Never relax tolerances or hack around failures without proving the numerical expectation is wrong."
    • Fix:
      • Keep 1 mm for all components, with the RV route (strict <) only as a fallback for component 3.
      • Assert that the Python component 3 dipole satisfies ft_inside_headmodel.
      • Record the component 3 distance and both RVs in the PR body. (inline)

Nits

  • eeglab_migration.rst:107-109 makes a general claim. "EEGPrep keeps the lower-residual fit" reads as if EEGPrep compares fits and picks one. It doesn't: this was observed for one sample component.
    • Fix: say that on the sample dataset, BFGS reached a lower residual than fminunc for component 3, and give the distance.
  • src/eegprep/plugins/dipfit/_bem_parity.py is still test-only code in the runtime plugin. This is still open from the previous two reviews. AGENTS.md puts "Python-only test/development support" in src/eegprep/utils/.

Test gaps

  • No inside-brain assertion for nonlinear BEM fits. A cheap check that needs no MATLAB: in test_pop_multifit_default_bem_returns_finite_positions, also assert ft_inside_headmodel(positions, headmodel).all() for components 1–3. This catches the unconstrained-BFGS failure mode in the default run.

EEGLAB parity notes

  • Merge-gate evidence is still missing. This PR changes core DIPFIT numerics: the default forward model, the 24×24×12 grid, the BFGS optimizer, and the cap385 co-registration. Before merging, AGENTS.md requires:
    • one eeglab-reference.yml run, or a local --eeglab-backend=matlab run, recorded in the PR body with the EEGLAB and eeglab_tests commits, pass/fail/skip counts, and runtime;
    • the test_bem_leadfield_and_multifit_match_fieldtrip numbers: leadfield relative error, the three distances, and the three RVs;
    • human approval.
  • The missing penalty now matters more. The parity gate has been relaxed for component 3, so whether FieldTrip's dipole_fit rejects dipoles outside the source compartment decides whether "lower RV" is better or just unconstrained. Please confirm against the pinned FieldTrip version and say which applies in eeglab_migration.rst.

What I checked: the full 0e585c2 diff (test, MATLAB reference script, parity payload, docs); the BEM objective and optimizer branch in _fitting.py; that the rv values compared on both sides come from pop_multifit models on the same leadfield. I did not run tests or MATLAB.

Comment thread tests/test_dipfit_bem.py
Comment on lines +356 to +361
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]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 (

def objective(values: np.ndarray) -> float:
positions = unpack(values)
if forward.headmodel is None and np.any(np.linalg.norm(positions, axis=1) >= forward.head_radius * 0.995):
return 1e3 + float(np.max(np.linalg.norm(positions, axis=1)))
return float(_fit_positions_to_topography(forward.positions, topography, positions, forward=forward)["rv"])
). Without it, a lower RV can mean BFGS left the brain mesh: potentials from a dipole near or outside the inner skull can fit a topography "better" while the location is not physically valid. So 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."

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

cursoragent and others added 2 commits November 18, 2026 07:05
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]>
@suraj-ranganath
suraj-ranganath marked this pull request as draft November 18, 2026 08:03
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 18, 2026 08:03

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Code review skipped — your organization has no extra usage available to pay for this review.

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

claude Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @suraj-ranganath's task in 1m 44s —— View job


Code review

  • Overall assessment: Needs changes.
    • The MATLAB reference evidence is now in the PR body: 42/42 passed on R2025b, EEGLAB d0963be9, eeglab_tests fec88f9f; leadfield max relative error 3.8e-15; components 1 and 2 within 0.0007 mm.
    • The merge with Fit standardBESA dipoles with the four-shell BESA leadfield #611 leaves one leadfield dispatch for spheres and BEM.
    • Earlier review items are still fixed:
      • the template transform is kept when the channel lookup misses
      • the grid leadfield is shared across components
      • BEM head-model files are recognized by their contents
      • BESA files are checked by name before the disk is touched
      • maxiter is passed through
      • the parity helper is now in src/eegprep/utils/
  • Highest-risk area: BEM nonlinear refinement (_optimize_positions, BFGS branch). It has no inside-brain constraint, and sample component 3 ends outside the brain mesh.
  • Merge recommendation: Needs changes. One documentation-or-constraint decision is left, and the human approval AGENTS.md requires for core-function PRs is still needed.

Blocking

None.

Important

  1. BEM refinement can return a dipole outside the brain, and the docs don't say so (_fitting.py:479-498; inline).
    • What happens: the objective's guard only applies when forward.headmodel is None, so BFGS can leave the source compartment.
    • Evidence: your reply on tests/test_dipfit_bem.py says the default pop_multifit dipole for sample component 3 gives ft_inside_headmodel == False. EEGLAB's dipole is inside the mesh, 8.3 mm away.
    • What the docs say: the reply says this difference is described in eeglab_migration.rst. The current DIPFIT MNI row (lines 102-111) only calls component 3's lower residual "an observation". Nothing there, or in pop_multifit.md / pop_dipfit_nonlinear.md, warns that a fit can end outside the brain.
    • Why it matters: the gate is now python_rv[2] <= matlab_rv[2], so an out-of-brain fit passes as "better" without users being told.
    • Fix (pick one):
      • Add an ft_inside_headmodel penalty to the BEM objective, then rerun the MATLAB comparison.
      • Or state the unconstrained behavior explicitly in the migration row and the two help files, and assert in the parity test that component 3 is outside the mesh, so the documented deviation is locked in.

Nits

None.

Test gaps

None beyond the assertion in Important 1.

EEGLAB parity notes

  • Electrode co-registration differs on purpose and is documented. For a standard-10-5-cap385 channel file, EEGLAB switches to the BESA sphere. EEGPrep instead keeps the MNI model with the cap385-to-MNI transform.
  • The optimizer differs and is documented. EEGPrep uses BFGS where EEGLAB uses fminunc. If you keep the unconstrained fit, document that as well (see Important 1).

What I checked: the full origin/develop...ded2716 diff of _fitting.py, the forward/ dispatch modules, fieldtrip/bem.py (loading, .mat parsing, validation, the system-matrix row check), _fieldtrip_workflows.py callers, the migration docs, and the parity test. I did not run tests or MATLAB, and the vendored EEGLAB/FieldTrip .m files are not in this checkout.

result = minimize(
objective,
start,
method="BFGS",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 (

def objective(values: np.ndarray) -> float:
positions = unpack(values)
if forward.headmodel is None and np.any(np.linalg.norm(positions, axis=1) >= forward.head_radius * 0.995):
return 1e3 + float(np.max(np.linalg.norm(positions, axis=1)))
fit = _fit_positions_to_topography(forward.positions, topography, positions, forward.headmodel)
rv = float(fit["rv"])
if not np.isfinite(rv):
return 1.0
return rv
start = np.asarray(initial_params, dtype=float).ravel()
if _is_bem(forward.headmodel):
result = minimize(
objective,
start,
method="BFGS",
options={"maxiter": int(maxiter), "gtol": 1e-9, "eps": 1e-3, "disp": False},
)
fitted = result.x if result.success or np.isfinite(result.fun) else start
else:
). In the review reply on 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 (

- The default head model is the packaged dipoli boundary-element volume
from DIPFIT ``standard_vol.mat``. Grid search uses EEGLAB's
``linspace(-85,85,24)`` and ``linspace(0,85,12)`` points that fall
inside the brain mesh, then refines each dipole with SciPy BFGS.
That optimizer is the analogue of ``fminunc`` and is not bit-identical
to MATLAB. Components 1 and 2 of the sample dataset land within 1 mm
of EEGLAB. On that sample, component 3's lower residual than EEGLAB
is an observation, not a general rule. EEGLAB's settings
dialog switches a channel file whose name contains
``standard-10-5-cap385`` to the BESA sphere. EEGPrep keeps the MNI
) only calls component 3's lower residual "an observation". AGENTS.md: "Any user-facing EEGPrep change must include matching Sphinx updates".

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.md that 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.

cursoragent and others added 2 commits November 18, 2026 09:05
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]>
@suraj-ranganath
suraj-ranganath marked this pull request as draft November 18, 2026 09:32
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 18, 2026 09:32
@claude

claude Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @suraj-ranganath's task in 41s —— View job


Code review

  • Overall assessment: Looks good. e7f4b0f resolves the one open item from the last review (an out-of-brain BEM fit was undocumented). 836ddde merges develop and changes no DIPFIT code.
  • Highest-risk area: BEM nonlinear refinement (_fitting.py, BFGS branch). It still has no inside-brain constraint, but that is now a documented and tested deviation.
  • Merge recommendation: Safe to merge once a human approves. The MATLAB reference evidence AGENTS.md requires is in the PR body: 42/42 tests passed, EEGLAB d0963be9, eeglab_tests fec88f9f, leadfield relative max error 3.8e-15.

The previous Important item, checked against the current code:

  • Migration docs: the DIPFIT MNI row in eeglab_migration.rst now says BFGS refinement has no inside-brain constraint, can land outside the brain mesh with a lower residual than EEGLAB's, and that sample component 3 does this.
  • Help pages: pop_multifit.md and pop_dipfit_nonlinear.md say the same.
  • Parity test: test_bem_leadfield_and_multifit_match_fieldtrip now asserts not ft_inside_headmodel(python_positions[2:3], headmodel).any(). If a future constraint or optimizer change moves component 3 back inside the brain, that assertion will fail, and the docs will have to be revisited.

Blocking

None.

Important

None.

Nits

None.

Test gaps

None.

EEGLAB parity notes

  • Optimizer: EEGPrep uses BFGS where EEGLAB uses fminunc, with no inside-brain penalty. This is documented and locked by the assertion above.
  • Channel-file switch: for a standard-10-5-cap385 channel file, EEGLAB switches to the BESA sphere. EEGPrep keeps the MNI model and applies the cap385-to-MNI transform. This is documented.

What I checked: the e7f4b0f diff (migration row, both help files, the new assertion and its imports); that ft_inside_headmodel in fieldtrip/geometry.py is the BEM implementation that forward/ft_inside_headmodel.py dispatches to; that 836ddde touches no DIPFIT files. I did not run the tests or MATLAB here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

2 participants