Repository navigation
Stream 4: Signal processing - #560
Conversation
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 encountered an error after 0s —— View job I'll analyze this and get back to you. |
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]>
There was a problem hiding this comment.
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 finished @suraj-ranganath's task in 2m 4s —— View job Code review
BlockingNone. Important
Nits
Test gaps
EEGLAB parity notes
|
| 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) | ||
|
|
There was a problem hiding this comment.
🤖 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.
| 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) |
There was a problem hiding this comment.
🤖 Nit (duplication): the odd-length branch repeats the symmetric/antisymmetric check in fir_filterdcpadded.py L64-65 (
eegprep/src/eegprep/plugins/firfilt/fir_filterdcpadded.py
Lines 63 to 66 in 1ebbad2
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.
| 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) |
There was a problem hiding this comment.
🤖 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]>
|
🤖 The deliberate EEGLAB deviations stay. EEGPrep does the mathematically correct thing, and each one is documented and tested. The |
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
|
Claude finished @suraj-ranganath's task in 3m 6s —— View job Code review
BlockingNone. Important
Nits
Test gaps
EEGLAB parity notesI checked these against EEGLAB
Callers of the 1-based |
| 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 |
There was a problem hiding this comment.
🤖 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:
| 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) |
| def dialog_msec(seconds: Any) -> str: | ||
| """Format a latency in seconds as truncated milliseconds.""" | ||
| return str(int(np.trunc(float(seconds) * 1000.0))) |
There was a problem hiding this comment.
🤖 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_zerowith a fixture where the two differ (e.g.xmaxending in.6ms); - fix the "truncated toward zero" wording in
pop_newtimef.md,pop_newcrossf.mdandchangelog.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]>
|
Claude finished @suraj-ranganath's task in 1m 56s —— View job Code review
BlockingNone. Important
NitsNone. Test gaps
EEGLAB parity notes
|
| 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)))) |
There was a problem hiding this comment.
🤖 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:
| 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]>
|
Claude finished @suraj-ranganath's task in 53s —— View job Code review
BlockingNone. Important
NitsNone. Test gapsNone. Each EEGLAB parity notes
|
|
Review follow-up at a7334bf. Claude r2/r3 points, fixed:
Claude r4, MATLAB evidence on the final head: the full reference suite ran on a7334bf on our MATLAB R2025b bench, pinned to EEGLAB
Each changed site was also checked against the EEGLAB source it mirrors, and all of them use MATLAB
|
Keep Stream 4 MATLAB half-away-from-zero rounding and Stream 10 export/BIDS changes. Co-authored-by: Suraj Ranganath <[email protected]>
Refs #549
Signal-processing numerics for the release-readiness audit (F58, F59, F60, F69, F91, F92, F126), plus the
pop_interpindex-base part of F70.8ac485f6is the GUI comparison pin. The numerical oracle and the jamming run used0963be9. Where that tree is wrong, EEGPrep keeps the correct behaviour and a test records the difference.Findings
plotfresprequired 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.allclosetest asfir_filterdcpadded. The error namesplotfrespand the fix.test_f58_plotfresp_accepts_windowed_sinc_onepass_zerophase,test_f58_pop_eegfiltnew_frequency_response_plot_opens(xmin, xmax)tuple, and the restore usedfloor(t*srate)throughpnts-2(eeg_interp.m:322). The second-to-last sample stayed original, the range endpoint was excluded, and the final sample stayed interpolated.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 requiresEEG.timesof lengthpnts; otherwiseeeg_interpraises and nameseeg_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_timespop_interp.m:61setst_range = '', so a scripted range interpolates the whole recording. EEGPrep already honoured the range.pop_interphelp.test_f60_pop_interp_honours_a_scripted_time_range(citespop_interp.m:61). MATLAB:test_f60_pinned_pop_interp_discards_the_fourth_argumentrandintandm2 + 1e-10.runica.m:890-903usesfix(rand*datalength)on the same MT19937 stream and(m4./m2)-3. The default 6-output sort used activation energy;runica.m:1472and:1519use sphered-channel energy unlessposactis on.test_f69_kurtosis_subset_uses_fix_rand_on_the_twister_streampinsrand('twister',5489); fix(rand(1,17)*30504). MATLAB:test_f69_runica_short_run_matches_pythoncompatnewcrossfleftfreqsunset, sotimefreqran to Nyquist (6–64 Hz, 30 bins at 128 Hz,padratio1).newcrossf.m:396-397defaults to[0, 50].[0, 50],maxfreqreplaces 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_hzint2strrounds, halves away from zero (pop_newcrossf.m:87,pop_newtimef.m:172,pop_newtimef.m:292).round_mat.0.9996s is1000ms, andxmin-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_zerodata_time_slicedropped the sample after the truncated limit and passed the kept sample times intonewtimef.pointrangeusednp.round, which sends a half to even, so[25 800]ms at 100 Hz starts at sample 2.pop_newtimef.m:305-306usesround, which sends that half to sample 3, and passes the requested limits. Pinnedpop_newcrossf.m:189omits the +1 and drops the last sample.plot_utils.pointrangewithround_matand pass the requested limits. Thepop_newcrossfdifference 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_dropsroundandint2str: 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.round_mat. Display rounding, GUI pixel math, andpop_rejcont's early window length stay as they were. Pinnedpop_rejcont.mdoes not round those lengths.newtimefcall already passed the same frames, limits, sampling rate, cycles, andpadratioto both sides.timefreqdropped indices that round to the same sample, so ERSP was(4, 104).timefreq.mgettimesonly uniques whenlength(timeindices) < length(unique(timeindices)), which never happens, so EEGLAB returns 111 times. Keeping those repeats exposed the value gap:np.linspacediffered from MATLABlinspaceby 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).timevectand the requested times asstart + i * (stop - start) / (n - 1), then set the last point to the end. Shared helper:eegprep.functions.miscfunc.linspace. Rounding staysfloor(points + 0.5) - 1.test_newtimef_keeps_repeated_sample_times,test_linspace_matches_matlab_values,test_linspace_keeps_matlab_half_sample_tiespop_interpindices were 0-based, unlikepop_interp.m.test_pop_interp_channel_indices_are_one_basedOutside this stream's files
src/eegprep/functions/adminfunc/console.py(stream 11): stopped subtracting 1 when replayingpop_interpchannel lists, so history stays 1-based. One expression.tests/test_console_workspace.pyexpectation 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 pinnedfloorwindow),tests/test_phase4_timefreq_statistics.py(time-warp markers on the requested limits).MATLAB reference run
Run on
1ebbad27on jamming, MATLAB R2025b, EEGLABd0963be9: 2153 tests, 1 failure. The failure is the known R2025bpop_rereffloat32 average-reference case (max abs 0.109375). Stream 4 had 22 passed. Time-frequency parity had 63 passed.assert_matlab_nearuses the existing suite epsilon1e-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.test_f91_f126_time_frequency_matches_eeglab: eachnewcrossfsignal is a row vector whose length isframestimes the trial count (newcrossf.mreturns before assigningRwhenmin(size(X))is not 1). Plotting is off withplotampandplotphase(ploterspandplotitcare ignored).nargoutis 4, which assignsR,mbase,timesout, andfreqs. The comparison is still the frequency axis at the existing epsilon.newtimefERSP/ITC still usesplotersp/plotitc/verboseoff, with the same frames, limits, sampling rate, cycles,padratio, and baseline as EEGPrep. The time grid now follows MATLABlinspace, which on jamming made all 111 indices match and brought ERSP max abs to about4.4e-15.test_f60_pinned_pop_interp_discards_the_fourth_argument: the EEG iseeg_emptyset, then filled.chaninfo,reject, andetcare scalar structs (an empty dict survivessavematas a non-struct, andeeg_checkset.mthen dot-indexes them).chanlocsis a struct array. The assertion is unchanged: pinnedpop_interp.m:61makes a ranged call equal the full interpolation.test_f69_runica_short_run_matches_pythoncompat: extended 0 and 1,maxsteps2, full-rank 4×300,rndresetoff,pythoncompaton. Weights and sphere. This run, withtest_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 MATLABeeg_interp; the final sample stays original in Python and interpolated in pinnedeeg_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.linspacecall sites:timefreqfrequency grids,newtimeffull_times,dftfilt2/dftfilt3, datasettimesrebuilds, andrejtrend.pop_interpindices are 1-based whileeeg_interpinteger indices are still 0-based.Not closed by the local run
Raw tutorial
runicamatches MATLAB (|r|about 1.0). The average-referenced rank-31 sphere gap is pre-existing ondevelopand is out of scope.The research comment on issue 549 was not posted: the token cannot
addComment.