Skip to content

Stream 5: Channel locations and re-reference (F36, F45, F46, F43, F62, F70, F12, F61) - #573

Merged
suraj-ranganath merged 21 commits into
developfrom
stream5-chanlocs
Nov 11, 2026
Merged

suraj-ranganath merged 21 commits into
developfrom
stream5-chanlocs

Conversation

@suraj-ranganath

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

Copy link
Copy Markdown
Member

Channel-location lookup now uses the expected standard-montage orientation, recognizes BESA ELP files, and preserves polar-file units and labels. The channel editor supports its action buttons, ordered edits, and replayable history. Rereferencing and interpolation consistently accept one-based public channel numbers, including GUI fields, console replay, CLI, and internal callers.

Findings

  • F36: Channel-editor action buttons enabled and wired through S2's run_dialog_action; automatic lookup when labels exist without coordinates; channel index navigation preserved after insert/delete.
  • F45: .elc lookup orientation fixed (no more X/Y swap); .elp matching fixed; zero matches no longer wipe coordinates.
  • F46: .locs Cartesian defaults to 85 mm head radius; EOG labels preserved.
  • F43: Non-numeric coordinate fields rejected with a helpful error (eegprep does the correct thing; EEGLAB accepts them).
  • F62 / F70: pop_reref exclude/ref indices are 1-based in the GUI and API; history records 1-based indices.
  • eeg_interp takes 0-based channel indices while pop_interp takes 1-based #569: eeg_interp takes 1-based indices like eeg_interp.m / pop_interp; out-of-range errors name 1..nbchan.
  • F12 / F61: Empty reference state displays as unknown.
  • F49 leftover: pop_chanedit history emits MATLAB cell-array form.

Validation

Unit / CI

  • Focused tests, sample-data checks, offscreen Qt action/navigation checks, pre-commit, Ruff, and changed-module type checks passed.
  • GitHub Actions on head 0d9a2909 green (ubuntu/macOS/Windows, Python 3.12/3.13, EEGLAB Python backend, docs, Claude review check).

F62 live GUI e2e (Tools → Re-reference, exclude 2 6, accept new-dataset)

  • New set committed: #2: reref_excl_26, ref=average, CURRENTSET=2.
  • Channels 2 and 6 unchanged vs pre-reref originals (max_abs=0.0); other channels changed as expected for average reference with those excludes.
  • History: EEG = pop_reref( EEG, [], 'exclude', [2 6]); then pop_newset(..., 'setname', 'reref_excl_26', 'overwrite', 'off', 'savenew', 'on').
  • Screenshots: eegprep committed state + EEGLAB pop_reref with exclude 2 6 (earlier blank EEGLAB shot retaken).

EEGLAB reference suite (jamming, flock; mirrors eeglab-reference.yml)

workflow_dispatch is 403 for this token, so the suite was run on jamming under flock ~/eegprep-bench/matlab.lock with the same shard matrix and pins as the workflow.

Pin Commit
eegprep (stream5-chanlocs) 585a4463d7afa45e4d6434336d2f714a33024a04
EEGLAB (EEGLAB_TESTS_EEGLAB_COMMIT) d0963be9d81acc5b66e84f8d3d7c89e3ce127cc4
eeglab_tests (EEGLAB_TESTS_COMMIT) fec88f9ffe7c225eb1de8924db8b6a3e0d53a4d9
Shard Passed Failed Skipped Notes
heavy 3 0 0 (+29 deselected by -k)
hybrid 143 0 4
stats 257 0 0
study 352 0 27 (+3 deselected by -k)
misc 621 0 9
core 2434 2 14
parity 9 1 2
Total 3819 3 56 3878 collected

Failure analysis (no tolerances loosened):

  1. tests/test_bids_preproc.py::test_crashability_slow / test_end2end (core, 2): On hostname jamming the suite expects a local data/ directory. That path was missing in the Stream 5 worktree, so os.listdir raised instead of skipping. Same host mapping exists on develop; GHA runners are not jamming and set root_path=None so these skip there. Not a Stream 5 code regression.
  2. test_average_reference_matches_matlab_on_64_channel_float32 (parity, 1): max_abs=0.109375 µV vs 1e-5. Reproduced on origin/develop with the same pins and the same max_abs. reref.py is unchanged in this PR; empty-ref average reference does not go through the new 1-based index conversion. Pre-existing float32 BLAS vs MATLAB accumulation difference on this host (scipy-openblas), not introduced by Stream 5. Downstream parity stages that share a Python reref input (clean / interp / etc.) still passed.

Intentional EEGLAB departures (documented)

Listed under Known Differences in docs/source/user_guide/eeglab_migration.rst (pinned EEGLAB pop_chanedit.m / 8ac485f6):

  1. Coordinate validation — EEGLAB str2num+eval accepts non-numeric text; EEGPrep rejects with a field-specific error (F43). Test: test_chanedit_rejects_nonnumeric_coordinates.
  2. Transforms — EEGLAB unrestricted eval; EEGPrep AST-limited numeric assignments only. Tests: test_chanedit_transform_rejects_arbitrary_code (new), happy-path test_chanedit_transform_and_repeated_fields_replay_in_order.
  3. Count mismatch — EEGLAB ignores edits with a console warning; EEGPrep raises and leaves the input unchanged. Tests: test_chanedit_insert_data_channel_count_mismatch_raises (new), test_chanedit_cannot_delete_a_data_channel_or_overwrite_data.

Gap-close on 22cfc64b

  • Dedicated transform rejection + insert count-mismatch tests; migration Known Differences rows for all three departures.
  • GitHub Actions on 22cfc64b were green; superseded by nit-fix head below.

Claude review

Initial review requested changes (nodatchans/datachan, dead _validate_channel_text, fiducial/_is_data_location nit). All addressed on 585a4463; Claude then said Looks good / Safe to merge on code review.
Gap-close re-review of 22cfc64b (run 42406786128): Looks good with two nits (Pow/Constant hang; pin citation).
Nit-fix re-review of 0d9a2909 (Claude Code run 42407932423): Looks good. Both prior nits resolved. Blocking/Important: none. Merge recommendation: Safe to merge on code review (still needs human approval per AGENTS.md). Optional leftover: NumPy RuntimeWarning on (-Y)**0.5 before the ValueError — harmless, no change.

Nit fix on 0d9a2909

  • Transform AST rejects non-numeric / huge Constants and bounds Pow exponents (±12) before exec; regression tests (test_chanedit_transform_rejects_expensive_expressions) finish in <1s.
  • Known Differences rows cite both EEGLAB pins 8ac485f6 and d0963be9 (shared pop_chanedit.m logic/line ranges; verified identical at those ranges).
  • Extra checks (no code change): EEGLAB dialog/help/headrad/tutorial transform corpus all accepted with matching coordinates; GUI count-mismatch shows QMessageBox and keeps the app alive (screenshot pr573_count_mismatch_dialog.png).

Notes

Fixes #550
Fixes #569

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

Copy link
Copy Markdown
Contributor

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


Code review

  • Overall assessment: Needs changes. One blocking problem: pop_chanedit raises on datasets that already have reference locations in nodatchans. The 1-based conversion for pop_reref and eeg_interp is consistent across the API, GUI validation, console replay, CLI, pop_rejchanspec, the fuzz harness and the docs.
  • Highest-risk area: how pop_chanedit merges chaninfo.nodatchans and then checks the location count against the data.
  • Merge recommendation: Needs changes.

Blocking

pop_chanedit fails after a common-reference pop_reref (src/eegprep/functions/popfunc/pop_chanedit.py:557-560, same problem at :77)

  • Cause: _apply_chanedit adds chaninfo["nodatchans"] entries to the location list. It then splits data from non-data channels with loc.get("datachan", True). Entries that EEGPrep creates itself have no datachan key:
    • pop_reref(EEG, 'Cz') stores deep copies of the removed data chanlocs (sigprocfunc/reref.py:108). Those copies have no datachan because eeg_checkchanlocs.py:96 removes it, and eeg_checkset never runs eeg_checkchanlocs again.
    • readegilocs stores raw readlocs fiducial rows.
  • Effect: those entries count as data channels, so the check at line 698 ("location count does not match data channels") fails.
    • Every later pop_chanedit(EEG, 'changefield', ...) raises.
    • Ok in the channel editor also raises, even with no edits.
    • The datachan checkbox shows these reference locations as data channels.
  • Fix: set "datachan": 0 on nodatchans entries when they are merged, in both places.
  • Test: add a regression test that runs pop_reref(EEG, 5) followed by pop_chanedit(EEG, 'changefield', [1, 'labels', 'X']). Inline comment posted. Fix this →

Important

_validate_channel_text in qt.py is now dead code and still assumes 0-based numbers (src/eegprep/functions/guifunc/qt.py:1002, also listed at :101 and :1899)

  • This PR removed its only caller from _validate_pop_reref_dialog. AGENTS.md says: "Remove imports, variables, functions, and files that your change made unused."
  • The function still checks 0 <= index < len(labels), so anyone who reuses it would get the old 0-based validation for a 1-based field.
  • Fix: delete the function and its two registry entries.

Nits

None.

Test gaps

  • pop_chanedit with existing nodatchans: no test runs pop_chanedit on a dataset that already has entries in chaninfo.nodatchans. That is how the blocking issue got through. The test above covers it.

EEGLAB parity notes

  • Numerics need MATLAB reference evidence: convertlocs now uses an 85 mm default sph_radius instead of 1.0 when a location has no radius (F46). That changes core numerical output, and pop_reref/eeg_interp change their public index base. Per AGENTS.md, the PR body needs the EEGLAB reference workflow run (commits and pass/fail/skip counts) before merge. The PR body already says this is in progress.
  • Reference checkout missing: the src/eegprep/eeglab/ reference is not checked out in this CI runner, so I could not compare against convertlocs.m and pop_chanedit.m (headrad scaling and lookup nosedir) line by line. Please confirm these against the pinned EEGLAB commit.
  • Documented deviations are fine: the F43 coordinate validation, the restricted transform syntax and the count-mismatch error are documented in pop_chanedit.md.

Also checked: every in-repo caller of pop_reref and eeg_interp uses the new index base. That covers BIDS preproc, ICLabel features, std_interp, eeg_getdatact, pop_averef, pop_rejchanspec, the CLI channel_tokens(output_base=1) call, and fuzz dispatch_python/MATLAB dispatch. Removing _convert_pop_reref from console replay matches the 1-based history. Moving _zero_based_channels from pop_interp into eeg_interp does not convert indices twice. One limitation: I couldn't run Python in this job (no tool approval), so the blocking issue comes from reading the code. I traced it through reref.py, pop_reref.py and eeg_checkchanlocs.py but did not execute it.

urchans = chanlocs_as_list(eeg.get("urchanlocs")) if eeg is not None else []

for key, value in options.items():
chanlocs.extend(chanlocs_as_list(chaninfo.pop("nodatchans", [])))

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.

Blocking: nodatchans entries without a datachan key are counted as data channels, so pop_chanedit stops working on a dataset after a common reref.

Line 557 adds every chaninfo["nodatchans"] entry to chanlocs. Lines 559-560 then sort them with loc.get("datachan", True). Entries that EEGPrep creates itself usually have no datachan key:

  • pop_reref(EEG, 'Cz') with keepref='off': reref() returns copy.deepcopy(locs[idx]) (sigprocfunc/reref.py:108). _store_removed_ref_channels appends that copy to nodatchans. Data chanlocs have no datachan because eeg_checkchanlocs removes it (eeg_checkchanlocs.py:96), and eeg_checkset never runs eeg_checkchanlocs again.
  • readegilocs puts raw readlocs fiducial rows into nodatchans.

On such a dataset, len(data_locs) == nbchan + n_nodat, so line 698 raises "location count does not match data channels". That happens for any later pop_chanedit(EEG, 'changefield', ...) and for Ok in the channel editor, even when the user changed nothing. The editor's datachan checkbox also shows these reference locations as data channels (line 77 has the same problem).

Suggested fix: mark the entries as non-data when they are merged, here and at line 77:

nodat = chanlocs_as_list(chaninfo.pop("nodatchans", []))
chanlocs.extend({**loc, "datachan": 0} for loc in nodat)

Please also add a regression test that runs pop_reref(EEG, 5) and then pop_chanedit(EEG, 'changefield', [1, 'labels', 'X']).

Copy link
Copy Markdown
Member Author

Addressed Claude's review on head 9ee7fb9a (pushed to stream5-chanlocs):

Blocking — nodatchans without datachan: Fixed. Both merge sites in pop_chanedit now mark merged nodatchans entries with datachan=0. Confirmed locally: pop_reref(EEG, 5) then pop_chanedit(..., changefield=[1,'labels','X']) succeeds. Added regression coverage in tests/test_phase1b_file_edit_pop_functions.py.

Important — dead _validate_channel_text: Deleted the function and its registry entries from qt.py.

MATLAB / GUI evidence (also for the parity note):

  • jamming MATLAB (eeglab('nogui'), pinned eeglab-8ac485f6): lookup_elc Fp1 X=83.9171 Y=29.4367 theta=-19.33; lookup_elp Fp1 X=80.784 theta=-17.926; loadlocs FPz X=84.9812 Z=-1.7863 label EOG1; reref_excl [2 6] preserves ch2/ch6 (maxabs 0); reref_avg ch1 samples match the audit to float32.
  • eegprep GUI on this branch: F36 all 27 action buttons enabled; channel 5 navigates to F4; F12/F61 dialog header shows unknown. Screenshots under /workspace/gui-parity/screenshots/pr573_*.

Retriggering Claude after this push.

@suraj-ranganath
suraj-ranganath marked this pull request as draft November 7, 2026 17:30
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 7, 2026 17:30
@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review (re-review of 3eb17da)

  • Overall assessment: Needs changes. Both findings from the last review are fixed: nodatchans entries are now merged with datachan=0 at both sites (pop_chanedit.py:70, :557), and _validate_channel_text is gone. One new issue: loading a location file that contains fiducials fails.
  • Highest-risk area: the data / non-data split in pop_chanedit._apply_chanedit when the location list comes from readlocs.
  • Merge recommendation: Needs changes (one Important item). It also needs the EEGLAB reference workflow evidence that AGENTS.md requires before merge.

Blocking

None.

Important

pop_chanedit "load" / Read locations raises on files that contain fiducials (src/eegprep/functions/popfunc/pop_chanedit.py:561-562)

  • Cause: the data / non-data split only checks loc.get("datachan", True).
    • readlocs never sets datachan. It marks fiducials (Nz, LPA, RPA, FidNz, FidT9, FidT10, …) as type="FID" instead (readlocs.py:256-258).
    • load replaces the whole location list, so those fiducials are counted as data channels.
  • Effect: a 128-channel dataset plus a GSN .sfp file with 3 fiducials gives 131 data locations. Line 563 then raises "location count does not match data channels". This happens for both pop_chanedit(EEG, 'load', f) and Read locations → Ok.
  • EEGLAB: pop_chanedit.m runs eeg_checkchanlocs after readlocs, which moves FID/ignore into nodatchans. EEGPrep's eeg_checkchanlocs.py:92 already has the same _NO_DATA_TYPES rule.
  • Fix: when datachan is absent, use the type field: fid and ignore are non-data. Alternatively, run the loaded locations through eeg_checkchanlocs.
  • Test: load an .sfp file with 3 fiducials plus N data rows onto an N-channel EEG. Check that nbchan == N and that 3 entries end up in nodatchans.
  • Inline comment posted. Fix this →

Nits

None.

Test gaps

  • load with fiducials: no test covers loading a location file that contains fiducials. The test described above covers it.

EEGLAB parity notes

  • MATLAB evidence in the PR body: the jamming MATLAB checks in the PR comments (lookup orientation, .locs 85 mm radius, reref exclude) cover the numerics this PR changes. AGENTS.md still asks for the formal eeglab-reference.yml run, with its commits and pass/fail/skip counts, in the PR body before human approval.
  • Reference checkout missing: src/eegprep/eeglab/ is not checked out on this runner, so I could not compare convertlocs.m (default sph_radius 85 vs 1 across all *2all paths) or the headrad rescaling line by line.

What I checked

  • 1-based index change across callers: pop_reref, eeg_interp, pop_interp, pop_rejchanspec, CLI channel_tokens(output_base=1), console replay (the _convert_pop_reref removal), GUI validation, and the help text are consistent. No caller converts indices twice or passes 0-based indices.
  • Earlier blocking fix: the nodatchans fix is correct.
  • Editor state handling: checked the replay of ordered editor commands, the sharing of state["displays"] with navigation, and the plot/help resources (pop_readlocs.md, the packaged montage).
  • Limitation: I could not run Python in this job (uv run needs tool approval), so these findings come from reading the code.

Comment on lines +561 to +562
data_locs = [loc for loc in chanlocs if loc.get("datachan", True)]
chaninfo["nodatchans"] = [loc for loc in chanlocs if not loc.get("datachan", 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: Read locations fails on files that contain fiducials.

This split only checks datachan. Locations returned by readlocs never have that key. readlocs does tag fiducials (Nz, LPA, RPA, FidNz, FidT9, FidT10, …) with type="FID" (readlocs.py#L256-L258), but that tag is ignored here. Because load replaces the whole list (L594-L595), the fiducials are counted as data channels.

Example: a 128-channel EGI dataset plus a GSN .sfp file with 3 fiducials gives 131 "data" locations. Line 563 then raises "location count does not match data channels". This happens for pop_chanedit(EEG, 'load', 'GSN.sfp') and for Read locations → Ok in the editor.

EEGLAB handles this case: pop_chanedit.m runs eeg_checkchanlocs after readlocs, which moves FID/ignore types into chaninfo.nodatchans. EEGPrep's eeg_checkchanlocs applies the same _NO_DATA_TYPES rule.

Suggested fix: when datachan is absent, decide data vs. non-data from the type. One way is a small helper used by both lines:

def _is_data_location(loc):
    if "datachan" in loc:
        return bool(loc["datachan"])
    return str(loc.get("type", "")).strip().lower() not in {"fid", "ignore"}

Alternatively, run the loaded locations through eeg_checkchanlocs in the load branch.

Test: load an .sfp file with FidNz/FidT9/FidT10 plus N data rows onto an N-channel EEG. Check that nbchan == N and that the 3 fiducials end up in chaninfo["nodatchans"].

Copy link
Copy Markdown
Member Author

Addressed Claude's Important finding from the 3eb17da re-review on head acbccbc6:

pop_chanedit load / Read locations with fiducials: Fixed. The data/non-data split now uses an _is_data_location helper: an explicit datachan flag wins; otherwise type values fid and ignore are treated as non-data (same rule as eeg_checkchanlocs._NO_DATA_TYPES). Confirmed locally: loading an .sfp with FidNz/FidT9/FidT10 plus 32 data rows onto a 32-channel set keeps nbchan==32 and puts the 3 fiducials in chaninfo["nodatchans"]. Regression added in tests/test_phase1b_file_edit_pop_functions.py.

Retriggering Claude after this push.

@suraj-ranganath
suraj-ranganath marked this pull request as draft November 7, 2026 17:38
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 7, 2026 17:38
@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review (re-review of acbccbc)

  • Overall assessment: Looks good. The fix for loading fiducials is correct. One nit and no new blocking or important issues.
  • Highest-risk area: how pop_chanedit decides which locations hold data and which don't.
  • Merge recommendation: Safe to merge on code review. AGENTS.md still requires human approval and the formal eeglab-reference.yml evidence (commits plus pass/fail/skip counts) in the PR body, because this PR changes core numerics (convertlocs now defaults the radius to 85 mm, and pop_reref/eeg_interp indices are now 1-based).

Blocking

None.

Important

None.

Nits

_is_data_location repeats the no-data type list (src/eegprep/functions/popfunc/pop_chanedit.py:551)

  • The {"fid", "ignore"} literal is a copy of eeg_checkchanlocs._NO_DATA_TYPES, and pop_chanedit already imports from that module.
  • If a no-data type is added later in only one place, the two functions will sort locations differently.
  • Fix: import the shared constant instead of repeating it. Inline comment posted. Committing the suggestion alone won't work: the import on line 18 also needs to change.

Test gaps

None.

  • The new parametrized load test (with and without lookup) covers the fiducial case from the last review.
  • The new type-classification test covers explicit datachan taking priority over type, with mixed-case and whitespace-padded values.

EEGLAB parity notes

None new.

  • The rule now matches EEGLAB: an explicit datachan decides first; otherwise FID/ignore types are non-data. That is what eeg_checkchanlocs does after readlocs in pop_chanedit.m.
  • The same rule now also drives the editor's datachan checkbox (:132, :519) and the lookup output (:758), so the GUI and the API agree.

What I checked

  • The diff 3eb17da..acbccbc against the full _apply_chanedit / _edit_locations flow and eeg_checkchanlocs.
  • nodatchans entries are still forced to datachan=0, so the earlier pop_reref regression stays fixed.
  • Limitation: I didn't run the tests in this job. These findings come from reading the code.

def _is_data_location(loc: dict[str, Any]) -> bool:
if "datachan" in loc:
return bool(loc["datachan"])
return str(loc.get("type", "")).strip().lower() not in {"fid", "ignore"}

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: this repeats eeg_checkchanlocs._NO_DATA_TYPES as a second literal.

The same {"fid", "ignore"} set already lives in eeg_checkchanlocs.py, and this module already imports from it (line 18). If someone adds a no-data type there later, pop_chanedit and eeg_checkchanlocs will sort the same location differently.

AGENTS.md says: "Put magic strings and magic numbers in top-level constants when they are reused or semantically important", and lists "Parallel implementations of existing helpers" as a pattern to avoid. Fix: import the constant. Either make it public (NO_DATA_TYPES) or import the private name, whichever this repo usually does:

Suggested change
return str(loc.get("type", "")).strip().lower() not in {"fid", "ignore"}
return str(loc.get("type", "")).strip().lower() not in NO_DATA_TYPES

(and add NO_DATA_TYPES to the eeg_checkchanlocs import on line 18).

Copy link
Copy Markdown
Member Author

Addressed the remaining Claude nit and the CI failures on head 585a4463:

Nit — _is_data_location duplicated type set: Fixed. pop_chanedit now imports _NO_DATA_TYPES from eeg_checkchanlocs instead of repeating {"fid", "ignore"}.

CI (macos/windows): Two tests asserted pre-parity behavior. Updated expectations only:

  • test_current_eeg_checkchanlocs_...: Cartesian expectations now use the 85 mm default radius from convertlocs.m / F46.
  • test_current_eeglab_execmenu_...: urchan after lookup is 1 (1-based, matching pop_chanedit.m).

Retriggering Claude after this push. Still not merging without Suraj's explicit approval.

@suraj-ranganath
suraj-ranganath marked this pull request as draft November 7, 2026 17:43
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 7, 2026 17:43
@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review (re-review of 585a446)

  • Overall: Looks good. Since acbccbc there are three changes: the nit fix and two updated test expectations. I found no new issues.
  • Recommendation: Safe to merge on code review. Two things are still needed under AGENTS.md before merge:
    • Human approval.
    • Formal eeglab-reference.yml run: put the EEGLAB and eeglab_tests commits and the pass/fail/skip counts in the PR body. This PR changes core numerics (convertlocs default radius of 85 mm) and the public index base of pop_reref and eeg_interp. The jamming MATLAB spot checks in the comments help, but they don't replace this run.

Blocking

None.

Important

None.

Nits

None. pop_chanedit.py:18,551 now imports the shared _NO_DATA_TYPES (frozenset({"fid", "ignore"}), eeg_checkchanlocs.py:32), so pop_chanedit and eeg_checkchanlocs now use the same non-data rule.

Test changes in this push

  • test_admin_data_access_eeglab_tests.py:121: the expected output is now [[1,0,0],[0,0,85],[-85,0,0]].
    • The mixed scale is intended. Fz comes in as Cartesian X=1 and is kept as-is.
    • Cz and Pz come in as polar locations with no radius, so they go through topo→sph→cart with the 85 mm default from convertlocs.m. This matches F46.
  • test_eeglab_execmenu.py:199: after lookup, urchan == 1 is the 1-based value that pop_chanedit.m gives. It matches the rest of the PR's index-base change.
  • Neither test had a tolerance loosened. Only the expected values changed, to match EEGLAB.

Test gaps

None new.

Limitation

I didn't run the tests in this job: the uv run pytest command needed tool approval that I don't have. This review comes from reading the code. CI on this head is the evidence for whether the tests pass.

Copy link
Copy Markdown
Member Author

claude review this

Please re-review head 22cfc64b after the gap-close: dedicated transform rejection + insert count-mismatch tests, and the three Known Differences rows in eeglab_migration.rst.

Copy link
Copy Markdown
Member Author

@claude review

claude review this

Re-review PR head 22cfc64b (gap-close after 585a4463): new tests test_chanedit_transform_rejects_arbitrary_code and test_chanedit_insert_data_channel_count_mismatch_raises, plus three Known Differences rows in docs/source/user_guide/eeglab_migration.rst. CI is green. Please post the usual Overall / Merge recommendation.

@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review (re-review of 22cfc64b)

  • Overall: Looks good. Since 585a4463 this push only adds two tests and three rows to the docs table. Both tests check behavior that already exists, and the docs rows describe that behavior correctly. I found nothing blocking and nothing important. There are two nits below.

  • Merge recommendation: Safe to merge on code review. AGENTS.md still requires human approval because this PR changes core functions (convertlocs now defaults the radius to 85 mm, and pop_reref and eeg_interp now take 1-based indices). The PR body now has the EEGLAB reference run from jamming: 3819 passed, 3 failed, 56 skipped. The explanations for the 3 failures look reasonable to me:

    • Two fail because the data/ directory is missing on the jamming host.
    • One is the float32 average-reference difference, which you also reproduced on origin/develop. reref.py is unchanged in this PR.

    The reviewer should know this run was on jamming, not a workflow_dispatch run, because the dispatch returned 403.

Blocking

None.

Important

None.

Nits

1. The transform check still lets through expressions that hang or use huge memory (src/eegprep/functions/popfunc/pop_chanedit.py:465-487)

  • Cause: the allowlist permits ast.Pow and any ast.Constant, including integers and strings. X=-Y; X=9**9**9**9 passes the AST check, and exec then computes a huge Python integer. That hangs instead of raising ValueError. X='a'*10**9 passes the same way and allocates about 1 GB before _validated_field_value rejects the string.
  • Why it's only a nit: the transform string comes from the local user, who can already run any Python in eegprep-console. So this is not a security boundary. But the new docs row says imports, calls and similar input "raise ValueError without changing the input locations", and these two inputs don't.
  • Fix: allow only int/float constants:
    isinstance(node, ast.Constant) and not isinstance(node.value, (int, float))
    Then either convert constants to float before evaluating, or limit the size of Pow exponents.
  • Fix this →

2. The docs table cites one EEGLAB commit and the reference suite pins another (docs/source/user_guide/eeglab_migration.rst:191,199,206)

  • Cause: the three new rows cite pop_chanedit.m line numbers at EEGLAB 8ac485f6. The reference suite and docs/source/development.rst pin d0963be9.
  • Why it's only a nit: this page already uses 8ac485f6 once (line 53), so the rows follow existing practice.
  • Suggestion: check that the line ranges (681-685, 1119-1124, 599-643, 1095-1110, 485-492) are the same at d0963be9, or say in the text that the line numbers refer to 8ac485f6.
  • I couldn't check this myself: there is no EEGLAB checkout on this runner, and network fetches needed approval.

New tests

  • test_chanedit_transform_rejects_arbitrary_code: good coverage. It tests five kinds of rejected input: import, attribute, call, Python indexed assignment, and MATLAB chans(1)=1, which Python can't parse. Each input comes after a valid X=-Y, so the test also shows that a valid prefix is not applied. It checks that the input chanlocs and data are unchanged. The match regex checks the message wording, including the TMP=X; X=-Y; Y=TMP example.
  • test_chanedit_insert_data_channel_count_mismatch_raises: this tests a documented difference from EEGLAB: inserting a data channel makes the count mismatch raise an error, instead of EEGLAB's warn-and-ignore. It checks that the input is not modified and that the error message points to pop_select and to marking the location as a non-data channel.
  • Both tests are justified under AGENTS.md: they cover rules EEGPrep adds on purpose, which the @eeglab_test suite can't test.

Docs

  • All three new rows are accurate for the code: _validated_field_value, the AST allowlist in _transform_locations, and the count check at pop_chanedit.py:571.
  • They are written for an EEGPrep user and tell the user what to do instead: use pop_select, or mark the location as non-data.

Tests run

  • uv run pytest tests/test_phase1b_file_edit_pop_functions.py -k "transform or count_mismatch": 7 passed, 1 failed.
    • All 6 new test cases passed (5 transform parameters and the count-mismatch test).
    • The one failure is test_chanedit_action_dialog_applies_to_the_current_montage[button_transform_axes…], which raised RuntimeError: PySide6 is required. PySide6 isn't installed in this runner. The test didn't change in this push, and it passes in CI, where the GUI extra is installed.

Copy link
Copy Markdown
Member Author

@claude review

Please re-review head 0d9a2909 after the Claude-nit fix:

  1. Transform AST now rejects non-numeric / huge Constants and bounds Pow exponents before exec (regression tests finish in <1s for power towers and string allocations).
  2. Known Differences rows cite both EEGLAB pins 8ac485f6 and d0963be9 (same pop_chanedit.m logic/line ranges).

Focus on whether those two nits are resolved and whether anything new is Blocking/Important.

@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review (re-review of 0d9a2909)

  • Overall: Looks good. Both nits from the last review are fixed, and I found nothing new that is Blocking or Important.
  • Merge recommendation: Safe to merge on code review. AGENTS.md still requires human approval, because this PR changes core functions (convertlocs default radius, 1-based pop_reref/eeg_interp). The jamming reference-suite evidence is already in the PR body.

Nit 1: transform AST bounds — resolved

_transform_locations (pop_chanedit.py:484-498) now checks the whole tree before compile/exec, so every rejection happens up front:

  • A constant must be exactly int or float. type(...) not in (int, float) also rejects bool, strings, bytes, None and complex numbers.
  • Integer constants must be within ±2**53. Every constant is converted to float and must be finite, so 1e309 is rejected.
  • A Pow exponent must pass ast.literal_eval and lie within ±12. Power towers, variable exponents and computed exponents ((1+1)) all fail before evaluation.
  • OverflowError is now in the caught exceptions, so a nested power such as ((9**12)**12)**12 that overflows in float arithmetic raises the documented ValueError instead of escaping.

I also probed some extra inputs locally. Each one raised the wrapped ValueError in about 1 ms:

Input Result
X=Y**12**12 rejected (exponent is not a literal)
X=Y**(1+1) rejected (exponent is not a literal)
X=2**53*2**53 rejected (exponent 53 > 12)
X, Y = Y, X rejected (Tuple node not allowed)
X=1e300*1e300 evaluates to inf, then _validated_field_value rejects it
X=(-Y)**0.5 evaluates to nan, then _validated_field_value rejects it

Nit 2: EEGLAB pin citations — resolved

All three Known Differences rows (eeglab_migration.rst:189-213) now name both 8ac485f6 and d0963be9 and say the logic and line ranges are the same at both. I could not check the line ranges myself because there is no EEGLAB checkout on this runner, so this relies on your statement. The new text about constants and powers (finite numbers, ±2**53 integers, literal exponents from -12 to 12) matches the code.

Blocking

None.

Important

None.

Nits (optional)

  • NumPy warning: X=(-Y)**0.5 prints NumPy's RuntimeWarning: invalid value encountered in sqrt before the ValueError. It is harmless and does not need a change.
  • Exponent ±13 vs ±12: the large-exponent and negative-large-exponent test cases use ±13, and test_chanedit_transform_accepts_bounded_numeric_powers covers ±12 being accepted. Together they pin both sides of the limit. No change needed.

Tests run

uv run pytest tests/test_phase1b_file_edit_pop_functions.py -k transform: 26 passed, 1 failed.

  • All 14 test_chanedit_transform_rejects_expensive_expressions cases passed, each well under 1 s, and so did all 6 accepts_bounded_numeric_powers cases.
  • The one failure is test_chanedit_action_dialog_applies_to_the_current_montage[button_transform_axes…]. It raised RuntimeError: PySide6 is required because PySide6 is not installed on this runner. This push did not change that test, and it passes in CI, where the GUI extra is installed.

cursoragent and others added 3 commits November 10, 2026 23:49
Co-authored-by: Suraj Ranganath <[email protected]>

# Conflicts:
#	docs/source/changelog.rst
Keep both Stream 11 and Stream 5 changelog entries.

Co-authored-by: Suraj Ranganath <[email protected]>
pop_reref now treats numeric channels as 1-based and subtracts one itself.
pop_biosig still subtracted one before that call, so ref=[2] removed
channel 1 instead of channel 2. The Stream 9 reader expectation matches
the documented 1-based reference.

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

cursor Bot commented Nov 11, 2026

Copy link
Copy Markdown

🤖 @claude review

Please re-review head abf1c8a0 (changes since 0d9a2909), including the merge of origin/develop (#574 and #575) and the pop_biosig 1-based reference fix. CI is green. Please post the usual Overall / Merge recommendation, and flag anything Blocking or Important.

@cursor
cursor Bot marked this pull request as draft November 11, 2026 05:41
@cursor
cursor Bot marked this pull request as ready for review November 11, 2026 05:41

@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.

@suraj-ranganath
suraj-ranganath marked this pull request as draft November 11, 2026 06:34
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 11, 2026 06:34
@claude

claude Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review (re-review of abf1c8a0)


  • Overall assessment: Looks good. The pop_biosig fix is correct, and the develop merge didn't add any caller that still uses 0-based channel numbers.
  • Highest-risk area: importers from Stream 9: Importers and dataset files (F10, F15, F18–F23, F26, F34, F119) #575 that call pop_reref. pop_biosig was the only one.
  • Merge recommendation: Safe to merge on code review. AGENTS.md still requires human approval because this PR changes core functions. The EEGLAB reference run in the PR body was done on 585a4463. The only core-function change since then is the one-line pop_biosig index fix, which I don't think needs a new run. The human reviewer should make that call.

Blocking

None.

Important

None.

Nits

None.

Test gaps

None. tests/test_stream9_readers.py:48-51 runs pop_biosig(..., ref=[2]) and expects channel 2, which is row [1] in the 0-based array, to be subtracted. Before abf1c8a this test would have failed, because pop_biosig subtracted 1 and then pop_reref subtracted 1 again. So the fix already has a regression test.

EEGLAB parity notes

None new. pop_biosig now hands its ref numbers to pop_reref unchanged. The pop_reref helper _channel_index (pop_reref.py:372-383) converts them from 1-based once. That matches pop_biosig.m, which also passes 1-based reference channels to pop_reref. The range check now accepts 1..nbchan, and the error message already says 1-based.

What I checked

  • abf1c8a (pop_biosig.py:79-85): removed the extra - 1 and changed the bounds to 1..nbchan. There is no double conversion left.
  • Callers after the merge: every pop_reref(, eeg_interp( and pop_interp( call in src/ (outside the vendored eeglab/):
    • pop_averef, ICL_feature_extractor and bids_preproc:1019 pass [].
    • bids_preproc:923, std_interp and eeg_getdatact pass chanlocs, not numbers.
    • pop_rejchanspec passes 1-based excludes.
    • The CLI uses output_base=1.
    • menu_actions:1267/1271 (from Stream 11: Main window, menus, datasets, preferences, help #574) go through the GUI path.
    • pop_reref:121 passes interpchan location dicts to pop_interp.
  • Merge resolution in qt.py and console.py:
    • The 1-based _validate_pop_reref_dialog is kept, and _validate_channel_text stays deleted.
    • The _run_dialog_action index_tag update for F36 navigation is kept.
    • Console replay converts pop_select arguments only. pop_reref history is already 1-based.
  • Not done: I didn't run tests in this job. I relied on the green CI you reported for this head.

@suraj-ranganath
suraj-ranganath merged commit be5aecf into develop Nov 11, 2026
14 of 15 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.

eeg_interp takes 0-based channel indices while pop_interp takes 1-based [Release readiness] Stream 5: Channel locations and re-reference

2 participants