I will summarize the method using numpy and scipy in FFT processing. This page compares processing times.
I referred to the following page. ■ Python NumPy SciPy: Waveform shaping by FFT processing (smoother) https://org-technology.com/posts/smoother.html
First, create sample data to process.
import numpy as np
from scipy import fftpack
import matplotlib.pyplot as plt
#Sample data creation
n = 512 #The number of data
dt = 0.01 #Sampling interval
f = 1 #frequency
t = np.linspace(1, n, n)*dt-dt
y = np.sin(2*np.pi*f*t)+0.5*np.random.randn(t.size)
#FFT processing and frequency axis creation
yf = fftpack.fft(y)/(n/2)
freq = fftpack.fftfreq(n, dt)
① How to use scipy fftpack (fft, ifft)
yf = fftpack.fft(y)/(n/2)
freq = fftpack.fftfreq(n, dt)
fs = 2
yf2 = np.copy(yf)
yf2[(freq > fs)] = 0
yf2[(freq < 0)] = 0
y2 = np.real(fftpack.ifft(yf2)*n)
Calculation time: 48.2 µs ± 869 ns per loop (mean ± std. Dev. Of 7 runs, 10000 loops each)
② How to use scipy fftpack (rfft, irfft)
yf = fftpack.rfft(y)/(n/2)
freq = fftpack.fftfreq(n, dt)
fs = 2
yf2 = np.copy(yf)
yf2[(freq > fs)] = 0
yf2[(freq < 0)] = 0
y2 = np.real(fftpack.irfft(yf2)*(n/2))
Calculation time: 38.7 µs ± 723 ns per loop (mean ± std. Dev. Of 7 runs, 10000 loops each)
③ How to use numpy fft
yf = np.fft.fft(y)/(n/2)
freq = np.fft.fftfreq(n, d=dt)
fs = 2
yf2 = np.copy(yf)
yf2[(freq > fs)] = 0
yf2[(freq < 0)] = 0
y2 = np.real(np.fft.ifft(yf2)*n)
Calculation time: 41.3 µs ± 2.3 µs per loop (mean ± std. Dev. Of 7 runs, 10000 loops each)
Result is 1st place 38.7us ② How to use scipy fftpack (rfft, irfft) 2nd place 41.3us ③ How to use numpy fft 3rd place 48.2us ① How to use scipy fftpack (fft, ifft)
that's all.
Recommended Posts