%pylab
%matplotlib inline
Using matplotlib backend: Qt4Agg Populating the interactive namespace from numpy and matplotlib
Correlation is a measurement of how similar two signals. The cross correlation allows us to measure the similiarity between two signals at different lag positions.
# Sin function to generate signals
delay = 0.6 # ms
f = lambda(x) : np.sin(x) # original signal
g = lambda(x) : np.sin(x - delay)
dt = 0.05 # sampling interval (in ms)
time = np.arange(start = 0, stop = 30.00, step = dt) # sample 30 ms seconds at 20 kHz (100 samples)
# generate signals
A, B = f(time), g(time)
# Plot signals
plt.plot(time, A, lw=1, color = 'magenta');
plt.plot(time, B, lw=1, color = 'blue');
plt.xlabel('Time (ms)');
plt.ylabel('Signal (AU)');
# compute signal autocorrelation
coor = np.correlate(A, A, 'full')
maxlag = coor.size/2
lag = np.arange(-maxlag, maxlag+1)*dt
plt.plot(lag, coor, lw=1);
line = plt.axvline(x=0, ymin=-40, ymax = 50, linewidth=1.5, color='r')
line.set_dashes([8, 4, 2, 4, 2, 4])
# compute cross correlation
coor = np.correlate(A, B, 'full')
maxlag = (coor.size-1)/2
lag = np.arange(-maxlag, maxlag+1)*dt
# plot cross correlogram with line about 1 ms
plt.plot(lag, coor, lw=1);
line = plt.axvline(x=-delay, ymin=np.min(coor), ymax = np.max(coor), linewidth=1.5, color='c')
line.set_dashes([8, 4, 2, 4, 2, 4])
# Calculate lag position of maximal correlation
def lag_ix(x,y):
corr = np.correlate(x,y,mode='full')
pos_ix = np.argmax( np.abs(corr) )
lag_ix = pos_ix - (corr.size-1)/2
return lag_ix
lag_ix(A,B)
-11
delay_estimation = -lag_ix(A,B)*dt
delay_estimation
0.55000000000000004
plt.plot(lag, coor, lw=1);
line = plt.axvline(x=-delay_estimation, ymin=-40, ymax = 50,
linewidth=1.5, color='r', label='estimated delay')
line = plt.axvline(x=-delay, ymin=np.min(coor), ymax = np.max(coor),
linewidth=1.5, color='c', label='true delay')
line.set_dashes([8, 4, 2, 4, 2, 4])
plt.xlim(-2*delay, 0)
plt.legend(loc='lower right');