Last active
May 29, 2024 13:54
-
-
Save danilo-bc/489d23ef498d6adc1d6c57b970d54c06 to your computer and use it in GitHub Desktop.
Handy Numpy FFT crash course to revise the main concepts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import numpy as np | |
| from numpy.fft import fft, fftfreq | |
| import matplotlib.pyplot as plt | |
| # Input: Sine wave with 30º offset | |
| # Expected results: discrete impulse with A/2 amplitude at fc | |
| # Phase equal to 90 - phase offset | |
| # | |
| # Phase may be noisy given lower oversampling rate | |
| # Have to adjust the threshold parameter | |
| A = 2 | |
| fc = 10 | |
| fs = 32 * fc # oversampling rate | |
| phi_offset_deg = 30 | |
| t = np.arange(0, 4, 1/fs) | |
| window_size = 1024 | |
| N = window_size | |
| df = fs / N | |
| sig = A * np.sin(2 * np.pi * fc * t + np.deg2rad(phi_offset_deg)) | |
| sig_freq = fft(sig, N) / N #normalize amplitude | |
| f = fftfreq(sig_freq.size, 1/fs) | |
| # Signal plot | |
| plt.figure(figsize=(16,9)); | |
| plt.plot(t, sig); | |
| # Amplitude plot | |
| plt.figure(figsize=(16,9)); | |
| plt.stem(f, np.abs(sig_freq)); | |
| # Phase plot | |
| sig_freq_filtered = 1 * sig_freq | |
| sig_freq_filtered[sig_freq < np.max(np.abs(sig_freq))/10000] = 1e-16 | |
| plt.figure(figsize=(16,9)); | |
| phase = np.rad2deg(np.angle(sig_freq_filtered)) | |
| plt.plot(f, phase); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment