我正在识别Python中两个正弦信号之间的时移。对此的一些研究表明,两个输入信号之间的相关性可以解决这个问题。然而,在处理相关性时,我不理解np.correlate
和scipy.signal.correlate()
的结果,因为结果与先验结果不同。
让
t = np.arange(0, 10, 0.01)
sig1 = np.sin(t)
sig2 = np.cos(t)
我希望两个信号之间的差为pi/2 = 1.571。但是,以下代码确定|1.490|.
import scipy
import numpy as np
t = np.arange(0, 10, 0.01)
sig1 = np.sin(t)
sig2 = np.cos(t)
# Scipy
#x = scipy.signal.correlate(sig1, sig2, mode='full')
#tx = signal.correlation_lags(len(sig1), len(sig2))
# Numpy
x = np.correlate(sig1, sig2, 'full')
tx = np.linspace(-t[-1], t[-1], 2*len(t)-1)
ndx = np.argmax(np.abs(x))
print(tx[ndx])
>>> -1.4900000000000002
我是不是漏掉了什么相关模式?
然而,余弦相似性或最小二乘优化给出了正确的结果。此外,两个信号的极值的简单比较正确地工作。
包含绘图的完整代码:
import scipy
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots(3, figsize=(8,6))
t = np.arange(0, 10, 0.01)
sig1 = np.sin(t)
sig2 = np.cos(t)
# Plot 1: Both input signals
ax[0].plot(t, sig1, label='sig1')
ax[0].plot(t, sig2, label='sig2')
ax[0].legend()
ax[0].set_xlabel('time in s')
## Apply correlation between the two given signals
# Scipy
#x = scipy.signal.correlate(sig1, sig2, mode='full')
#tx = signal.correlation_lags(len(sig1), len(sig2))
# Numpy
x = np.correlate(sig1, sig2, 'full')
tx = np.linspace(-t[-1], t[-1], 2*len(t)-1)
# Plot 2: Correlation between two input signals
ax[1].plot(tx, x, label='correlation', c='k')
ndx = np.argmax(np.abs(x))
ax[1].plot(tx[ndx], x[ndx], 'rx')
ax[1].legend()
# Plot 3: Both input signals, sig2 on corrected time values
ax[2].plot(t, sig1, label='sig1')
t_corr = t - tx[ndx] # Correct the time
ax[2].plot(t_corr, sig2, label='sig2')
ax[2].set_xlabel(r'Shift: %.5f' %(tx[ndx]))
ax[2].legend()
print(tx[ndx]) # Display the shift
1条答案
按热度按时间wxclj1h51#
你的代码是正确的,问题是相关性。此方法假设您有一个无限大的信号。然后,信号越短,误差将越大。
我用一个更长的
t
向量执行了你的代码,结果是|1.569999999999709|,这更类似于pi/2 = 1.571。如果你确定信号是正弦的,我建议你使用你所引用的另一种方法。