简体   繁体   English

scipy.signal welch 与 matlab pwelch 的等效性

[英]equivalence scipy.signal welch to matlab pwelch

I have the following MATLAB code to compute the PSD of a signal:我有以下 MATLAB 代码来计算信号的 PSD:

x = linspace(0, 10, 100001);
dt = x(2) - x(1);
Fs = 1 / dt;
a1 = 1;
f1 = 500;
a2 = 10;
f2 = 2000;
y = a1 * sin(2*pi*f1*x) + a2 * sin(2*pi*f2*x);

nblock=1024;
overlap=128;
windowsel=hann(nblock);
[Pxx,f]=pwelch(y,windowsel,overlap,nblock,Fs,'onesided');
figure()
semilogy(f,Pxx, '-o')

I have tried to reproduce the same calculation using welch in scipy.signal .我试图在scipy.signal使用welch重现相同的计算。 However, for low frequency, the behavior is clearly not the same.然而,对于低频,行为显然不一样。 I have checked that the hanning window is the same in both.我已经检查过两者的汉宁窗口是否相同。 What other parameter can I change in order to reproduce the results?为了重现结果,我还可以更改哪些其他参数?

import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import welch, hanning

x = np.linspace(0, 10, 100001)
dt = x[1] - x[0]
fs = 1 / dt

a1 = 1
f1 = 500

a2 = 10
f2 = 2000

y = a1 * np.sin(2*np.pi*f1*x) + a2 * np.sin(2*np.pi*f2*x)

datos = y

nblock = 1024
overlap = 128
win = hanning(nblock, True)

f, Pxxf = welch(datos, fs, window=win, noverlap=overlap, nfft=nblock, return_onesided=True)

plt.semilogy(f, Pxxf, '-o')

plt.grid()
plt.show()

MATLAB: MATLAB:

Matlab pwelch Matlab pwelch-zoom

PYTHON: PYTHON: 在此处输入图片说明

问题在使用detrend=False时解决,如 GitHub 问题https://github.com/scipy/scipy/issues/8045#issuecomment-337319294 中所述

Your parameters seem correct and I can reproduce your result in Python.您的参数似乎正确,我可以在 Python 中重现您的结果。

An explanation for the difference is possibly the different implementation of the Welch' method in MATLAB and SciPy.差异的一个解释可能是 MATLAB 和 SciPy 中 Welch' 方法的不同实现。 Looking at the graph and that the behavior manifests only close to zero I find this likely.查看图表并且行为表现仅接近于零,我发现这很可能。

You could try to play with input values (window length, sample frequency, FFT length) a little bit and see if the problem persists.您可以尝试稍微处理输入值(窗口长度、采样频率、FFT 长度),看看问题是否仍然存在。 If not you may have found an edge case (perhaps do to numerical errors) in the function and there is nothing you can do about it apart from digging into the implementation details which is not possible in MATLAB's case.如果没有,您可能在函数中发现了一个边缘情况(可能是数值错误),除了深入研究在 MATLAB 情况下不可能的实现细节之外,您无能为力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM