Created
June 4, 2021 15:04
-
-
Save fsheikh/70b343e2a265f9b130f049a19095f118 to your computer and use it in GitHub Desktop.
sinusoid recovery from low SNR signal
This file contains 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 scipy.signal import firwin, lfilter, butter, medfilt | |
import matplotlib | |
matplotlib.use('TkAgg') | |
import matplotlib.pyplot as plt | |
# sampling frequency in Hz | |
Fs = 8000 | |
# center frequency of a band-limited signal | |
fc = 50 | |
# Observe duration in seconds, forumulate a time-axis | |
T = 1 | |
tvals = np.arange(0, T, 1/Fs) | |
fig=plt.figure(figsize=(10,10)) | |
s_t = np.sin(2*np.pi*fc*tvals) | |
# Noise amplitude 5x signal strength | |
noiseA = 5 | |
n_t = np.random.rand(len(s_t)) * noiseA * np.sqrt(np.power(10, -0.3)) | |
plt.subplot(2,2,1) | |
plt.plot(tvals, s_t) | |
plt.ylabel('band-limited signal') | |
plt.grid() | |
# Signal + noise | |
x_t = s_t + n_t | |
plt.subplot(2,2,2) | |
plt.plot(tvals, x_t) | |
plt.ylabel('Low SNR noisy signal') | |
plt.grid() | |
# Simple FIR/IIR filtering, taps and filter order respectively | |
N = 31 | |
L = 3 | |
taps_lowpass = firwin(N, (fc)/Fs) | |
b,a = butter(L, 2 * (fc)/Fs, btype='low') | |
lp_filtered_signal = lfilter(taps_lowpass, 1.0, x_t) | |
bp_filtered_signal = lfilter(b, a, x_t) | |
plt.subplot(2,2,3) | |
plt.plot(tvals, lp_filtered_signal) | |
plt.grid() | |
plt.xlabel('Time') | |
plt.ylabel('FIR Low pass filtered signal') | |
plt.tight_layout() | |
plt.subplot(2,2,4) | |
plt.plot(tvals, bp_filtered_signal) | |
plt.xlabel('Time') | |
plt.ylabel('IIR Low pass filtered signal') | |
plt.tight_layout() | |
plt.grid() | |
plt.figure(2) | |
# Frequency analysis for non-linear filtering | |
X_w = np.fft.fft(x_t) | |
# Filter low energy noise components | |
max_freq_comp = np.max(np.abs(X_w)) | |
X_w_ignore_low = np.where(np.abs(X_w) > max_freq_comp/10, X_w, 0+0j) | |
# Filter DC component | |
X_w_ignore_low[0] = 0+0j | |
F_w = np.fft.fftfreq(tvals.shape[-1]) | |
y_t = np.fft.ifft(X_w_ignore_low) | |
plt.title('Non-linear filtering of AWGN tempered signal') | |
plt.subplot(2,2,1) | |
plt.plot(tvals, x_t) | |
plt.xlabel('Time') | |
plt.ylabel('Low SNR noisy signal') | |
plt.grid() | |
plt.subplot(2,2,2) | |
plt.plot(F_w, np.abs(X_w)) | |
plt.xlabel('Frequency axis') | |
plt.ylabel('Frequency response noisy signal') | |
plt.grid() | |
plt.subplot(2,2,3) | |
plt.plot(F_w, np.abs(X_w_ignore_low)) | |
plt.xlabel('Frequency axis') | |
plt.ylabel('Frequency response after non-linear filtering') | |
plt.grid() | |
plt.subplot(2,2,4) | |
plt.plot(tvals, y_t) | |
plt.ylabel('Recovered signal') | |
plt.xlabel('Time') | |
plt.grid() | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Quick plotting python