1"""
2========
3CSD Demo
4========
5
6Compute the cross spectral density of two signals
7"""
8import numpy as np
9import matplotlib.pyplot as plt
10
11
12fig, (ax1, ax2) = plt.subplots(2, 1)
13# make a little extra space between the subplots
14fig.subplots_adjust(hspace=0.5)
15
16dt = 0.01
17t = np.arange(0, 30, dt)
18
19# Fixing random state for reproducibility
20np.random.seed(19680801)
21
22
23nse1 = np.random.randn(len(t))                 # white noise 1
24nse2 = np.random.randn(len(t))                 # white noise 2
25r = np.exp(-t / 0.05)
26
27cnse1 = np.convolve(nse1, r, mode='same') * dt   # colored noise 1
28cnse2 = np.convolve(nse2, r, mode='same') * dt   # colored noise 2
29
30# two signals with a coherent part and a random part
31s1 = 0.01 * np.sin(2 * np.pi * 10 * t) + cnse1
32s2 = 0.01 * np.sin(2 * np.pi * 10 * t) + cnse2
33
34ax1.plot(t, s1, t, s2)
35ax1.set_xlim(0, 5)
36ax1.set_xlabel('time')
37ax1.set_ylabel('s1 and s2')
38ax1.grid(True)
39
40cxy, f = ax2.csd(s1, s2, 256, 1. / dt)
41ax2.set_ylabel('CSD (db)')
42plt.show()
43