Repository navigation
Fit standardBESA dipoles with the four-shell BESA leadfield - #611
Conversation
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]>
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.
|
🤖 ## Problem
ApproachPort the fieldtrip-20250523 concentric-sphere path under Key code
TestsAgainst 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 From the repository root on the MATLAB machine: That writes a MAT file and runs FieldTrip leadfield and position parity: FieldTrip must be installed under that EEGLAB |
|
Claude finished @suraj-ranganath's task in 2m 37s —— View job Code review
Blocking
Important
Nits
Test gaps
EEGLAB parity notes
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: | |||
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
🤖 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.
| best_rv = fit["rv"] | ||
| if best is None: | ||
| topography = _average_reference(_component_topography(forward, component)) | ||
| fields = leadfield_matrix(forward.positions, candidates, forward.headmodel) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
🤖 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.
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]>
|
Claude finished @suraj-ranganath's task in 1m 44s —— View job Code review
Blocking
ImportantNone. Nits
Test gapsNone. MNI nonlinear refinement is now covered by EEGLAB parity notes
Checks covered: correctness of the four-shell series, shell padding, origin shift and average reference, |
| 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) |
There was a problem hiding this comment.
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.
eegprep/tests/test_dipfit_four_shell.py
Lines 139 to 145 in 3416193
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]>
|
Claude finished @suraj-ranganath's task in 1m 19s —— View job Code review
Blocking
ImportantNone. NitsNone. Test gaps
EEGLAB parity notes
The sandbox denied permission to run pytest, so I could not time |
| 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()}" |
There was a problem hiding this comment.
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]>
|
Claude finished @suraj-ranganath's task in 45s —— View job Code review
Blocking
ImportantNone. Nits
Test gapsNone. EEGLAB parity notes
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 |
| 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) |
There was a problem hiding this comment.
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.
| 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) |
eegprep/tests/test_dipfit_four_shell.py
Lines 175 to 177 in a6eb97f
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]>
|
Claude finished @suraj-ranganath's task in 27s —— View job Code review
Blocking
ImportantNone. NitsNone. Test gapsNone. EEGLAB parity notesNone new. My earlier notes still apply:
Checked
The sandbox denied |
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]>
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 39s —— View job Code review
Blocking
ImportantNone. NitsNone. Test gapsNone. EEGLAB parity notes
The head commit matches the checkout (7c28dbb). The sandbox would not let me run |
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]>
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