Repository navigation
[Phase 2] Complete FIR filtering parity - #73
suraj-ranganath merged 3 commits into
Conversation
|
Claude finished @suraj-ranganath's task in 11m 37s —— View job Code review
BlockingNone. Important
Nits
Test gaps
EEGLAB parity notes
Tasks
|
|
🤖 Phase 2 completion spec and GUI parity evidence. ProblemPhase 2 still had FIR/filtering menu placeholders after #70 landed baseline parity. The remaining user-visible gaps were ApproachThis PR adds standalone Python pop wrappers and shared firfilt helpers under Key codesegments = 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 Tests and verificationFocused 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 -qResults: The MATLAB parity smoke used the local full EEGLAB reference as a temporary development-only symlink, then restored GUI side-by-side attachments |
| 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 |
There was a problem hiding this comment.
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.
| 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 :] |
There was a problem hiding this comment.
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).
| 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 |
There was a problem hiding this comment.
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".
| 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)});" |
There was a problem hiding this comment.
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.
|
🤖 Updated visual parity attachments after review fixes. These refresh the dialogs where previously enabled no-op buttons are now disabled with tooltips. |
d3bb2df to
204412e
Compare
|
@claude review this |
|
Claude finished @suraj-ranganath's task in 8m 20s —— View job Code review
Verification of the prior review's "causal/minphase" finding (not a bug)The prior reviewer claimed 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
And Prior-review findings: status on this branch
Remaining nits (non-blocking)
EEGLAB parity notes (positive)
Tests run locally
Tasks
|








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