Created
September 28, 2019 00:45
-
-
Save Factoid/ae6212d552217b1559a6f3541d491074 to your computer and use it in GitHub Desktop.
Example Zoom FFT Implementation
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
from pyqtgraph.Qt import QtGui, QtCore | |
import numpy as np | |
import pyqtgraph as pg | |
from scipy import signal | |
import math | |
import random | |
import cmath | |
def gen_tone_data( sampleRate, seconds ): | |
samples = int(sampleRate * seconds) | |
f1 = 12140.0 | |
f2 = 12145.1 | |
dt = 1/sampleRate | |
pi2dt = 2.0*math.pi*dt; | |
return [ 2*math.sin(pi2dt*f1*i)+1*math.sin(pi2dt*f2*i)+(random.random()-0.5) for i in range(samples)] | |
def myfft( signalBuf, sampleRate, nBins, offset ): | |
outBins = (nBins//2) | |
binWidth = (sampleRate/2) / outBins | |
# print( "sampleRate", sampleRate, "min", offset, "outbins", outBins, "binWidth", binWidth, "max", (outBins-1)*binWidth+offset ) | |
return [ [ offset + i * binWidth for i in range(outBins) ], [abs(x) for x in np.fft.fft(signalBuf,n=nBins)[0:outBins] ] ] | |
def shiftFrequency( samples, sampleRate, adjustBy ): | |
dt = 1/sampleRate | |
pi2dtcf = 2*math.pi*dt*adjustBy | |
vals = [ cmath.exp(1j*pi2dtcf*i)*samples[i] for i in range(len(samples)) ] | |
return vals | |
def zoom_fft( samples, sampleRate, nBins, fStart, fEnd ): | |
bandwidth = (fEnd - fStart) | |
decFactor = sampleRate//bandwidth//2 | |
shifted = shiftFrequency( samples, sampleRate, -fStart ) | |
resampled = signal.decimate(shifted,decFactor,ftype='fir') | |
newSampleRate = sampleRate//decFactor | |
# print("decFactor",decFactor,"newSampleRate",newSampleRate) | |
vals = myfft( resampled, newSampleRate, nBins, fStart ) | |
return vals | |
def update(): | |
pass | |
app = QtGui.QApplication([]) | |
win = pg.GraphicsWindow(title="Basic plotting examples") | |
win.resize(1900,600) | |
win.setWindowTitle('pyqtgraph example: Plotting') | |
sampleRate = 48000 | |
n = 512 | |
signalData = gen_tone_data(sampleRate, 0.5) | |
fftData = myfft(signalData, sampleRate, n, 0.0) | |
zoomFFTData = zoom_fft( signalData, sampleRate, n, 12130, 12160 ) | |
signalGraph = win.addPlot(title="Signal Graph") | |
sigPlot = signalGraph.plot(pen='y') | |
sigPlot.setData( signalData ) | |
fftOutput = win.addPlot(title="FFT Output") | |
fftPlot = fftOutput.plot(pen='y') | |
fftPlot.setData( *fftData ) | |
zoomFFTOutput = win.addPlot(title="Zoom FFT Output") | |
zoomFFTPlot = zoomFFTOutput.plot(pen='y') | |
zoomFFTPlot.setData( *zoomFFTData ) | |
timer = QtCore.QTimer() | |
timer.timeout.connect(update) | |
timer.start(1) | |
app.exec_() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment