Skip to content

Stream 4: Signal processing - #560

Merged
suraj-ranganath merged 11 commits into
developfrom
cursor/stream-4-signal-processing-ddd0
Nov 6, 2026
Merged

suraj-ranganath merged 11 commits into
developfrom
cursor/stream-4-signal-processing-ddd0

Conversation

@suraj-ranganath

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

Copy link
Copy Markdown
Member

Refs #549

Signal-processing numerics for the release-readiness audit (F58, F59, F60, F69, F91, F92, F126), plus the pop_interp index-base part of F70. 8ac485f6 is the GUI comparison pin. The numerical oracle and the jamming run use d0963be9. Where that tree is wrong, EEGPrep keeps the correct behaviour and a test records the difference.

Findings

Finding Root cause Fix Test
F58 plotfresp required bit-identical coefficient reversal (plotfresp.m:67). A 1 Hz Hamming highpass is linear-phase but not bit-identical, so the default frequency-response plot raised. Use the same symmetric/antisymmetric allclose test as fir_filterdcpadded. The error names plotfresp and the fix. test_f58_plotfresp_accepts_windowed_sinc_onepass_zerophase, test_f58_pop_eegfiltnew_frequency_response_plot_opens
F59 A GUI full range is a list, so it never equalled the (xmin, xmax) tuple, and the restore used floor(t*srate) through pnts-2 (eeg_interp.m:322). The second-to-last sample stayed original, the range endpoint was excluded, and the final sample stayed interpolated. Inclusive EEG.times (milliseconds), continuous and epoched. A range equal to [xmin, xmax] does not restore. Channel-location structures are not restored (eeglab#980). A partial range requires EEG.times of length pnts; otherwise eeg_interp raises and names eeg_checkset. test_f59_full_range_list_does_not_restore_the_second_to_last_sample, test_f59_gui_empty_time_field_matches_unrestricted_interpolation, test_f59_partial_range_includes_both_endpoints_and_keeps_the_final_sample, test_f59_epoched_range_restores_every_trial, test_f59_channel_location_structure_is_not_restored_outside_the_range, test_eeg_interp_time_range_requires_sample_times
F60 Pinned pop_interp.m:61 sets t_range = '', so a scripted range interpolates the whole recording. EEGPrep already honoured the range. No behaviour change. Documented in pop_interp help. test_f60_pop_interp_honours_a_scripted_time_range (cites pop_interp.m:61). MATLAB: test_f60_pinned_pop_interp_discards_the_fourth_argument
F69 Extended kurtosis used randint and m2 + 1e-10. runica.m:890-903 uses fix(rand*datalength) on the same MT19937 stream and (m4./m2)-3. The default 6-output sort used activation energy; runica.m:1472 and :1519 use sphered-channel energy unless posact is on. Kurtosis columns and the division match those lines. Sort energy matches line 1519. test_f69_kurtosis_subset_uses_fix_rand_on_the_twister_stream pins rand('twister',5489); fix(rand(1,17)*30504). MATLAB: test_f69_runica_short_run_matches_pythoncompat
F91 newcrossf left freqs unset, so timefreq ran to Nyquist (6–64 Hz, 30 bins at 128 Hz, padratio 1). newcrossf.m:396-397 defaults to [0, 50]. Default [0, 50], maxfreq replaces that upper limit, and a log scale lifts a zero lower edge to 3 Hz (newcrossf.m:461). test_f91_newcrossf_default_frequencies_stop_at_50_hz, test_f91_newcrossf_log_scale_lifts_a_zero_lower_edge_to_3_hz
F92 Dialog limits and the prestimulus window truncated toward zero. MATLAB int2str rounds, halves away from zero (pop_newcrossf.m:87, pop_newtimef.m:172, pop_newtimef.m:292). Both use round_mat. 0.9996 s is 1000 ms, and xmin -0.1 s at 256 Hz is a 26-sample window. test_f92_dialogs_round_epoch_limits_half_away_from_zero, test_f92_prestimulus_window_rounds_half_away_from_zero
F126 data_time_slice dropped the sample after the truncated limit and passed the kept sample times into newtimef. pointrange used np.round, which sends a half to even, so [25 800] ms at 100 Hz starts at sample 2. pop_newtimef.m:305-306 uses round, which sends that half to sample 3, and passes the requested limits. Pinned pop_newcrossf.m:189 omits the +1 and drops the last sample. Both wrappers use plot_utils.pointrange with round_mat and pass the requested limits. The pop_newcrossf difference is documented in the help text and changelog. test_pointrange_half_sample_starts_at_sample_3, test_f126_pop_newtimef_keeps_the_last_sample_and_a_prestimulus_baseline, test_f126_pop_newcrossf_keeps_the_end_sample_pinned_eeglab_drops
MATLAB round ties The same banker's tie remained at the other ports of MATLAB round and int2str: time-warp frames, the envtopo window, dftfilt tapers, spectopo percent and window length, scroll-window bounds, rejection regions, the joint-probability trim, scalp-map and epoch dialogs, and epoch latencies. Those sites use round_mat. Display rounding, GUI pixel math, and pop_rejcont's early window length stay as they were. Pinned pop_rejcont.m does not round those lengths. One half-sample test per site. The changelog lists the EEGLAB line each one mirrors.
newtimef time count The F91/F126 newtimef call already passed the same frames, limits, sampling rate, cycles, and padratio to both sides. timefreq dropped indices that round to the same sample, so ERSP was (4, 104). timefreq.m gettimes only uniques when length(timeindices) < length(unique(timeindices)), which never happens, so EEGLAB returns 111 times. Keeping those repeats exposed the value gap: np.linspace differed from MATLAB linspace by 1 ULP at 26 of 111 points and flipped five half-sample ties (20, 72, 77, 79, 106). Position 20 is in the baseline, so every ERSP row took a constant dB offset (max abs about 8 dB). Keep every in-range index, including repeats. Space timevect and the requested times as start + i * (stop - start) / (n - 1), then set the last point to the end. Shared helper: eegprep.functions.miscfunc.linspace. Rounding stays floor(points + 0.5) - 1. test_newtimef_keeps_repeated_sample_times, test_linspace_matches_matlab_values, test_linspace_keeps_matlab_half_sample_ties
F70 (this stream) Programmatic pop_interp indices were 0-based, unlike pop_interp.m. Integers are 1-based. Channel 1 is the first channel. The GUI still stores 0-based picks and converts them at this boundary. test_pop_interp_channel_indices_are_one_based

Outside this stream's files

src/eegprep/functions/adminfunc/console.py (stream 11): stopped subtracting 1 when replaying pop_interp channel lists, so history stays 1-based. One expression. tests/test_console_workspace.py expectation updated.

Existing tests updated because the behaviour changed: tests/test_pop_interp.py, tests/test_sample_data_pop_functions.py, tests/test_eeg_interp.py (partial-range parity no longer requires the pinned floor window), tests/test_phase4_timefreq_statistics.py (time-warp markers on the requested limits).

MATLAB reference run

Run on 1ebbad27 on jamming, MATLAB R2025b, EEGLAB d0963be9: 2153 tests, 1 failure. The failure is the known R2025b pop_reref float32 average-reference case (max abs 0.109375). Stream 4 had 22 passed. Time-frequency parity had 63 passed. assert_matlab_near uses the existing suite epsilon 1e-4. No tolerance was added or loosened.

On e7599269, jamming confirmed the hard-coded kurtosis oracle matches MATLAB exactly. Stream 4 had 23 passed. Time-frequency parity had 63 passed.

uv run --no-sync pytest \
  tests/test_stream4_signal_processing.py::test_f91_f126_time_frequency_matches_eeglab \
  tests/test_stream4_signal_processing.py::test_f60_pinned_pop_interp_discards_the_fourth_argument \
  --eeglab-backend=matlab \
  --eeglab-root=<eeglab checkout at d0963be9> \
  --eeglab-suite-root=<eeglab_tests checkout>
  • test_f91_f126_time_frequency_matches_eeglab: each newcrossf signal is a row vector whose length is frames times the trial count (newcrossf.m returns before assigning R when min(size(X)) is not 1). Plotting is off with plotamp and plotphase (plotersp and plotitc are ignored). nargout is 4, which assigns R, mbase, timesout, and freqs. The comparison is still the frequency axis at the existing epsilon. newtimef ERSP/ITC still uses plotersp/plotitc/verbose off, with the same frames, limits, sampling rate, cycles, padratio, and baseline as EEGPrep. The time grid now follows MATLAB linspace, which on jamming made all 111 indices match and brought ERSP max abs to about 4.4e-15.
  • test_f60_pinned_pop_interp_discards_the_fourth_argument: the EEG is eeg_emptyset, then filled. chaninfo, reject, and etc are scalar structs (an empty dict survives savemat as a non-struct, and eeg_checkset.m then dot-indexes them). chanlocs is a struct array. The assertion is unchanged: pinned pop_interp.m:61 makes a ranged call equal the full interpolation.
  • test_f69_runica_short_run_matches_pythoncompat: extended 0 and 1, maxsteps 2, full-rank 4×300, rndreset off, pythoncompat on. Weights and sphere. This run, with test_parity_sample_data_extended_ica_initial_sphere, confirms the sphered-channel energy sort.
  • test_parity_custom_time_range: inside the inclusive window, Python matches a full MATLAB eeg_interp; the final sample stays original in Python and interpolated in pinned eeg_interp.m:322.
  • test_parity_sample_data_extended_ica_initial_sphere: existing one-step extended ICA sphere, signs, and learning rates, now with the kurtosis and sort changes.

Follow-ups

Remaining np.linspace call sites: timefreq frequency grids, newtimef full_times, dftfilt2/dftfilt3, dataset times rebuilds, and rejtrend. pop_interp indices are 1-based while eeg_interp integer indices are still 0-based.

Not closed by the local run

Raw tutorial runica matches MATLAB (|r| about 1.0). The average-referenced rank-31 sphere gap is pre-existing on develop and is out of scope.

The research comment on issue 549 was not posted: the token cannot addComment.

Open in Web Open in Cursor 

Frequency-response plots accept the same linear-phase FIR filters the
zerophase filter already runs. Interpolation time ranges use inclusive
EEG.times, including epochs. runica kurtosis follows fix(rand) and the
default sort uses sphered-channel energy. Cross-coherence stops at 50 Hz,
dialog limits truncate like int2str, and time-frequency calls keep
EEGLAB's sample window and requested limits.

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

claude Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Claude encountered an error after 0s —— View job


I'll analyze this and get back to you.

cursoragent and others added 4 commits November 6, 2026 01:33
Pinned pop_newcrossf.m line 189 drops the last sample; EEGPrep keeps the inclusive end used by pop_newtimef. The MATLAB newcrossf comparison turns every plot flag off so R is assigned, and the pinned pop_interp comparison starts from an eeg_checkset-clean EEG.

Co-authored-by: Suraj Ranganath <[email protected]>
newcrossf takes a vector and turns plotting off with plotamp and plotphase, then returns R through freqs. The interpolation oracle starts from eeg_emptyset and passes chaninfo, reject, and etc as structs so eeg_checkset can index them.

Co-authored-by: Suraj Ranganath <[email protected]>
timefreq dropped sample indices that rounded to the same point, so a
128-sample epoch returned 104 times instead of EEGLAB's 111. gettimes
never takes that unique branch.

Co-authored-by: Suraj Ranganath <[email protected]>
np.linspace moved 26 of 111 output times by one ULP and flipped five
half-sample ties, including one in the baseline.

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

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

Copy link
Copy Markdown
Contributor

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


Code review

  • Overall assessment: No blocking problems in the diff. I checked the 1-based conversion in pop_interp (the GUI picks, the console history replay, and the pop_reref caller, which passes chanloc dicts and is unaffected), the restore window in eeg_interp, including the C-order (nbad, pnts·trials) reshape for epoched data, the inclusive sample windows in pop_newtimef/pop_newcrossf, the fix(rand) kurtosis subset and sort-energy change in runica, the newcrossf frequency defaults, and the timefreq change that keeps repeated time indices.
  • Highest-risk area: the core numerics in runica, timefreq and eeg_interp. None of the MATLAB oracles were re-run.
  • Merge recommendation: needs changes. They are small, and the EEGLAB reference run is still required by AGENTS.md before merge.

Blocking

None.

Important

  • Duplicated window helpers. _dialog_msec, _requested_tlimits and _pointrange are copied between pop_newtimef.py:239-269 and pop_newcrossf.py:168-198. end_offset is only ever passed 1.0. Keeping these two wrappers on the same inclusive window is the point of F126, so a single helper in plot_utils.py should own it. (Inline comment.)
  • EEGLAB reference run not done. This PR changes core processing in runica, timefreq, eeg_interp and newcrossf. Per AGENTS.md, trigger .github/workflows/eeglab-reference.yml on this branch, or run the suite locally with --eeglab-backend=matlab, and add the counts and commits to the PR body. The description also mixes two EEGLAB commits: the pinned tree is 8ac485f6, but the oracle traces cite d0963be9. Please say which one the reference run used.

Nits

  • plotfresp._linear_phase_fir (plotfresp.py:61-69) repeats the check in fir_filterdcpadded.py:64-65. Sharing one helper would keep them in sync, and the odd/even split isn't needed. (Inline comment.)
  • eeg_interp._sample_times_ms (eeg_interp.py:190-203) quietly falls back to a regenerated linspace whenever EEG['times'] is missing, has the wrong length, or has the wrong span. eeg_checkset keeps times consistent, so this is defensive code for a state that shouldn't happen. Either use EEG['times'] directly or raise a clear error.

Test gaps

  • test_f69_kurtosis_subset_uses_fix_rand_on_the_twister_stream rebuilds the expected value with the same algorithm as _kurtosis_columns, so it can't catch an off-by-one or a wrong RNG draw order. Hard-code the MATLAB fix(rand(1,17)*30504) output for seed 5489 instead. (Inline comment.)
  • I couldn't run pytest here (the job's tool permissions blocked uv run pytest), so these results come from reading the code only. Please confirm that CI is green on 1ebbad2.

EEGLAB parity notes

  • Deliberate deviations from the pinned tree:

    • pop_newcrossf keeps the +1 end sample, which pinned pop_newcrossf.m:189 drops.
    • A scripted t_range is honoured, which pinned pop_interp.m:61 discards.
    • Epoched data is restored outside t_range. Pinned eeg_interp.m only restores continuous data.
    • plotfresp uses an allclose symmetry test where plotfresp.m:67 checks for bit-exact symmetry.

    Each one is documented in the help files and changelog and has a test. That is in line with AGENTS.md ("choose the simpler maintainable implementation and document the tradeoff").

  • Index base differs between functions (follow-up, outside this PR). pop_interp now takes 1-based indices like EEGLAB, but the public eeg_interp still takes 0-based integer indices. EEGLAB's eeg_interp.m is also 1-based, so eeg_interp(EEG, [1]) and pop_interp(EEG, [1]) now interpolate different channels. If the rest of F70 doesn't cover eeg_interp, it should get a tracking issue.

  • runica sort energy. projected_energy is taken from data before sphere @ rowmeans is added back (runica.py:1249-1252). I can't check that ordering against runica.m:1519 here because the EEGLAB sources aren't vendored on this runner. Please confirm it in the MATLAB run of test_f69_runica_short_run_matches_pythoncompat and test_parity_sample_data_extended_ica_initial_sphere.


  • Load review playbook
  • Read diff against origin/develop
  • Review correctness / EEGLAB parity
  • Post review (3 inline comments)

Comment on lines +239 to +269
def _dialog_msec(seconds: Any) -> str:
return str(int(np.trunc(float(seconds) * 1000.0)))


def _requested_tlimits(EEG: dict[str, Any], tlimits: Any) -> np.ndarray:
bounds = numeric_vector(tlimits)
if bounds.size == 2:
return np.asarray([float(bounds[0]), float(bounds[1])], dtype=float)
return np.asarray(
[float(EEG.get("xmin", 0) or 0) * 1000.0, float(EEG.get("xmax", 0) or 0) * 1000.0],
dtype=float,
)


def _pointrange(EEG: dict[str, Any], tlimits: Any, *, end_offset: float, function: str) -> slice:
pnts = int(EEG.get("pnts") or np.asarray(EEG["data"]).shape[1])
bounds = numeric_vector(tlimits)
if bounds.size != 2:
return slice(0, pnts)
xmin = float(EEG.get("xmin", 0.0) or 0.0)
srate = float(EEG.get("srate", 1.0) or 1.0)
first = int(np.round(max((float(bounds[0]) / 1000.0 - xmin) * srate, 1.0)))
last = int(np.round(min((float(bounds[1]) / 1000.0 - xmin) * srate + end_offset, float(pnts))))
if last < first:
raise ValueError(
f"{function}: time limits [{float(bounds[0]):g} {float(bounds[1]):g}] ms contain no samples "
f"at {srate:g} Hz (xmin {xmin:g} s, {pnts} points). "
"Widen the limits so they cover at least one sample."
)
return slice(first - 1, last)

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 / AGENTS.md): _dialog_msec, _requested_tlimits, and _pointrange are copied almost line for line into pop_newcrossf.py (L168-198). The only difference is that pop_newcrossf._pointrange hard-codes + 1.0 and its own function name. Here end_offset is only ever called with 1.0 (L272), so the keyword is configurability nothing uses. AGENTS.md lists "Parallel implementations of existing helpers" and "speculative configurability" as failure patterns.

The PR's main goal is to keep the two wrappers on the same inclusive window, and that is exactly the part that can drift if one copy changes and the other doesn't.

Fix: move a single pointrange(EEG, tlimits, function) (with +1 fixed), requested_tlimits, and dialog_msec into plot_utils.py. data_time_slice already lives there. Import them in both wrappers and drop end_offset.

Comment on lines +61 to +69
def _linear_phase_fir(b: np.ndarray) -> bool:
if b.size % 2 == 0:
return bool(np.allclose(b, b[::-1]) or np.allclose(b, -b[::-1]))
group_delay = (b.size - 1) // 2
if group_delay == 0:
return True
symmetric = np.allclose(b[:group_delay], b[:group_delay:-1])
antisymmetric = np.allclose(b[:group_delay], -b[:group_delay:-1]) and np.isclose(b[group_delay], 0.0)
return bool(symmetric or antisymmetric)

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 (duplication): the odd-length branch repeats the symmetric/antisymmetric check in fir_filterdcpadded.py L64-65 (

if not causal:
is_sym = np.allclose(coeffs[:group_delay], coeffs[:group_delay:-1])
is_antisym = np.allclose(coeffs[:group_delay], -coeffs[:group_delay:-1]) and np.isclose(coeffs[group_delay], 0)
if not (is_sym or is_antisym):
). The PR description says the two are meant to use the same test, so a shared helper would stop them drifting apart. Move a single is_linear_phase_fir(b) into a small firfilt private module (or into fir_filterdcpadded.py) and call it from both places.

The odd/even split is also unnecessary. For odd lengths, np.allclose(b, -b[::-1]) already forces the center tap to about 0, so np.allclose(b, b[::-1]) or np.allclose(b, -b[::-1]) is enough for every length. The only exception is the group_delay == 0 single-tap case.

Comment thread tests/test_stream4_signal_processing.py Outdated
Comment on lines +229 to +240
def test_f69_kurtosis_subset_uses_fix_rand_on_the_twister_stream():
datalength = 30504
kurtsize = 17
got = _kurtosis_columns(np.random.RandomState(5489), datalength, kurtsize)
rng = np.random.RandomState(5489)
expected = np.fix(rng.rand(kurtsize) * datalength).astype(np.int64)
while np.any(expected == 0):
missing = expected == 0
expected[missing] = np.fix(rng.rand(int(np.count_nonzero(missing))) * datalength).astype(np.int64)
np.testing.assert_array_equal(got, expected - 1)
randint_columns = np.random.RandomState(5489).randint(1, datalength, size=kurtsize)
assert not np.array_equal(randint_columns, got)

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.

🤖 Test gap (tautological test): the expected value here is the same fix(rand*datalength) and retry-on-zero loop as _kurtosis_columns itself, so the test passes whatever that algorithm is. AGENTS.md says "Do not write tautological tests that only assert ... implementation details." It would not catch an off-by-one in the - 1 0-based conversion or a wrong RNG draw order.

Fix: hard-code the MATLAB oracle. Run rand('twister',5489); fix(rand(1,17)*30504) (or the rng(5489,'twister') equivalent used by pythoncompat) once, paste the 17 integers as a literal, and assert got + 1 == expected_matlab. The randint inequality assertion can then go.

Drop the copied pop_newtimef and pop_newcrossf window helpers, use one
FIR symmetry check, and require EEG.times for a partial interpolation
range. Pin the kurtosis subset to the MATLAB twister draws.

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

cursor Bot commented Nov 6, 2026

Copy link
Copy Markdown

🤖 The deliberate EEGLAB deviations stay. EEGPrep does the mathematically correct thing, and each one is documented and tested. The pop_interp 1-based versus eeg_interp 0-based split is a tracked follow-up, outside this stream. The runica energy sort is taken before sphere @ rowmeans so it matches runica.m:1519. The MATLAB reference run of test_f69_runica_short_run_matches_pythoncompat and test_parity_sample_data_extended_ica_initial_sphere confirms that order.

cursoragent and others added 2 commits November 6, 2026 05:33
The GUI history test and the other partial-range fixtures now set
EEG.times from xmin to xmax with MATLAB linspace, so the missing-times
error stays and those calls still run.

Co-authored-by: Suraj Ranganath <[email protected]>
…gnal-processing-ddd0

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

# Conflicts:
#	docs/source/changelog.rst
@suraj-ranganath
suraj-ranganath marked this pull request as draft November 6, 2026 08:22
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 6, 2026 08:22
@claude

claude Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review

  • Overall assessment: Needs one change. The earlier review's points are fixed: the window helpers are now shared (plot_utils.pointrange / requested_tlimits / dialog_msec), is_linear_phase_fir is shared, eeg_interp now raises a clear error when EEG.times is missing or has the wrong length, and the kurtosis test checks against a hard-coded MATLAB oracle. CI is green on 0592322. One new parity problem: F92 assumes MATLAB int2str truncates, but it rounds.
  • Highest-risk area: the dialog limits and the injected winsize in pop_newtimef/pop_newcrossf (F92); the core numerics in runica, timefreq and eeg_interp.
  • Merge recommendation: Needs changes.

Blocking

None.

Important

  • F92: int2str rounds, it does not truncate (plot_utils.dialog_msec, pop_newtimef.py:232). MATLAB int2str rounds to the nearest integer, with halves going away from zero (int2str(2.7) is '3').
    • Dialog limits: pop_newtimef.m:172 / pop_newcrossf.m:87 show xmax*1000 = 999.6 as 1000, but EEGPrep shows 999.
    • winsize is now a regression: pop_newtimef.m:292 uses int2str(-EEG.xmin*EEG.srate). develop already rounded this correctly. With xmin = -0.1 at 256 Hz, EEGLAB uses 26 and this PR uses 25.
    • Why the test misses it: its fixture (1992.1875) gives the same answer whether you round or truncate.
    • Fix: use half-away-from-zero rounding in both places. Reuse statcond._matlab_round as a shared helper. Add a test fixture where rounding and truncation differ. Fix the "truncated toward zero" text in both help files and changelog.rst:76. Details are in the inline comment.
  • The MATLAB reference evidence is older than the head commit. The full-suite run was on 1ebbad27. After it, e759926 reworked the symmetry check in fir_filterdcpadded (into is_linear_phase_fir) and moved pointrange, and develop was then merged in. Both changes look behaviour-neutral. Still, AGENTS.md asks for one run on the final branch. Rerun eeglab-reference.yml after the F92 fix and update the PR body.

Nits

  • eeg_interp._restore_outside_time_range: the fallback branch at eeg_interp.py:225 can never run, because d is always (nbchan, pnts*trials). A suggestion is in the inline comment.

Test gaps

  • F92: the fixture can't tell rounding from truncation (covered under Important). Beyond that, every behaviour change has a direct test.

EEGLAB parity notes

I checked these against EEGLAB d0963be9, fetched with gh api because src/eegprep/eeglab/ isn't on this runner:

  • newcrossf.m:396-397,461: maxfreq defaults to 50 and freqs to [0 g.maxfreq]. An explicit freqs ignores maxfreq, and log scale lifts a zero lower edge to 3 Hz. _apply_cross_frequency_defaults matches.
  • pop_newtimef.m:305-307: the round(max(...,1)) / round(min(...+1, pnts)) window. pointrange matches.
  • runica.m:1468-1522: the 6-output path sorts on sphered data without the row means. Python takes projected_energy before data += sphere @ rowmeans, which matches. MATLAB switches to activations when nargout > 6, but no current Python caller needs that.
  • Deliberate deviations (pop_interp.m:61 range, pop_newcrossf.m:189 end sample, epoched restore, plotfresp allclose) are each documented and tested. That is in line with the project policy.

Callers of the 1-based pop_interp change: the GUI (0→1 at _gui_channels_as_one_based), console replay (console.py), and pop_reref (passes chanloc dicts). All three are consistent.

Comment on lines +217 to +226
restored = np.array(bad_data, dtype=float, copy=True)
original = np.asarray(original_bad_data, dtype=float)
flat = original.shape[1]
if pnts > 0 and flat % pnts == 0:
restored = restored.reshape(restored.shape[0], pnts, flat // pnts)
original = original.reshape(original.shape[0], pnts, flat // pnts)
restored[:, outside, :] = original[:, outside, :]
return restored.reshape(restored.shape[0], flat)
restored[:, outside] = original[:, outside]
return restored

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, "no error handling for impossible states"): d = EEG['data'].reshape(EEG['nbchan'], -1) (L151) always gives pnts * trials columns, so flat % pnts == 0 is always true. The fallback restored[:, outside] = original[:, outside] can never run. If it did run, outside (length pnts) would not match flat and it would raise. Since the C-order reshape already covers continuous data (trials == 1), the branch can go:

Suggested change
restored = np.array(bad_data, dtype=float, copy=True)
original = np.asarray(original_bad_data, dtype=float)
flat = original.shape[1]
if pnts > 0 and flat % pnts == 0:
restored = restored.reshape(restored.shape[0], pnts, flat // pnts)
original = original.reshape(original.shape[0], pnts, flat // pnts)
restored[:, outside, :] = original[:, outside, :]
return restored.reshape(restored.shape[0], flat)
restored[:, outside] = original[:, outside]
return restored
restored = np.array(bad_data, dtype=float, copy=True).reshape(len(bad_data), pnts, -1)
original = np.asarray(original_bad_data, dtype=float).reshape(len(bad_data), pnts, -1)
restored[:, outside, :] = original[:, outside, :]
return restored.reshape(len(bad_data), -1)

Comment on lines +196 to +198
def dialog_msec(seconds: Any) -> str:
"""Format a latency in seconds as truncated milliseconds."""
return str(int(np.trunc(float(seconds) * 1000.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.

🤖 Important (EEGLAB parity, F92): MATLAB int2str rounds non-integer input to the nearest integer, with halves going away from zero. It does not truncate: int2str(2.7) is '3' and int2str(-0.6) is '-1'. So pop_newtimef.m:172 / pop_newcrossf.m:87 show xmax = 0.9996 s as 1000, but np.trunc gives 999. The test fixture (1992.1875) only passes because rounding and truncation agree there.

The same mistake affects the injected winsize at pop_newtimef.py:232. pop_newtimef.m:292 uses int2str(-EEG.xmin*EEG.srate), and develop already had this right with round. This PR turns it into a regression, for example xmin = -0.1 at 256 Hz gives EEGLAB 26 and this PR 25.

Fix: round half away from zero in both places. statcond._matlab_round already does this (statcond.py#L475-L477), so promote it to a shared helper instead of adding another copy. Then:

  • update test_f92_dialogs_truncate_epoch_limits_toward_zero with a fixture where the two differ (e.g. xmax ending in .6 ms);
  • fix the "truncated toward zero" wording in pop_newtimef.md, pop_newcrossf.md and changelog.rst:76.

int2str rounds halves away from zero. A 0.9996 s limit is 1000 ms, and
a -0.1 s epoch at 256 Hz keeps a 26-sample window. Partial interpolation
always restores the time range as epochs.

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

claude Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review

  • Overall assessment: I found one rounding difference from EEGLAB in the new shared pointrange, and the MATLAB reference evidence predates the head commit. The earlier review rounds are resolved: F92 now uses round_mat for both the dialog limits and winsize, and the redundant eeg_interp restore branch is gone. On head d370e0f I also checked:
    • pop_interp 1-based conversion for the GUI, console replay, and pop_reref (which passes chanloc dicts) paths
    • eeg_interp restore with the C-order epoched reshape
    • runica kurtosis subset and sort energy, against runica.m:889-903,1469-1519
    • newcrossf frequency defaults (newcrossf.m:396-397)
    • timefreq keeping repeated indices, with MATLAB linspace
    • the shared is_linear_phase_fir
  • Highest-risk area: the inclusive sample window in plot_utils.pointrange, which pop_newtimef and pop_newcrossf both use.
  • Merge recommendation: Needs changes. Only small fixes are needed.

Blocking

None.

Important

  • pointrange uses np.round, which rounds halves to even (plot_utils.py:220-221).
    • The ported lines pop_newtimef.m:305-306 use MATLAB round, which rounds halves away from zero.
    • Example: an epoch with xmin = 0 at 100 Hz and tlimits = [25 800]. 0.025*100 is exactly 2.5, so EEGLAB starts at sample 3 and EEGPrep starts at sample 2.
    • That shifts the F126 window by one sample, which changes the ERSP/ITC and the cross-coherence.
    • Fix: use round_mat, which is already imported there, and add a tie case to the F126 tests. A committable suggestion is in the inline comment.
  • The MATLAB reference evidence is older than the head commit. The PR body reports runs on 1ebbad27 and e7599269. Commit d370e0f then changed the GUI winsize that is passed into newtimef, and the pointrange fix above will change windowing again. AGENTS.md asks for one run on the final branch, so after the fix:
    • re-trigger eeglab-reference.yml;
    • update the counts in the PR body;
    • say which EEGLAB commit the run used (the body still names both 8ac485f6 and d0963be9).

Nits

None.

Test gaps

  • There is no test where the pointrange start or end lands on an exact half sample. The F126 tests use limits where half-to-even and half-away-from-zero rounding give the same sample.

EEGLAB parity notes

  • I checked these against EEGLAB d0963be9 via gh api, because src/eegprep/eeglab/ isn't on this runner:
    • runica.m:889-903 uses fix(rand*datalength), retries zero draws, and computes (m4./m2)-3. _kurtosis_columns and the unguarded division match.
    • runica.m:1469-1519 adds the row means back only when nargout > 6 or posact is on, so the 6-output sort uses sphered data. The Python projected_energy matches.
    • newcrossf.m:396-397: maxfreq defaults to 50 and freqs to [0 maxfreq]. _apply_cross_frequency_defaults matches.
    • pop_newtimef.m:292 uses int2str for winsize and :305-306 sets the window bounds. winsize is now right; the window bounds still need the round_mat fix above.
  • Deliberate deviations (pop_interp.m:61 range, pop_newcrossf.m:189 end sample, epoched restore, plotfresp allclose) are documented and tested, which is in line with the project policy.
  • I could not run pytest on this runner because uv run needs approval, so these findings come from reading the code.

  • Load review playbook
  • Pre-review gate and head check (d370e0f matches the PR head)
  • Read diff against origin/develop
  • Review passes
  • Post review (1 inline comment)

Comment on lines +220 to +221
first = int(np.round(max((float(bounds[0]) / 1000.0 - xmin) * srate, 1.0)))
last = int(np.round(min((float(bounds[1]) / 1000.0 - xmin) * srate + 1.0, float(pnts))))

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 (EEGLAB parity, F126): np.round rounds halves to even. The MATLAB lines this ports (pop_newtimef.m:305-306, pointrange1 = round(max(...,1)) / pointrange2 = round(min(...+1, EEG.pnts))) round halves away from zero. Here is a case that hits an exact tie: an epoch with xmin = 0 at 100 Hz and tlimits = [25 800]. 0.025*100 is exactly 2.5, so EEGLAB starts at sample 3 and this code starts at sample 2. The window, and therefore the ERSP/ITC and cross-coherence, then differ by one sample. The F92 commit already moved dialog_msec and winsize to round_mat for this same reason, and round_mat is imported in this module, so the window bounds should use it too:

Suggested change
first = int(np.round(max((float(bounds[0]) / 1000.0 - xmin) * srate, 1.0)))
last = int(np.round(min((float(bounds[1]) / 1000.0 - xmin) * srate + 1.0, float(pnts))))
first = int(round_mat(max((float(bounds[0]) / 1000.0 - xmin) * srate, 1.0)))
last = int(round_mat(min((float(bounds[1]) / 1000.0 - xmin) * srate + 1.0, float(pnts))))

Please also add a tie case to the F126 tests, for example pointrange({'pnts': 100, 'xmin': 0.0, 'srate': 100.0, ...}, [25, 800], 'pop_newtimef').start == 2.

np.round and Python round send n+0.5 to even. EEGLAB round and int2str
send halves away from zero, so [25 800] ms at 100 Hz starts at sample 3.

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

claude Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review

  • Overall assessment: All code findings from the earlier rounds are fixed. pointrange now uses round_mat, and the new test_pointrange_half_sample_starts_at_sample_3 covers the [25 800] ms at 100 Hz tie. I checked head a7334bf, which matches the PR head. Areas checked:
    • the round_mat swap in plot_utils.pointrange, the time-warp frames in newtimef, envtopo._limcontrib_frames, the dftfilt tapers, spectopo percent and window length, the eegplot/eegbrowser sample bounds, eegrej regions, the _rejection trim, the dialogs in pop_topoplot, pop_headplot and pop_epoch, and the eeg_checkset epoch latencies;
    • that round_mat works on both scalars and arrays, keeps the sign, and that every new call site imports it;
    • pop_epoch.m against EEGLAB d0963be9: it uses num2str(round(EEG.xmin)), so -0.5 becomes -1, which matches the new test.
  • Highest-risk area: the core numerics changed since the last MATLAB run (eegrej, newtimef time warping, dftfilt, spectopo, envtopo, eeg_checkset).
  • Merge recommendation: Needs changes. The only gap is the evidence: the code is ready, but the reference run must be redone on the final head.

Blocking

None.

Important

  • The MATLAB reference evidence does not cover the head commit. The PR body reports runs on 1ebbad27 and e7599269. Since then:

    • d370e0f changed the injected winsize;
    • a7334bf changed rounding in core ported functions: eegrej.py:55, newtimef.py:564,572, dftfilt.py:26-27, spectopo.py:132,139, envtopo.py:318-319, eeg_checkset.py:554, and plot_utils.pointrange.

    AGENTS.md (Testing) asks for one run on the final branch before human approval of a core-function PR. Please do this:

    • trigger eeglab-reference.yml on a7334bf, or run the suite locally with --eeglab-backend=matlab;
    • replace the counts, commit, and runtime in the PR body;
    • explain the known R2025b pop_reref failure again if it still appears.

Nits

None.

Test gaps

None. Each round_mat site added in a7334bf has a half-sample tie test that rounding half to even would fail.

EEGLAB parity notes

  • pop_epoch.m (d0963be9): epochlim = [num2str(round(EEG.xmin)) ' ' num2str(round(EEG.xmax))]. _default_epoch_limits now rounds halves away from zero the same way.
  • The deliberate deviations from the earlier reviews are unchanged, and each is still documented and tested:
    • pop_interp.m:61 (scripted range is honoured);
    • pop_newcrossf.m:189 (end sample is kept);
    • epoched data is restored outside the time range;
    • plotfresp uses an allclose symmetry test.
  • I could not run pytest on this runner, so these results come from reading the code.

  • Pre-review gate and head check (a7334bf)
  • Read the diff against origin/develop, focusing on a7334bf
  • Review passes and validation
  • Post review

Copy link
Copy Markdown
Member Author

Review follow-up at a7334bf.

Claude r2/r3 points, fixed:

  • F92: int2str rounds half away from zero, so the dialog limits and prestimulus window now use round_mat.
  • The unreachable flat fallback in eeg_interp is removed.
  • pointrange used np.round (half to even); it now uses round_mat. A package-wide audit moved every MATLAB round/int2str mirror to round_mat, and each site has a half-sample tie test.

Claude r4, MATLAB evidence on the final head: the full reference suite ran on a7334bf on our MATLAB R2025b bench, pinned to EEGLAB d0963be9, with no tolerance changes and 0 mismatches:

  • Tie oracle: [25 800] ms @ 100 Hz gives sample 3; round(2.5)=3; int2str(2.5)=3.
  • stream4 + linspace 26, timefreq parity 64, epoch/checkset 34, rejection 38, plots 117, Picard w0 1.

Each changed site was also checked against the EEGLAB source it mirrors, and all of them use MATLAB round/int2str, not floor, ceil or fix:

  • plot_utils.py:220-221 ↔ pop_newtimef.m:305-306
  • eegrej.py:55 ↔ eegrej.m:82
  • newtimef.py:564,572 ↔ newtimef.m:630,635
  • dftfilt.py:26-27 ↔ dftfilt.m:70-71
  • envtopo.py:318-319 ↔ envtopo.m:418-419
  • _rejection.py:405 ↔ rejkurt.m:110-111
  • pop_epoch.py:520 ↔ pop_epoch.m:122

eeglab-reference.yml is dispatch-only and its hosted runner hasn't passed since October, so the bench run stands in for it. CI is green on Ubuntu 3.12/3.13, macOS and Windows.

Keep Stream 4 MATLAB half-away-from-zero rounding and Stream 10 export/BIDS changes.

Co-authored-by: Suraj Ranganath <[email protected]>
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.

2 participants