[英]Get lag with cross-correlation?
Let's say have have two signals:假设有两个信号:
import numpy
dt = 0.001
t_steps = np.arange(0, 1, dt)
a_sig = np.sin(2*np.pi*t_steps*4+5)
b_sig = np.sin(2*np.pi*t_steps*4)
I want to shift the first signal to match the second signal.我想移动第一个信号以匹配第二个信号。 I know this can be completed using cross-correlation, as evidenced by Matlab, but how do I accomplish this with SciPy.
我知道这可以使用互相关来完成,如 Matlab 所证明的那样,但是我如何使用 SciPy 来完成此操作。
As defined in this Wikipedia article , the lag between signals is given by the argmax of the cross-correlation. 如本Wikipedia文章中所定义,信号之间的延迟由互相关的argmax给出。 Consequently, the following code will shift the
b_sig
to be in phased with a_sig
to minimize the error. 因此,以下代码将
b_sig
与a_sig
移相以使错误最小化。
from scipy.signal import correlate
lag = np.argmax(correlate(a_sig, b_sig))
c_sig = np.roll(b_sig, shift=int(np.ceil(lag)))
See some examples first.先看一些例子。 Assume we are in unit tests class already.
假设我们已经在单元测试类中。
# Autocorrelation.
y1 = [1, 1, 0, 0, 1, -1, -1]
corr, lag = cross_corr(y1, y1)
self.assertEqual(lag, 0)
y1 = [1, 1, 0 ,1, -1, -1]
y2 = [1, 0, 1, 0, 0, 2]
corr, lag = cross_corr(y1, y2)
self.assertEqual(lag, -2)
here is my code.这是我的代码。
import numpy as np
def cross_corr(y1, y2):
"""Calculates the cross correlation and lags without normalization.
The definition of the discrete cross-correlation is in:
https://www.mathworks.com/help/matlab/ref/xcorr.html
Args:
y1, y2: Should have the same length.
Returns:
max_corr: Maximum correlation without normalization.
lag: The lag in terms of the index.
"""
if len(y1) != len(y2):
raise ValueError('The lengths of the inputs should be the same.')
y1_auto_corr = np.dot(y1, y1) / len(y1)
y2_auto_corr = np.dot(y2, y2) / len(y1)
corr = np.correlate(y1, y2, mode='same')
# The unbiased sample size is N - lag.
unbiased_sample_size = np.correlate(
np.ones(len(y1)), np.ones(len(y1)), mode='same')
corr = corr / unbiased_sample_size / np.sqrt(y1_auto_corr * y2_auto_corr)
shift = len(y1) // 2
max_corr = np.max(corr)
argmax_corr = np.argmax(corr)
return max_corr, argmax_corr - shift
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.