I'm trying to see if I can obtain identical coherence values for two signals when computing them two different ways:
Method 1: I first compute the cross-correlation and the two auto-correlations. Then I take the DFT of the results to obtain the cross-spectral density and the power spectral densities, from which the coherence can be computed.
Method 2: I simply apply the coherence
function from scipy.signal.
import numpy as np
from matplotlib import pyplot as plt
from scipy.signal import correlate,coherence
t = np.arange(0, 1, 0.001);
dt = t[1] - t[0]
fs=1/dt
f0=250
f1=400
x=np.cos(2*np.pi*f0*t)+np.cos(2*np.pi*f1*t)
y=np.cos(2*np.pi*f0*(t-.035))+np.cos(2*np.pi*f1*(t-.05))
fig, ax = plt.subplots(2,sharex=True)
# Coherence using method 1:
Rxx = correlate(x,x)
Pxx= abs(np.fft.rfft(Rxx))
Ryy = correlate(y,y)
Pyy = abs(np.fft.rfft(Ryy))
Rxy = correlate(x,y)
Pxy = abs(np.fft.rfft(Rxy))
f = np.fft.rfftfreq(len(Rxy))*fs
Coh1=np.divide(Pxy**2,np.multiply(Pxx,Pyy))
#Start at nonzero index, e.g. 50, since Pxx[0]=Pyy[0] where Coh[0] would be undefined
ax[0].plot(f[50:], Coh1[50:])
both equal zero
ax[0].set_xlabel('frequency [Hz]')
ax[0].set_ylabel('Coherence')
# Coherence using method 2:
f,Coh2=coherence(x,y)
ax[1].plot(f*fs,Coh2)
ax[1].set_xlabel('frequency [Hz]')
ax[1].set_ylabel('Coherence')
plt.show()
I obtain the graphs shown below.
The results don't make sense to me. Not only are they different, but neither produces coherence values equal to one at frequencies 250 and 400. The second method should yield an undefined coherence except at 250 and 400.