Get lag with cross-correlation?
<p>Let's say have have two signals:</p>

<pre><code>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)
</code></pre>

<p>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.</p>

<p>As defined in <a href="https://en.wikipedia.org/wiki/Cross-correlation#Time_delay_analysis" rel="nofollow">this Wikipedia article</a>, the lag between signals is given by the argmax of the cross-correlation. Consequently, the following code will shift the <code>b_sig</code> to be in phased with <code>a_sig</code> to minimize the error.</p>

<pre><code>from scipy.signal import correlate

lag = np.argmax(correlate(a_sig, b_sig))
c_sig = np.roll(b_sig, shift=int(np.ceil(lag)))
</code></pre>

python numpy scipy signal-processing