Repository navigation
Align complex Welch coefficient scaling with multitaper - #14574
Arham-Begani wants to merge 2 commits into
Conversation
tsbinns
left a comment
There was a problem hiding this comment.
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.
| # 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 |
There was a problem hiding this comment.
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.
|
mne-python/mne/time_frequency/tests/test_psd.py Lines 229 to 246 in 3d46981 (here it is scaling DC and Nyquist differently from the one-sided bins, which this PR would no longer require) |
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 * 2give 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.