Skip to content

[topoplot] Average near-coincident sensors and select channels with their values - #672

Merged
suraj-ranganath merged 7 commits into
developfrom
agent/20261123-fix-670
Nov 24, 2026
Merged

suraj-ranganath merged 7 commits into
developfrom
agent/20261123-fix-670

Conversation

@claude

@claude claude Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

griddata_v4 now averages values at coincident positions before solving, as MATLAB griddata does, so duplicate sensors no longer produce an all-NaN map. topoplot now subsets the value vector with plotchans, matching topoplot.m, so dropping a NaN or Inf channel no longer shifts later values onto the wrong sensors. Adds regression tests for both.

Fixes #670

🤖 Generated with Claude Code

griddata_v4 averages near-coincident sensors the way MATLAB R2025b griddata mergepoints2D does, and topoplot applies plotchans, the common-reference drop, and NaN/Inf removal to the locations and the values together. plotchans is 1-based, matching EEGLAB, envtopo, and headplot. pop_topoplot option text is parsed as the cell MATLAB evals, so cells, nested brackets, commas, semicolons, doubled quotes, and a trailing comma survive. A cell inside brackets or a % comment raises ValueError. emarker and emarker2 raise ValueError from topoplot until they are drawn. The merge comparison is strict <. One remaining location raises ValueError instead of leaking LinAlgError. Fixes #670. Follow-up for the options topoplot still ignores: #683.

Measured on MATLAB R2025b against 9e7005d, and the strict < fix follows that measurement. mergesimpts([0;0.5;1],0.5,'average') keeps all three rows. A 2-D point exactly at the per-axis tolerance is not merged (nout 6); <= merged it (nout 5). nextafter(tol,-inf) merges in both and nextafter(tol,+inf) stays separate in both. Rows sort by (y, x, v). Grouping uses the anchor, not neighbor transitivity: chain A-B-C leaves C out when C is outside tolerance of A, and an outlier that sorts between A and D does not keep D out of A's group. griddata v4 Zi max abs difference is about 1e-15. topoplot on eeglab_data.set max abs difference is about 3e-12.

Before this branch, an extra sensor at +1e-9 on the 8-point unit circle differed from the averaged sensor by 1.589616e+08 on an 11x11 grid, and by 1.340261e+06 at 1e-7. The same 1e-9 offset inside topoplot differed by 3.625761e+07. Sixteen values with seventeen chanlocs raised IndexError: index 16 is out of bounds. After the merge, the 1e-9 grid difference is 0, the 1e-7 grid difference is 1.443e-15, and the topoplot 1e-9 difference is 3.553e-15. An offset of 1e-3 is not merged (max abs versus the collapsed map 3.005e+02). A single selected channel raised UnboundLocalError because intdatavector was never set. One unique location raised LinAlgError: Singular matrix. Both now raise ValueError from topoplot griddata_v4. MATLAB griddata returns a non-finite map and warns in that case. The duplicate warning is "topoplot griddata_v4: Duplicate x-y data points detected: using average values for duplicate points." and it is emitted whenever the point count drops.

tol = spacing(0.5 * (max - min)) ** (1/3) per axis. The value column is ignored.

% Chains. Column order is [y x v], matching griddata's mergesimpts call.
% tol on this span is about 6.055e-6. Confirmed on R2025b.
span = [-1 -1 -1; 1 -1 0; -1 1 0.5; 1 1 1];
tol = eps(0.5 * (max(span(:,1:2)) - min(span(:,1:2)))) .^ (1/3);

% A=(x0,y0,v1), B=(4e-6,0,3), C=(9e-6,0,7). Merge A+B; leave C.
chain = [0 0 1; 0 4e-6 3; 0 9e-6 7];
disp(matlab.internal.math.mergesimpts([span; chain], [tol(1) tol(2) Inf], 'average'));

% Outlier (y=1e-6,x=0.5,v=10) sorts between A and D=(y=2e-6,x=1e-6,v=3).
% D stays with A. The outlier stays.
outlier = [0 0 1; 1e-6 0.5 10; 2e-6 1e-6 3];
disp(matlab.internal.math.mergesimpts([span; outlier], [tol(1) tol(2) Inf], 'average'));

% Strict < boundary. Exact tol keeps all three.
disp(matlab.internal.math.mergesimpts([0; 0.5; 1], 0.5, 'average'));

Ported topoplot.m lines 605-608 and 703-716 (plotchans must be in range, then intersect located channels; EEGPrep indices are 1-based), 749-753 (drop the last location when there is one extra chanloc and it is selected), 760-763 plus 769-779 (sorted removal of NaN/Inf, abs, then subset locations, labels, and values together), and 918-923 (subset values when length(Values) == length(Th), including one channel). Not ported: 725-743 (chaninfo.icachansind). topoplot has no chaninfo input; pop_topoplot and the ICLabel feature extractor already pass the ICA channel subset. Not ported: 764-766 (plotgrid setxor). There is no singular-G fallback. MATLAB griddata does not regularize.

tests/test_topoplot.py::test_reference_near_duplicate_and_nan_channel calls the eeglab_backend fixture and compares Zi at rtol 1e-5, atol 1e-8. It is deselected unless --eeglab-backend=matlab.

EEGLAB reference on this head: https://github.com/sccn/eegprep/actions/runs/45321807736, dispatched by suraj-ranganath on 59dc280 (EEGLAB d0963be9, eeglab_tests fec88f9f). Workflow wall 27m 41s (19:46:29–20:14:10 PT). Shards heavy, hybrid, misc, parity, and stats passed. core: 4 failed, 3318 passed, 17 skipped (wall 19m 53s). study: 1 failed, 352 passed, 27 skipped (wall 14m 06s). Totals: 4760 passed, 5 failed, 58 skipped.

The 5 failures are the develop failures tracked in #685: tests/test_coregister_parity.py::test_coregister_traditional_warp_matches_eeglab, test_coregister_parity.py::test_synthetic_traditional_warp_matches_fieldtrip, test_dipfit_bem.py::test_bem_leadfield_and_multifit_match_fieldtrip, test_study_clustering.py::test_matlab_kmeans_numbering_matches_fixed_initial_centroids, and test_phase2_file_channel_location.py::test_struct_near_assertion_matches_source. This PR does not touch those tests or the MATLAB transport.

gradmap coverage: test_reference_gradmap_center, test_reference_gradmap_center_file, and test_reference_gradmap_corner all passed in the misc shard. MATLAB-backend topoplot tests also passed, including test_reference_topoplot and test_reference_near_duplicate_and_nan_channel.

Skips (58): 36 are heavy-suite tests left to --run-heavy-reference (the heavy shard's three tests passed). 8 need Biosig openbdf (7 plus one where openbdf is not on the MATLAB path). 3 need the neuroscanio plugin. 2 need the ERPSS plugin. 3 need a functional AMICA binary, which the ubuntu-22.04 runner does not have. 2 are bids_preproc tests restricted to known hosts. 1 is a Windows-only path test. 1 is eeglab_execmenu pop_chanedit lookup, which blocks in a headless batch session. 2 are eegprep-lean dependency-floor checks for packages lean does not declare (h5py, numpy).

Open in Web Open in Cursor 

EEGLAB reference run

MATLAB reference run 45326085929 ran eeglab-reference.yml on 59dc28077ce2505fdb4bc6b165f8eeca9e3d8faa in 26m 05s. It used EEGLAB d0963be9d81acc5b66e84f8d3d7c89e3ce127cc4 and eeglab_tests fec88f9ffe7c225eb1de8924db8b6a3e0d53a4d9.

Shard Passed Failed Skipped pytest time (s)
Core 2,886 4 17 1346.65
Study 340 1 27 877.19
Misc 656 0 8 466.32
Hybrid 143 0 4 36.81
Stats 257 0 0 119.03
Parity 10 0 2 844.29
Heavy 3 0 0 319.04
Total 4,295 5 58

Counts follow the pytest summaries, which report 465 passing subtests separately. All five failures match the known develop failures in #685. The six-file diff against develop changes only topoplot, pop_topoplot, their tests and documentation. The failing assertions exercise independent code paths.

  • Core registration — test_coregister_traditional_warp_matches_eeglab and test_synthetic_traditional_warp_matches_fieldtrip
  • DIPFIT — test_bem_leadfield_and_multifit_match_fieldtrip
  • STUDY clustering — test_matlab_kmeans_numbering_matches_fixed_initial_centroids
  • MATLAB struct comparison — test_struct_near_assertion_matches_source

Topoplot results

  • Core passed all 26 tests in tests/test_topoplot.py, including test_reference_topoplot, test_reference_near_duplicate_and_nan_channel, TestTopoplotParity::test_parity_gridscale_32 and TestTopoplotParity::test_parity_single_component_noplot. The near-duplicate and NaN test compared each interpolated grid directly with MATLAB.
  • Study passed test_reference_pop_topoplot_original_montage_variants and the companion layout and polarity test. The separate heavy case test_reference_std_topoplot[teststudy] was skipped in this shard.
  • Misc passed all 23 tests in tests/test_pop_topoplot.py. The 11 MATLAB test_reference_colorbar_* cases were positive, negative, symmetric, asymmetric, zero_lower, zero_upper, multiple_positive, multiple_symmetric, default, zero_component and unrelated_axes. test_reference_gradmap_center, test_reference_gradmap_center_file and test_reference_gradmap_corner also passed, covering the gradmap caller of griddata_v4.

Of the 58 skips, 36 required --run-heavy-reference in their shard, 8 lacked Biosig openbdf, 3 lacked Neuroscan I/O, 2 lacked ERPSS and 3 required a working AMICA binary. Two BIDS tests require specific hosts, two dependency-floor checks cover packages outside eegprep-lean, one path test requires Windows, and one pop_chanedit menu lookup requires an interactive session.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor Author

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 marked this pull request as draft November 23, 2026 23:04
@cursor cursor Bot changed the title [topoplot] Fix coincident sensors and non-finite value alignment [topoplot] Average near-coincident sensors and select channels with their values Nov 23, 2026
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 24, 2026 01:55

Copy link
Copy Markdown
Member

claude review this

@claude

claude Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Code review

  • Overall assessment: Looks good. I re-reviewed head 59dc2807. The earlier Important finding is resolved: the PR body now records EEGLAB reference run 45321807736 with the EEGLAB (d0963be9) and eeglab_tests (fec88f9f) commits, pass/fail/skip counts, runtime, and the reason for each skip. The 5 failures are the existing develop failures tracked in EEGLAB reference: 5 tests fail on develop (coregister warp x2, BEM multifit, kmeans numbering, struct near) #685, and the gradmap and topoplot MATLAB-backend tests passed. The two earlier nits (_OptionCursor scope and merged_count) were answered in the thread, and I am not raising them again. Re-checked at this head:
    • _merge_coincident_points / _average_similar_points: anchor grouping, strict <, and the (y, x, v) sort
    • griddata_v4 without regularization, including the gradmap caller
    • _plot_channel_indices: 1-based input, the out-of-range error, and intersecting with located channels
    • the common-reference drop, plus NaN/Inf removal applied to locations and values together
    • pop_topoplot option parsing for ranges (1:3, [1:3 5]), signed values, cells, and trailing commas
  • Highest-risk area: griddata_v4 numerics, covered by the reference run.
  • Merge recommendation: Safe to merge after human approval of the core-function change, as AGENTS.md requires.

Blocking

None.

Important

None.

Nits

None.

Test gaps

None.

EEGLAB parity notes

None.

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

@cursor

cursor Bot commented Nov 24, 2026

Copy link
Copy Markdown

🤖 plotchans is now 1-based in topoplot._plot_channel_indices, same as envtopo and headplot. 'plotchans', [1 2 3] from the pop_topoplot options text draws channels 1-3, and index n_channels selects the last channel. The out-of-range error names topoplot and the range 1..n.

The _merge_coincident_points / _average_similar_points split stays on purpose. The split lets the 1-D nextafter cases inject a 0.5 tolerance, and merged_count is used in the 2-D boundary test.

github-actions Bot and others added 5 commits November 24, 2026 02:20
Average points within MATLAB griddata's per-axis tolerance, including
chains judged from the sorted anchor, and solve the Green's system
without the zero Tikhonov term. Validate 0-based plotchans, drop one
extra reference location, and remove NaN or Inf channels from the
values and the locations together.

Co-authored-by: Suraj Ranganath <[email protected]>
A gap equal to the axis tolerance stays separate, one plotchans index
reaches the interpolant, and a single remaining location raises ValueError.

Co-authored-by: Suraj Ranganath <[email protected]>
EEGLAB option text and envtopo/headplot already count channels from 1.
topoplot now uses that same range, including the last channel.

Co-authored-by: Suraj Ranganath <[email protected]>
Option text is the cell EEGLAB evals. Cells, nested brackets, and
doubled quotes stay intact, and text that cannot be parsed raises.

Co-authored-by: Suraj Ranganath <[email protected]>
@cursor
cursor Bot force-pushed the agent/20261123-fix-670 branch from c612f89 to 596af0c Compare November 24, 2026 02:24
emarker and emarker2 raise until they are drawn. Option text keeps a
trailing comma and rejects a cell inside brackets or a % comment.

Co-authored-by: Suraj Ranganath <[email protected]>
Ruff format collapses the ValueError onto one line at the 120-column limit.

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

Copy link
Copy Markdown
Member

claude review this

Copy link
Copy Markdown
Member

On the two nits from the review of 59dc280:

The _OptionCursor parser stays in this PR. EEGLAB pop_topoplot evals the options field as a MATLAB cell, and users type legal MATLAB literals for options this PR already applies (plotchans, electrodes, and the rest of the supported set), not only emarker/emarker2. The earlier regex path already turned 'plotchans', [1 2 3] into a list, but it broke on cells, nested brackets, commas or semicolons inside brackets, doubled quotes, and a trailing comma. Raising on a % comment or a cell inside [] also matches MATLAB eval failing those forms, instead of silently misparsing them. #683 is the follow-up for drawing the options topoplot still does not implement, not for making the GUI option text parse as the cell MATLAB evals.

_merge_coincident_points keeps returning merged_count. The 2-D exact-tolerance test uses that count to check that a point at the per-axis tolerance is not merged, which is the mergesimpts strict-< rule. griddata_v4 still discards it because MATLAB griddata does not surface a merge count to callers. The helper remains the test hook; this is not unused production state.

Copy link
Copy Markdown
Member

claude review this

@suraj-ranganath
suraj-ranganath merged commit 057c6d0 into develop Nov 24, 2026
24 of 28 checks passed
neuromechanist added a commit to nemarOrg/neuroschema that referenced this pull request Nov 27, 2026
* Regenerate sensor vectors at eegprep 871bc7f8

Pin the vectors group to eegprep 871bc7f8 and regenerate the
sensor-field and sensor-layout vectors. Maps match the previous
vectors within the regeneration tolerance; the exact_duplicates and
nan_values quirk fields now record that sccn/eegprep#672 fixed both.
Tested: pytest (3523 passed), both vector --check runs, ruff, ajv.

* Describe eegprep 871bc7f8 in the sensor docs

* Reword the duplicate-sensor notes for eegprep#672

Tested: pytest.

* Release 0.6.1 version and changelog

Bump pyproject, __version__, README, the examples' schema_version and
every schema $id (SCHEMA_BASE, ajv BASE) to 0.6.1; date the 0.6.1
changelog and name nemar-process#101 as the eegprep move.
Tested: pytest (3523 passed), the three vector --check runs, ruff,
ajv (45 schemas, 255 verdicts).
neuromechanist added a commit to nemarOrg/nemar-cli that referenced this pull request Nov 27, 2026
Duplicates and non-finite values: true at edf694c8, fixed at
871bc7f8 (sccn/eegprep#672); the merge and drop rules still
decide. Part of #2411.
neuromechanist added a commit to nemarOrg/nemar-cli that referenced this pull request Nov 27, 2026
* Move the recipe engine to eegprep 871bc7f8

RECIPE_ENGINE is now [email protected]+871bc7f8 (nemar-process#101's
lock). The contract test holds the vectors' eegprep commit to the
engine, so neuroschema is re-vendored at nemarOrg/neuroschema#40's
head (sensor vectors regenerated at 871bc7f8); it moves to the 0.6.1
release commit later. Part of #2411.
Tested: typecheck; targeted suites incl. the process drift test
against nemar-process feature/66-mir.

* Drop frame_rotated from nemar-process skip words

nemar-process#101 removes the word: eegprep 871bc7f8 orients the
CTF, 4DBti and KitYokogawa frames. Part of #2411.
Tested: quality-documents-contract unit test.

* Vendor neuroschema 0.6.1

Re-vendor at v0.6.1 (86f28d18) and set NEUROSCHEMA_VERSION to
0.6.1; the served metadata.json now says 0.6.1. The bundle never
checks a stamp, so stored 0.6.0 documents still validate (new test).
Part of #2411. Tested: contract-neuroschema*, contract-schemas,
data-route, zarr-engine-protocol-contract.

* Copy the ica-views product at nemar-process 90e248d7

The fixture is nemar-process#101's product: nemar-quality 0.2.0 with
mutualInformationReduction, which sorts first in the plugin step's
qualityMetrics, so the __proto__ case anchors on it. Part of #2411.
Tested: quality-documents-contract (byte comparison against
90e248d7), schema-check, view-digest and the backend quality suites.

* Note eegprep 871bc7f8 in ADR 0137 and CHANGELOG

Part of #2411.

* Format the stamp test

* Check out nemar-process dev in CI again

Removes the a5125c7b pin and its comment: nemar-process dev carries
the epic once nemarOrg/nemar-process#98 merges. Closes #2411.

* Mark eegprep's fixed divergences in ADR 0137

Duplicates and non-finite values: true at edf694c8, fixed at
871bc7f8 (sccn/eegprep#672); the merge and drop rules still
decide. Part of #2411.

* Spell out the deploy order and retired word

The hold from a premature deploy stops the recipe everywhere and
never clears on its own; follow the 0.10.40 procedure. A stored
frame_rotated is still admitted. Part of #2411.

* Test MIR in the fixture and a retired skip word

The fixture must carry mutualInformationReduction (entry and a
one-recording distribution), and a stored frame_rotated skip is
admitted by the entry and its Ajv mirror. Part of #2411.
Tested: quality-documents-contract, adr-index.
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.

topoplot griddata_v4: pinv fallback unreachable; non-finite values misalign sensors

2 participants