Skip to content

Reject identical and collinear electrode positions - #609

Merged
suraj-ranganath merged 6 commits into
developfrom
cursor/degenerate-electrode-positions-3446
Nov 18, 2026
Merged

suraj-ranganath merged 6 commits into
developfrom
cursor/degenerate-electrode-positions-3446

Conversation

@suraj-ranganath

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

Copy link
Copy Markdown
Member

Reject identical or collinear electrode positions in clean_channels, spherical interpolation, and headplot. Planar layouts, including a ring, warn and still run, matching what EEGLAB accepts. The cutoff is one quarter of the centered singular-value thickness of a hemispherical shell.

MATLAB verification: checked on jamming with MATLAB R2025b, EEGLAB d0963be9, and eeglab_tests fec88f9f, compared against develop 2736f99, on 2026-11-17 between about 13:16 and 17:50 PT. The full suite, run with --run-heavy-reference, had 3745 outcomes: 3709 passed, 22 skipped, and 14 failed or timed out. 13 of those 14 fail the same way on develop, so they are pre-existing: the limo reference tests, riemannian ASR, float32 avg-ref, BIDS e2e/import, pop_studydesign history, the tutorial movie/event study, the replay_20261015 fuzz test and limo hybrid. The 14th, test_pop_load_frombids_reads_bom_json_sidecars, failed only inside the full suite; it passes on its own on both this branch and develop.

Fixes #539

Open in Web Open in Cursor 

Raise when centered coordinates have no second principal axis, and warn
when a layout is only planar, so channel cleaning and spherical
interpolation no longer treat a collapsed montage as a normal cap.

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.

@claude

claude Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review

  • Overall assessment: Needs changes. The validation logic is sound: I re-derived σ3/σ1 = 1/2 for a uniform hemispherical shell, which puts the cutoff at 0.125. It is wired into clean_channels, eeg_interp and headplot_setup before any numeric work, and non-degenerate numerics are untouched. Two cleanups remain, and the MATLAB reference run is still missing.
  • Highest-risk area: new ValueErrors on inputs EEGLAB accepts, in clean_channels and spherical eeg_interp.
  • Merge recommendation: Needs changes.

Blocking

  • MATLAB reference evidence is missing. This PR changes core ported functions: clean_channels.py, eeg_interp.py, sphericalSplineInterpolate.py and headplot.py. AGENTS.md §Testing requires one run of .github/workflows/eeglab-reference.yml (or the local --eeglab-backend=matlab run) on the final branch, with commits, counts and runtime in the PR body, before human approval. The description says it was not run.

Important

  • _check_positions flag on spheric_spline and sphericalSplineInterpolate (eeg_interp.py:449, sphericalSplineInterpolate.py:81). The only in-tree callers, eeg_interp and RANSAC, both pass False, so the default True path only runs from tests. The flag also makes both MATLAB ports differ from their .m sources. Fix: validate only at the public entry points and drop the flag and the helper-level checks. See the inline comment. Fix this →

Nits

  • test_degenerate_threshold_is_one_quarter_of_a_hemisphere only compares constants with each other, which AGENTS.md calls a tautological test. That test and test_standard_montages_with_missing_channels_stay_silent also import inside the function. See the inline comment.

Test gaps

None. The tests cover identical, collinear, nearly collinear, ring, jittered-planar, invdist and headplot cases, plus standard montages with channels removed. I could not run them in this job because pytest needs approval in this sandbox.

EEGLAB parity notes

  • This is an intentional deviation: EEGLAB clean_channels.m and eeg_interp.m do not check the layout. It is documented in eeglab_migration.rst, pop_clean_rawdata.md and pop_interp.md, and the tests lock it in. That fits the "mathematically correct, documented and tested" rule. Planar layouts only warn, so montages EEGLAB accepts keep working unless they are actually collinear or identical.



def spheric_spline(xelec, yelec, zelec, xbad, ybad, zbad, values, params, dtype='float32'):
def spheric_spline(xelec, yelec, zelec, xbad, ybad, zbad, values, params, dtype='float32', *, _check_positions=True):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important (maintainability): _check_positions is a private flag on a public signature, and the only in-tree caller passes False (

if method in ('spherical', 'sphericalKang', 'sphericalCRD', 'sphericalfast'):
bad_data = spheric_spline(
xelec=xyz_good[0],
yelec=xyz_good[1],
zelec=xyz_good[2],
xbad=xyz_bad[0],
ybad=xyz_bad[1],
zbad=xyz_bad[2],
values=d[good_idx, :],
params=params,
dtype=dtype,
_check_positions=False,
)
). sphericalSplineInterpolate has the same pattern: its only caller, RANSAC, also passes False (
def op(src, dest):
return sphericalSplineInterpolate(src.T, dest.T, _check_positions=False)[0]
). So the True branch only runs from tests. The MATLAB ports also differ from spheric_spline.m / sphericalSplineInterpolate.m only to support that flag. AGENTS.md calls out "Boolean dispatch where separate clear functions would be simpler."

Suggested fix: Keep validation at the public entry points (clean_channels, eeg_interp, headplot_setup). Remove the flag and the validation from both spline helpers, and drop the matching assertions in test_spline_helpers_reject_a_line_and_warn_on_a_ring.

Comment on lines +216 to +225
def test_degenerate_threshold_is_one_quarter_of_a_hemisphere():
"""A hemispherical shell has thickness 1/2; the cutoff is a quarter of that."""
from eegprep.functions.sigprocfunc.electrode_geometry import (
DEGENERATE_THICKNESS_RATIO,
HEMISPHERE_THICKNESS_RATIO,
)

assert _hemisphere_thickness_ratio() == pytest.approx(0.5, abs=1e-12)
assert HEMISPHERE_THICKNESS_RATIO == pytest.approx(_hemisphere_thickness_ratio())
assert DEGENERATE_THICKNESS_RATIO == HEMISPHERE_THICKNESS_RATIO / 4.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 (AGENTS.md §Testing / §Code Style): This test only checks module constants against each other (DEGENERATE_THICKNESS_RATIO == HEMISPHERE_THICKNESS_RATIO / 4.0). AGENTS.md says: "Do not write tautological tests that only assert types, constants, or implementation details." The behavior tests below already lock in the threshold. The function-level imports here and at L346 also go against "All imports go at the top."

Suggested fix: Delete this test, or keep only the _hemisphere_thickness_ratio() ≈ 0.5 derivation if you want the math documented. Move the electrode_geometry import to the top of the module.

Public spheric_spline and sphericalSplineInterpolate still reject
identical or collinear electrodes. eeg_interp and RANSAC call the
unchecked kernels after the full montage has already been checked.

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

claude Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review

  • Overall assessment: Needs changes. The only blocker is that the MATLAB reference run is still missing. The follow-up commit afa35dd resolves the earlier review:
    • The geometry checks now sit in thin public wrappers: spheric_spline and sphericalSplineInterpolate.
    • eeg_interp and RANSAC call the private kernels _spheric_spline and _spherical_spline_weights directly, with no boolean flag.
    • The tautological constants test is gone, and the imports are at module top.
  • Highest-risk area: the new ValueError raised before any numeric work in clean_channels, spherical, invdist and spacetime eeg_interp, and headplot_setup. These run on layouts that EEGLAB accepts without a check.
  • Merge recommendation: Needs changes. Attach the MATLAB reference evidence; the rest is a nit.

Blocking

  • MATLAB reference evidence is still missing. This PR changes core ported functions: clean_channels.py, eeg_interp.py, sphericalSplineInterpolate.py, ransac.py and headplot.py.
    • AGENTS.md §Testing requires one run on the final branch before human approval: either .github/workflows/eeglab-reference.yml (workflow_dispatch on this branch) or the local --eeglab-backend=matlab run.
    • Record the EEGLAB and eeglab_tests commits, pass/fail/skip counts and runtime in the PR body.
    • The PR body still says the suite was not run.

Important

None.

Nits

  • eeg_interp validates good and bad channels together (eeg_interp.py:153-158). The spline and invdist fits depend only on good_idx, so bad channels can push a degenerate good set past the check. Validate good_idx only. See the inline comment.

Test gaps

None. The new tests cover:

I could not run pytest in this job because the sandbox requires approval for it.

EEGLAB parity notes

  • This is an intentional deviation: EEGLAB clean_channels.m and eeg_interp.m / spheric_spline.m do not check the layout.
    • It is documented in docs/source/user_guide/eeglab_migration.rst, resources/help/pop_clean_rawdata.md and resources/help/pop_interp.md, and the new tests lock it in.
    • Planar layouts only warn, so planar montages that EEGLAB accepts keep running. Only identical or collinear ones now raise.
  • Calling the private kernels keeps RANSAC and eeg_interp numerically unchanged for non-degenerate montages. tests/test_utils_ransac.py still compares against the public sphericalSplineInterpolate, which now only adds the guard.

Comment on lines +153 to +158
located = good_idx + bad_idx
if located and method in ('spherical', 'sphericalKang', 'sphericalCRD', 'sphericalfast'):
raw = np.vstack([[locs[i][c] for i in located] for c in ('X', 'Y', 'Z')]).astype(float).T
validate_electrode_positions(raw, operation='eeg_interp')
elif located and method in ('invdist', 'v4', 'spacetime'):
validate_electrode_positions(_planar_points(locs, located), operation='eeg_interp')

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 (correctness of the guard): The check runs on good_idx + bad_idx, but the spline fit (Gelec in _spheric_spline, and _planar_v4_interpolate / _spacetime_interpolate) depends only on the good channels. If the remaining good channels are collinear or identical, the bad channels can still add enough spread to pass the check, and the degenerate fit runs anyway. For example, interpolating several channels off a sparse strip, or interpolating channels added through _handle_chanloc_interpolation, which have real positions.

located = good_idx + bad_idx
if located and method in ('spherical', 'sphericalKang', 'sphericalCRD', 'sphericalfast'):
raw = np.vstack([[locs[i][c] for i in located] for c in ('X', 'Y', 'Z')]).astype(float).T
validate_electrode_positions(raw, operation='eeg_interp')
elif located and method in ('invdist', 'v4', 'spacetime'):
validate_electrode_positions(_planar_points(locs, located), operation='eeg_interp')

Suggested fix: Validate good_idx only, since the fit's well-posedness depends on those positions. The if located guard becomes if good_idx.

eeg_interp classifies the channels it fits when three or more remain,
so filled-in channels off a line no longer hide a degenerate fit.
Two source channels stay legal, because any two positions are collinear
and EEGLAB still interpolates from them.

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

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


Code review

  • Overall assessment: Needs changes. The only blocker is still the missing MATLAB reference run. The new commit 76d7c3b fixes the last nit: eeg_interp now checks the channels it actually interpolates from, so bad channels placed off a line can no longer hide a collinear set of good channels. I checked:
    • raw[: len(good_idx)] and flat[: len(good_idx)] select the good rows, because located = good_idx + bad_idx keeps that order.
    • _planar_points keeps the row order too.
    • stacklevel=3 still points the warning at the validate_* caller.
    • Numeric results for valid montages do not change.
  • Highest-risk area: the new ValueError / UserWarning raised before any computation in eeg_interp (spherical, invdist, spacetime), clean_channels and headplot_setup, on layouts EEGLAB accepts without checking.
  • Merge recommendation: Needs changes (attach the MATLAB reference evidence).

Blocking

  • MATLAB reference evidence is still missing. This PR changes core ported functions (clean_channels.py, eeg_interp.py, sphericalSplineInterpolate.py, ransac.py, headplot.py). AGENTS.md §Testing requires one run on the final branch before human approval: either .github/workflows/eeglab-reference.yml (workflow_dispatch on cursor/degenerate-electrode-positions-3446) or the local --eeglab-backend=matlab run. Record the EEGLAB and eeglab_tests commits, pass/fail/skip counts and runtime in the PR body. The body still says "The MATLAB reference suite was not run here."

Important

None.

Nits

  • "Two source channels … are not rejected" is not quite true (electrode_geometry.py validate_interpolation_sources docstring, eeg_interp docstring, pop_interp.md, eeglab_migration.rst). With two distinct sources, the code falls back to checking every located channel, bad ones included. So three electrodes on a line, interpolating the middle one from its two neighbours, still raises collinear. Raising is reasonable for a one-dimensional montage, but the docs suggest it cannot happen. Suggested fix: reword to "With fewer than three source channels, the whole located montage is checked instead" (the docstring already says this a sentence later), and drop the absolute claim from the help page and migration notes.

Test gaps

None. The new tests cover:

  • a collinear source strip with off-strip bad channels (spherical, raises)
  • identical sources (raises)
  • a flat collinear strip under invdist (raises)
  • two sources from a non-planar montage (no warning)

I could not run pytest in this job because the sandbox needs approval for it.

EEGLAB parity notes

  • This is still an intentional deviation: EEGLAB eeg_interp.m / spheric_spline.m and clean_channels.m do not check the layout. The new source-set rule is documented in pop_interp.md and eeglab_migration.rst and covered by the new tests, so it follows the documented-deviation rule. Planar source sets only warn, so montages EEGLAB accepts keep running unless the channels interpolated from are collinear or identical.

cursoragent and others added 2 commits November 18, 2026 07:03
Two distinct source channels are not rejected for collinearity alone.
The whole located montage is still classified and can raise or warn.

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

claude Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review

  • Overall assessment: Looks good. The only remaining blocker, the missing MATLAB reference run, is now in the PR body. It ran on EEGLAB d0963be9 and eeglab_tests fec88f9f, with 3709 passed, 22 skipped and 14 failed. 13 of those 14 fail the same way on develop. The 14th fails only inside the full suite and passes when run on its own. Commit 7f06031 fixes the last nit: the docstrings, pop_interp.md and eeglab_migration.rst now say that two sources fall back to checking the whole montage, so the docs no longer claim this case can never raise.
  • Highest-risk area: the new ValueError and UserWarning raised before any computation in clean_channels, eeg_interp (spherical, invdist/v4 and spacetime) and headplot_setup. These run on layouts that EEGLAB accepts without checking.
  • Merge recommendation: Safe to merge once a human approves, as AGENTS.md requires for core-function PRs.

Blocking

None.

Important

None.

Nits

None.

Test gaps

None. I did not run pytest in this job. The tests cover:

  • the issue clean_channels: raise on degenerate channel locations instead of returning a meaningless result #539 reproduction (true, collinear and identical layouts)
  • a noisy line, which raises
  • a ring and a jittered plane, which warn and still run
  • a collinear source strip whose bad channels sit off the strip
  • identical sources
  • invdist on a collinear strip
  • two sources from a non-planar montage
  • both public spline helpers
  • headplot_setup
  • the packaged 10-20, 10-10, BioSemi 128/256 and EGI 129/257 montages, with channels removed in blocks or strides, which stay silent

EEGLAB parity notes

None blocking. This is an intentional deviation: EEGLAB's clean_channels.m, eeg_interp.m and spheric_spline.m do not check the layout. The deviation is documented in eeglab_migration.rst, pop_clean_rawdata.md and pop_interp.md, and the new tests lock it in. RANSAC and eeg_interp now call the private kernels _spherical_spline_weights and _spheric_spline directly, so results on valid montages do not change.

What I checked:

  • raw[: len(good_idx)] selects the source rows, because located = good_idx + bad_idx.
  • stacklevel=3 makes the warning point at the code that called validate_*.
  • Channels without a location are filtered out before the check in both clean_channels and eeg_interp.
  • headplot's theta/radius fallback (Z = 0) correctly hits the planar warning.

…electrode-positions-3446

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

# Conflicts:
#	docs/source/user_guide/eeglab_migration.rst
@suraj-ranganath
suraj-ranganath marked this pull request as draft November 18, 2026 08:07
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 18, 2026 08:07
@claude

claude Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review

  • Overall assessment: Looks good. Since the last review, the only new commit is a1a38ec, a merge of origin/develop, which brought in Fit standardBESA dipoles with the four-shell BESA leadfield #611 (standardBESA dipfit). That merge leaves every file in this PR's diff unchanged: git diff origin/develop...HEAD still shows the same 11 files. Develop also added no new callers of spheric_spline, sphericalSplineInterpolate, clean_channels or headplot_setup that this PR's checks would affect.
  • Highest-risk area: the new ValueError / UserWarning raised before any computation in clean_channels, eeg_interp (spherical, invdist/v4 and spacetime) and headplot_setup, on layouts that EEGLAB accepts without a check.
  • Merge recommendation: Safe to merge once a human approves, as AGENTS.md requires for core-function PRs. The MATLAB reference run is in the PR body.

Blocking

None.

Important

None.

Nits

None.

Test gaps

None.

EEGLAB parity notes

None blocking. The checks are an intentional, documented and tested deviation. EEGLAB's clean_channels.m, eeg_interp.m and spheric_spline.m do not check the layout. The deviation is documented in eeglab_migration.rst, pop_clean_rawdata.md and pop_interp.md, and tests/test_degenerate_electrode_positions.py locks it in.

What I checked:

  • Head and gate: the checked-out head and the PR head are both a1a38ec, and no earlier review marker was found.
  • eeg_interp: channels without a location are dropped from good_idx/bad_idx before located is built. Because located starts with good_idx, raw[: len(good_idx)] selects exactly the channels the fit uses.
  • clean_channels: the check runs after the NaN-location filter and before calc_projector. RANSAC calls the private _spherical_spline_weights directly, so the projector numerics do not change.
  • electrode_geometry: the checks do not depend on position or scale, the roundoff cutoff for identical positions grows with ||P||_F, and stacklevel=3 makes the warning point at the code that called validate_*.
  • pytest config: it does not turn warnings into errors, so planar layouts in existing tests only warn.

I could not run pytest in this job because the sandbox needs approval for uv run pytest.

Checked for correctness bugs, EEGLAB parity, data structure compatibility, changed-behavior tests, and CLAUDE.md/AGENTS.md compliance.

@suraj-ranganath
suraj-ranganath merged commit 24a2ffc into develop Nov 18, 2026
13 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.

clean_channels: raise on degenerate channel locations instead of returning a meaningless result

2 participants