Discrete Fourier Transform#

import numpy as np
import scipy.linalg as la
import matplotlib.pyplot as plt
from IPython.display import Audio
plt.rcParams["figure.figsize"]=(15,4) # Set default figure size

Examples of sinusoids#

N = 100
k = 3
n = np.arange(0,N)
phi = np.pi/4
x = np.cos(2*np.pi*k*n/N + phi)
plt.stem(x,use_line_collection=True)
plt.grid(True); plt.show();
../_images/20a4987d1e5da5b37e1553fddb59624e6902454775343a72b6ce4d7c4734536d.png

Compute FFT#

N = 100
k = 3
n = np.arange(0,N)
phi = np.pi/4
x = np.cos(2*np.pi*k*n/N + phi)
y = np.fft.fft(x)

plt.figure(figsize=(15,8))
plt.subplot(3,1,1)
plt.stem(x,use_line_collection=True)
plt.title('Signal'); plt.grid(True);

plt.subplot(3,1,2)
plt.stem(np.abs(y),use_line_collection=True)
plt.title('Magnitude of DFT(x)'); plt.grid(True);

plt.subplot(3,1,3)
y_angle = np.angle(y)
y_angle[np.abs(y) < 1e-12] = 0
plt.stem(y_angle,use_line_collection=True)
plt.title('Phase of DFT(x)'); plt.grid(True)

plt.show();
../_images/28fb4db1f4c360a5b6b15b973212e6a39c89b035d1e708fe97596a69b455796f.png

Play audio signal#

N = 44100
k1 = 500; k2 = 750; k3 = 1100;
n = np.arange(0,N)
x = sum([np.cos(2*np.pi*k*n/N) for k in [k1,k2,k3]])
Audio(x,rate=N)

Filtering#

N = 100
k = 3
n = np.arange(0,N)
phi = np.pi/4
x = np.cos(2*np.pi*k*n/N + phi) + np.random.random(N)
y = np.fft.fft(x)

plt.figure(figsize=(15,8))
plt.subplot(3,1,1)
plt.stem(x,use_line_collection=True)
plt.title('Signal'); plt.grid(True);

plt.subplot(3,1,2)
plt.stem(np.abs(y),use_line_collection=True)
plt.title('Magnitude of DFT(x)'); plt.grid(True);

plt.subplot(3,1,3)
plt.stem(y_angle,use_line_collection=True)
plt.title('Phase of DFT(x)'); plt.grid(True)

plt.show();
../_images/d3d9f4786fd9710c729a4a77d58acb39be0ee3a01ed0e15c437ab777fc9a0e16.png
y_filtered = y.copy()
y_filtered[y < 10] = 0.0
plt.figure(figsize=(15,8))
x_filtered = np.fft.ifft(y_filtered).real

plt.subplot(2,1,1)
plt.stem(x,use_line_collection=True)
plt.title('Signal'); plt.grid(True);

plt.subplot(2,1,2)
plt.stem(x_filtered,use_line_collection=True)
plt.title('Filtered Signal'); plt.grid(True);

plt.show();
../_images/e25d05fec283ba4f45f7b9a0bd268cab8a43331ad10f8cce5871d8f02671509d.png