Skip to content

Fit standardBESA dipoles with the four-shell BESA leadfield - #611

Merged
suraj-ranganath merged 8 commits into
developfrom
cursor/dipfit-four-shell-882a
Nov 18, 2026
Merged

suraj-ranganath merged 8 commits into
developfrom
cursor/dipfit-four-shell-882a

Conversation

@suraj-ranganath

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

Copy link
Copy Markdown
Member

standardBESA dipole fits now use FieldTrip's four-shell concentric-sphere leadfield, with the standard_BESA.mat radii and conductivities, and the DIPFIT grid and nonlinear fit. Component positions on the sample ICA dataset match the EEGLAB table in issue 600. MNI boundary-element fits still use the infinite-medium kernel.

MATLAB verification

Head 7c28dbb passed 9/9 in tests/test_dipfit_four_shell.py, including the FieldTrip/pop_multifit MATLAB parity test. The run used MATLAB R2025b, EEGLAB d0963be9, eeglab_tests fec88f9f, and matlabengine 25.2.2, and finished on 2026-11-17 at 22:49 PT in about 16 s.

Fixes #600

Open in Web Open in Cursor 

The previous kernel was an infinite homogeneous medium, so fitted
positions sat 20-40 mm closer to the origin than EEGLAB. standardBESA
now uses FieldTrip's concentric-sphere series, the DIPFIT 24x24x12
grid inside the brain shell, and fminsearch-style Nelder-Mead.

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

🤖 ## Problem

standardBESA fits used an infinite homogeneous leadfield, so dipoles were pulled toward the origin. On sample_data/eeglab_data_epochs_ica.set, components 1-3 differed from EEGLAB by 21.12, 23.56, and 42.44 mm.

Approach

Port the fieldtrip-20250523 concentric-sphere path under src/eegprep/plugins/dipfit/forward/ with the FieldTrip names: eeg_leadfield4, eeg_leadfield4_prepare, eeg_leadfield1, and the sphere branches of ft_compute_leadfield, ft_prepare_vol_sens, and ft_inside_headmodel. Radii are 71, 72, 79, 85 mm and conductivities are 0.33, 1, 0.0042, 0.33. Electrodes are projected onto the outer sphere. The grid is linspace(-85,85,24) by linspace(0,85,12), kept inside the 71 mm brain shell. Nonlinear refinement is Nelder-Mead with FieldTrip's fminsearch simplex and limits, symmetry is a mirror, and RV is the residual sum of squares over the data sum of squares. BEM types raise NotImplementedError from ft_compute_leadfield so the boundary-element port can add that branch. MNI/standardBEM settings still use the infinite-medium kernel.

Key code

  • src/eegprep/plugins/dipfit/forward/eeg_leadfield4.py
  • src/eegprep/plugins/dipfit/forward/ft_compute_leadfield.py
  • src/eegprep/plugins/dipfit/_fitting.py

Tests

Against the published EEGLAB positions, the 3-D distances are 0.000075 mm, 0.000041 mm, and 0.000019 mm, with residual variances 0.026193, 0.043325, and 0.003737. Equal-conductivity four-shell leadfields match the single-sphere closed form. The MATLAB comparison is deselected unless --eeglab-backend=matlab because MATLAB is not on this machine. The EEGLAB reference suite was not run.

From the repository root on the MATLAB machine:

matlab -batch "addpath('tools'); dipfit_standard_besa_parity('/path/to/eeglab')"

That writes a MAT file and runs tools/dipfit_standard_besa_parity.py, which prints the per-component distance and the leadfield max relative error. To run only the Python half after the MAT file exists:

.venv/bin/python tools/dipfit_standard_besa_parity.py /tmp/dipfit_standard_besa_reference.mat

FieldTrip leadfield and position parity:

uv run --no-sync pytest tests/test_dipfit_four_shell.py --eeglab-backend=matlab --eeglab-root=/path/to/eeglab

FieldTrip must be installed under that EEGLAB plugins directory (Fieldtrip* or fieldtrip* with ft_defaults.m). The reference keeps ICA components 1-3 and calls pop_multifit with threshold 100 and an empty coord_transform. pop_multifit grid-searches every component in the dataset; components 4-32 do not change these three fits.

@claude

claude Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review

  • Overall assessment: Needs changes. The four-shell port is tested well: there are checks against the single-sphere solution, a rotation-invariance check, 2-shell padding, electrode projection, the inside-shell boundary, a MATLAB FieldTrip leadfield comparison, and position parity with the table in DIPFIT standardBESA: eegprep and EEGLAB dipole positions differ by 21 to 42 mm #600. Two problems remain. The change also affects the MNI path, and the PR body is missing the reference-suite evidence AGENTS.md requires before merge.
  • Highest-risk area: _optimize_positions in src/eegprep/plugins/dipfit/_fitting.py. The guard that kept dipoles inside the head was removed for every head model, including the MNI/infinite-medium path.
  • Merge recommendation: Needs changes.

Blocking

  • Missing MATLAB reference-suite evidence (AGENTS.md §Testing). This PR changes core ported processing code: _fitting.py and the new forward/ FieldTrip ports. AGENTS.md says the author must "trigger .github/workflows/eeglab-reference.yml … or run the suite locally once on the final branch" and "put that run in the PR description: the exact command or workflow run, the EEGLAB and eeglab_tests commits, pass/fail/skip counts, runtime". The PR body does not have this. It also gives no evidence that test_fieldtrip_leadfields_and_pop_multifit_positions_match_eeglab ran against real MATLAB with FieldTrip.
    • Fix: Run the EEGLAB reference workflow on this branch, or run uv run --no-sync pytest tests --eeglab-backend=matlab ... locally, and paste the result into the PR description.

Important

  • The nonlinear fit can now leave the head on the MNI path (_fitting.py, objective in _optimize_positions, about L404). The old norm >= 0.995 * head_radius penalty is gone for every head model. That is right for standardBESA, because FieldTrip does not constrain the fit there and EEGLAB's component 3 sits at about 78.5 mm. But standardBEM/MNI still uses the unbounded _unit_moment_leadfield kernel, so a focal component can now drift onto an electrode, where only the 1e-3 mm clamp stops it.
    • Fix: Keep the penalty when forward.headmodel is None, and add an MNI pop_dipfit_nonlinear test to tests/test_dipfit_workflows.py.
  • The grid leadfield is rebuilt for every component (fit_component_grid, L207, called from the loop at L88). There are about 2,000 inside-shell candidates, each needing a 60-term Legendre series, and all of that is redone for each component. EEGLAB's dipfit_gridsearch makes one ft_dipolefitting call for all components, so it computes the grid once.
    • Fix: Compute leadfield_matrix(forward.positions, candidates, forward.headmodel) once in dipfit_gridsearch and pass it into fit_component_grid.

Nits

  • forward/__init__.py re-exports 9 names in a new __all__, but every caller imports from the full module path (forward.ft_compute_leadfield, etc.). AGENTS.md lists "__all__ churn in __init__.py without a real API need" as a pattern to avoid. Leaving only the docstring would be enough.
  • _electrode_positions is written twice, in ft_compute_leadfield.py and in ft_prepare_vol_sens.py, and the two versions behave slightly differently: only one has a clear missing-elecpos/chanpos error. Keep one and import it in the other module.
  • The first four lines of test_standard_besa_grid_matches_the_dipfit_scan check size == 24 and the endpoints, which only restates the constants in default_scan_axes. AGENTS.md says not to write tests that "only assert types, constants". The pop_multifit parity test already exercises the grid, so these assertions can go.

Test gaps

  • No test covers MNI/standardBEM nonlinear refinement after the optimizer change (see Important).
  • tests/test_dipfit_four_shell.py::test_pop_multifit_standard_besa_positions_match_the_published_eeglab_table runs the full grid plus nonlinear fit on 3 components in the default suite. If it is slow, add it to the slow map in tests/conftest.py, as AGENTS.md asks for "obvious slow" coverage.

EEGLAB parity notes

  • The bilateral starting positions now overwrite the y axis (or x for MNI) with [-40, 40], which matches what pop_multifit.m does for 'dipoles', 2.
  • diffmap = Vmodel - Vdata matches dipfit_nonlinear.m.
  • The fminsearch-style simplex and TolFun/TolX = 1e-4 match the FieldTrip dipole_fit defaults.
  • The deviation for standardBEM is documented in eeglab_migration.rst.
  • I could not check default_scan_axes (24/24/12, floor(85)) or the new maxiter=3000 against dipfitdefs.m/dipole_fit.m, because neither file is vendored in this checkout. The MATLAB reference run above will confirm them.

I could not run the test suite or any local timing script in this sandbox (permission denied), so the performance point comes from reading the code, not from a measurement.

@@ -341,26 +402,59 @@ def unpack(values: np.ndarray) -> np.ndarray:
return values.reshape(initial_positions.shape)

def objective(values: np.ndarray) -> float:

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 (regression, MNI path): This removes the old norm >= 0.995 * head_radius penalty for every head model, not only for standardBESA. For the four-shell model that matches FieldTrip, since EEGLAB's component 3 ends up at about 78.5 mm, outside the 71 mm brain shell. The MNI/standardBEM path still uses _unit_moment_leadfield, though, and that is an infinite-medium kernel with nothing bounding it. Nelder-Mead can now push a dipole out through the 85 mm electrode sphere and onto an electrode, where the only limit is MIN_DIPOLE_ELECTRODE_DISTANCE_MM = 1e-3. A focal component would collapse onto a single electrode and still get a low RV. Before this PR the optimizer could not do that, and no test covers MNI nonlinear refinement after this change.

Suggested fix: keep the guard when forward.headmodel is None, for example:

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

Then add an MNI pop_dipfit_nonlinear case to tests/test_dipfit_workflows.py that asserts the refined dipole stays inside head_radius.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🤖 The outside-head penalty is back when forward.headmodel is None, so the infinite-medium MNI path cannot cross 0.995 of the head radius. standardBESA still has no barrier, which is what lets component 3 sit near 78.5 mm. test_mni_nonlinear_fit_stays_inside_the_head starts from a focal map that previously finished at 85.001 mm and now stays inside the head.

Comment thread src/eegprep/plugins/dipfit/_fitting.py Outdated
best_rv = fit["rv"]
if best is None:
topography = _average_reference(_component_topography(forward, component))
fields = leadfield_matrix(forward.positions, candidates, 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): fit_component_grid is called once per component from the loop at L88, and every call rebuilds the leadfield for all candidates. The new default grid is 24×24×12 = 6912 points, and about 2,000 of them fall inside the 71 mm shell. Each point now evaluates a 60-term Legendre series (eeg_leadfield4) instead of a closed-form kernel, so on a 64-component dataset the same grid leadfield is computed 64 times. EEGLAB's dipfit_gridsearch sends all components through a single ft_dipolefitting call, so the grid leadfield is computed once.

Suggested fix: in dipfit_gridsearch, compute fields = leadfield_matrix(forward.positions, candidates, forward.headmodel) once before the component loop and pass it into fit_component_grid.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🤖 dipfit_gridsearch now builds the candidate leadfield once and passes that matrix into fit_component_grid, so a multi-component scan does not repeat the series.

cursoragent and others added 2 commits November 11, 2026 21:35
The infinite-medium kernel has no skull boundary, so nonlinear search
still stops at 0.995 of the head radius. standardBESA stays unbounded,
matching FieldTrip. The scan leadfield is built once per grid.

Co-authored-by: Suraj Ranganath <[email protected]>
Callers import FieldTrip helpers by module path, so the package __all__
was unused. Both leadfield paths now use the same sensor-position check,
and the grid test no longer restates the scan-axis constants.

Co-authored-by: Suraj Ranganath <[email protected]>
@suraj-ranganath
suraj-ranganath marked this pull request as draft November 11, 2026 21:38
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 11, 2026 21:38
@claude

claude Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review

  • Overall assessment: Needs changes, but only for the missing evidence. The four-shell port looks correct as written. The earlier review findings are fixed: the MNI outside-head penalty is back, the grid leadfield is built once per scan, the forward/__init__.py __all__ is gone, and _electrode_positions is shared.
  • Highest-risk area: _optimize_positions / fit_component_grid in src/eegprep/plugins/dipfit/_fitting.py. They change standardBESA positions and RV numerically, and nothing has been run against MATLAB yet.
  • Merge recommendation: Needs changes.

Blocking

  • There is still no MATLAB reference evidence for a core-numerics PR (AGENTS.md §Testing). The author's comment says "The EEGLAB reference suite was not run", and test_fieldtrip_leadfields_and_pop_multifit_positions_match_eeglab has never run against real FieldTrip. The only parity evidence is the published table in DIPFIT standardBESA: eegprep and EEGLAB dipole positions differ by 21 to 42 mm #600. That covers positions only, at a 1 mm tolerance, and does not check the leadfield or RV. This matters most here because several values cannot be checked from this checkout, since dipfitdefs.m, dipole_fit.m, and eeg_leadfield4.m are not vendored:
    • the series order of 60
    • maxiter=3000 with maxfev = 2*maxiter*n
    • floor(85) with a 24/24/12 grid
    • the lpmv Condon–Shortley sign convention
    • Fix: Run .github/workflows/eeglab-reference.yml on this branch, or run uv run --no-sync pytest tests --eeglab-backend=matlab --eeglab-root=… --eeglab-suite-root=… with FieldTrip under plugins/. Paste the command, the EEGLAB and eeglab_tests commits, the pass/fail/skip counts, the runtime, and the result of the new FieldTrip leadfield test into the PR description. A human needs to approve before merge.

Important

None.

Nits

  • tests/test_dipfit_four_shell.py::test_standard_besa_grid_matches_the_dipfit_scan now asserts only posxyz.shape == (1, 3). That is a shape-only test, which AGENTS.md §Testing rules out, and the pop_multifit parity test already covers the default grid. Delete it, or assert a known EEGLAB grid-search position. (Inline comment posted.)

Test gaps

None. MNI nonlinear refinement is now covered by test_mni_nonlinear_fit_stays_inside_the_head.

EEGLAB parity notes

  • _make_bilateral_starting_models now sets the [-40, 40] starting positions on y (spherical) or x (MNI), which matches what pop_multifit does for two dipoles.
  • remove_outside_head still uses 85 mm (the scalp), while the grid only keeps points inside the 71 mm brain shell (ft_inside_headmodel). This is consistent with EEGLAB keeping fitted dipoles between brain and scalp, like component 3 at about 78.5 mm.
  • The MNI/standardBEM path still uses the infinite-medium kernel. This is documented as a known difference in eeglab_migration.rst.

Checks covered: correctness of the four-shell series, shell padding, origin shift and average reference, ft_inside_headmodel boundary strictness, grid ordering (ravel(order="F")), the RV and diffmap sign, the MNI optimizer guard, docs and help updates, and AGENTS.md compliance. I could not run pytest in this sandbox (permission denied), so I couldn't time the default-suite pop_multifit test or confirm whether it needs a slow entry in tests/conftest.py.

Comment thread tests/test_dipfit_four_shell.py Outdated
Comment on lines +140 to +144
def test_standard_besa_grid_matches_the_dipfit_scan():
x_values, y_values, z_values = default_scan_axes(85.0)
dataset = pop_dipfit_settings(pop_loadset(SAMPLE_EPOCHS), model="standardBESA")
scanned = dipfit_gridsearch(dataset, component=[1], xgrid=x_values, ygrid=y_values, zgrid=z_values)
assert np.asarray(scanned["dipfit"]["model"][0]["posxyz"]).shape == (1, 3)

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 (test value): When the constant checks were removed, this test was left asserting only that posxyz has shape (1, 3). Any grid search that returns a single dipole passes, so it no longer checks that the scan "matches the dipfit scan". That is a shape-only test, which AGENTS.md §Testing rules out: "Do not write tautological tests that only assert types, constants, or implementation details." The pop_multifit parity test below already runs this grid, with the default axes, against the EEGLAB positions.

Suggested fix: delete the test. If grid-only coverage is worth keeping, assert the grid-search position for component 1 against a known EEGLAB dipfit_gridsearch result, which needs the MATLAB reference values.

def test_standard_besa_grid_matches_the_dipfit_scan():
x_values, y_values, z_values = default_scan_axes(85.0)
dataset = pop_dipfit_settings(pop_loadset(SAMPLE_EPOCHS), model="standardBESA")
scanned = dipfit_gridsearch(dataset, component=[1], xgrid=x_values, ygrid=y_values, zgrid=z_values)
assert np.asarray(scanned["dipfit"]["model"][0]["posxyz"]).shape == (1, 3)

The scan is already checked by the pop_multifit position comparison.
A shape assertion on posxyz did not test the grid.

Co-authored-by: Suraj Ranganath <[email protected]>
@suraj-ranganath
suraj-ranganath marked this pull request as draft November 11, 2026 21:41
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 11, 2026 21:41
@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: The code looks correct. One blocker remains, and it is process, not code: there is still no MATLAB evidence for this core-numerics change. The fix in 601832a removes the shape-only grid test from the last review, and I found no new correctness problems.
  • Highest-risk area: The standardBESA numbers in src/eegprep/plugins/dipfit/_fitting.py (fit_component_grid, _optimize_positions, RV and diffmap) and the series in forward/eeg_leadfield4.py. None of it has been run against FieldTrip.
  • Merge recommendation: Needs changes.

Blocking

  • There is still no MATLAB reference evidence (AGENTS.md §Testing: "Put that run in the PR description: the exact command or workflow run, the EEGLAB and eeglab_tests commits, pass/fail/skip counts, runtime"). The PR body has not changed, and the author's comment says "The EEGLAB reference suite was not run." So test_fieldtrip_leadfields_and_pop_multifit_positions_match_eeglab has never run, and that test is the only check on:
    • the 60-term series
    • the lpmv sign convention
    • maxiter=3000 with maxfev = 2*maxiter*n
    • the 24/24/12 floor(85) grid
    • Fix: Run .github/workflows/eeglab-reference.yml on cursor/dipfit-four-shell-882a, or run uv run --no-sync pytest tests --eeglab-backend=matlab --eeglab-root=… --eeglab-suite-root=… locally with FieldTrip under plugins/. Paste the result into the PR body. A human must approve before merge.

Important

None.

Nits

None.

Test gaps

  • The MATLAB parity test ignores fitrv (tests/test_dipfit_four_shell.py:175). The MATLAB helper returns it, but the test only compares positions, at 1 mm, even though this PR changes the RV and diffmap semantics. Add an RV assertion; the inline comment has a suggested snippet.

EEGLAB parity notes

  • The FieldTrip ports match on these points:
    • ft_compute_leadfield shifts to the sphere origin, pads 2 or 3 shells out to 4, and average-references when there is no tra.
    • ft_prepare_vol_sens projects electrodes onto the outer sphere.
    • ft_inside_headmodel keeps only points strictly inside the 71 mm shell.
  • _make_bilateral_starting_models sets [-40, 40] on x for MNI and on y otherwise, as pop_multifit.m does.
  • The fminsearch initial simplex (5% step, or 0.00025 for zero entries) and the non-adaptive Nelder–Mead match MATLAB.
  • diffmap = Vmodel - Vdata matches dipfit_nonlinear.m.
  • The MNI infinite-medium path keeps the outside-head guard, and test_mni_nonlinear_fit_stays_inside_the_head covers it. Keeping that path is a documented difference in eeglab_migration.rst.
  • I checked the published-table test and the MATLAB helper against the Python defaults: both use an empty coord_transform and components 1–3, so they test the same setup.

The sandbox denied permission to run pytest, so I could not time test_pop_multifit_standard_besa_positions_match_the_published_eeglab_table. If it takes more than a few seconds, add it to the slow map in tests/conftest.py.

fitted = pop_multifit(dataset, [1, 2, 3], "threshold", 100, "dipplot", "off")
positions = np.vstack([np.asarray(fitted["dipfit"]["model"][index]["posxyz"], dtype=float) for index in range(3)])
distances = np.linalg.norm(positions - matlab_positions.reshape(3, 3), axis=1)
assert np.all(distances < POSITION_TOLERANCE_MM), f"3-D distances mm={distances.tolist()}"

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.

Test gap: dipfit_standard_besa_reference.m returns fitrv (L48-L60), but this test never reads it. This PR changes how RV is computed: the residual is now Vmodel - Vdata, the grid uses an average reference, and the nonlinear fit uses the fminsearch tolerance TolFun = 1e-4. Right now the only RV evidence is the numbers in the author's comment. A 1 mm position match can hide an RV mismatch, for example from a different rv normalization or an average-reference mistake, and rv is the value dipfit_reject and the threshold option act on.

Suggested fix: after the position check, compare RV too:

python_rv = np.array([float(fitted["dipfit"]["model"][index]["rv"]) for index in range(3)])
np.testing.assert_allclose(python_rv, np.asarray(reference["fitrv"], dtype=float).ravel(), atol=1e-3)

The reference helper already returns fitrv. The position check alone
can pass when the residual used by threshold and dipfit_reject differs.

Co-authored-by: Suraj Ranganath <[email protected]>
@suraj-ranganath
suraj-ranganath marked this pull request as draft November 11, 2026 21:44
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 11, 2026 21:44
@claude

claude Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review

  • Overall assessment: The code looks correct. The last open test gap is fixed: a6eb97f adds the fitrv comparison to the MATLAB parity test. One blocker remains, and it is process, not code: there is still no MATLAB reference evidence for this core-numerics change.
  • Highest-risk area: the standardBESA numerics, which have never been run against FieldTrip. These are fit_component_grid and _optimize_positions in src/eegprep/plugins/dipfit/_fitting.py, and the 60-term series in forward/eeg_leadfield4.py.
  • Merge recommendation: Needs changes.

Blocking

  • There is still no MATLAB reference evidence in the PR body (AGENTS.md §Testing). AGENTS.md says to "Put that run in the PR description: the exact command or workflow run, the EEGLAB and eeglab_tests commits, pass/fail/skip counts, runtime". The PR body has not changed, and the author's comment says "The EEGLAB reference suite was not run."
    • test_fieldtrip_leadfields_and_pop_multifit_positions_match_eeglab is the only check on the leadfield, the lpmv sign convention, maxiter=3000 with maxfev = 2*maxiter*n, the 24/24/12 floor(85) grid, and now RV. It has never run.
    • Fix: Run .github/workflows/eeglab-reference.yml on cursor/dipfit-four-shell-882a. Alternatively, run uv run --no-sync pytest tests --eeglab-backend=matlab --eeglab-root=… --eeglab-suite-root=… locally with FieldTrip under plugins/. Paste the result into the PR body, and include the outcome of the new FieldTrip test. A human must approve before merge.

Important

None.

Nits

  • The RV tolerance is too loose for small RVs (tests/test_dipfit_four_shell.py:177, inline comment posted). atol=1e-3 allows about 27% relative error on component 3 (RV ≈ 0.0037).
    • Fix: Use rtol=1e-2, atol=1e-5.

Test gaps

None.

EEGLAB parity notes

  • dipfit_standard_besa_reference.m reads fitrv from EEG.dipfit.model(index).rv after pop_multifit. That is the same field the Python test compares, and both use an empty coord_transform and components 1–3.
  • My earlier parity notes still apply:
    • ft_compute_leadfield handles the origin shift, shell padding, and average reference.
    • ft_prepare_vol_sens projects electrodes onto the outer sphere.
    • ft_inside_headmodel uses a strict 71 mm brain-shell test.
    • The fminsearch simplex is replicated.
    • diffmap = Vmodel - Vdata matches dipfit_nonlinear.m.
    • The MNI path keeps its outside-head guard. It still uses the infinite-medium kernel, which is documented in eeglab_migration.rst.

Checked since the previous review: a6eb97f, the MATLAB helper's RV output, and the PR head (a6eb97f matches the checkout). I could not query earlier eeglab-reference.yml runs from this sandbox because the command was denied permission.

Comment thread tests/test_dipfit_four_shell.py Outdated
distances = np.linalg.norm(positions - matlab_positions.reshape(3, 3), axis=1)
assert np.all(distances < POSITION_TOLERANCE_MM), f"3-D distances mm={distances.tolist()}"
python_rv = np.array([float(fitted["dipfit"]["model"][index]["rv"]) for index in range(3)])
np.testing.assert_allclose(python_rv, np.asarray(reference["fitrv"], dtype=float).ravel(), atol=1e-3)

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 (tolerance too loose for small RVs): atol=1e-3 is a reasonable bound for component 1 (RV ≈ 0.026). For component 3 (RV ≈ 0.0037, from the author's comment) it allows about 27% relative error. So this assertion can miss the kind of RV normalization or average-reference mismatch it was added to catch, at least on the best-fitting component. Positions already agree to about 1e-4 mm, so RV should agree to well under 1% relative.

Suggested change
np.testing.assert_allclose(python_rv, np.asarray(reference["fitrv"], dtype=float).ravel(), atol=1e-3)
np.testing.assert_allclose(python_rv, np.asarray(reference["fitrv"], dtype=float).ravel(), rtol=1e-2, atol=1e-5)

assert np.all(distances < POSITION_TOLERANCE_MM), f"3-D distances mm={distances.tolist()}"
python_rv = np.array([float(fitted["dipfit"]["model"][index]["rv"]) for index in range(3)])
np.testing.assert_allclose(python_rv, np.asarray(reference["fitrv"], dtype=float).ravel(), atol=1e-3)

An absolute tolerance of 1e-3 allows a large relative error on the
small residual of component 3. Require 1% relative agreement.

Co-authored-by: Suraj Ranganath <[email protected]>
@suraj-ranganath
suraj-ranganath marked this pull request as draft November 11, 2026 21:47
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 11, 2026 21:47
@claude

claude Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review

  • Overall assessment: The code looks correct. The latest commit, 433a7a9, makes the change suggested in the last review: the RV check now uses rtol=1e-2, atol=1e-5, so a mismatch on component 3 (RV ≈ 0.0037) will fail the test. That was the only change since the previous review. One blocker is left, and it is a process requirement, not a code problem.
  • Highest-risk area: The standardBESA numerics have not been run against FieldTrip. That covers the 60-term series in forward/eeg_leadfield4.py and fit_component_grid / _optimize_positions in src/eegprep/plugins/dipfit/_fitting.py.
  • Merge recommendation: Needs changes.

Blocking

  • The PR body still has no MATLAB reference evidence (AGENTS.md §Testing: "Put that run in the PR description: the exact command or workflow run, the EEGLAB and eeglab_tests commits, pass/fail/skip counts, runtime"). The body is still the short summary, and the author's earlier comment says "The EEGLAB reference suite was not run."
    • Why it matters: test_fieldtrip_leadfields_and_pop_multifit_positions_match_eeglab has never run. It is the only check on these points:
      • the leadfield
      • the lpmv sign convention
      • maxiter=3000 with maxfev = 2*maxiter*n
      • the 24/24/12 floor(85) grid
      • RV
    • Fix:
      1. Run .github/workflows/eeglab-reference.yml on cursor/dipfit-four-shell-882a. Alternatively, run uv run --no-sync pytest tests --eeglab-backend=matlab --eeglab-root=… --eeglab-suite-root=… locally with FieldTrip under plugins/.
      2. Paste the result into the PR body, including the outcome of the new FieldTrip test.
      3. A human must approve before merge.

Important

None.

Nits

None.

Test gaps

None.

EEGLAB parity notes

None new. My earlier notes still apply:

  • ft_compute_leadfield shifts to the sphere origin, pads shells, and applies the average reference.
  • Electrodes are projected onto the outer sphere.
  • ft_inside_headmodel tests strictly against the 71 mm shell.
  • The fminsearch simplex is replicated.
  • diffmap = Vmodel - Vdata matches dipfit_nonlinear.m.
  • The MNI path keeps its outside-head guard and its infinite-medium kernel. That kernel is a known difference documented in eeglab_migration.rst.

Checked

  • The head commit matches the checkout (433a7a9).
  • The diff since the previous review.
  • The current PR body.

The sandbox denied gh run list, so I could not check whether an eeglab-reference.yml run already exists for this branch. If one passed, linking it in the PR body clears the blocker.

The RV comparison was wrapped in a way ruff format rejects.

Co-authored-by: Suraj Ranganath <[email protected]>
pop_multifit calls eeg_checkset, which reads EEG.icaact. An empty
field makes checkset recompute activations for the three kept components.

Co-authored-by: Suraj Ranganath <[email protected]>
@suraj-ranganath
suraj-ranganath marked this pull request as draft November 18, 2026 06:51
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 18, 2026 06:51

@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 39s —— View job


Code review

  • Overall assessment: The code looks correct. Since the last review there are two new commits. ff47be2 only reformats the code for ruff. 7c28dbb changes the MATLAB reference to set EEG.icaact = [] instead of calling rmfield, so eeg_checkset inside pop_multifit now recomputes activations for the 3 kept components instead of failing on the missing field. That fix is correct, and it suggests someone has started running the MATLAB path. One blocker is still open, and it is about process, not code.
  • Highest-risk area: The standardBESA numbers have not yet been checked against FieldTrip. This covers the 60-term series in forward/eeg_leadfield4.py and fit_component_grid / _optimize_positions in src/eegprep/plugins/dipfit/_fitting.py.
  • Merge recommendation: Needs changes.

Blocking

  • The PR body still has no MATLAB reference evidence. AGENTS.md §Testing says: "Put that run in the PR description: the exact command or workflow run, the EEGLAB and eeglab_tests commits, pass/fail/skip counts, runtime, and an explanation for any failures or skips." The body is still the short summary. This PR is now ready for review, so a human needs this evidence before approving.
    • Why it matters: test_fieldtrip_leadfields_and_pop_multifit_positions_match_eeglab is the only check on the leadfield, the lpmv sign convention, maxiter=3000 with maxfev = 2*maxiter*n, the 24/24/12 floor(85) grid, and RV.
    • Fix: If 7c28dbb came from a local MATLAB run, rerun it on this head (7c28dbb) and paste the command, the EEGLAB and FieldTrip/eeglab_tests commits, the counts, the runtime, and the result of the new FieldTrip test into the PR body. Otherwise, run .github/workflows/eeglab-reference.yml on cursor/dipfit-four-shell-882a and link the run.

Important

None.

Nits

None.

Test gaps

None.

EEGLAB parity notes

  • The MATLAB reference fits with only ICA components 1–3, while the Python side runs pop_multifit on all 32 components. The helper says components 4 and later do not change the fits of 1–3. That holds for a fit that runs component by component, and it means the parity test checks this claim implicitly. If the claim were false, the test would fail; it would not hide the difference.
  • My earlier notes still apply:
    • The origin shift, shell padding and average reference in ft_compute_leadfield match FieldTrip.
    • Electrodes are projected onto the outer sphere.
    • ft_inside_headmodel tests strictly against the 71 mm shell.
    • The fminsearch simplex is replicated.
    • diffmap = Vmodel - Vdata matches dipfit_nonlinear.m.
    • The MNI path keeps its outside-head guard. It still uses the infinite-medium kernel, which eeglab_migration.rst documents as a known difference.

The head commit matches the checkout (7c28dbb). The sandbox would not let me run gh run list, so I could not check for an existing eeglab-reference.yml run. If one has passed, linking it in the PR body clears the blocker.

@suraj-ranganath
suraj-ranganath merged commit bf35e2d into develop Nov 18, 2026
16 checks passed
cursor Bot pushed a commit that referenced this pull request Nov 18, 2026
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]>
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 standardBESA: eegprep and EEGLAB dipole positions differ by 21 to 42 mm

2 participants