Skip to content

[Phase 2] Complete FIR filtering parity - #73

Merged
suraj-ranganath merged 3 commits into
feature/eeglab-completionfrom
phase/2-filtering-cleaning-completion
May 28, 2026
Merged

suraj-ranganath merged 3 commits into
feature/eeglab-completionfrom
phase/2-filtering-cleaning-completion

Conversation

@suraj-ranganath

Copy link
Copy Markdown
Member

Complete standalone FIR filtering workflows for Phase 2 by adding pop_eegfilt, pop_eegfiltnew, and the bundled firfilt plugin dialogs/actions. Boundary-aware continuous and epoched filtering now clears ICA activations like EEGLAB, records replayable history, and is covered by GUI, sample-data, and MATLAB parity tests.\n\nFixes #62

@claude

claude Bot commented May 28, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review

  • Overall assessment: Needs changes — two important parity issues and one GUI crash.
  • Highest-risk area: _filter_segment causal/minphase code path in src/eegprep/plugins/firfilt/_filtering.py.
  • Merge recommendation: Needs changes before merge.

Blocking

None.

Important

  • pop_eegfilt silently swaps the filter algorithm. src/eegprep/functions/popfunc/pop_eegfilt.py:67-76 always calls design_eegfiltnew (Hamming-windowed sinc), discarding firtype. EEGLAB's pop_eegfilt/eegfilt.m uses fir1 or firls based on this flag, with different default filter orders. The help text only promises "menu and command-history compatibility," but a ported script that sets firtype='firls' will silently get different numerical results. Either honor firtype properly or raise NotImplementedError when a non-default firtype is supplied and document the substitution in resources/help/pop_eegfilt.md. (See inline comment.)

  • Causal / minphase filtering path doesn't match EEGLAB. src/eegprep/plugins/firfilt/_filtering.py:244-262: in causal=True mode, _filter_segment pads with 2 * group_delay repeats of the first sample, runs lfilter, then trims 2 * group_delay from the front. That's a left-edge-padded zero-phase output, not the standard EEGLAB causal filter(b, 1, x) (which leaves the natural group-delay shift). With pop_eegfiltnew(..., minphase=True) this is materially wrong: a minimum-phase filter's true group delay is much smaller than (len(b)-1)/2, so the function discards ~2 * group_delay real samples and replaces them with a constant first-sample tail. There is no MATLAB parity test for either causal=True or minphase=True, so this divergence is invisible to CI. Recommended fix: in causal mode return lfilter(b, [1.0], segment, axis=1) (or the fftconvolve analog) directly. (See inline comment.)

  • pop_eegfiltnew GUI crashes on channel labels. src/eegprep/plugins/firfilt/pop_eegfiltnew.py:144-151: the channel selector accepts both 1-based indices and labels in EEGLAB, but here vector_or_none("Cz Pz") raises ValueError on float("Cz") before the channels.split() fallback can run — the dialog crashes instead of resolving labels. Wrap the call in try/except ValueError or pre-check for numeric tokens before parsing as a vector. (See inline comment.)

Nits

  • chantype history is not valid MATLAB. src/eegprep/plugins/firfilt/_pop_common.py:91-103: with cell_for_sequence=None, list-of-strings options serialize as ['EOG'] rather than {'EOG'}, so pop_eegfiltnew(EEG, chantype=["EOG"]) produces a history line that won't replay in EEGLAB. Python replay still works; only MATLAB round-tripping breaks. (See inline comment.)
  • "Estimate" buttons in pop_firws_dialog_spec and pop_firpm_dialog_spec (pop_firws.py:92,93,107, pop_firpm.py:88,92) have no callback=... wired up, so clicks are no-ops. Not a regression, but worth tracking — at minimum a tooltip note that order/Kaiser-beta estimation is not implemented yet.

Test gaps

  • No parity assertion exists for pop_eegfiltnew with minphase=True, with causal=True, with chantype=, or with a continuous boundary event. The only MATLAB parity case in tests/test_pop_firfilt.py is the simple hicutoff=40, filtorder=100 lowpass and a pop_firma boundary split. Given the issue flagged above on _filter_segment, please add at minimum:
    • a pop_eegfiltnew(eeg, hicutoff=40, filtorder=100, minphase=True) MATLAB parity test;
    • a parity test that exercises a continuous boundary event for pop_eegfiltnew (analogous to the existing pop_firma one);
    • a Python regression test for pop_eegfiltnew(eeg, gui=True, renderer=...) with channels="Cz Pz" (covers the GUI crash above and any fix).
  • tests/test_pop_firfilt.py:111-123 only asserts shape and replay text for pop_firws/pop_firpm — consider one parity assertion against MATLAB for at least the pop_firws bandpass to lock in the windowed-sinc coefficients (the lowpass/usefftfilt equivalence test on line 125 only proves the two code paths agree with each other, not with EEGLAB).

EEGLAB parity notes

  • Aside from the items above, the dialog specs, menu wiring (menu_actions.py, menu_placeholders.py), _continuous_bounds (1-based latency + 0.5 → 0-based conversion via round_mat), epoched-trial flattening, ICA-activations clearing, and saved = "no" behavior all line up with EEGLAB conventions. Package exports and visual-parity case wiring look complete.

Tasks
  • Read CLAUDE.md / AGENTS.md and changed files
  • Audit correctness, regressions, edge cases
  • Audit EEGLAB parity vs filter algorithm and history format
  • Audit tests, GUI menu, package exports
  • Post review summary + inline comments
· `phase/2-filtering-cleaning-completion`

@suraj-ranganath

Copy link
Copy Markdown
Member Author

🤖 Phase 2 completion spec and GUI parity evidence.

Problem

Phase 2 still had FIR/filtering menu placeholders after #70 landed baseline parity. The remaining user-visible gaps were pop_eegfilt, pop_eegfiltnew, pop_firws, pop_firpm, and pop_firma: menu items existed, but dispatch/help/history/GUI/API behavior was not implemented. Filtering also needed EEGLAB-style boundary splitting, epoched-data handling, and ICA activation invalidation so GUI and eegprep-console users see the same state/history behavior.

Approach

This PR adds standalone Python pop wrappers and shared firfilt helpers under src/eegprep/plugins/firfilt/, plus the legacy src/eegprep/functions/popfunc/pop_eegfilt.py. The shared helper designs Hamming/windowed, least-squares, Parks-McClellan, and moving-average kernels, filters continuous data segment-by-segment across EEGLAB boundary events, filters epoched data trial-wise, clears icaact, and keeps structural fields such as event, urevent, epoch, times, and ICA weights/sphere intact. Menu dispatch, package exports, help Markdown, console-replayable history strings, and visual parity capture cases are wired for each new dialog.

Key code

segments = boundary_segments(eeg)
for start, stop in segments:
    output[:, start:stop] = _filter_segment(
        output[:, start:stop], coefficients, causal=causal, use_fft=use_fft
    )

That is the core EEGLAB parity rule from firfilt: continuous recordings are filtered within each non-boundary segment instead of across boundary events. Epoched data uses the same filter path after trial-wise flattening and reshape back to (channels, points, trials).

Tests and verification

Focused and integration tests cover synthetic continuous data, epoched data, boundary events, sample_data/eeglab_data.set, replayable console commands, GUI renderer results, menu dispatch, package exports, placeholder inventory, and visual parity manifest coverage.

Commands run:

uv run --no-sync ruff check .
uv run --no-sync ruff format --check .
uv run --no-sync ty check
./pre-commit.py
./pre-commit.py --changed-from origin/feature/eeglab-completion
EEGPREP_SKIP_MATLAB=1 uv run --no-sync pytest -m "not slow"
uv run --no-sync pytest tests/test_pop_firfilt.py::TestPopFirfiltParity -q

Results:

ruff check: passed
ruff format --check: passed
ty check: passed
pre-commit staged and PR-scope: passed
non-slow pytest: 1195 passed, 216 skipped, 11 deselected
FIR MATLAB parity smoke: 2 passed

The MATLAB parity smoke used the local full EEGLAB reference as a temporary development-only symlink, then restored src/eegprep/eeglab so no runtime dependency was introduced.

GUI side-by-side attachments

EEGLAB vs EEGPrep FIR/filter dialogs

pop_eegfilt legacy filter dialog:
pop_eegfilt side by side

pop_eegfiltnew FIR filter dialog:
pop_eegfiltnew side by side

pop_firws windowed-sinc FIR dialog:
pop_firws side by side

pop_firpm Parks-McClellan FIR dialog:
pop_firpm side by side

pop_firma moving-average FIR dialog:
pop_firma side by side

Comment on lines +67 to +76
b, _metadata = design_eegfiltnew(
float(EEG["srate"]),
locutoff=locutoff,
hicutoff=hicutoff,
filtorder=filtorder,
revfilt=revfilt,
)
output = apply_fir_filter(EEG, b, causal=causal, usefftfilt=usefft)
command = _history_command(locutoff, hicutoff, filtorder, revfilt, usefft, plotfreqz, firtype, causal)
return (output, command) if return_com else output

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: pop_eegfilt always designs its filter with design_eegfiltnew (Hamming-windowed sinc) and ignores firtype. EEGLAB's pop_eegfilt/eegfilt.m picks fir1 vs firls based on this flag and uses substantially different default filter orders, so pop_eegfilt(EEG, 1, 40, [], 0, 0, 0, 'firls') produces a different filter here than in MATLAB.

The help text says only "kept for menu and command-history compatibility" — it doesn't disclose the algorithm swap, so users who call this from a ported script will get silently different numerical results. Either implement firls/fir1 properly, or raise a clear NotImplementedError when a non-default firtype is supplied (and document the substitution in resources/help/pop_eegfilt.md).

Why it matters: EEGLAB users porting scripts that pin firtype for reproducibility will see drift and have no diagnostic.

Comment on lines +244 to +262
def _filter_segment(b: np.ndarray, segment: np.ndarray, *, causal: bool, usefftfilt: bool) -> np.ndarray:
group_delay = (b.size - 1) // 2
if group_delay == 0:
return segment.copy()
if segment.shape[1] == 0:
return segment.copy()
start_width = 2 * group_delay if causal else group_delay
start_pad = np.repeat(segment[:, :1], start_width, axis=1)
end_pad = (
np.empty((segment.shape[0], 0), dtype=segment.dtype)
if causal
else np.repeat(segment[:, -1:], group_delay, axis=1)
)
padded = np.concatenate([start_pad, segment, end_pad], axis=1)
if usefftfilt:
filtered = fftconvolve(padded, b.reshape(1, -1), mode="full", axes=1)[:, : padded.shape[1]]
else:
filtered = lfilter(b, [1.0], padded, axis=1)
return filtered[:, 2 * group_delay :]

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 — causal/minphase semantics: when causal=True, this pads with 2 * group_delay repeats of the first sample, runs lfilter, then trims 2 * group_delay from the front. That returns the zero-phase output with a left-edge replicate pad — not the standard EEGLAB causal filter(b, 1, x) (no group-delay compensation).

Trace for b = [1,2,1]/4, X = [10,20,30], group_delay = 1:

  • padded = [10,10,10,20,30], lfilter → [2.5, 7.5, 10, 12.5, 20], trim 2 → [10, 12.5, 20].
  • Expected EEGLAB causal output filter(b,1,X) = [2.5, 10, 20].

The two diverge at every sample within 2 * group_delay of a segment boundary. This is especially incorrect for minphase=True (the path pop_eegfiltnew(..., minphase=True) takes): a minimum-phase filter's actual group delay is much smaller than (len(b)-1)/2, so trimming 2 * group_delay discards real, valid output and pads with 2 * group_delay of the first sample. Suggested fix: in causal mode skip the padding/trim entirely and return lfilter(b, [1.0], segment, axis=1) (or fftconvolve analog) directly, matching firfilt.m's causal branch.

There is no MATLAB parity test for causal=True or minphase=True, so the divergence is currently invisible to CI — please add one (see test gap note in the summary).

Comment on lines +144 to +151
chantype = str(result.get("chantype", "")).strip()
channels = str(result.get("channels", "")).strip()
if chantype:
options["chantype"] = chantype.split()
elif channels:
parsed = vector_or_none(channels)
options["channels"] = parsed if parsed is not None else channels.split()
return options

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 — GUI crashes on channel labels: EEGLAB's pop_eegfiltnew channel selector accepts both 1-based indices ("1 2") and channel labels ("Cz Pz"). Here, if the user types labels, vector_or_none("Cz Pz") calls float("Cz") and raises ValueError, so the else channels.split() fallback on line 150 is unreachable — the dialog crashes instead of resolving labels via resolve_channel_indices.

Suggested fix: catch the conversion failure (or check the tokens for ^-?\d+(\.\d+)?$ before calling vector_or_none) and fall through to the label-based path:

elif channels:
    try:
        options["channels"] = vector_or_none(channels)
    except ValueError:
        options["channels"] = channels.split()

This is also worth a unit test in tests/test_gui_pop_firfilt.py for channels="Cz".

Comment on lines +91 to +103
def history_command(function_name: str, options: dict[str, Any]) -> str:
"""Build an EEGLAB-style key/value history command."""
parts = []
for key, value in options.items():
if value is None:
continue
if isinstance(value, bool) and value is False:
continue
history_value = int(value) if isinstance(value, bool) else value
parts.extend([format_history_value(key), format_history_value(history_value, cell_for_sequence=None)])
if not parts:
return f"EEG = {function_name}(EEG);"
return f"EEG = {function_name}(EEG, {', '.join(parts)});"

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 — MATLAB history replay: format_history_value(["EOG"], cell_for_sequence=None) emits ['EOG'], so the history line for pop_eegfiltnew(EEG, chantype=["EOG"]) becomes EEG = pop_eegfiltnew(EEG, 'chantype', ['EOG']);. That's invalid MATLAB — EEGLAB expects a cell array {'EOG'}. Same applies to multi-label chantype from the GUI (which _run_gui splits into a list).

Suggested fix: when serializing the chantype / channels (label form) values for history, pass cell_for_sequence="all_strings" (or special-case those two keys in history_command) so list-of-strings becomes {'EOG'}. This keeps Python replay working (Python evaluator already accepts both) and restores MATLAB round-tripping.

@suraj-ranganath

Copy link
Copy Markdown
Member Author

🤖 Updated visual parity attachments after review fixes. These refresh the dialogs where previously enabled no-op buttons are now disabled with tooltips.

Updated FIR plugin dialog screenshots

pop_firws windowed-sinc FIR dialog:
pop_firws side by side

pop_firpm Parks-McClellan FIR dialog:
pop_firpm side by side

pop_firma moving-average FIR dialog:
pop_firma side by side

@suraj-ranganath
suraj-ranganath force-pushed the phase/2-filtering-cleaning-completion branch from d3bb2df to 204412e Compare May 28, 2026 09:03
@suraj-ranganath

Copy link
Copy Markdown
Member Author

@claude review this

@claude

claude Bot commented May 28, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review

  • Overall assessment: LGTM. The two follow-up commits address every actionable finding from the prior review. The "causal/minphase" finding in that prior review was based on a misreading of upstream fir_filterdcpadded — see verification below — so no fix was needed there, and the current implementation matches EEGLAB exactly.
  • Highest-risk area: _filter_segment (now verified against upstream).
  • Merge recommendation: Approve, modulo two small follow-ups noted below.

Verification of the prior review's "causal/minphase" finding (not a bug)

The prior reviewer claimed _filter_segment should be a plain lfilter(b, [1.0], segment) in causal mode, and that the current pad/trim diverges from EEGLAB. I fetched the upstream widmann/firfilt/fir_filterdcpadded.m to confirm:

if causal
    startPad = repmat(data(1, :), [2 * groupDelay 1]);
    endPad = [];
else
    startPad = repmat(data(1, :), [groupDelay 1]);
    endPad = repmat(data(end, :), [groupDelay 1]);
end
data = filter(double(b), 1, double([startPad; data; endPad]));
data = data(2 * groupDelay + 1:end, :);

This is exactly what _filter_segment in src/eegprep/plugins/firfilt/_filtering.py:320-340 does:

  • Causal: pad 2*groupDelay repeats of first sample, no end-pad, filter, trim 2*groupDelay from front.
  • Non-causal: pad groupDelay of first sample at start + groupDelay of last sample at end, filter, trim 2*groupDelay from front.

And pop_eegfiltnew.m dispatches minphase/usefftfilt via firfiltsplit → fir_filterdcpadded (verified upstream). So the test added at tests/test_pop_firfilt.py:193 (test_parity_pop_eegfiltnew_minphase_sample_data, atol=3e-3) is the correct authority and the implementation is correct. The earlier "use lfilter(b, [1.0], segment) directly" suggestion would have broken EEGLAB parity for minphase=True.

Prior-review findings: status on this branch

Prior finding Status Evidence
pop_eegfilt ignores firtype (silently swaps to design_eegfiltnew) Fixed pop_eegfilt.py:72-79 calls design_eegfilt_legacy(..., firtype=firtype). design_eegfilt_legacy (_filtering.py:124-135) honors both fir1 and firls. Covered by test_pop_eegfilt_legacy_firtype_changes_filter_coefficients and parity test test_parity_pop_eegfilt_legacy_firls_sample_data.
Causal/minphase _filter_segment wrong Not a bug (incorrect prior claim — verified against upstream fir_filterdcpadded.m) See section above.
pop_eegfiltnew GUI crashes on channel labels Fixed pop_eegfiltnew.py:148-153 wraps vector_or_none in try/except ValueError and falls back to channels.split(). Test test_pop_eegfiltnew_gui_accepts_channel_labels in tests/test_gui_pop_firfilt.py:73.
chantype history emits ['EOG'] instead of {'EOG'} Fixed format_history_value default cell_for_sequence="all_strings" produces cell arrays for string lists. Confirmed by test_pop_eegfiltnew_chantype_history_uses_matlab_cell_array asserting "'chantype', {'EOG'}" in command.
Estimate buttons are clickable no-ops Fixed pop_firws.py:89-103, pop_firpm.py:88-94, pop_firma.py:62-67 mark the buttons enabled=False with tooltip="...not yet implemented in EEGPrep." Covered by test_unimplemented_firfilt_dialog_buttons_are_disabled.
Test gaps (minphase, boundary, GUI label crash, chantype cell) Addressed New tests at lines 73, 81, 193, 202 add the requested coverage.

Remaining nits (non-blocking)

  1. pop_firws bandpass parity test still missing. test_pop_firws_usefftfilt_matches_time_domain_filtering (tests/test_pop_firfilt.py:134-140) only checks that the two internal code paths agree with each other — it does not lock in the windowed-sinc coefficients against MATLAB. Adding one test_parity_pop_firws_bandpass_sample_data against eeglab.pop_firws would lock the design in. Low priority.
  2. pop_firws/pop_firpm don't surface a channels/chantype option. EEGLAB's pop_firws.m accepts a 'channels' argument (passed through to firfilt), and there's no equivalent here. Not user-reachable from the GUI either (the dialog has no channel picker in the upstream version), so it's only a CLI parity gap. Worth tracking as a follow-up issue.
  3. Help docs for pop_eegfilt.md could mention causal= and the order-default heuristic — currently the help text is minimal, and the parameter list isn't enumerated. Optional polish.

EEGLAB parity notes (positive)

  • _continuous_bounds correctly rounds latency + 0.5 and converts to 0-based starts. Verified against firfiltsplit.m's dcArray semantics.
  • apply_fir_filter uses DC-padded filtering (matches modern pop_eegfiltnew path); apply_eegfilt_legacy uses filtfilt/lfilter directly (matches legacy eegfilt.m).
  • Epoched data is flattened to (nbchan, pnts*trials) and filtered with dcArray = 1:pnts:pnts*(trials+1), then reshaped back — matches EEGLAB exactly.
  • icaact is cleared and saved="no" set, matching EEGLAB behavior.
  • Menu dispatch (menu_actions.py:288-305, 774-797), package exports (__init__.py:77-78, 91-93), and visual parity case wiring (visual_capture.py:23, 41-44) are all complete.

Tests run locally

  • uv run --no-sync pytest tests/test_pop_firfilt.py tests/test_gui_pop_firfilt.py tests/test_menu_placeholder_inventory.py -q → 28 passed, 5 skipped (MATLAB engine not available in this sandbox; MATLAB parity cases skip via the existing EEGPREP_SKIP_MATLAB guard).
Tasks
  • Read AGENTS.md / CLAUDE.md
  • Pull branch + inspect diff vs origin/feature/eeglab-completion
  • Audit _filtering.py (causal/minphase, boundary segments)
  • Audit pop_eegfilt.py (firtype handling)
  • Audit pop_eegfiltnew.py GUI (channel labels)
  • Audit _pop_common.py (history serialization, especially chantype cells)
  • Audit pop_firws.py / pop_firpm.py (estimate buttons)
  • Audit tests (parity coverage, gaps)
  • Cross-check _filter_segment against upstream widmann/firfilt/fir_filterdcpadded.m
  • Run focused pytest suite locally
· `phase/2-filtering-cleaning-completion`

@suraj-ranganath
suraj-ranganath merged commit 0753aa1 into feature/eeglab-completion May 28, 2026
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.

1 participant