Fixed spectrogram plotting axis.
[debian/gnuradio] / gr-utils / src / python / gr_plot_qt.py
index 7c744f2c6991740f8d185c384f957b66f7dc676a..5579bbce29de9176b3628f525583ccbe8a9a5748 100755 (executable)
@@ -16,6 +16,37 @@ from gnuradio import eng_notation
 
 from pyqt_plot import Ui_MainWindow
 
+class SpectrogramData(Qwt.QwtRasterData):
+
+    def __init__(self, f, t):
+        Qwt.QwtArrayData.__init__(self, Qt.QRectF(0, 0, 0, 0))
+        self.sp = scipy.array([[0], [0]])
+
+    def set_data(self, xfreq, ytime, data):
+        self.sp = data
+        self.freq = xfreq
+        self.time = ytime
+        boundingBox = Qt.QRectF(self.freq.min(), self.time.min(),
+                                self.freq.max() - self.freq.min(),
+                                self.time.max() - self.time.min())
+        self.setBoundingRect(boundingBox)
+
+    def rasterHint(self, rect):
+        return Qt.QSize(self.sp.shape[0], self.sp.shape[1])
+        
+    def copy(self):
+        return self
+
+    def range(self):
+        
+        return Qwt.QwtDoubleInterval(self.sp.min(), self.sp.max())
+
+    def value(self, x, y):
+        f = int(self.freq.searchsorted(x))
+        t = int(self.time.searchsorted(y))
+        return self.sp[f][t-1]
+
+
 class gr_plot_qt(QtGui.QMainWindow):
     def __init__(self, qapp, filename, options, parent=None):
         QtGui.QWidget.__init__(self, parent)
@@ -32,21 +63,31 @@ class gr_plot_qt(QtGui.QMainWindow):
         self.datatype = scipy.complex64
         self.iq = list()
         self.time = list()
-        
+
         # Set up basic plot attributes
         self.gui.timePlot.setAxisTitle(self.gui.timePlot.xBottom, "Time (sec)")
         self.gui.timePlot.setAxisTitle(self.gui.timePlot.yLeft, "Amplitude (V)")
         self.gui.freqPlot.setAxisTitle(self.gui.freqPlot.xBottom, "Frequency (Hz)")
         self.gui.freqPlot.setAxisTitle(self.gui.freqPlot.yLeft, "Magnitude (dB)")
+        self.gui.specPlot.setAxisTitle(self.gui.specPlot.xBottom, "Frequency (Hz)")
+        self.gui.specPlot.setAxisTitle(self.gui.specPlot.yLeft, "Time (sec)")
 
         # Set up FFT size combo box
-        self.gui.fftComboBox.addItems(["128", "256", "512", "1024", "2048",
-                                       "4096", "8192", "16384", "32768"])
-        pos = self.gui.fftComboBox.findText(Qt.QString("%1").arg(self.psdfftsize))
-        self.gui.fftComboBox.setCurrentIndex(pos)
-        self.connect(self.gui.fftComboBox,
+        self.fftsizes = ["128", "256", "512", "1024", "2048",
+                         "4096", "8192", "16384", "32768"]
+        self.gui.psdFFTComboBox.addItems(self.fftsizes)
+        self.gui.specFFTComboBox.addItems(self.fftsizes)
+        pos = self.gui.psdFFTComboBox.findText(Qt.QString("%1").arg(self.psdfftsize))
+        self.gui.psdFFTComboBox.setCurrentIndex(pos)
+        pos = self.gui.specFFTComboBox.findText(Qt.QString("%1").arg(self.specfftsize))
+        self.gui.specFFTComboBox.setCurrentIndex(pos)
+
+        self.connect(self.gui.psdFFTComboBox,
                      Qt.SIGNAL("activated (const QString&)"),
-                     self.fftComboBoxEdit)
+                     self.psdFFTComboBoxEdit)
+        self.connect(self.gui.specFFTComboBox,
+                     Qt.SIGNAL("activated (const QString&)"),
+                     self.specFFTComboBoxEdit)
 
         # Set up color scheme box
         self.color_modes = {"Black on White" : self.color_black_on_white,
@@ -74,6 +115,12 @@ class gr_plot_qt(QtGui.QMainWindow):
                                             Qwt.QwtPicker.AlwaysOn,
                                             self.gui.freqPlot.canvas())
 
+        self.specZoomer = Qwt.QwtPlotZoomer(self.gui.specPlot.xBottom,
+                                            self.gui.specPlot.yLeft,
+                                            Qwt.QwtPicker.PointSelection,
+                                            Qwt.QwtPicker.AlwaysOn,
+                                            self.gui.specPlot.canvas())
+
         self.picker = Qwt.QwtPlotPicker(self.gui.timePlot.xBottom,
                                         self.gui.timePlot.yLeft,
                                         Qwt.QwtPicker.PointSelection,
@@ -137,9 +184,25 @@ class gr_plot_qt(QtGui.QMainWindow):
         self.psdcurve = Qwt.QwtPlotCurve("PSD")
         self.psdcurve.attach(self.gui.freqPlot)
 
+        # Set up specTab plot as a spectrogram
+        self.specdata = SpectrogramData(range(0, 10), range(0, 10))
+
+        colorMap = Qwt.QwtLinearColorMap(Qt.Qt.darkCyan, Qt.Qt.red)
+        colorMap.addColorStop(0.1, Qt.Qt.cyan)
+        colorMap.addColorStop(0.6, Qt.Qt.green)
+        colorMap.addColorStop(0.95, Qt.Qt.yellow)
+
+        self.spec = Qwt.QwtPlotSpectrogram()
+        self.spec.setColorMap(colorMap)
+        self.spec.attach(self.gui.specPlot)
+        self.spec.setContourLevels([0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5])
+        self.spec.setDisplayMode(Qwt.QwtPlotSpectrogram.ImageMode, True)
+        self.spec.setData(self.specdata)
+
         # Set up initial color scheme
         self.color_modes["Blue on Black"]()
 
+        # Connect a signal for when the sample rate changes
         self.set_sample_rate(self.sample_rate)
         self.connect(self.gui.sampleRateLineEdit,
                      Qt.SIGNAL("editingFinished()"),
@@ -152,25 +215,34 @@ class gr_plot_qt(QtGui.QMainWindow):
 
     def open_file(self):
         filename = Qt.QFileDialog.getOpenFileName(self, "Open", ".")
-        print filename
-        self.initialize(filename)
+        if(filename != ""):
+            print filename
+            self.initialize(filename)
 
     def initialize(self, filename):
         self.hfile = open(filename, "r")
 
         self.setWindowTitle(("GNU Radio File Plot Utility: %s" % filename))
-        
+
+        self.gui.filePosStartLineEdit.setText("0")
+        self.gui.filePosStopLineEdit.setText("0")
+        self.gui.fileTimeStartLineEdit.setText("0")
+        self.gui.fileTimeStopLineEdit.setText("0")
+
         self.cur_start = 0
         self.cur_stop = self.block_length
 
         self.init_data_input()
         self.get_data(self.cur_start, self.cur_stop)
         self.get_psd()
+        self.get_specgram() 
         self.gui.plotHBar.setSliderPosition(0)
         self.gui.plotHBar.setMaximum(self.signal_size)
 
+
         self.update_time_curves()
         self.update_psd_curves()
+        self.update_specgram_curves()
 
     def init_data_input(self):
         self.hfile.seek(0, os.SEEK_END)
@@ -182,16 +254,24 @@ class gr_plot_qt(QtGui.QMainWindow):
         if(end > start):
             self.hfile.seek(start*self.sizeof_data, os.SEEK_SET)
             self.position = start
-            iq = scipy.fromfile(self.hfile, dtype=self.datatype,
-                                count=end-start)
-            if(len(iq) < (end-start)):
-                print "End of File"
-            else:
+            try:
+                iq = scipy.fromfile(self.hfile, dtype=self.datatype,
+                                    count=end-start)
+
+                if(len(iq) < (end-start)):
+                    end = len(iq)
+                    self.gui.filePosLengthLineEdit.setText(Qt.QString("%1").arg(end))
+                    self.gui.plotHBar.setMaximum(end)
+                    self.gui.plotHBar.setSingleStep(end)
+                    self.file_length_changed()
+
                 tstep = 1.0 / self.sample_rate
                 self.iq = iq
                 self.time = [tstep*(self.position + i) for i in xrange(len(self.iq))]
 
-            self.set_file_pos_box(start, end)
+                self.set_file_pos_box(start, end)
+            except MemoryError:
+                pass
         else:
             # Do we want to do anything about this?
             pass
@@ -203,17 +283,34 @@ class gr_plot_qt(QtGui.QMainWindow):
                                 noverlap=self.psdfftsize/4.0,
                                 window=winpoints,
                                 scale_by_freq=False)
+
         self.iq_psd = 10.0*scipy.log10(abs(fftpack.fftshift(iq_psd)))
         self.freq = freq - self.sample_rate/2.0
 
+    def get_specgram(self):
+        winpoints = self.winfunc(self.specfftsize)
+        iq_spec, f, t = mlab.specgram(self.iq, Fs=self.sample_rate,
+                                      NFFT=self.specfftsize,
+                                      noverlap=self.specfftsize/4.0,
+                                      window=winpoints,
+                                      scale_by_freq=False)
+        
+        self.iq_spec = 10.0*scipy.log10(abs(iq_spec))
+        self.spec_f = f
+        self.spec_t = t
 
     def clickMe(self, qPoint):
         print qPoint.x()
 
-    def fftComboBoxEdit(self, fftSize):
+    def psdFFTComboBoxEdit(self, fftSize):
         self.psdfftsize = fftSize.toInt()[0]
         self.get_psd()
         self.update_psd_curves()
+
+    def specFFTComboBoxEdit(self, fftSize):
+        self.specfftsize = fftSize.toInt()[0]
+        self.get_specgram()
+        self.update_specgram_curves()
         
     def colorComboBoxEdit(self, colorSelection):
         colorstr = str(colorSelection.toAscii())
@@ -226,8 +323,10 @@ class gr_plot_qt(QtGui.QMainWindow):
 
         self.get_data(pos_start, pos_end)
         self.get_psd()
+        self.get_specgram()
         self.update_time_curves()
         self.update_psd_curves()
+        self.update_specgram_curves()
 
     def set_sample_rate(self, sr):
         self.sample_rate = sr
@@ -240,8 +339,10 @@ class gr_plot_qt(QtGui.QMainWindow):
         self.set_file_pos_box(self.cur_start, self.cur_stop)
         self.get_data(self.cur_start, self.cur_stop)
         self.get_psd()
+        self.get_specgram()
         self.update_time_curves()
         self.update_psd_curves()
+        self.update_specgram_curves()
 
     def set_file_pos_box(self, start, end):
         tstart = start / self.sample_rate
@@ -271,6 +372,7 @@ class gr_plot_qt(QtGui.QMainWindow):
 
             self.update_time_curves()
             self.update_psd_curves()
+            self.update_specgram_curves()
 
         # If there's a non-digit character, reset box
         else:
@@ -289,6 +391,7 @@ class gr_plot_qt(QtGui.QMainWindow):
 
             self.update_time_curves()
             self.update_psd_curves()
+            self.update_specgram_curves()
         # If there's a non-digit character, reset box
         else:
             self.set_file_pos_box(self.cur_start, self.cur_stop)
@@ -296,6 +399,7 @@ class gr_plot_qt(QtGui.QMainWindow):
     def file_length_changed(self):
         start = self.gui.filePosStartLineEdit.text().toInt()
         length = self.gui.filePosLengthLineEdit.text().toInt()
+
         if((start[1] == True) and (length[1] == True)):
             self.cur_start = start[0]
             self.block_length = length[0]
@@ -312,9 +416,11 @@ class gr_plot_qt(QtGui.QMainWindow):
 
             self.get_data(self.cur_start, self.cur_stop)
             self.get_psd()
+            self.get_specgram()
 
             self.update_time_curves()
             self.update_psd_curves()
+            self.update_specgram_curves()
         # If there's a non-digit character, reset box
         else:
             self.set_file_pos_box(self.cur_start, self.cur_stop)
@@ -336,9 +442,11 @@ class gr_plot_qt(QtGui.QMainWindow):
 
             self.get_data(self.cur_start, self.cur_stop)
             self.get_psd()
+            self.get_specgram()
 
             self.update_time_curves()
             self.update_psd_curves()
+            self.update_specgram_curves()
         # If there's a non-digit character, reset box
         else:
             self.set_file_pos_box(self.cur_start, self.cur_stop)
@@ -369,12 +477,29 @@ class gr_plot_qt(QtGui.QMainWindow):
         self.gui.freqPlot.setAxisScale(self.gui.freqPlot.xBottom,
                                        min(self.freq),
                                        max(self.freq))
-
+                                       
         # Set the zoomer base to unzoom to the new axis
         self.freqZoomer.setZoomBase()
 
         self.gui.freqPlot.replot()
 
+    def update_specgram_curves(self):
+        # We don't have to reset the data for the speccurve here
+        # since this is taken care of in the SpectrogramData class
+        self.specdata.set_data(self.spec_f, self.spec_t, self.iq_spec)
+
+        self.gui.specPlot.setAxisScale(self.gui.specPlot.xBottom,
+                                       min(self.spec_f),
+                                       max(self.spec_f))
+        self.gui.specPlot.setAxisScale(self.gui.specPlot.yLeft,
+                                       min(self.spec_t),
+                                       max(self.spec_t))
+
+        # Set the zoomer base to unzoom to the new axis
+        self.specZoomer.setZoomBase()
+
+        self.gui.specPlot.replot()
+
     def tabChanged(self, index):
         self.gui.timePlot.replot()
         self.gui.freqPlot.replot()
@@ -481,7 +606,7 @@ def setup_options():
                       help="Set the sampler rate of the data [default=%default]")
     parser.add_option("", "--psd-size", type="int", default=2048,
                       help="Set the size of the PSD FFT [default=%default]")
-    parser.add_option("", "--spec-size", type="int", default=256,
+    parser.add_option("", "--spec-size", type="int", default=2048,
                       help="Set the size of the spectrogram FFT [default=%default]")
 
     return parser