Coherence Part 1 (Two noise signals)

# Load modules we'll need.
from scipy.io import loadmat
import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import spectrogram

Make two noise signals

N = 1000;
dt= 0.001;
T = N*dt;
x = np.random.randn(N)
y = np.random.randn(N)
t = np.arange(0,N)*dt

plt.plot(t,x)
plt.plot(t,y)
plt.xlabel('Time [s]');

Compute the cross-covariance

cc_xy = "SOMETHING"                          # Compute the covariance.
lags = np.arange(-N + 1, N)                  # Create a lag axis,
plt.plot(lags * dt, cc_xy)                   # ... and plot the result.
plt.ylim([-0.1, 1])
plt.xlabel('Lag [s]')
plt.ylabel('Cross-covariance');

Compute the coherence

Xf = np.fft.fft(x - x.mean())           # Compute Fourier transform of x
Yf = np.fft.fft(y - y.mean())           # Compute Fourier transform of y

# Compute the spectra
Sxx = "SOMETHING"  # Spectrum of x
Syy = "SOMETHING"  # ... and y
Sxy = "SOMETHING"  # ... and the cross spectrum

# Compute the coherence.
cohr = "SOMETHING"

# Define a frequency axis.
f = np.fft.fftfreq(N, dt)

# Plot the result.
plt.plot(f, cohr.real)