Wow, that’s a mouthfull. This is a total hack, but it works — and barely I might add! I spent all night jumping through hoops to get this thing to run on Windows. The problem is that I designed my previous UI in a version of GLADE which is newer than that supported by Windows. It looks like it’s not backward-compatible, so I have to re-design the GUI from scratch using an earlier version of GLADE. I’ll probably stick to GTK version 2.12 and Python version 2.6 because they play nicely on Windows. It’s a quick and dirty script, but I was able to make the following run on Windows as a single EXE file!glade_windows_python

WHAT A NIGHTMARE





Additional Resources

While continuing to investigate my options for the new version of QRSS VD, I re-visited Glade, the GTK GUI designer. In short, it lets you draw widgets (combo boxes, scrollbars, labels, images, buttons, etc) onto windows and then makes it easy to add code to the GUI. I *hated* the old QRSS VD development because of the ridiculously large amount of time I had to spend coding the UI. Hopefully by migrating from TKinter to GTK – while it opens a whole new can of worms – will let me add functionality rapidly without hesitation.glade_python_improving

Here’s a quick screenshot of my running this new version of the software with a GUI I made in less than an hour. The bars for brightness and contrast can be adjusted which modify the spectrograph in real time. The audio is whatever is playing in Pandora. I like the “fantastic plastic machine” radio station!





Additional Resources

I had TKinter all wrong! While my initial tests with PyGame’s rapid ability to render Numpy arrays in the form of pixel maps proved impressive, it was only because I was comparing it to poor TK code. I don’t know what I was doing wrong, but when I decided to give TKinter one more shot I was blown away — it’s as smooth or smoother as PyGame. Forget PyGame! I’m rendering everything in raw TK from now on. This utilizes the Python Imaging Library (PIL) so it’s EXTREMELY flexible (supports fancy operations, alpha channels, etc).fast_scroll_tk

The screenshot shows me running the script (below) generating random noise and “scrolling” it horizontally (like my spectrograph software does) at a fast rate smoothly (almost 90 FPS!). Basically, it launches a window, creates a canvas widget (which I’m told is faster to update than a label and reduces flickering that’s often associated with rapid redraws because it uses double-buffering). Also, it uses threading to handle the calculations/redraws without lagging the GUI. The code speaks for itself.

import Tkinter
from PIL import Image, ImageTk
import numpy
import time

class mainWindow():
	times=1
	timestart=time.clock()
	data=numpy.array(numpy.random.random((400,500))*100,dtype=int)

	def __init__(self):
		self.root = Tkinter.Tk()
		self.frame = Tkinter.Frame(self.root, width=500, height=400)
		self.frame.pack()
		self.canvas = Tkinter.Canvas(self.frame, width=500,height=400)
		self.canvas.place(x=-2,y=-2)
		self.root.after(0,self.start) # INCREASE THE 0 TO SLOW IT DOWN
		self.root.mainloop()

	def start(self):
		global data
		self.im=Image.fromstring('L', (self.data.shape[1],
			self.data.shape[0]), self.data.astype('b').tostring())
		self.photo = ImageTk.PhotoImage(image=self.im)
		self.canvas.create_image(0,0,image=self.photo,anchor=Tkinter.NW)
		self.root.update()
		self.times+=1
		if self.times%33==0:
			print "%.02f FPS"%(self.times/(time.clock()-self.timestart))
		self.root.after(10,self.start)
		self.data=numpy.roll(self.data,-1,1)

if __name__ == '__main__':
    x=mainWindow()




Additional Resources

While continuing my quest into the world of linear data analysis and signal processing, I came to a point where I wanted to emphasize variations in FFT traces. While I am keeping my original data for scientific reference, visually I want to represent it emphasizing variations rather than concentrating on trends. I wrote a detrending function which I’m sure will be useful for many applications:detrend_fft

def detrend(data,degree=10):
	detrended=[None]*degree
	for i in range(degree,len(data)-degree):
		chunk=data[i-degree:i+degree]
		chunk=sum(chunk)/len(chunk)
		detrended.append(data[i]-chunk)
	return detrended+[None]*degree

However, this method is extremely slow. I need to think of a way to accomplish this same thing much faster. [ponders]

UPDATE: It looks like I’ve once again re-invented the wheel. All of this has been done already, and FAR more efficiently I might add. Simply:

import scipy.signal
ffty=scipy.signal.detrend(ffty)

Now I’m looking into scipy.signal.triang()





Additional Resources

I’m attempting to thoroughly re-write the data assessment portions of my QRSS VD software, and rather than rushing to code it (like I did last time) I’m working hard on every step trying to optimize the code. I came across some notes I made about Fast Fourier Transformations from the first time I coded the software, and though I’d post some code I found helpful. Of particular satisfaction is an email I received from Alberto, I2PHD, the creator of Argo (the “gold standard” QRSS spectrograph software for Windows). In it he notes:

I think that [it is a mistake to] throw away the imaginary part of the FFT. What I do in Argo, in Spectran, in Winrad, in SDRadio and in all of my other programs is compute the magnitude of the [FFT] signal, then compute the logarithm of it, and only then I do a mapping of the colors on the screen with the result of this last computation.

These concepts are simple to visualize when graphed. Here I’ve written a short Python script to listen to the microphone (which is being fed a 2kHz sine wave), perform the FFT, and graph the real FFT component, imaginary FFT component, and their sum. The output is:real_imaginary_fft_pcm

Of particular interest to me is the beautiful complementarity of the two curves. It makes me wonder what types of data can be extracted by the individual curves (or perhaps their difference?) down the road. I wonder if phase measurements would be useful in extracting weak carries from beneath the noise floor?

Here’s the code I used to generate the image above. Note that my microphone device was set to listen to my stereo output, and I generated a 2kHz sine wave using the command speaker-test -t sine -f 2000 on a PC running Linux. I hope you find it useful!

import numpy
import pyaudio
import pylab
import numpy

### RECORD AUDIO FROM MICROPHONE ###
rate=44100
soundcard=1 #CUSTOMIZE THIS!!!
p=pyaudio.PyAudio()
strm=p.open(format=pyaudio.paInt16,channels=1,rate=rate,
			input_device_index=soundcard,input=True)
strm.read(1024) #prime the sound card this way
pcm=numpy.fromstring(strm.read(1024), dtype=numpy.int16)

### DO THE FFT ANALYSIS ###
fft=numpy.fft.fft(pcm)
fftr=10*numpy.log10(abs(fft.real))[:len(pcm)/2]
ffti=10*numpy.log10(abs(fft.imag))[:len(pcm)/2]
fftb=10*numpy.log10(numpy.sqrt(fft.imag**2+fft.real**2))[:len(pcm)/2]
freq=numpy.fft.fftfreq(numpy.arange(len(pcm)).shape[-1])[:len(pcm)/2]
freq=freq*rate/1000 #make the frequency scale

### GRAPH THIS STUFF ###
pylab.subplot(411)
pylab.title("Original Data")
pylab.grid()
pylab.plot(numpy.arange(len(pcm))/float(rate)*1000,pcm,'r-',alpha=1)
pylab.xlabel("Time (milliseconds)")
pylab.ylabel("Amplitude")
pylab.subplot(412)
pylab.title("Real FFT")
pylab.xlabel("Frequency (kHz)")
pylab.ylabel("Power")
pylab.grid()
pylab.plot(freq,fftr,'b-',alpha=1)
pylab.subplot(413)
pylab.title("Imaginary FFT")
pylab.xlabel("Frequency (kHz)")
pylab.ylabel("Power")
pylab.grid()
pylab.plot(freq,ffti,'g-',alpha=1)
pylab.subplot(414)
pylab.title("Real+Imaginary FFT")
pylab.xlabel("Frequency (kHz)")
pylab.ylabel("Power")
pylab.grid()
pylab.plot(freq,fftb,'k-',alpha=1)
pylab.show()

After fighting for a while long with a “shifty baseline” of the FFT, I came to another understanding. Let me first address the problem. Taking the FFT of different regions of the 2kHz wave I got traces with the peak in the identical location, but the “baselines” completely different. fft_base2

Like many things, I re-invented the wheel. Since I knew the PCM values weren’t changing, the only variable was the starting/stopping point of the linear sample. “Hard edges”, I imagined, must be the problem. I then wrote the following function to shape the PCM audio like a triangle, silencing the edges and sweeping the volume up toward the middle of the sample:

def shapeTriangle(data):
	triangle=numpy.array(range(len(data)/2)+range(len(data)/2)[::-1])+1
	return data*triangle

After shaping the data BEFORE I applied the FFT, I made the subsequent traces MUCH more acceptable. Observe:fft_base3

Now that I’ve done all this experimentation/thinking, I remembered that this is nothing new! Everyone talks about shaping the wave to minimize hard edges before taking the FFT. BAH! Another case of me re-inventing the wheel because I’m too lazy to read others’ work. However, in my defense, I learned a lot by trying all this stuff — far more than I would have learned simply by copying someone else’s code into my script. Experimentation is the key to discovery!