I am trying to perform Fourier transformation in python. And I would like to know, how to store the noise
obtained from Fourier transformation
as a variable
?
Python code:
import numpy as np
# Create a simple signal with two frequencies
dt = 0.001
t = np.arange(0,1,dt)
f = np.sin(2*np.pi*50*t) + np.sin(2*np.pi*120*t) # Sum of 2 frequencies
f_clean = f
noise = 2.5*np.random.randn(len(t))
f = f + noise # Add some noise
## Compute the Fast Fourier Transform (FFT)
n = len(t)
fhat = np.fft.fft(f,n) # Compute the FFT
PSD = fhat * np.conj(fhat) / n # Power spectrum (power per freq)
freq = (1/(dt*n)) * np.arange(n) # Create x-axis of frequencies in Hz
L = np.arange(1,np.floor(n/2),dtype='int') # Only plot the first half of freqs
## Use the PSD to filter out noise
indices = PSD > 100 # Find all freqs with large power
PSDclean = PSD * indices # Zero out all others
fhat = indices * fhat # Zero out small Fourier coeffs. in Y
ffilt = np.fft.ifft(fhat) # Inverse FFT for filtered time signal
I have tried using the following lines of code to store the noise values, but not sure whether it is right syntax or approach to perform this task.
## To store the noise using the PSD
low_indices = PSD < 100 # Find all freqs with small power
PSDnoise = PSD * low_indices # zero out larger freqs
fhat_noise = low_indices * fhat
Is there any better approach to store these values?
If you do
PSDnoise = PSD * low_indices
You will have 0
values where there was a False
in low_indices
.
If you just want to keep the values of PSD
at indices where you're lower than your threshold, you can use array indexing, like so:
PSDnoise = PSD[low_indices]