Repository navigation
[DIPFIT] Match FieldTrip fminunc dipole fits on BESA and MNI - #666
Conversation
…tting with sub-0.01mm MATLAB parity (#660)
Co-authored-by: Suraj Ranganath <[email protected]>
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]>
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]>
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]>
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 3m 28s —— View job Code review
BlockingNone. Important
Nits
Test gapsNone. The new MATLAB parity tests cover grid counts, all 32 single-dipole fits, 10 symmetric pairs, the coregister warp and the EEGLAB parity notes
|
| 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) |
There was a problem hiding this comment.
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 baresqrt(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.
| ) | ||
|
|
||
| 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) |
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
Nit: np.asarray already handles arrays, lists, and scalars, so the hasattr(value, "size") branch isn't needed. AGENTS.md also discourages hasattr dispatch.
| 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 |
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]>
Co-authored-by: Suraj Ranganath <[email protected]>
|
Claude finished @suraj-ranganath's task in 2m 16s —— View job Code review
BlockingNone. ImportantNone. Nits
Test gapsNone. MATLAB parity covers:
EEGLAB parity notes
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. |
| @@ -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 | |||
There was a problem hiding this comment.
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.
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.