You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
ENH: Fast adaptive line-noise removal via sinusoid regression (~50× speedup over spectrum_fit) #14392
I was wondering whether we could actually port the method to mne, long term. Replacing the current "spectrum_fit" method, which has been a pain point in the past, as discussed in
You were mentioning that you needed the flexibility and speed of shipping it on your own, and I totally understand that. But would you be open to having this method in mne, too? It'd make adoption easier in pyprep.
Of course, we need a few other stakeholders to agree that this would be an improvement, too. cc @larsoner for example.
Regarding integration here, the func could be exposed as:
An additional method in notch_filter(method="regression") (or replacing spectrum_fit), and/or
A dedicated preprocessing function: mne.preprocessing.remove_line_noise().
Yes sure, if others want it in MNE I'm happy to move it there. We should really replace the existing one though, because as you say it has been a pain point and is still extremely slow.
spectrum_fit had a number of bugs for a long time but works much better following #14310 (esp. when you specify the freqs). I'd keep it.
Adding a new method seems potentially fine, though. Is regression just multiplication by sin/cos (or complex exponential) at the exact specified freqs over the length of a recording (or regression I guess if they're not orthogonal)? If so then maybe some parts of spectrum_fit (like zoom FFT) could be used to more accurately estimate the true underlying freqs (e.g., 59.95 instead of 60.0 Hz), too... I don't think that's the slow part but we could check.
It's least squares regression, but local rather than over the entire recording. Also, the method only used the fixed given frequencies (plus harmonics), it doesn't handle any deviations. I guess this is really a weak point of this implementation - I'm OK with having users set the nominal line noise frequency (as opposed to finding everything from the data), but we should adapt to the actual frequency over time nonetheless. I think this wouldn't really hurt performance since we'd have to do it only once, but I'd have to take a look how zoom FFT works (so it could be that I'm wrong).
Anyway, it looks like the algorithms are rather different, so we'd probably keep them in separate packages for now. Speed is most important for my use case, since I don't want users to wait over a minute just to remove line noise in a typical EEG recording (but of course we'll have to see how much estimating the actual frequency costs in terms of runtime).
I work on numerical optimization and profiling, and line-noise removal looks like a good place to start: it is self-contained, easy to measure, and users feel it directly. I read the discussion above, measured the methods that exist today, and implemented the regression approach as a patch, so there is something concrete to talk about.
Numbers first.
Setup. 64 EEG channels, 20 min, 250 Hz (19.2 M samples). Synthetic: white noise 20 µV + line noise 5 µV at 60 Hz + 2 µV at 120 Hz. One machine: Intel Xeon E5-2698 v4 @ 2.20 GHz, Windows 10, Python 3.11, mne 1.13.2, numpy 2.4.6, one process, one run per method.
method
time
residual at 60 Hz
a 5 µV tone at 59.4 Hz
spectrum_fit
44.0 s
2.7e-05
100 %
fft
2.1 s
1.2e-06
97.2 %
regression
1.8 s
7.1e-06
99.9 %
With a drifting line (60.00 → 59.97 Hz over the recording, which is what real data looks like):
method
time
residual at 60 Hz
a 5 µV tone at 59.4 Hz
spectrum_fit
44.4 s
3.0e-04
100 %
fft
0.9 s
3.9e-07
97.5 %
regression
1.8 s
1.2e-05
100.0 %
The regression method is about 25 times faster than spectrum_fit and leaves a smaller residual at the line (3.8 times smaller on the stable case, 26 times smaller with drift). fft is faster still and cleaner at the line, but it removes a band: its default notch width is freqs / 200 (0.3 Hz at 60 Hz), and in this test a real component 0.6 Hz away loses about 2.8 % of its amplitude, while the regression fit leaves it unchanged. The trade-off is a slightly larger residual at the line itself in exchange for not touching activity next to it.
What the patch is. 135 lines in mne/filter.py, no new dependencies. The data are split into windows of 5 s with 50 % overlap; in each window the offset, cosine and sine at the line frequency and its harmonics are fitted by least squares across all picked channels at once, and the fitted sinusoids are subtracted. Windows are combined with a Hann taper. The other method branches are untouched.
One tuning result that may be interesting on its own. The window length is a trade-off between frequency resolution (longer is better) and tracking of the line drift (shorter is better). On the drifting case:
window
overlap
time
residual, relative to unfiltered
10 s
0.5
2.6 s
7.0e-04
5 s
0.5
2.0 s
2.6e-04
2.5 s
0.5
2.2 s
1.4e-04
2.5 s
0.75
4.2 s
5.8e-05
Shorter windows win at the same runtime, because the cost is dominated by the per-window preparation rather than by the number of windows.
Honest limitations.
A line offset of 0.37 Hz is outside the default ±0.1 Hz tolerance and is not
tracked; the tolerance would have to be exposed.
When the line is absent, the estimator still picks a frequency inside the tolerance and subtracts a small fitted sinusoid; a significance check before subtracting would be the next step. With 2.5 s windows a strong neighbouring tone changed by about 3 % in my test; at the 5 s default it was unchanged.
All numbers are from this one machine and from synthetic data. Absolute times will differ on other hardware; the ratios are the part that should generalise. benchmark_notch.py in the branch reproduces both tables, and it also runs on an unpatched checkout.
Tests.test_notch_filters with regression added to the parametrization, plus a test that a tone 0.65 Hz from the line survives while the line is removed: 12 selected notch-related tests pass in a checkout of main.
Question. Would a method="regression" be wanted in MNE, or do you prefer to keep this in mnextend? I can open a PR with the tests and a changelog fragment, or reshape it however fits — for example landing only the window and overlap handling if the method itself is not wanted here.
If it is easier to look at the code than at the numbers: the branch is here — mikech76/mne-python@main...regression-notch — three files: the method, the tests, and benchmark_notch.py, which prints both tables above and also runs on an unpatched checkout. I have not opened a PR.
Disclosure: I drafted the implementation with an AI coding agent and verified it myself — all numbers above come from a script I ran locally, and the MNE test suite was run against the patched checkout.
Did you use the latest version from MNEXTEND? I added frequency tracking in cbrnr/mnextend#19 and fixed a bug with offsets in cbrnr/mnextend#21 (both are available in v0.5.1).
Thanks — that question was worth asking, because it made me find a bug in my own code.
On the version: I compared against mnextendmain (0.6.0.dev0), so both #19 and #21 are in the numbers above. I had to load line_noise.py directly because the package __init__ imports onnx, which is not installed here; the module itself has _FrequencyTracker, so the frequency tracking was active.
But my patch is not a port of mnextend. It is an independent implementation of the same idea, and the only thing I took from mnextend was the reference to compare against. My frequency estimate is a coarse scan plus Gauss-Newton refinement on the residual, not your block demodulation.
Your #21 applies to my code as well - guilty as charged. I did exactly the same thing you fixed: I fitted an offset in each window and then subtracted the whole fit, which shifts the data by the window mean. A 50 µV DC offset disappeared completely. Fixed now: the offset is fitted but not subtracted. On the drifting case with a 50 µV offset, after the fix:
line before
line after
DC before
DC after
my patch
3.9e-02
1.1e-05
5.0e-05
5.0e-05
mnextend main
3.9e-02
4.1e-04
5.0e-05
5.0e-05
On the comparison, with a caveat. Four scenarios, same synthetic data, both methods:
line
5 µV tone at 59.4 Hz
before
my patch
mnextend main
stable
no
5.6e-01
7.1e-06
1.0e-06
stable
yes
5.6e-01
7.5e-06
1.0e-06
drifts to 59.97 Hz
no
3.9e-02
1.0e-05
2.5e-05
drifts to 59.97 Hz
yes
3.9e-02
1.2e-05
4.0e-04
So the answer is not "mine is better": your tracker wins on a stable line by about 7 times, and mine wins under drift, by 2.5 times without a neighbouring tone and much more with it. I suspect that is the window length rather than the estimator — I re-estimate every 5 s and never carry state between windows, so a drifting line is easy, but a stable line gets a noisier estimate per window. I would rather use your estimator inside my window loop than argue about which is better.
I tried the combination you implied. Since the two methods fail in different places, I wired your _FrequencyTracker into my window loop and compared three things on the same four scenarios:
line
tone
mine (my estimator)
mnextend
your estimator + my windows
stable
no
7.1e-06
1.0e-06
9.0e-07
stable
yes
7.5e-06
1.0e-06
1.1e-06
drifts
no
1.0e-05
2.5e-05
6.6e-06
drifts
yes
1.2e-05
4.0e-04
7.0e-06
The combination is the best of the three everywhere, and it runs at the speed of my loop (1.7–2.0 s against 43–44 s for spectrum_fit). So the honest summary is: your estimator is better than mine, my windowing is better for drift, and the useful contribution here is the combination, not either implementation alone. The tracker is the part that made it work — thank you for writing it and for pointing me at #19/#21; I would not have looked there on my own.
What I propose as the next step, if you think any of this belongs in MNE: implement the block-demodulation tracker in the window loop (my branch currently has my own estimator, which is the weaker half), expose window_length, overlap and freq_tolerance, and add a test that covers a drifting line and a DC offset — the two cases where I got it wrong or would not have looked. I can do that work in the branch and open a draft PR for review whenever you want it.
What I would still like to know from you: is the offset handling the only thing #21 changed, or were there other cases? I would like my implementation to fail in the same places as yours does, not in different ones.
You asked whether window_length=5 was all that was needed. It was — and I want to say plainly what that means, because my earlier messages made this look like two competing implementations. It is not.
Your method is sufficient. Mine is not better. The combination I reported last time was your tracker inside my loop, and the sweep showed why it matched mnextend exactly: the win was the window length, not my code. There is nothing in my patch worth putting into MNE, so I am dropping it.
What is left is a practical question: which window_length and overlap to use. I swept both and there is one thing worth knowing.
The trap. The residual kept improving towards shorter windows, which usually means the metric is measuring the wrong thing. It was: below about 2 s the filter stops removing only the line and starts removing the neighbouring signal. With a 5 µV tone 0.6 Hz away:
window (overlap 0.75)
line power left
neighbour tone kept
0.5 s
1.5e-04
14 %
1 s
6.0e-04
46 %
2 s
4.5e-03
100.5 %
5 s
4.7e-03
100.0 %
The reason is physical: at 0.5 s the window holds less than one period of the 0.6 Hz difference between tone and line, so the two are not separable and the fit removes both.
So 2 s is a floor, not a sweet spot. Among the safe combinations, on 64 channels × 20 min:
window / overlap
line left (stable)
line left (drift)
tone kept
time
2 s / 0.50
4.4e-05
1.4e-04
101 %
8 s
2 s / 0.75
2.3e-05
1.1e-04
101 %
14 s
2 s / 0.90
1.8e-05
1.0e-04
101 %
34 s
3 s / 0.75
7.6e-05
1.0e-04
101 %
10 s
5 s / 0.75
3.2e-04
3.5e-04
100 %
7 s
10 s / 0.50 (today)
—
4.0e-04
100 %
12 s
My recommendation: window_length=2, overlap=0.75. It is the best balance in the table — about four times lower residual than the 10 s default on a drifting line, the neighbouring tone intact, and half the cost of the 0.90 overlap, which buys very little.
If you would rather stay conservative, 5 s is safe and simple; the difference is a factor of three, not thirty.
Caveat: synthetic data with a deliberately close neighbour. On real recordings the floor depends on how close real activity sits to the line, so treat 2 s as a lower bound to test, not a value to hard-code.
If it is useful, I can turn this into a test in mnextend: a neighbouring tone keeps its amplitude while the line is removed, so a future change of the default cannot quietly go below the floor.
Thank you for the questions about the version, the offsets and the window — they are what turned my original patch into something useful for your package instead of a second implementation nobody needs.
all of @mikech76's posts in this thread read like they come straight from an agent. Consider this a reminder of our policy on AI assistance in contributions (particularly the paragraph that begins "Please do not paste AI generated text in the description of issues, PRs or in comments...")
The text was drafted with an AI assistant, and I use it for the English as well — I said so at the end of my first message, but a disclosure at the bottom does not make the writing mine, and the shape of my posts reads as machine-written. That is on me.
To be clear about what is open and what is not. The 135-line patch I linked earlier is not going anywhere: the sweep showed it is not better than mnextend, so there is no PR against MNE and there will not be one.
The only PR is cbrnr/mnextend#22, and there is deliberately almost nothing to review in it: one constant (10 s to 5 s) and one test, which fails if a shorter window starts removing a tone next to the line. Every number behind it comes from benchmark_notch.py in the branch, which anyone can run in a few minutes.
Whether that fits your plans is your call — I am reporting a measurement and the change it implies, nothing more.
Activity
cbrnr commentedon Oct 9, 2026
Yes sure, if others want it in MNE I'm happy to move it there. We should really replace the existing one though, because as you say it has been a pain point and is still extremely slow.
larsoner commentedon Oct 9, 2026
spectrum_fithad a number of bugs for a long time but works much better following #14310 (esp. when you specify the freqs). I'd keep it.Adding a new method seems potentially fine, though. Is
regressionjust multiplication by sin/cos (or complex exponential) at the exact specified freqs over the length of a recording (or regression I guess if they're not orthogonal)? If so then maybe some parts ofspectrum_fit(like zoom FFT) could be used to more accurately estimate the true underlying freqs (e.g., 59.95 instead of 60.0 Hz), too... I don't think that's the slow part but we could check.cbrnr commentedon Oct 9, 2026
It's least squares regression, but local rather than over the entire recording. Also, the method only used the fixed given frequencies (plus harmonics), it doesn't handle any deviations. I guess this is really a weak point of this implementation - I'm OK with having users set the nominal line noise frequency (as opposed to finding everything from the data), but we should adapt to the actual frequency over time nonetheless. I think this wouldn't really hurt performance since we'd have to do it only once, but I'd have to take a look how zoom FFT works (so it could be that I'm wrong).
Anyway, it looks like the algorithms are rather different, so we'd probably keep them in separate packages for now. Speed is most important for my use case, since I don't want users to wait over a minute just to remove line noise in a typical EEG recording (but of course we'll have to see how much estimating the actual frequency costs in terms of runtime).
mikech76 commentedon Nov 30, 2026
Hi , I would like to help with this one.
I work on numerical optimization and profiling, and line-noise removal looks like a good place to start: it is self-contained, easy to measure, and users feel it directly. I read the discussion above, measured the methods that exist today, and implemented the regression approach as a patch, so there is something concrete to talk about.
Numbers first.
Setup. 64 EEG channels, 20 min, 250 Hz (19.2 M samples). Synthetic: white noise 20 µV + line noise 5 µV at 60 Hz + 2 µV at 120 Hz. One machine: Intel Xeon E5-2698 v4 @ 2.20 GHz, Windows 10, Python 3.11, mne 1.13.2, numpy 2.4.6, one process, one run per method.
spectrum_fitfftregressionWith a drifting line (60.00 → 59.97 Hz over the recording, which is what real data looks like):
spectrum_fitfftregressionThe regression method is about 25 times faster than
spectrum_fitand leaves a smaller residual at the line (3.8 times smaller on the stable case, 26 times smaller with drift).fftis faster still and cleaner at the line, but it removes a band: its default notch width isfreqs / 200(0.3 Hz at 60 Hz), and in this test a real component 0.6 Hz away loses about 2.8 % of its amplitude, while the regression fit leaves it unchanged. The trade-off is a slightly larger residual at the line itself in exchange for not touching activity next to it.What the patch is. 135 lines in
mne/filter.py, no new dependencies. The data are split into windows of 5 s with 50 % overlap; in each window the offset, cosine and sine at the line frequency and its harmonics are fitted by least squares across all picked channels at once, and the fitted sinusoids are subtracted. Windows are combined with a Hann taper. The othermethodbranches are untouched.One tuning result that may be interesting on its own. The window length is a trade-off between frequency resolution (longer is better) and tracking of the line drift (shorter is better). On the drifting case:
Shorter windows win at the same runtime, because the cost is dominated by the per-window preparation rather than by the number of windows.
Honest limitations.
tracked; the tolerance would have to be exposed.
benchmark_notch.pyin the branch reproduces both tables, and it also runs on an unpatched checkout.Tests.
test_notch_filterswithregressionadded to the parametrization, plus a test that a tone 0.65 Hz from the line survives while the line is removed: 12 selected notch-related tests pass in a checkout ofmain.Question. Would a
method="regression"be wanted in MNE, or do you prefer to keep this in mnextend? I can open a PR with the tests and a changelog fragment, or reshape it however fits — for example landing only the window and overlap handling if the method itself is not wanted here.If it is easier to look at the code than at the numbers: the branch is here — mikech76/mne-python@main...regression-notch — three files: the method, the tests, and
benchmark_notch.py, which prints both tables above and also runs on an unpatched checkout. I have not opened a PR.Disclosure: I drafted the implementation with an AI coding agent and verified it myself — all numbers above come from a script I ran locally, and the MNE test suite was run against the patched checkout.
cbrnr commentedon Nov 30, 2026
Did you use the latest version from MNEXTEND? I added frequency tracking in cbrnr/mnextend#19 and fixed a bug with offsets in cbrnr/mnextend#21 (both are available in v0.5.1).
mikech76 commentedon Nov 30, 2026
Thanks — that question was worth asking, because it made me find a bug in my own code.
On the version: I compared against
mnextendmain(0.6.0.dev0), so both #19 and #21 are in the numbers above. I had to loadline_noise.pydirectly because the package__init__importsonnx, which is not installed here; the module itself has_FrequencyTracker, so the frequency tracking was active.But my patch is not a port of mnextend. It is an independent implementation of the same idea, and the only thing I took from mnextend was the reference to compare against. My frequency estimate is a coarse scan plus Gauss-Newton refinement on the residual, not your block demodulation.
Your #21 applies to my code as well - guilty as charged. I did exactly the same thing you fixed: I fitted an offset in each window and then subtracted the whole fit, which shifts the data by the window mean. A 50 µV DC offset disappeared completely. Fixed now: the offset is fitted but not subtracted. On the drifting case with a 50 µV offset, after the fix:
On the comparison, with a caveat. Four scenarios, same synthetic data, both methods:
So the answer is not "mine is better": your tracker wins on a stable line by about 7 times, and mine wins under drift, by 2.5 times without a neighbouring tone and much more with it. I suspect that is the window length rather than the estimator — I re-estimate every 5 s and never carry state between windows, so a drifting line is easy, but a stable line gets a noisier estimate per window. I would rather use your estimator inside my window loop than argue about which is better.
I tried the combination you implied. Since the two methods fail in different places, I wired your
_FrequencyTrackerinto my window loop and compared three things on the same four scenarios:The combination is the best of the three everywhere, and it runs at the speed of my loop (1.7–2.0 s against 43–44 s for
spectrum_fit). So the honest summary is: your estimator is better than mine, my windowing is better for drift, and the useful contribution here is the combination, not either implementation alone. The tracker is the part that made it work — thank you for writing it and for pointing me at #19/#21; I would not have looked there on my own.What I propose as the next step, if you think any of this belongs in MNE: implement the block-demodulation tracker in the window loop (my branch currently has my own estimator, which is the weaker half), expose
window_length,overlapandfreq_tolerance, and add a test that covers a drifting line and a DC offset — the two cases where I got it wrong or would not have looked. I can do that work in the branch and open a draft PR for review whenever you want it.What I would still like to know from you: is the offset handling the only thing #21 changed, or were there other cases? I would like my implementation to fail in the same places as yours does, not in different ones.
cbrnr commentedon Nov 30, 2026
So this means that setting
window_length=5in MNEXTEND'sremove_line_noise()is all we needed to change, or no?mikech76 commentedon Nov 30, 2026
You asked whether
window_length=5was all that was needed. It was — and I want to say plainly what that means, because my earlier messages made this look like two competing implementations. It is not.Your method is sufficient. Mine is not better. The combination I reported last time was your tracker inside my loop, and the sweep showed why it matched
mnextendexactly: the win was the window length, not my code. There is nothing in my patch worth putting into MNE, so I am dropping it.What is left is a practical question: which
window_lengthandoverlapto use. I swept both and there is one thing worth knowing.The trap. The residual kept improving towards shorter windows, which usually means the metric is measuring the wrong thing. It was: below about 2 s the filter stops removing only the line and starts removing the neighbouring signal. With a 5 µV tone 0.6 Hz away:
The reason is physical: at 0.5 s the window holds less than one period of the 0.6 Hz difference between tone and line, so the two are not separable and the fit removes both.
So 2 s is a floor, not a sweet spot. Among the safe combinations, on 64 channels × 20 min:
My recommendation:
window_length=2,overlap=0.75. It is the best balance in the table — about four times lower residual than the 10 s default on a drifting line, the neighbouring tone intact, and half the cost of the 0.90 overlap, which buys very little.If you would rather stay conservative, 5 s is safe and simple; the difference is a factor of three, not thirty.
Caveat: synthetic data with a deliberately close neighbour. On real recordings the floor depends on how close real activity sits to the line, so treat 2 s as a lower bound to test, not a value to hard-code.
If it is useful, I can turn this into a test in
mnextend: a neighbouring tone keeps its amplitude while the line is removed, so a future change of the default cannot quietly go below the floor.Thank you for the questions about the version, the offsets and the window — they are what turned my original patch into something useful for your package instead of a second implementation nobody needs.
cbrnr commentedon Nov 30, 2026
Thanks for the table - really nice overview! Then I think we should change the default to 5 or 3 in MNEXTEND - feel free to submit a PR!
drammock commentedon Nov 30, 2026
all of @mikech76's posts in this thread read like they come straight from an agent. Consider this a reminder of our policy on AI assistance in contributions (particularly the paragraph that begins "Please do not paste AI generated text in the description of issues, PRs or in comments...")
mikech76 commentedon Nov 30, 2026
Fair point, and thank you for saying it directly.
The text was drafted with an AI assistant, and I use it for the English as well — I said so at the end of my first message, but a disclosure at the bottom does not make the writing mine, and the shape of my posts reads as machine-written. That is on me.
To be clear about what is open and what is not. The 135-line patch I linked earlier is not going anywhere: the sweep showed it is not better than
mnextend, so there is no PR against MNE and there will not be one.The only PR is cbrnr/mnextend#22, and there is deliberately almost nothing to review in it: one constant (10 s to 5 s) and one test, which fails if a shorter window starts removing a tone next to the line. Every number behind it comes from
benchmark_notch.pyin the branch, which anyone can run in a few minutes.Whether that fits your plans is your call — I am reporting a measurement and the change it implies, nothing more.