Python – FTT – with Scipy

Python FFT or Sinewave with two components using Scipy-FFT

Show result in plots using Matplotlib(r) library

Starting point was from a Chat AI which did not put the import Matplotlib

Modification added to get plots and limit frequency span.

Also limited frequency components via a threshold value on relative amplitude.

Presentation

Code

# -*- coding: utf-8 -*-
"""
Created on Wed Nov 29 07:38:05 2023

@author: aleja
"""
#Testing G-AI created code
#added modifications
 
import numpy as np
import matplotlib.pyplot as plt #added was missing
import scipy.fft as fft

# Create a sine wave
freq=10
resolution=0.001
t = np.arange(0, freq, resolution)
#freq and 10xfreq
y = 4.0*np.sin(2.0 * np.pi * t)+2.0*np.sin(2.0 * np.pi * 10.0*t)
print("number of points:",freq/resolution)
print (np.max(y))
print (np.min(y))
# Calculate the fft
yf = fft.fft(y)
yfa=np.abs(yf)/np.max(np.abs(yf)) #relative amplitude
yfa=yfa[0:1000]

threshold_of_yffamp=0.2
indexs=np.where(yfa>threshold_of_yffamp) #remember indexs[0] holds the tuples

#convert indexs tuple to list
list_indexs=list(indexs[0])
print("==============")
print("freq,rel-amp")
for index in list_indexs:
    print (index,",",yfa[index]) 
print("==============")

#limit freq range
freq_range=np.max(indexs)*2
# Plot the fft
plt.close('all')
fig, [plt1,plt2] = plt.subplots(nrows=2, ncols=1)
plt1.plot(t,y,"b.")
plt1.set_xlabel("period")
plt1.set_ylabel("amplitude")
plt1.set_title("Sample data-fictional")


plt2.set_xlim(0,freq_range) #limit x axis freq range
plt2.plot(np.abs(yfa),"r-")
plt2.set_xlabel("freq")
plt2.set_ylabel("relative amp")
plt2.set_title("FFT")
for n in list_indexs:
 plt_text=(str(yfa[n])+","+ str(n))
 plt2.text(n,yfa[n],plt_text)

plt.get_current_fig_manager().window.setGeometry(10,50,1000,500)
plt.tight_layout()

plt.show

Code

Notes

  • Presentation: Testing FTT module from Scipy on two component sinewave
  • Programming Language used: Python 3.11.3 in Spyder5.4.3,Matplotlib 3.7.2
  • Presentation app: Microsoft’s PowerPoint
  • Helpful resource: Stackoverflow, Search Engines , Chat AI, and Python communities.
  • Python, Tkinter, Matplotlib, Scipy are products of respective companies
  • Presentation shown to spark ideas of use.
  • This presentation is not connected to or endorsed by any company.
  • Use at your own risk.
  • Tags: Python, Python3.11, numpy Matplotlib , Scipy, FFT, List, Sinewave, np.where.
Unknown's avatar

About LV_TS_Test_Engineer_3000_VI

Automated Test Equipment Software
This entry was posted in Python, SciPy, Test Sector and tagged , , , , , . Bookmark the permalink.

Leave a comment