Skip to content

Align complex Welch coefficient scaling with multitaper - #14574

Open
Arham-Begani wants to merge 3 commits into
mne-tools:mainfrom
Arham-Begani:fix-14426-welch-scaling
Open

Arham-Begani wants to merge 3 commits into
mne-tools:mainfrom
Arham-Begani:fix-14426-welch-scaling

Conversation

@Arham-Begani

@Arham-Begani Arham-Begani commented Nov 20, 2026 •

Copy link
Copy Markdown

Fixes #14426

Welch and multitaper used different scaling conventions for complex coefficients, so converting those coefficients to power required special handling at the ends of the spectrum. For real input, Welch now divides the DC coefficient and, for even-length FFTs, the Nyquist coefficient by √2. This makes (coefs * np.conj(coefs)).real * 2 give the per-segment power at every returned frequency. Tests compare that result with direct Welch power for odd and even FFT lengths and cropped frequency ranges.

I used OpenAI Codex to implement the Welch scaling fix, update the tests and documentation, and revise the patch after review. I reviewed commit 3afea41 myself and tested it byconverting complex coefficients to power with (coefs * np.conj(coefs)).real * 2 matched the power Welch returned directly. The tests covered odd and even FFT lengths and cropped frequency ranges.

@tsbinns tsbinns left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR @Arham-Begani. A couple of comments and suggestions below.
I haven't dug into the tests yet, so this is not covered in the review.

Comment thread mne/time_frequency/psd.py Resolved
Comment thread mne/time_frequency/psd.py Resolved
Comment thread mne/time_frequency/psd.py Resolved
Comment thread mne/time_frequency/psd.py Resolved
Comment thread mne/time_frequency/spectrum.py Resolved
Comment thread mne/time_frequency/spectrum.py Outdated
# Handle legacy Welch spectra and other complex SpectrumArray data.
if np.iscomplexobj(data):
data = (data * data.conj()).real # Scaling may be slightly off
data = (data * data.conj()).real

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rather than treating legacy Welch separately, I would suggest to handling it in one place, e.g.:

# convert complex → power (not for multitaper)
if np.iscomplexobj(data) and "taper" not in self._dims:
    data = (data * data.conj()).real * 2

# handle unaggregated Welch
if "segment" in self._dims:
    logger.info("Aggregating Welch estimates (median) before plotting...")
    data = np.nanmedian(data, axis=self._dims.index("segment"))

I think it's worth handling the power conversion and segment aggregation seperately, as then it would be compatible with custom methods peopel have stored in SpectrumArray objects.

It does mean the legacy Welch scaling will be wrong, but it was already wrong.

Also worth noting that it's important segments are aggregated after conversion to power.

Comment thread mne/time_frequency/spectrum.py Resolved
Comment thread mne/time_frequency/psd.py Resolved
Comment thread mne/time_frequency/spectrum.py Resolved
@tsbinns

tsbinns commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

2 * abs(coef) ** 2 is also not the appropriate conversion to power. (coefs * conj(coefs)).real * 2 is what gives an output identical to computing power directly from psd_array_welch.

coefs, freqs = psd_array_welch(
data, sfreq, average=None, output="complex", **kwargs
)
assert coefs.shape[-1] > 1
scale = np.where((freqs == 0) | np.isclose(freqs, sfreq / 2), 1.0, 2.0)
segment_power = (coefs * np.conj(coefs)).real * scale[:, np.newaxis]
for average in ("mean", "median"):
power, freqs_power = psd_array_welch(
data, sfreq, average=average, output="power", **kwargs
)
assert_array_equal(freqs, freqs_power)
if average == "mean":
converted = segment_power.mean(axis=-1)
else:
converted = np.median(segment_power, axis=-1) / _median_bias(
segment_power.shape[-1]
)
assert_allclose(converted, power)

(here it is scaling DC and Nyquist differently from the one-sided bins, which this PR would no longer require)

@tsbinns tsbinns left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Arham-Begani Thanks for the changes. Just two minor comments for now.
I still haven't added anything on the tests, as there are some broader questions I have about what we are expected to support (see #14596).

Until that is clearer, I would hold off on providing any further comments, so that I don't end up asking you to change things which you later have to roll back.

Comment on lines +1723 to +1724
# _psd_from_mt expects tapers second from last, even for segmented data.
data = np.moveaxis(data, self._dims.index("taper"), -2)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
# _psd_from_mt expects tapers second from last, even for segmented data.
data = np.moveaxis(data, self._dims.index("taper"), -2)

This should not be necessary. Only one of taper or segment dimensions can be present, and if tapers is present, it is required to be in the penultimate position, so by this point, the taper dimension is in the correct position.

Comment thread mne/time_frequency/spectrum.py Outdated
Comment on lines +2784 to +2789

Notes
-----
Complex Welch spectra saved before version 1.14 retain their original
coefficient scaling. Recompute the spectrum from the time series to use the
scaling described in :func:`~mne.time_frequency.psd_array_welch`.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Notes
-----
Complex Welch spectra saved before version 1.14 retain their original
coefficient scaling. Recompute the spectrum from the time series to use the
scaling described in :func:`~mne.time_frequency.psd_array_welch`.

I don't think a note like this for a bug fix is necessary.

@tsbinns tsbinns left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, after clarification in #14596, support for two-sided spectra is not intentional, and will be removed from accepted input to SpectrumArray objects.

Comment thread mne/time_frequency/psd.py
Comment on lines +50 to +52
if np.iscomplexobj(epoch):
# SciPy switches to a two-sided spectrum for complex input.
spect /= np.sqrt(2.0)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we want to downscale every bin for the two-sided spectrum.
Is the ouput not equivalent to the one-sided complex (stft) output in the sense that the internal (non-DC and non-Nyquist) freq bins are not yet scaled?

Comment thread mne/time_frequency/psd.py Outdated
Comment on lines +203 to +204
For complex-valued input, Welch uses a two-sided FFT and divides all
coefficients by the square root of two.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this can be removed outright.

Comment thread mne/utils/docs.py
Comment on lines +3106 to +3111
docdict["notes_fourier_coefficient_scaling"] = """
For one-sided spectra, the DC coefficient and, for even-length FFTs, the Nyquist
coefficient are divided by the square root of two. At every frequency,
``(coefs * np.conj(coefs)).real * 2`` gives the power before averaging over
segments or tapers.
"""

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
docdict["notes_fourier_coefficient_scaling"] = """
For one-sided spectra, the DC coefficient and, for even-length FFTs, the Nyquist
coefficient are divided by the square root of two. At every frequency,
``(coefs * np.conj(coefs)).real * 2`` gives the power before averaging over
segments or tapers.
"""
docdict["notes_fourier_coefficient_scaling"] = """
For one-sided spectra, the DC coefficient and, for even-length FFTs, the Nyquist
coefficient are divided by the square root of two, such that at every frequency,
``(coefs * np.conj(coefs)).real * 2`` gives the conversion to power.
"""

Please also remove mention about this being specific to one-sided spectra.

Remove the read_spectrum note about legacy complex Welch spectra and the
psd_array_welch note about complex-valued input, and reword the shared
coefficient scaling note so it no longer refers to one-sided spectra.

Claude Code made these changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCTjcGVPzrnSDUW3sbB3yn
@tsbinns

tsbinns commented Nov 27, 2026

Copy link
Copy Markdown
Member

@Arham-Begani If you are working with agents, make sure they are directed to our AGENTS.md file, in particular the instruction to not add AI co-authorship trailers to commits: https://github.com/mne-tools/mne-python/blob/main/AGENTS.md#ai-assistance-policy-read-first.

You will need to remove Claude as a co-author of that last commit.

This branch has not been deployed

No deployments
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.

Possible scaling error for 0 and Nyquist frequencies in multitaper spectra

2 participants