Skip to content

[DIPFIT] Match FieldTrip fminunc dipole fits on BESA and MNI - #666

Merged
suraj-ranganath merged 19 commits into
developfrom
cursor/dipfit-660
Nov 22, 2026
Merged

suraj-ranganath merged 19 commits into
developfrom
cursor/dipfit-660

Conversation

@suraj-ranganath

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

Copy link
Copy Markdown
Member

Fixes #660

Equivalent-dipole fitting keeps FieldTrip's TypicalX of 10 mm and the scaled BFGS update. Jamming at c955d6d matched the BEM single-dipole fits except the ill-conditioned component 21. Suraj approved one test change: every other component keeps its position check, and standardBEM component 21 passes when eegprep's residual variance is no higher than MATLAB's within atol 1e-8 and rtol 1e-6. MATLAB reaches residual variances 0.162062, 0.183774, and 0.181845 under 1e-12 start perturbations, and eegprep reaches the same three within 1e-4 mm. Suraj approved the same residual-variance check for standardBEM symmetric component 1. MATLAB's own positions for that fit move by up to 0.025 mm under 1e-12 perturbations, and eegprep stays within 0.0015 mm of the nearest perturbed MATLAB run. Every other symmetric component, and BESA, keep the position check. The bracket end a is the last step that met sufficient decrease. Sectioning clips the next trial to 10% from a and 50% from b. A nonnegative slope during bracketing swaps the ends before sectioning. Sectioning returns that clipped step without evaluating it when (a-c)phi'(a) is at most eps(max(1,|f|)), and keeps the value and gradient from the last evaluated trial. coregister still accepts .elc and .elp templates and uses the FieldTrip traditional warp, including the degree-to-radian conversion and the yaw/pitch sign check. eeg_checkset rebuilds an empty icawinv with pinv(icaweightsicasphere).

Dipole fitting and the electrode warp share one fminunc. Both stop when ||g||_inf < TolFun*(1+||g0||_inf) and both use the forward difference sqrt(eps)sign'(x)max(|x|, TypicalX). Dipole fits pass TypicalX 10 and MaxFunEvals 2MaxItern from ft_inverse_dipolefit.m. The warp passes TolFun 1e-4 and MaxIter 1500 from ft_warp_optim.m, and leaves TypicalX and MaxFunEvals at the fminunc defaults of ones and 100*n. Neither path replaces the search direction with steepest descent. The synthetic traditional warp is compared to MATLAB ft_warp_optim parameters and fitted points at the existing coregister allowance, atol 1e-3 and rtol 1e-4. The non-MATLAB check only requires a tenfold drop in mean distance and that the rigid-body stage stops on TolFun or TolX. The traditional stage on Linux still uses all 900 evaluations.

Sign-off: residual variance is assert_allclose(atol=1e-8, rtol=1e-6). Suraj approved that pair from the measured gaps outside the two ill-conditioned components, 1.2e-9 absolute and 9.3e-8 relative. The same allowance applies to the one-sided checks for standardBEM component 21 and standardBEM symmetric component 1. Position limits were not changed.

Suraj approved replacing the documented #610 difference with a match to EEGLAB, on the condition that all 32 components match.

MATLAB tests for jamming. The three component tests need --run-heavy-reference.

uv run pytest tests/test_dipfit_component_parity.py tests/test_dipfit_loreta_key.py tests/test_dipfit_bem.py::test_bem_leadfield_and_multifit_match_fieldtrip tests/test_dipfit_four_shell.py::test_fieldtrip_leadfields_and_pop_multifit_positions_match_eeglab tests/test_coregister_parity.py --eeglab-backend=matlab --eeglab-root= --run-heavy-reference -m matlab

tests/test_dipfit_component_parity.py::test_inside_brain_grid_counts_match_eeglab
tests/test_dipfit_component_parity.py::test_single_dipole_fits_match_eeglab
tests/test_dipfit_component_parity.py::test_symmetric_two_dipole_fits_match_eeglab
tests/test_dipfit_loreta_key.py::test_loreta_key_leadfield_matches_fieldtrip_for_the_selected_head_model
tests/test_dipfit_bem.py::test_bem_leadfield_and_multifit_match_fieldtrip
tests/test_dipfit_four_shell.py::test_fieldtrip_leadfields_and_pop_multifit_positions_match_eeglab
tests/test_coregister_parity.py::test_coregister_traditional_warp_matches_eeglab
tests/test_coregister_parity.py::test_synthetic_traditional_warp_matches_fieldtrip
tests/test_coregister_parity.py::test_empty_icawinv_matches_eeglab

MATLAB reference evidence. Jamming ran the suite on 55da31e. 9ec714b differs only by a deleted comment.
Full suite: pytest --eeglab-backend=matlab --eeglab-root= --eeglab-suite-root=<eeglab_tests> -p no:cacheprovider, with the repo default addopts and no --run-heavy-reference. MATLAB R2025b on jamming. EEGLAB d0963be9d81acc5b66e84f8d3d7c89e3ce127cc4. eeglab_tests fec88f9ffe7c225eb1de8924db8b6a3e0d53a4d9. 4255 passed, 5 failed, 62 skipped, 51m37s. The five failures are unrelated to this PR. Three need data absent on that host: test_openneuro_edf_import_matches_matlab_pop_importbids ds003194, and test_bids_preproc test_end2end and test_crashability_slow wt/data. Two also fail on develop 6883cdc: test_struct_near_assertion_matches_source and test_matlab_kmeans_numbering_matches_fixed_initial_centroids.
DIPFIT parity command: 9 passed, 1 deselected. Targeted dipfit, checkset, pop_editset, study dipplot, phase4 plot wrappers, miscfunc, and coregister: 202 passed.
Coregister against FieldTrip ft_warp_optim at atol 1e-3 and rtol 1e-4: synthetic parameters max abs gap 8.1e-6, points 6.8e-7, sample .elc 1.7e-5, .elp 0.
Stopping: fminunc stop tests match MATLAB fminusub testStop (gradient TolFun*(1+||g0||inf), relative step norm(dx./(1+|x|),inf) < TolX, line-search failure, budget). On the synthetic warp MATLAB's rescale and traditional stages stop on step size at 672 and 840 evaluations. eegprep reaches the budget because rigid-body stops on the loose TolFun 1e-4 gradient test 5.2e-5 from MATLAB's point and roundoff drift grows from there. Started from MATLAB's stage points, eegprep stops on step size at 672 and 820. Final fits agree within the coregister allowance.

Open in Web Open in Cursor 

arnodelorme and others added 14 commits November 19, 2026 10:13
pop_leadfield stores explicit points and the 20 mm LORETA-KEY grid
through ft_dipolefitting. pop_dipfit_loreta checks that leadfield and
reports that eLORETA is not bundled. MATLAB-marked tests cover the
sample ICA components, symmetric pairs, and inside-brain grid counts.

Co-authored-by: Suraj Ranganath <[email protected]>
The standard BESA comparison script still imported the removed forward
package, which made ty fail.

Co-authored-by: Suraj Ranganath <[email protected]>
Use the forward-difference step and relative TolFun/TolX stops that land
on the R2025b dipole, accept .elc/.elp templates through the FieldTrip
warp, and rebuild an empty icawinv from icaweights*icasphere.

Co-authored-by: Suraj Ranganath <[email protected]>
The unscaled sqrt(eps) step moved MNI components 21 and 31 by about 11 mm
and slowed the fits. Dipole fminunc again uses sqrt(eps)*sign'(x)*max(|x|, 10 mm),
scales the identity Hessian on the first accepted step, and stops on the
relative gradient and step tests. A cubic trial that is worse than its
bracket keeps the lowest value already evaluated. The traditional warp
keeps the solver that matched EEGLAB coregistration.

Co-authored-by: Suraj Ranganath <[email protected]>
Sectioning keeps the next trial 10% off the better endpoint and 50% off
the other. A nonnegative slope stores that trial as the better end and
the previous step as the other. The search ends when the alpha bracket
is within TolX and returns the latest trial. Finite differences reuse
the function value already computed at the point.

Co-authored-by: Suraj Ranganath <[email protected]>
The trial stays 10% from that step and 50% from the other end. A
nonnegative bracketing slope swaps the ends first. Sectioning returns
the clipped step without evaluating it once (a-c)*phi'(a) is within
eps of the function value, and keeps the last evaluated value.

Co-authored-by: Suraj Ranganath <[email protected]>
eeg_checkset fills an empty icawinv from icaweights and icasphere.
The editset assignment test still expected that field to stay empty.

Co-authored-by: Suraj Ranganath <[email protected]>
The sample-data BEM fit is ill-conditioned. MATLAB reaches several
minima under a 1e-12 start perturbation, so that component passes when
eegprep's residual variance is within the existing tolerance of MATLAB's
or lower. Every other single-dipole position check stays exact.

Co-authored-by: Suraj Ranganath <[email protected]>
MATLAB's own positions for that fit move by more than the position
limit under a 1e-12 perturbation. The component passes when eegprep's
residual variance is within the existing tolerance of MATLAB's or
lower. The other symmetric components and BESA keep the position check.

Co-authored-by: Suraj Ranganath <[email protected]>
Suraj approved atol 1e-8 and rtol 1e-6 from the measured gaps outside
the two ill-conditioned components. The same allowance covers the
one-sided checks for BEM component 21 and BEM symmetric component 1.

Co-authored-by: Suraj Ranganath <[email protected]>
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 22, 2026 07:00

@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 22, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @suraj-ranganath's task in 3m 28s —— View job


Code review

  • Overall assessment: The approach holds up. I found no correctness bugs in the new FieldTrip-style solver (ft_dipolefitting.py), the eeg_checkset change that rebuilds icawinv, or the coregister warp path. The remaining problems are process and maintainability gaps that AGENTS.md requires to be closed before merge.
  • Highest-risk area: the optimizer in ft_dipolefitting.py, which has two diverging BFGS loops, plus a test tolerance that was loosened.
  • Merge recommendation: Needs changes.

Blocking

None.

Important

  1. The PR description doesn't include the required MATLAB reference evidence. This PR changes core ported functions: eeg_checkset.py, sigprocfunc/coregister.py, and the whole DIPFIT solver. AGENTS.md §Testing asks for one .github/workflows/eeglab-reference.yml run (or a local --eeglab-backend=matlab run of the full suite) on the final branch, and the description has to list:

    • the exact command or workflow run
    • the EEGLAB and eeglab_tests commits
    • pass/fail/skip counts
    • the runtime

    The description currently lists only a targeted 8-test command, with no commits, counts or runtime. Please trigger the reference workflow on cursor/dipfit-660 and paste those results.

  2. Duplicate fminunc implementations (ft_dipolefitting.py: _fminunc L571 and _fminunc_coregister L620). They share _line_search but differ in four ways:

    • the gradient stop (1+‖g0‖ vs max(1,‖g0‖))
    • the steepest-descent reset
    • the MaxFunEvals budget
    • the finite-difference step

    Some of these may be intentional (TypicalX). The rest look accidental, and a fix to one loop will miss the other. The core sigprocfunc/coregister.py also now depends on this private plugin helper. Fold them into one loop with explicit typical_x, tol_fun, tol_x and max_fun_evals parameters. Details are in the inline comment.

  3. Loosened tolerance in tests/test_phase4_plot_wrappers.py:355. atol goes from 1e-6 to 5e-3 with no reason given. AGENTS.md forbids relaxing tolerances "without proving the numerical expectation is wrong". If the cause is ft_warp_optim's TolFun 1e-4, record that in the PR notes and keep the parity check in test_coregister_parity.py.

Nits

  • eeg_checkset._array_is_empty can be value is None or np.asarray(value).size == 0, which drops the hasattr branch. I left a suggestion inline.
  • ft_dipolefitting.py L597 and L671 check alpha is None, but _line_search never returns None, so that check is dead. Drop it.

Test gaps

None. The new MATLAB parity tests cover grid counts, all 32 single-dipole fits, 10 symmetric pairs, the coregister warp and the icawinv rebuild. The two residual-variance-only exceptions for ill-conditioned components are documented and were approved in the description.

EEGLAB parity notes

  • Rebuilding icawinv = pinv(icaweights*icasphere) when it is empty matches EEGLAB's eeg_checkset. The pop_editset test now expects this.
  • DIPFITUnavailableError now inherits from NotImplementedError, which is still a subclass of RuntimeError. Existing except RuntimeError handlers in console.py, qt.py and main_window.py still catch it.
  • I couldn't run Python or tests in this job because uv needed approval, so this review is static.

Comment on lines +620 to +636
def _fminunc_coregister(
fun,
start,
maxiter=1000,
tol_fun=_FUNCTION_TOLERANCE,
tol_x=_STEP_TOLERANCE,
max_fun_evals=None,
):
"""Quasi-Newton BFGS used by the traditional electrode warp.

``ft_warp_optim`` leaves ``TypicalX`` unset. This forward difference is
``sqrt(eps) * sign'(x)``, with ``sign'(0) = 1``, which is the step that
matches EEGLAB's traditional warp. TolFun stops on the relative
infinity-norm of the gradient. TolX stops on the relative step. The
default evaluation budget is ``100 * n``.
"""
x = np.asarray(start, dtype=float).ravel().astype(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 (maintainability, AGENTS.md "Parallel implementations of existing helpers"): _fminunc_coregister is a second BFGS loop next to _fminunc (L571-613). Both claim to be MATLAB fminunc, and both use the same _line_search, but they've already drifted apart:

  • gradient stop: < TolFun * (1 + ||g0||) here vs <= tol_fun * max(1, ||g0||) in the coregister version
  • only the coregister version resets to steepest descent when g @ direction >= 0
  • only the coregister version enforces MaxFunEvals
  • finite-difference step: max(|x|, 10) vs a bare sqrt(eps)*sign'(x)

Some of these differences may be intentional (TypicalX is 10 for dipoles and unset for the warp). Others look accidental: either both callers need the descent reset and the eval budget, or neither does. A future fix to one loop will silently skip the other. Also, sigprocfunc/coregister.py now depends on this private plugin helper through plugins.dipfit._coordinates (L16).

Suggested fix: keep one _fminunc(fun, x0, *, typical_x, tol_fun, tol_x, maxiter, max_fun_evals) and pass the dipole values (typical_x=10, 1e-9, 1e-6) and the warp values (ft_warp_optim: 1e-4, default TolX and MaxFunEvals) from the two call sites. If the stopping rules really do differ between the two MATLAB paths, cite where in a single parity comment.

Comment thread tests/test_phase4_plot_wrappers.py Outdated
)

np.testing.assert_allclose(apply_coregistration_transform(source.points, fitted), target.points, atol=1e-6)
np.testing.assert_allclose(apply_coregistration_transform(source.points, fitted), target.points, atol=5e-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.

Important (AGENTS.md §Testing: "Never relax tolerances or hack around failures without proving the numerical expectation is wrong"): this test's atol goes from 1e-6 to 5e-3, a 5000× increase, and neither the PR description nor the test says why. The target is an exact traditional transform of the source, so recovery used to be essentially exact.

A plausible explanation is that ft_warp_optim stops at TolFun 1e-4, so the 1e-6 expectation was never MATLAB-realistic. If so, say that in the PR notes. Better still, lock the parity in tests/test_coregister_parity.py, which already compares against EEGLAB, and keep this test checking only what the Python port guarantees. Otherwise, find the root cause of the extra residual (see the comment on the duplicate fminunc loops) before loosening the tolerance.

Comment on lines +335 to +340
def _array_is_empty(value) -> bool:
if value is None:
return True
if not hasattr(value, "size"):
return np.asarray(value).size == 0
return value.size == 0

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: np.asarray already handles arrays, lists, and scalars, so the hasattr(value, "size") branch isn't needed. AGENTS.md also discourages hasattr dispatch.

Suggested change
def _array_is_empty(value) -> bool:
if value is None:
return True
if not hasattr(value, "size"):
return np.asarray(value).size == 0
return value.size == 0
def _array_is_empty(value) -> bool:
return value is None or np.asarray(value).size == 0

cursoragent and others added 5 commits November 22, 2026 07:36
The warp step uses fminunc's default TypicalX of ones, and both callers
stop on TolFun times (1 + ||g0||). The synthetic warp check compares
that warp to a target built with it, at atol 1e-6.

Co-authored-by: Suraj Ranganath <[email protected]>
FieldTrip TolFun 1e-4 and TolX 1e-6 leave a point residual of 3.95e-7
on Linux and 1.55e-6 on macOS.

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

This reverts commit ac5d740.

Co-authored-by: Suraj Ranganath <[email protected]>
The non-MATLAB check requires a tenfold distance drop and a converged
rigid-body stage. The MATLAB comparison uses the existing coregister
atol of 1e-3 and rtol of 1e-4.

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

claude Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review

  • Overall assessment: Looks good, with one nit. This is a re-review of head 9ec714b. The three Important items from the previous review are addressed:
    • The two fminunc loops are now one shared functions/miscfunc/fminunc.py. Dipole fits pass TypicalX 10 and 2*MaxIter*n. The warp passes the ft_warp_optim values (TolFun 1e-4, MaxIter 1500) and the fminunc defaults.
    • The full MATLAB reference run is in the description: EEGLAB d0963be, eeglab_tests fec88f9, 4255 passed / 5 failed / 62 skipped, 51m37s, with each failure explained.
    • The phase-4 coregister test no longer asks for exact recovery. Parity is now pinned against FieldTrip ft_warp_optim in tests/test_coregister_parity.py.
  • Highest-risk area: the stop rules and line search in the shared fminunc. Static reading finds them consistent with the stopping rules described in the PR (||g||∞ < TolFun(1+||g0||∞), relative step, budget, first step min(1/||g0||∞, 1)). The MATLAB component parity tests guard them.
  • Merge recommendation: Safe to merge once a human approves, as AGENTS.md requires for core-function PRs.

Blocking

None.

Important

None.

Nits

  • warp_optim(return_status=...) exists only for one test assertion (plugins/dipfit/_coordinates.py:241-285). It gives the public warp a second return shape and a stages list. The only caller is tests/test_phase4_plot_wrappers.py:359, which asserts that the rigid-body stage stopped on a convergence rule. That is an implementation detail, and the MATLAB parity test already covers the outcome. Suggested fix: drop the flag and that assertion, and keep the mean-distance check. Details are in the inline comment.

Test gaps

None. MATLAB parity covers:

  • grid counts
  • all 32 single-dipole fits and the symmetric pairs, with the two approved residual-variance-only exceptions
  • the .elc/.elp coregister warp
  • the synthetic ft_warp_optim stages
  • the empty-icawinv rebuild

EEGLAB parity notes

  • eeg_checkset now rebuilds an empty icawinv as pinv(icaweights @ icasphere), as EEGLAB does. It sits inside the existing exception_type guard, so strict mode still raises. test_pop_editset was updated to expect this.
  • estimate_coregistration_transform no longer accepts initial. The GUI and coregister() both always start the warp from scratch, as ft_warp_optim does. Only the GUI dialog passed initial, and it was updated.
  • pop_multifit now passes threshold / 100 to dipfit_reject. This fixes thresholds of 1% or less, which used to be read as a fraction (1 meant 100%).
  • I couldn't verify the change that applies rmout only to spherical models against pop_multifit.m, because the vendored EEGLAB tree isn't present in this checkout. Please confirm that EEGLAB's non-spherical branch is either skipped or handled elsewhere.

I reviewed this statically and did not run tests. I checked for correctness bugs, EEGLAB parity, data structure compatibility, tests for changed behavior, and AGENTS.md compliance.

Comment on lines 241 to +285
@@ -243,22 +255,34 @@ def warp_optim(points: Any, target: Any, method: str = "traditional") -> tuple[n
raise ValueError("method must be rigidbody, globalrescale, traditional, or nonlin1..nonlin5")
level = _WARP_LEVELS[selected]
params: np.ndarray | None = None
status: dict[str, Any] | None = None
stages: list[dict[str, Any]] = []
if level >= 1:
params = _optimize_warp(np.zeros(6), source, target_points, "rigidbody")
assert params is not None
params, status = _optimize_warp(np.zeros(6), source, target_points, "rigidbody")
stages.append(status)
assert params is not None and status is not None
if level >= 2:
params = _optimize_warp(np.concatenate([params, [1.0]]), source, target_points, "globalrescale")
params, status = _optimize_warp(np.concatenate([params, [1.0]]), source, target_points, "globalrescale")
stages.append(status)
if level >= 3:
params = _optimize_warp(np.concatenate([params, [params[6], params[6]]]), source, target_points, "traditional")
params, status = _optimize_warp(
np.concatenate([params, [params[6], params[6]]]), source, target_points, "traditional"
)
stages.append(status)
if level >= 4:
transform = traditional(params)
params = np.column_stack([transform[:3, 3], transform[:3, :3]]).reshape(3, 4)
params = _optimize_warp(params, source, target_points, "nonlin1")
params, status = _optimize_warp(params, source, target_points, "nonlin1")
stages.append(status)
for order in range(2, max(level - 3, 1) + 1):
needed = _polynomial_term_count(order)
params = np.column_stack([params, np.zeros((3, needed - params.shape[1]))])
params = _optimize_warp(params, source, target_points, f"nonlin{order}")
return warp_apply(params, source, selected), np.asarray(params, dtype=float)
params, status = _optimize_warp(params, source, target_points, f"nonlin{order}")
stages.append(status)
fitted = warp_apply(params, source, selected), np.asarray(params, dtype=float)
if return_status:
return (*fitted, {**status, "stages": stages})
return fitted

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 (AGENTS.md: "Boolean dispatch where separate clear functions would be simpler" and "Do not write tautological tests that only assert ... implementation details"): nothing in runtime code passes return_status=True to warp_optim. Only one assertion uses it: assert status["stages"][0]["converged"] in tests/test_phase4_plot_wrappers.py#L358-L360. For that one test, the public warp gets a second return shape and a stages list, and the type annotation becomes a union.

That assertion checks which internal stop rule the rigid-body stage hit, not anything a user can see. The behavior that matters is already covered: the mean-distance drop in the same test, and the MATLAB ft_warp_optim comparison in test_synthetic_traditional_warp_matches_fieldtrip.

Suggested fix: remove return_status, status and stages from warp_optim, so it calls params, _status = _optimize_warp(...) again. In the phase-4 test, drop the stages[0]["converged"] assertion and keep fitted * 10 < untransformed. _optimize_warp can keep its own fminunc(..., return_status=True) call if you want the reason available for debugging.

@suraj-ranganath
suraj-ranganath merged commit 6b8012c into develop Nov 22, 2026
19 checks passed
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 simple procedural dipole parity: 8 step bottom up verification and 3 model benchmark

3 participants