[PYTHON] FFT processing with numpy and scipy and low pass filter

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

FFT processing with numpy and scipy and low pass filter
Create filter with scipy
Use OpenBLAS with numpy, scipy
See the power of speeding up with NumPy and SciPy
Path processing with takewhile and dropwhile
Image processing with Python 100 knock # 10 median filter
Read and write csv files with numpy
Graph trigonometric functions with numpy and matplotlib
Image processing with Python 100 knocks # 9 Gaussian filter
Create filter with scipy
About django custom filter arguments
Image processing with Python 100 knocks # 9 Gaussian filter
I compared the moving average of IIR filter type with pandas and scipy
I want to use mkl with numpy and scipy under pyenv + poetry environment
Using Intel MKL with NumPy / SciPy (November 2019 version)
Pass an array from PHP to PYTHON and do numpy processing to get the result