Skip to content

[eeg_lat2point] Scale the out-of-range tolerance as EEGLAB does - #879

Merged
arnodelorme merged 2 commits into
developfrom
agent/issue-867
Nov 29, 2026
Merged

arnodelorme merged 2 commits into
developfrom
agent/issue-867

Conversation

@arnodelorme

@arnodelorme arnodelorme commented Nov 29, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #867.

Approval (Arno Delorme by email on November 29, 2026, after merging EEGLAB pull request 1002, eeg_lat2point: round-off tolerance, so pop_select no longer keeps the last sample at 250, 500 and 1000 Hz, commit 579a27d0d: sccn/eeglab#1002):

"Yes, put the same tolerance in EEGPrep 1a"

On recordings longer than 8,192 samples at 250, 500, and 1000 Hz, eeg_lat2point.py used a fixed tolerance of 1e-12 point, which is smaller than one floating-point eps of the sample count. It flagged the last sample as out of range, pop_select.py dropped the final rejection region, and the last sample was kept although it was not requested. This pull request ports the exact scaled tolerance, in-tolerance clamping, and NaN handling of the merged EEGLAB eeg_lat2point.m.

Example (100,000 samples at 250 Hz, EEG.data = 0:99999)

pop_select(EEG, point=[2, 99999]) Samples returned Start of last rejection region in eeg_lat2point flag
EEGLAB develop (579a27d0d, MATLAB R2025b) 99,998 (2 to 99999, as requested) 100000.00000000001 clamped to 100000 0
EEGPrep develop (e435f436) 99,999 (2 to 100000, last sample kept) 100000.00000000001 (1.46e-11 > 1e-12) 1
this pull request (5edd0e1a) 99,998 (2 to 99999, as requested) 100000.00000000001 clamped to 100000 0

Comparison with EEGLAB develop (579a27d0d, MATLAB R2025b)

Test set Calls Differ on develop (e435f436) Differ on this pull request
Short point ranges ([a, b] on 10 and 37 samples across 13 rates, 100 to 30,000 Hz) 9,243 0 0
Long point ranges (30,504 to 122,882 samples across 7 rates, 128 to 4096 Hz) 280 9 0
Extra-long and offset recordings (1 h at 250/500/1000 Hz, 10M samples, xmin = -10, 123.45, 1000 s) 75 21 0
Direct eeg_lat2point calls (random, boundary, out-of-range, outrange 1 and 0, NaN/Inf, overflow) 6,740 112 0 (max_ulp_diff = 0)
Multi-range and single-sample calls (10 samples at 5 rates) 135 15 15 (keep-range ordering/overlap in pop_select, unchanged)

Histogram: samples kept by EEGLAB develop (579a27d0d) minus samples kept by EEGPrep

Kept-sample difference (EEGLAB - EEGPrep) 9,243 short (before -> after) 280 long (before -> after) 75 extra-long/offset (before -> after)
-1 (EEGPrep kept one extra trailing sample) 0 -> 0 9 -> 0 21 -> 0
0 (exact match) 9,243 -> 9,243 271 -> 280 54 -> 75
+1 0 -> 0 0 -> 0 0 -> 0

EEGLAB reference run (rule of pull request #860)

  • Run on the head 5edd0e1a: all seven jobs passed. Workflow run https://github.com/sccn/eegprep/actions/runs/46289988718 (EEGLAB reference, MATLAB backend, started by hand on this branch), EEGLAB d0963be9 and eeglab_tests fec88f9f. 4,610 tests passed, 0 failed, 58 skipped, in 35 minutes. Per job: core 3,180 passed and 17 skipped, misc 676 and 8, study 341 and 27, stats 257, hybrid 143 and 4, parity 10 and 2, heavy 3.
  • The EEGLAB that this workflow pins (d0963be9) is 35 commits older than the merged fix 579a27d0d, so this run shows that nothing else moved. The agreement with fixed EEGLAB is the comparison above, run locally in MATLAB R2025b on develop 579a27d0d.
Cause, tolerance, and non-finite handling

eeg_lat2point computes newlat = (lat_array * timeunit - timewin_sec[0]) * srate + 1 + (epoch_array - 1) * pnts and compares it against max_valid = max(epoch_array * pnts). Because 1 / srate is not exact in binary floating point at rates such as 250, 500, and 1000 Hz, a latency at the last sample can evaluate 1 to 3 eps above max_valid. Above 8,192 samples, one eps exceeds 1e-12.

This pull request mirrors lines 107 to 123 of EEGLAB functions/popfunc/eeg_lat2point.m (579a27d0d):

  • Scaled tolerance capped at half a sample: min(16 * eps(max(max_valid, max(abs(timewin_sec)) * srate)), 0.5), implemented with np.spacing(abs(scale)) and np.fmax / np.fmin. On 100,000 samples at 250 Hz the tolerance is 2.33e-10 point, on 1 hour at 1000 Hz (3,600,000 samples) it is 7.45e-9 point, and on 10,000,000 samples it is 2.98e-8 point. A point one millionth of a sample past the end (1e-6) is still flagged at every tested length.
  • Clamping inside the tolerance: points in (max_valid, max_valid + tol] are set to max_valid without setting flag = 1, without logging a warning, and without raising when outrange=0, matching EEGLAB (develop left those values slightly above max_valid, causing 44 bit-level differences on direct calls).
  • Non-finite and overflow parity: MATLAB max and min omit NaN by default, so min(16 * eps(Inf), 0.5) evaluates to 0.5 when timewin_sec * srate overflows, and a NaN latency or epoch no longer suppresses detection of another out-of-range point in the same call. Using np.fmax.reduce and np.fmin inside np.errstate(over='ignore', invalid='ignore') reproduces MATLAB's results across all NaN, Inf, and overflow inputs with zero RuntimeWarnings.
Verification and regression tests
  • Fresh MATLAB R2025b run on a clean worktree of sccn/eeglab origin/develop (579a27d0d) confirmed byte-for-byte agreement with after2_1.tsv through after2_7.tsv and after2_multi.tsv from the EEGLAB parity run.
  • Added regression tests in tests/test_eeg_lat2point.py matching sccn/eeglab_tests pull request 17 (pass_roundoff.m, Tests for the last sample in eeg_lat2point and pop_select eeglab_tests#17) and the long-recording failure of eeg_lat2point: the fixed tolerance of 1e-12 point is too small above 8,192 samples (last sample kept at 250, 500 and 1000 Hz) #867:
    • eeg_lat2point on 10 and 100,000 samples at 250, 500, and 1000 Hz (flag == 0, exact float(n) returned, no warning, outrange=0 accepted, and mixed near/out-of-range call flagged).
    • eeg_lat2point on 100,000 samples at 250 Hz with points 1e-6 sample and 1 full sample past the end (flag == 1, ValueError with outrange=0).
    • eeg_lat2point with huge time origin [1e12, 1e12 + 1], overflowing timewin * srate ([1e306, 1e306 + 1e291]), and [NaN, 0.05].
    • pop_select(EEG, point=[2, 99999]) on 100,000 samples at 250 Hz returning 99,998 samples (1 through 99998 of 0:99999).
  • Local checks: pytest -Werror tests/test_eeg_lat2point.py (10 passed), pytest tests/test_eeg_lat2point.py --eeglab-backend=python (16 passed), tests/test_pop_select.py and tests/test_eeg_eegrej.py (53 passed, 2 MATLAB-engine skipped), ruff check, ruff format --check, ty check, and ./pre-commit.py --changed-from origin/develop all pass.

— orchestrator

Use 16*eps(max(max_valid, max(abs(timewin_sec))*srate)) capped at 0.5, clamp points within the tolerance to max_valid without flagging, and match MATLAB max/min NaN handling, as merged in sccn/eeglab#1002. Fixes #867.

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

Copy link
Copy Markdown
Contributor

Claude finished @arnodelorme's task in 38s —— View job


Code review

  • Overall assessment: Looks good. The change matches EEGLAB functions/popfunc/eeg_lat2point.m at 579a27d0d (lines 107–123) line for line, and I found no correctness issues.
  • Highest-risk area: Handling of NaN, Inf and overflow in the tolerance calculation in eeg_lat2point.py:72-76. I checked it and it matches MATLAB.
  • Merge recommendation: Safe to merge once the EEGLAB reference workflow run (46289988718) finishes and its counts are added to the PR body. This changes core numerics, so AGENTS.md also requires human approval. The approval quoted from Arno covers that.

Blocking

None.

Important

None.

Nits

None.

Test gaps

None. The new tests in tests/test_eeg_lat2point.py cover:

EEGLAB parity notes

None. What I checked against eeg_lat2point.m@579a27d0d:

  • Max of the valid range: MATLAB max((epoch_array(:))*pnts) ignores NaN. The PR's np.fmax.reduce(...) does the same.
  • Tolerance: MATLAB computes tol = min(16*eps(max([maxpnt abs(timewin(:)')*srate])), 0.5).
    • np.fmax/np.fmax.reduce ignore NaN like MATLAB max.
    • np.spacing(abs(x)) equals MATLAB eps(x), including eps(0), and eps(Inf) gives NaN in both.
    • np.fmin(nan, 0.5) gives 0.5, like MATLAB min(NaN, 0.5).
  • Out-of-range check: MATLAB max(newlat(:)) > maxpnt + tol ignores NaN. The PR's np.fmax.reduce(newlat.ravel()) does too, so one NaN latency no longer hides another point that is out of range.
  • Points inside the tolerance: MATLAB's else branch newlat(newlat > maxpnt) = maxpnt is ported as-is. These points are clamped with no flag, no message, and no error when outrange=0.
  • Comments: the only new comment cites the .m line range and explains the MATLAB NaN semantics, so it is allowed under AGENTS.md §Comments.
  • Changelog: docs/source/changelog.rst has an entry for the change.

The vendored src/eegprep/eeglab/ checkout is not in this CI checkout, so I fetched the reference .m from sccn/eeglab@579a27d0d instead. I could not run pytest here because the command needed approval. The PR body reports pytest -Werror tests/test_eeg_lat2point.py and the pop_select/eegrej suites passing locally.

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

@arnodelorme

Copy link
Copy Markdown
Collaborator Author

Code review

Independent review by Codex (OpenAI gpt-6.1-terra, high effort), asked by the orchestrator, which wrote this pull request on Google Gemini (Gemini 4 Carbon (High)). Codex reviewed commit 5edd0e1a in a read-only sandbox with no network access and found no blocking defect and no code defect. Its full text is folded below.

What was done with the findings

  • Important, verify MATLAB reference and preprocessing parity evidence before merge: addressed by the parity runs and workflow run. Inside its read-only sandbox Codex had neither network nor MATLAB access, so it could not read the pull request body or execute MATLAB. First, commit 5edd0e1a was verified locally against a clean worktree of EEGLAB origin/develop (579a27d0d) in MATLAB R2025b, matching in all 9,243 short ranges, all 280 long calls, all 75 extra-long and offset calls up to 10,000,000 samples, and all 6,740 direct eeg_lat2point calls (max_ulp_diff = 0), and the full 7-shard eeglab-reference.yml workflow on commit 5edd0e1a is running at https://github.com/sccn/eegprep/actions/runs/46289988718. Second, the 7-step preprocessing pipeline of sccn/eegprep_parity_test never calls eeg_lat2point (pop_select is called there only with channel or nochannel, and clean_windows calls eeg_eegrej directly), while the Reference (parity) shard of workflow run 46289988718 also runs the ds003061 stage parity suite.
  • Test gaps (exact tolerance boundary, negative/zero scales, NaN/Inf in epochs and time limits, empty and 2D shapes): left as is. AGENTS.md asks only for minimal regression tests rather than extra coverage tests. The four new test functions in tests/test_eeg_lat2point.py already cover 10 and 100,000 samples at 250, 500, and 1000 Hz, outrange=1 and outrange=0, the 0.5 cap on [1e12, 1e12 + 1], timewin * srate overflow on [1e306, 1e306 + 1e291], [NaN, 0.05], and pop_select(EEG, point=[2, 99999]) on 100,000 samples, and Codex confirmed that scalar, empty, single-element, and 2D inputs preserve expected shapes and float dtype. Non-finite epochs and time limits were also checked directly against MATLAB R2025b in the 6,740-call comparison with 0 differences. The pre-existing 0.0 * inf warning on infinite timewin lies outside the changed range-check block and was left untouched to keep the diff minimal.
Codex's review

Blocking

None.

Important

MATLAB reference evidence remains unverified. This numerical change requires a run against the pinned EEGLAB and eeglab_tests commits before merge. The preprocessing chain also requires an eegprep_parity_test run. GitHub was unreachable, so I could not check whether the PR already reports those results or whether its live head still matches the reviewed commit.

Nits

None.

Test gaps

The new tests cover the reported regression at all three sampling rates, strict and default out-of-range handling, a large time origin, overflow, and a NaN latency. They do not directly test the exact tolerance boundary, the half-sample cap, negative or zero scales, or NaN and Inf in epochs and time limits. Add targeted cases for those behaviors and for empty and 2D inputs.

The two empty-array guards prevent empty reductions. Local checks preserved the expected shapes and float dtype for the scalar, empty, single-element, and 2D cases checked. An infinite time limit still emits a NumPy invalid-multiply warning in the pre-existing calculation.

The changed tolerance logic matches the specified MATLAB reference for the cases inspected. The changed files are within the requested scope. A local comparison confirmed that the long-recording regression tests distinguish this commit from origin/develop. MATLAB itself was not available for a parity run.

Merge recommendation: Needs changes until the required parity evidence is verified.

— orchestrator

@arnodelorme

Copy link
Copy Markdown
Collaborator Author

Arno confirmed by email on November 29, 2026 ("So Python and EEGLAB agree, right? That's the case just merge.") after merging sccn/eeglab pull request 1002: sccn/eeglab#1002

Merged develop (commit 967a429) into agent/issue-867 (commit d679adf) to resolve the changelog entry conflict with pull request 797, verified that Documentation Build and Pre-commit checks pass on d679adf alongside the full test and EEGLAB reference runs on commit 5edd0e1, and merged this pull request into develop.

— orchestrator

@arnodelorme
arnodelorme merged commit 487ce5d into develop Nov 29, 2026
12 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_lat2point: the fixed tolerance of 1e-12 point is too small above 8,192 samples (last sample kept at 250, 500 and 1000 Hz)

1 participant