示例#1
0
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(1154, 710)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.textEdit = QtGui.QTextEdit(self.centralwidget)
        self.textEdit.setGeometry(QtCore.QRect(750, 340, 251, 61))
        self.textEdit.setObjectName(_fromUtf8("textEdit"))
        self.label9_input = QtGui.QLabel(self.centralwidget)
        self.label9_input.setGeometry(QtCore.QRect(750, 310, 111, 21))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label9_input.setFont(font)
        self.label9_input.setObjectName(_fromUtf8("label9_input"))
        self.splitter = QtGui.QSplitter(self.centralwidget)
        self.splitter.setGeometry(QtCore.QRect(750, 410, 256, 211))
        self.splitter.setOrientation(QtCore.Qt.Vertical)
        self.splitter.setObjectName(_fromUtf8("splitter"))
        self.label10_output = QtGui.QLabel(self.splitter)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label10_output.setFont(font)
        self.label10_output.setObjectName(_fromUtf8("label10_output"))
        self.textBrowser_2 = QtGui.QTextBrowser(self.splitter)
        self.textBrowser_2.setObjectName(_fromUtf8("textBrowser_2"))
        self.PORT_groupbox_1 = QtGui.QGroupBox(self.centralwidget)
        self.PORT_groupbox_1.setGeometry(QtCore.QRect(190, 50, 262, 120))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.PORT_groupbox_1.setFont(font)
        self.PORT_groupbox_1.setObjectName(_fromUtf8("PORT_groupbox_1"))
        self.gridLayout_4 = QtGui.QGridLayout(self.PORT_groupbox_1)
        self.gridLayout_4.setObjectName(_fromUtf8("gridLayout_4"))
        self.label1_com = QtGui.QLabel(self.PORT_groupbox_1)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label1_com.setFont(font)
        self.label1_com.setObjectName(_fromUtf8("label1_com"))
        self.gridLayout_4.addWidget(self.label1_com, 0, 0, 1, 1)
        self.label2_baud = QtGui.QLabel(self.PORT_groupbox_1)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label2_baud.setFont(font)
        self.label2_baud.setObjectName(_fromUtf8("label2_baud"))
        self.gridLayout_4.addWidget(self.label2_baud, 1, 0, 1, 2)
        self.lineEdit_baud = QtGui.QLineEdit(self.PORT_groupbox_1)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.lineEdit_baud.setFont(font)
        self.lineEdit_baud.setObjectName(_fromUtf8("lineEdit_baud"))
        self.gridLayout_4.addWidget(self.lineEdit_baud, 1, 2, 1, 1)
        self.label3_filename = QtGui.QLabel(self.PORT_groupbox_1)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label3_filename.setFont(font)
        self.label3_filename.setObjectName(_fromUtf8("label3_filename"))
        self.gridLayout_4.addWidget(self.label3_filename, 2, 0, 1, 1)
        self.lineEdit_filename = QtGui.QLineEdit(self.PORT_groupbox_1)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.lineEdit_filename.setFont(font)
        self.lineEdit_filename.setObjectName(_fromUtf8("lineEdit_filename"))
        self.gridLayout_4.addWidget(self.lineEdit_filename, 2, 2, 1, 1)
        self.lineEdit_com = QtGui.QLineEdit(self.PORT_groupbox_1)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.lineEdit_com.setFont(font)
        self.lineEdit_com.setObjectName(_fromUtf8("lineEdit_com"))
        self.gridLayout_4.addWidget(self.lineEdit_com, 0, 2, 1, 1)
        self.label3_filename.raise_()
        self.lineEdit_filename.raise_()
        self.lineEdit_baud.raise_()
        self.label1_com.raise_()
        self.lineEdit_com.raise_()
        self.label2_baud.raise_()
        self.virtualsound_groupBox_2 = QtGui.QGroupBox(self.centralwidget)
        self.virtualsound_groupBox_2.setGeometry(QtCore.QRect(680, 40, 391, 261))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.virtualsound_groupBox_2.setFont(font)
        self.virtualsound_groupBox_2.setObjectName(_fromUtf8("virtualsound_groupBox_2"))
        self.layoutWidget = QtGui.QWidget(self.virtualsound_groupBox_2)
        self.layoutWidget.setGeometry(QtCore.QRect(10, 20, 361, 211))
        self.layoutWidget.setObjectName(_fromUtf8("layoutWidget"))
        self.gridLayout_5 = QtGui.QGridLayout(self.layoutWidget)
        self.gridLayout_5.setObjectName(_fromUtf8("gridLayout_5"))
        self.freq_slider_1 = QtGui.QSlider(self.layoutWidget)
        self.freq_slider_1.setMaximum(20000)
        self.freq_slider_1.setSingleStep(10)
        self.freq_slider_1.setSliderPosition(0)
        self.freq_slider_1.setOrientation(QtCore.Qt.Vertical)
        self.freq_slider_1.setTickInterval(3)
        self.freq_slider_1.setObjectName(_fromUtf8("freq_slider_1"))
        self.gridLayout_5.addWidget(self.freq_slider_1, 0, 0, 3, 1)
        self.gridLayout_3 = QtGui.QGridLayout()
        self.gridLayout_3.setObjectName(_fromUtf8("gridLayout_3"))
        self.label4_sound1 = QtGui.QLabel(self.layoutWidget)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label4_sound1.setFont(font)
        self.label4_sound1.setFrameShape(QtGui.QFrame.Box)
        self.label4_sound1.setObjectName(_fromUtf8("label4_sound1"))
        self.gridLayout_3.addWidget(self.label4_sound1, 0, 0, 1, 1)
        self.label5_sound2 = QtGui.QLabel(self.layoutWidget)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label5_sound2.setFont(font)
        self.label5_sound2.setFrameShape(QtGui.QFrame.Box)
        self.label5_sound2.setObjectName(_fromUtf8("label5_sound2"))
        self.gridLayout_3.addWidget(self.label5_sound2, 0, 2, 1, 1)
        self.amp_dial = QtGui.QDial(self.layoutWidget)
        self.amp_dial.setObjectName(_fromUtf8("amp_dial"))
        self.gridLayout_3.addWidget(self.amp_dial, 1, 0, 1, 1)
        self.button1_generate = QtGui.QPushButton(self.layoutWidget)
        self.button1_generate.setObjectName(_fromUtf8("button1_generate"))
        self.gridLayout_3.addWidget(self.button1_generate, 1, 1, 1, 1)
        self.amp_dial_2 = QtGui.QDial(self.layoutWidget)
        self.amp_dial_2.setObjectName(_fromUtf8("amp_dial_2"))
        self.gridLayout_3.addWidget(self.amp_dial_2, 1, 2, 1, 1)
        self.gridLayout_5.addLayout(self.gridLayout_3, 0, 1, 1, 1)
        self.freq_slider_2 = QtGui.QSlider(self.layoutWidget)
        self.freq_slider_2.setMaximum(20000)
        self.freq_slider_2.setSingleStep(10)
        self.freq_slider_2.setSliderPosition(0)
        self.freq_slider_2.setOrientation(QtCore.Qt.Vertical)
        self.freq_slider_2.setTickInterval(3)
        self.freq_slider_2.setObjectName(_fromUtf8("freq_slider_2"))
        self.gridLayout_5.addWidget(self.freq_slider_2, 0, 2, 3, 1)
        self.time_progress = QtGui.QProgressBar(self.layoutWidget)
        self.time_progress.setProperty("value", 24)
        self.time_progress.setObjectName(_fromUtf8("time_progress"))
        self.gridLayout_5.addWidget(self.time_progress, 1, 1, 1, 1)
        self.gridLayout_2 = QtGui.QGridLayout()
        self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2"))
        self.amp_spin_1 = QtGui.QSpinBox(self.layoutWidget)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.amp_spin_1.setFont(font)
        self.amp_spin_1.setMaximum(20000)
        self.amp_spin_1.setSingleStep(10)
        self.amp_spin_1.setObjectName(_fromUtf8("amp_spin_1"))
        self.gridLayout_2.addWidget(self.amp_spin_1, 1, 0, 1, 1)
        self.freq_spin_1 = QtGui.QSpinBox(self.layoutWidget)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.freq_spin_1.setFont(font)
        self.freq_spin_1.setMaximum(20000)
        self.freq_spin_1.setSingleStep(10)
        self.freq_spin_1.setObjectName(_fromUtf8("freq_spin_1"))
        self.gridLayout_2.addWidget(self.freq_spin_1, 0, 0, 1, 1)
        self.freq_spin_2 = QtGui.QSpinBox(self.layoutWidget)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.freq_spin_2.setFont(font)
        self.freq_spin_2.setMaximum(20000)
        self.freq_spin_2.setSingleStep(10)
        self.freq_spin_2.setObjectName(_fromUtf8("freq_spin_2"))
        self.gridLayout_2.addWidget(self.freq_spin_2, 0, 2, 1, 1)
        self.label7_amp = QtGui.QLabel(self.layoutWidget)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label7_amp.setFont(font)
        self.label7_amp.setObjectName(_fromUtf8("label7_amp"))
        self.gridLayout_2.addWidget(self.label7_amp, 1, 1, 1, 1)
        self.amp_spin_2 = QtGui.QSpinBox(self.layoutWidget)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.amp_spin_2.setFont(font)
        self.amp_spin_2.setMaximum(20000)
        self.amp_spin_2.setSingleStep(10)
        self.amp_spin_2.setObjectName(_fromUtf8("amp_spin_2"))
        self.gridLayout_2.addWidget(self.amp_spin_2, 1, 2, 1, 1)
        self.dur_spin_1 = QtGui.QSpinBox(self.layoutWidget)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.dur_spin_1.setFont(font)
        self.dur_spin_1.setMaximum(20000)
        self.dur_spin_1.setSingleStep(10)
        self.dur_spin_1.setObjectName(_fromUtf8("dur_spin_1"))
        self.gridLayout_2.addWidget(self.dur_spin_1, 2, 0, 1, 1)
        self.label8_duration = QtGui.QLabel(self.layoutWidget)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label8_duration.setFont(font)
        self.label8_duration.setObjectName(_fromUtf8("label8_duration"))
        self.gridLayout_2.addWidget(self.label8_duration, 2, 1, 1, 1)
        self.dur_spin_2 = QtGui.QSpinBox(self.layoutWidget)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.dur_spin_2.setFont(font)
        self.dur_spin_2.setMaximum(20000)
        self.dur_spin_2.setSingleStep(10)
        self.dur_spin_2.setObjectName(_fromUtf8("dur_spin_2"))
        self.gridLayout_2.addWidget(self.dur_spin_2, 2, 2, 1, 1)
        self.label6_freq = QtGui.QLabel(self.layoutWidget)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label6_freq.setFont(font)
        self.label6_freq.setObjectName(_fromUtf8("label6_freq"))
        self.gridLayout_2.addWidget(self.label6_freq, 0, 1, 1, 1)
        self.gridLayout_5.addLayout(self.gridLayout_2, 2, 1, 1, 1)

        ### Matplot here
        self.matplotlibwidget = MatplotlibWidget(self.centralwidget)
        self.matplotlibwidget.setGeometry(QtCore.QRect(130, 210, 521, 401))
        self.matplotlibwidget.setObjectName(_fromUtf8("matplotlibwidget"))
        #self.canvas = FigureCanvas(self.figure)
        self.matplotlibwidget.draw()        # required to update the windows



        self.Button2_Plot = QtGui.QPushButton(self.centralwidget)
        self.Button2_Plot.setGeometry(QtCore.QRect(350, 620, 75, 23))
        self.Button2_Plot.setObjectName(_fromUtf8("Button2_Plot"))
        self.Button2_Plot.clicked.connect(self.plot)

        ############

        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1154, 21))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        self.menuFile = QtGui.QMenu(self.menubar)
        self.menuFile.setObjectName(_fromUtf8("menuFile"))
        self.menuSetting = QtGui.QMenu(self.menubar)
        self.menuSetting.setObjectName(_fromUtf8("menuSetting"))
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        MainWindow.setStatusBar(self.statusbar)
        self.actionOpen = QtGui.QAction(MainWindow)
        self.actionOpen.setObjectName(_fromUtf8("actionOpen"))
        self.actionSave = QtGui.QAction(MainWindow)
        self.actionSave.setObjectName(_fromUtf8("actionSave"))
        self.actionSave_as = QtGui.QAction(MainWindow)
        self.actionSave_as.setObjectName(_fromUtf8("actionSave_as"))
        self.actionQuit = QtGui.QAction(MainWindow)
        self.actionQuit.setObjectName(_fromUtf8("actionQuit"))
        self.actionTerminal = QtGui.QAction(MainWindow)
        self.actionTerminal.setObjectName(_fromUtf8("actionTerminal"))
        self.actionGraph = QtGui.QAction(MainWindow)
        self.actionGraph.setObjectName(_fromUtf8("actionGraph"))
        self.menuFile.addSeparator()
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionOpen)
        self.menuFile.addAction(self.actionSave)
        self.menuFile.addAction(self.actionSave_as)
        self.menuFile.addAction(self.actionQuit)
        self.menuSetting.addAction(self.actionTerminal)
        self.menuSetting.addAction(self.actionGraph)
        self.menubar.addAction(self.menuFile.menuAction())
        self.menubar.addAction(self.menuSetting.menuAction())

        self.retranslateUi(MainWindow)
        QtCore.QObject.connect(self.freq_spin_2, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.freq_slider_2.setValue)
        QtCore.QObject.connect(self.freq_slider_2, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.freq_spin_2.setValue)
        QtCore.QObject.connect(self.amp_dial, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.amp_spin_1.setValue)
        QtCore.QObject.connect(self.amp_spin_2, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.amp_dial_2.setValue)
        QtCore.QObject.connect(self.amp_dial_2, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.amp_spin_2.setValue)
        QtCore.QObject.connect(self.amp_spin_1, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.amp_dial.setValue)
        QtCore.QObject.connect(self.freq_spin_1, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.freq_slider_1.setValue)
        QtCore.QObject.connect(self.freq_slider_1, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.freq_spin_1.setValue)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
        self.label9_input.setText(_translate("MainWindow", "Input Textbox", None))
        self.label10_output.setText(_translate("MainWindow", "Output Textbox", None))
        self.PORT_groupbox_1.setTitle(_translate("MainWindow", "COM configuration", None))
        self.label1_com.setText(_translate("MainWindow", "COM", None))
        self.label2_baud.setText(_translate("MainWindow", "BAUD", None))
        self.label3_filename.setText(_translate("MainWindow", "Filename", None))
        self.virtualsound_groupBox_2.setTitle(_translate("MainWindow", "Virtual Sound Control Panel", None))
        self.label4_sound1.setText(_translate("MainWindow", "Sound 1", None))
        self.label5_sound2.setText(_translate("MainWindow", "Sound 2", None))
        self.button1_generate.setText(_translate("MainWindow", "GENERATE", None))
        self.label7_amp.setText(_translate("MainWindow", "Amplitude", None))
        self.label8_duration.setText(_translate("MainWindow", "Duration (ms)", None))
        self.label6_freq.setText(_translate("MainWindow", "Frequency (Hz)", None))
        self.Button2_Plot.setText(_translate("MainWindow", "Plot", None))
        self.menuFile.setTitle(_translate("MainWindow", "File", None))
        self.menuSetting.setTitle(_translate("MainWindow", "Setting", None))
        self.actionOpen.setText(_translate("MainWindow", "Open", None))
        self.actionSave.setText(_translate("MainWindow", "Save", None))
        self.actionSave_as.setText(_translate("MainWindow", "Save as", None))
        self.actionQuit.setText(_translate("MainWindow", "Quit", None))
        self.actionTerminal.setText(_translate("MainWindow", "Terminal", None))
        self.actionGraph.setText(_translate("MainWindow", "Graph", None))

    def plot(self):
        #populate the ra
        #ra =

        # plot a polar graph here
        ra = [random.randint(-50,100) for i in range(6)]
        #ra = [45, 40, 90, -75, 80.2, 106.7]            # angle  --> change to buffer_angle[4000]
        ra = [x / 180.0 * 3.141593 for x in ra]             # convert angle to radian

        dec = [1.01, 6.05, 5.6, 4.02, 9.1, 7.85]            # distance --> change to buffer_distance[4000]

        fig = pyplot.figure()
        ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True)
        ax.set_ylim(0, 10)
        ax.set_yticks(numpy.arange(0, 10, 2))
        ax.scatter(ra, dec, c='r')                          # plot the first microphone

        pyplot.show()
        #pyplot.draw()

    # open csv file to read the data
    def __read_csv_file(name=''):
        print "read the csv file"
        ra = []
        distance = []
        try:
            with open(name, 'rb') as csvfile:
                reading = csv.reader(csvfile, delimeter='')
                for row in reading:
                    if (row > 4000):
                        break;
                    ra.append(row[0])
                    distance.append(row[1])
        finally:
            csvfile.close()
        return ra
示例#2
0
class Cromatogram(QMainWindow):
    def __init__(self, parent, tmodel):
        QMainWindow.__init__(self, parent)
        self.ui = Ui_CromWindow()
        self.ui.setupUi(self)
        self.tmodel = tmodel

        # Creates the matplotlib window and the toolbar
        self.mpl_window = MatplotlibWidget()
        self.ui.vl_plot.addWidget(self.mpl_window)
        self.toolbar = NavigationToolbar(self.mpl_window, self)
        self.ui.vl_plot.addWidget(self.toolbar)
        self.color_list = generate_colors(self.tmodel.num_analites)
        # Plot the models
        conc = self.simulate()
        self.plot(conc)

    def simulate(self):
        """ This function simulate the exit of each analito through the column. """
        full_concentration = 0.998

        tmodel = self.tmodel

        if not tmodel.is_ideal_type:
            full_concentration = 0.5

        last_plate_conc = np.zeros(tmodel.num_analites)

        concentration = []
        for i in np.arange(tmodel.num_analites):
            concentration.append([])

        k = 0
        while True:
            tmodel.max_iter += 1
            tmodel.update(1)

            for i in np.arange(tmodel.num_analites):
                # amount of concentration in last plate
                aux = tmodel.current_state[4][i][tmodel.num_teo_plates - 1]
                last_plate_conc[i] += aux
                concentration[i].append(aux)

            flag = True
            for i in np.arange(tmodel.num_analites):
                if last_plate_conc[
                        i] < full_concentration * tmodel.conc_initial[i]:
                    flag = False

            if flag:
                # print last_plate_conc
                # print tmodel.conc_initial
                break

            k += 1

        return k + 1, concentration

    def plot(self, concentrations):

        for i in np.arange(self.tmodel.num_analites):
            self.mpl_window.axes.set_xlabel("Numero de Iteraciones")
            self.mpl_window.axes.set_ylabel("Concentracion")
            # print concentrations[0], len(concentrations[i + 1])
            self.mpl_window.axes.plot(np.arange(concentrations[0]),
                                      concentrations[1][i],
                                      color2str(self.color_list[i]),
                                      label=str(chr(65 + i)))
            self.mpl_window.axes.hold(True)

        self.mpl_window.axes.grid()
        self.mpl_window.axes.legend()
        self.mpl_window.draw()
示例#3
0
class UIMainWindow(object):
    def __init__(self, main_window):
        self.setup_vars()
        print("Setting up GUI")
        main_window.setObjectName(_fromUtf8("main_window"))
        main_window.resize(850, 858)
        self.centralwidget = QtGui.QWidget(main_window)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.grid_layout = QtGui.QGridLayout(self.centralwidget)
        self.grid_layout.setObjectName(_fromUtf8("grid_layout"))
        spacer_item = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Minimum)
        self.grid_layout.addItem(spacer_item, 4, 1, 1, 1)
        spacer_item1 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Minimum)
        self.grid_layout.addItem(spacer_item1, 4, 3, 1, 3)
        self.labelTime = QtGui.QLabel(self.centralwidget)
        self.labelTime.setMaximumSize(QtCore.QSize(16777215, 16777215))
        self.labelTime.setWordWrap(True)
        self.labelTime.setObjectName(_fromUtf8("labelTime"))
        self.grid_layout.addWidget(self.labelTime, 1, 0, 1, 6)
        self.check_box_date_end = QtGui.QCheckBox(self.centralwidget)
        self.check_box_date_end.setChecked(False)
        self.check_box_date_end.setObjectName(_fromUtf8("check_box_date_end"))
        self.grid_layout.addWidget(self.check_box_date_end, 15, 2, 1, 1)
        self.check_box_day_start = QtGui.QCheckBox(self.centralwidget)
        self.check_box_day_start.setChecked(False)
        self.check_box_day_start.setObjectName(_fromUtf8("check_box_day_start"))
        self.grid_layout.addWidget(self.check_box_day_start, 5, 0, 1, 1)
        spacer_item2 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Minimum)
        self.grid_layout.addItem(spacer_item2, 7, 0, 1, 1)
        self.labelDate = QtGui.QLabel(self.centralwidget)
        self.labelDate.setWordWrap(True)
        self.labelDate.setObjectName(_fromUtf8("labelDate"))
        self.grid_layout.addWidget(self.labelDate, 8, 0, 1, 6)
        self.label_unknown_times = QtGui.QLabel(self.centralwidget)
        self.label_unknown_times.setObjectName(_fromUtf8("label_unknown_times"))
        self.grid_layout.addWidget(self.label_unknown_times, 6, 1, 1, 2)
        self.time_edit_primary = QtGui.QTimeEdit(self.centralwidget)
        self.time_edit_primary.setEnabled(True)
        self.time_edit_primary.setLayoutDirection(QtCore.Qt.LeftToRight)
        self.time_edit_primary.setAutoFillBackground(False)
        self.time_edit_primary.setWrapping(True)
        self.time_edit_primary.setButtonSymbols(QtGui.QAbstractSpinBox.UpDownArrows)
        self.time_edit_primary.setCalendarPopup(False)
        self.time_edit_primary.setObjectName(_fromUtf8("time_edit_primary"))
        self.grid_layout.addWidget(self.time_edit_primary, 4, 0, 1, 1)
        self.label_primary_time = QtGui.QLabel(self.centralwidget)
        self.label_primary_time.setObjectName(_fromUtf8("label_primary_time"))
        self.grid_layout.addWidget(self.label_primary_time, 3, 0, 1, 1)
        self.label_secondary_time = QtGui.QLabel(self.centralwidget)
        self.label_secondary_time.setObjectName(_fromUtf8("label_secondary_time"))
        self.grid_layout.addWidget(self.label_secondary_time, 3, 2, 1, 1)
        spacer_item3 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Minimum)
        self.grid_layout.addItem(spacer_item3, 4, 6, 1, 1)
        self.date_primary = QtGui.QDateEdit(self.centralwidget)
        self.date_primary.setWrapping(True)
        # Setting the min/max times at start
        self.date_primary.setDateTime(
            QtCore.QDateTime(QtCore.QDate(self.earliest_date.year, self.earliest_date.month, self.earliest_date.day),
                             QtCore.QTime(0, 0, 0)))
        self.date_primary.setMaximumDateTime(
            QtCore.QDateTime(QtCore.QDate(self.latest_date.year, self.latest_date.month, self.latest_date.day),
                             QtCore.QTime(23, 59, 59)))
        self.date_primary.setMinimumDateTime(
            QtCore.QDateTime(QtCore.QDate(self.earliest_date.year, self.earliest_date.month, self.earliest_date.day),
                             QtCore.QTime(0, 0, 0)))
        self.date_primary.setCalendarPopup(False)
        self.date_primary.setObjectName(_fromUtf8("date_primary"))
        self.grid_layout.addWidget(self.date_primary, 14, 0, 1, 1)
        self.check_box_day_end = QtGui.QCheckBox(self.centralwidget)
        self.check_box_day_end.setChecked(False)
        self.check_box_day_end.setObjectName(_fromUtf8("check_box_day_end"))
        self.grid_layout.addWidget(self.check_box_day_end, 5, 2, 1, 1)
        self.label_secondary_date = QtGui.QLabel(self.centralwidget)
        self.label_secondary_date.setObjectName(_fromUtf8("label_secondary_date"))
        self.grid_layout.addWidget(self.label_secondary_date, 12, 2, 1, 1)
        self.time_edit_secondary = QtGui.QTimeEdit(self.centralwidget)
        self.time_edit_secondary.setLayoutDirection(QtCore.Qt.LeftToRight)
        self.time_edit_secondary.setAutoFillBackground(False)
        self.time_edit_secondary.setWrapping(True)
        self.time_edit_secondary.setDateTime(QtCore.QDateTime(QtCore.QDate(2000, 1, 1), QtCore.QTime(23, 59, 0)))
        self.time_edit_secondary.setCalendarPopup(False)
        self.time_edit_secondary.setObjectName(_fromUtf8("time_edit_secondary"))
        self.grid_layout.addWidget(self.time_edit_secondary, 4, 2, 1, 1)
        self.check_box_date_start = QtGui.QCheckBox(self.centralwidget)
        self.check_box_date_start.setChecked(False)
        self.check_box_date_start.setObjectName(_fromUtf8("check_box_date_start"))
        self.grid_layout.addWidget(self.check_box_date_start, 15, 0, 1, 1)
        self.matplotlib_map = MatplotlibWidget(self.centralwidget)
        self.matplotlib_map.setObjectName(_fromUtf8("matplotlib_map"))
        self.grid_layout.addWidget(self.matplotlib_map, 16, 0, 1, 7)
        self.label_primary_date = QtGui.QLabel(self.centralwidget)
        self.label_primary_date.setObjectName(_fromUtf8("label_primary_date"))
        self.grid_layout.addWidget(self.label_primary_date, 12, 0, 1, 1)
        self.date_secondary = QtGui.QDateEdit(self.centralwidget)
        self.date_secondary.setWrapping(True)
        # Setting the min/max times at start
        self.date_secondary.setDate(QtCore.QDate(self.latest_date.year, self.latest_date.month, self.latest_date.day))
        self.date_secondary.setMaximumDateTime(
            QtCore.QDateTime(QtCore.QDate(self.latest_date.year, self.latest_date.month, self.latest_date.day),
                             QtCore.QTime(23, 59, 59)))
        self.date_secondary.setMinimumDateTime(
            QtCore.QDateTime(QtCore.QDate(self.earliest_date.year, self.earliest_date.month, self.earliest_date.day),
                             QtCore.QTime(0, 0, 0)))
        self.date_secondary.setCalendarPopup(False)
        self.date_secondary.setObjectName(_fromUtf8("date_secondary"))
        self.grid_layout.addWidget(self.date_secondary, 14, 2, 1, 1)
        self.btnStart = QtGui.QPushButton(self.centralwidget)
        self.btnStart.setObjectName(_fromUtf8("btnStart"))
        self.grid_layout.addWidget(self.btnStart, 15, 6, 1, 1)
        self.combo_box_unknown_times = QtGui.QComboBox(self.centralwidget)
        self.combo_box_unknown_times.setObjectName(_fromUtf8("combo_box_unknown_times"))
        self.combo_box_unknown_times.addItem(_fromUtf8(""))
        self.combo_box_unknown_times.addItem(_fromUtf8(""))
        self.combo_box_unknown_times.addItem(_fromUtf8(""))
        self.grid_layout.addWidget(self.combo_box_unknown_times, 6, 0, 1, 1)
        self.spin_box_limit = QtGui.QSpinBox(self.centralwidget)
        self.spin_box_limit.setMinimum(1)
        self.spin_box_limit.setMaximum(20)
        self.spin_box_limit.setProperty("value", 10)
        self.spin_box_limit.setObjectName(_fromUtf8("spin_box_limit"))
        self.grid_layout.addWidget(self.spin_box_limit, 15, 5, 1, 1)
        self.label_spinner = QtGui.QLabel(self.centralwidget)
        self.label_spinner.setWordWrap(True)
        self.label_spinner.setObjectName(_fromUtf8("label_spinner"))
        self.grid_layout.addWidget(self.label_spinner, 14, 4, 1, 3)
        self.label = QtGui.QLabel(self.centralwidget)
        self.label.setWordWrap(True)
        self.label.setObjectName(_fromUtf8("label"))
        self.grid_layout.addWidget(self.label, 0, 0, 1, 3)
        self.labelinfo_update = QtGui.QLabel(self.centralwidget)
        self.labelinfo_update.setWordWrap(True)
        self.labelinfo_update.setObjectName(_fromUtf8("labelinfo_update"))
        self.grid_layout.addWidget(self.labelinfo_update, 17, 0, 1, 5)
        self.btn_reset_map = QtGui.QPushButton(self.centralwidget)
        font = QtGui.QFont()
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        self.btn_reset_map.setFont(font)
        self.btn_reset_map.setObjectName(_fromUtf8("btn_reset_map"))
        self.grid_layout.addWidget(self.btn_reset_map, 17, 6, 1, 1)
        main_window.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(main_window)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 850, 21))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        main_window.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(main_window)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        main_window.setStatusBar(self.statusbar)
        
        self.retranslate_ui(main_window)
        QtCore.QMetaObject.connectSlotsByName(main_window)
    
    def retranslate_ui(self, main_window):
        main_window.setWindowTitle(_translate("main_window", "main_window", None))
        self.labelTime.setText(_translate("main_window",
                                          "Enter a time range. The range will include the hours and minutes "
                                          "between the primary time and the secondary time, unless the "
                                          "primary time is higher than the secondary time, where it will "
                                          "instead exclude the time between them.",
                                          None))
        self.check_box_date_end.setText(_translate("main_window", "End at the latest date", None))
        self.check_box_day_start.setText(_translate("main_window", "Start from the beginning of the day", None))
        self.labelDate.setText(_translate("main_window",
                                          "Enter a date range. The range will include the dates between the "
                                          "primary date and the secondary date, unless the primary date is "
                                          "higher than the secondary date, where it will instead exclude "
                                          "the dates between them.",
                                          None))
        self.label_unknown_times.setText(_translate("main_window", "include unknown times", None))
        self.time_edit_primary.setDisplayFormat(_translate("main_window", "hh:mm", None))
        self.label_primary_time.setText(_translate("main_window", "Enter the primary time", None))
        self.label_secondary_time.setText(_translate("main_window", "Enter the secondary time", None))
        self.check_box_day_end.setText(_translate("main_window", "Finish at the end of the day", None))
        self.label_secondary_date.setText(_translate("main_window", "Enter the secondary date", None))
        self.time_edit_secondary.setDisplayFormat(_translate("main_window", "hh:mm", None))
        self.check_box_date_start.setText(_translate("main_window", "Start from the earliest date", None))
        self.label_primary_date.setText(_translate("main_window", "Enter the primary date", None))
        self.btnStart.setText(_translate("main_window", "Calculate", None))
        self.combo_box_unknown_times.setItemText(0, _translate("main_window", "Do", None))
        self.combo_box_unknown_times.setItemText(1, _translate("main_window", "Do not", None))
        self.combo_box_unknown_times.setItemText(2, _translate("main_window", "Only", None))
        self.label_spinner.setText(_translate("main_window",
                                              "Enter a value. It will pick the top most accident prone "
                                              "locations given your parameters. API limits prevent too many "
                                              "from being displayed.", None))
        self.label.setText(_translate("main_window",
                                      "This program calculates and displays the most hazardous locations in "
                                      "Montreal for a cyclist  between certain hours of the day over a "
                                      "period of time.\n"
                                      "Please have a stable internet connection.", None))
        self.labelinfo_update.setText(_translate("main_window",
                                                 "You are getting the locations of accidents at the times "
                                                 "between 0:00 and 23:59, between the dates of 2006-01-01 "
                                                 "and 2010-12-31, including the accidents without specific "
                                                 "times", None))
        self.matplotlib_map.setAutoFillBackground(True)
        self.btn_reset_map.setText(_translate("main_window", "Reset Map", None))

        QtCore.QObject.connect(self.btnStart, QtCore.SIGNAL('clicked()'), self.calculate_data_map)
        
        self.btnStart.clicked.connect(self.calculate_data_map)
        self.btn_reset_map.clicked.connect(self.get_map)
        self.btn_reset_map.clicked.connect(self.change_data_parameters)
        
        self.combo_box_unknown_times.currentIndexChanged.connect(self.change_data_parameters)
        self.check_box_date_end.stateChanged.connect(self.change_data_parameters)
        self.check_box_date_start.stateChanged.connect(self.change_data_parameters)
        self.check_box_day_end.stateChanged.connect(self.change_data_parameters)
        self.check_box_day_start.stateChanged.connect(self.change_data_parameters)
        
        self.date_primary.dateChanged.connect(self.change_data_parameters)
        self.date_secondary.dateChanged.connect(self.change_data_parameters)
        self.time_edit_primary.timeChanged.connect(self.change_data_parameters)
        self.time_edit_secondary.timeChanged.connect(self.change_data_parameters)
        self.spin_box_limit.valueChanged.connect(self.change_data_parameters)
        self.btn_reset_map.clicked.connect(self.reset_map)
        
        # We want to call it so the text is correct at the beginning
        self.change_data_parameters()
        
        self.get_map()
    
    def setup_vars(self):
        print("Loading map...")
        # Sets up variables for use in program
        self.gm = GetMap()
        self.img, self.fig, self.ax, self.imgplot = self.gm.get_current_map()
        
        self.bike_accidents = BikeAccidents()
        self.earliest_date = pd.to_datetime(self.bike_accidents.min_date)
        self.latest_date = pd.to_datetime(self.bike_accidents.max_date)
        self.getting_looking = "looking for"
    
    def calculate_data_map(self):
        self.getting_looking = "getting"
        self.change_data_parameters()
        
        # Filters out the data
        data = self.bike_accidents.accident_range(start_time=self.ptime,
                                                  end_time=self.stime,
                                                  include_unknown_time=self.include_unknown,
                                                  start_date=self.pdate.strftime("%Y-%m-%d"),
                                                  end_date=self.sdate.strftime("%Y-%m-%d"),
                                                  )
        
        data_accident_location = self.bike_accidents.accident_count(data)  # Groups the data according to location
        self.gm.draw_accidents_by_frequency(data_accident_location, self.top_accidents)
        
        self.matplotlib_map.draw()
    
    def reset_map(self):
        self.gm.reset_map()
        self.matplotlib_map.figure = self.fig
        self.matplotlib_map.draw()
    
    def get_map(self):
        self.matplotlib_map.figure = self.fig
        self.matplotlib_map.draw()
    
    def change_data_parameters(self):
        
        self.top_accidents = self.spin_box_limit.value()
        
        # Checks if our check boxes are checked, to see if we want to use the extreme dates or not
        if self.check_box_date_start.isChecked():
            # Set up so is time date
            self.pdate = self.earliest_date
        else:
            self.pdate = pd.to_datetime(self.date_primary.date().toString())
        
        if self.check_box_date_end.isChecked():
            # Set up so is time date
            self.sdate = self.latest_date
        else:
            self.sdate = pd.to_datetime(self.date_secondary.date().toString())
        
        pdate_y, p_date_m, p_date_d = self.pdate.year, self.pdate.month, self.pdate.day
        sdate_y, sdate_m, sdate_d = self.sdate.year, self.sdate.month, self.sdate.day
        
        # using pandas Timestamps for formatting
        if self.check_box_day_start.isChecked():
            self.ptime = pd.to_datetime("00:00:00")
        else:
            self.ptime = pd.to_datetime(self.time_edit_primary.time().toString(), format='%H:%M:%S')
        
        ptime_h, ptime_m = self.ptime.hour, self.ptime.minute
        if self.check_box_day_end.isChecked():
            self.stime = pd.to_datetime("23:59:59")
        else:
            self.stime = pd.to_datetime(self.time_edit_secondary.time().toString())
            
        stime_h, stime_m = self.stime.hour, self.stime.minute
        
        # We want to either get the dates between certain dates, or dates not between certain dates
        if self.sdate >= self.pdate:
            date_between_text = "between"
            mid_date_time_frame = "{}-{:02d}-{:02d} and {}-{:02d}-{:02d}".format(pdate_y, p_date_m, p_date_d, sdate_y,
                                                                                 sdate_m, sdate_d)
        else:
            date_between_text = "between " + self.earliest_date.strftime(
                "%Y-%m-%d") + " and " + self.latest_date.strftime("%Y-%m-%d") + ", excluding the dates between"
            mid_date_time_frame = "{}-{:02d}-{:02d} and {}-{:02d}-{:02d}".format(sdate_y, sdate_m, sdate_d,
                                                                                 pdate_y, p_date_m, p_date_d)
        
        end_text = "the accidents without specific times."
        unknown_time_text = ""
        if self.combo_box_unknown_times.currentText() == "Only":
            time_between_text = ""
            unknown_time_text = "only using"
            self.include_unknown = UnknownTime.only
        else:
            if self.stime >= self.ptime:
                time_between_text = "at the times between "
                time_between_text += "{}:{:02d} and {}:{:02d},".format(ptime_h, ptime_m, stime_h, stime_m)
            
            else:
                time_between_text = "excluding the times between "
                time_between_text += "{}:{:02d} and {}:{:02d},".format(stime_h, stime_m, ptime_h, ptime_m)
            
            if self.combo_box_unknown_times.currentText() == "Do":
                unknown_time_text = "including"
                self.include_unknown = UnknownTime.include
            
            elif self.combo_box_unknown_times.currentText() == "Do not":
                unknown_time_text = "not including"
                self.include_unknown = UnknownTime.exclude
        
        if self.top_accidents == 1:
            self.location_text = "location"
            self.accident_text = ""
        else:
            self.location_text = "locations"
            self.accident_text = str(self.top_accidents) + " "
        
        text = 'You are {getting_looking} the top {accident_text}accident {location_text} ' \
               '{time_between_text} {date_between_text} {time_frame}, ' \
               '{unknown_time_text} {end_text}'.format(
            getting_looking=self.getting_looking, accident_text=self.accident_text,
            location_text=self.location_text,
            time_between_text=time_between_text, date_between_text=date_between_text,
            unknown_time_text=unknown_time_text,
            time_frame=mid_date_time_frame,
            end_text=end_text)
        
        self.labelinfo_update.setText(text)
        
        # Changes "Getting" to "Looking For" after clicking since
        self.getting_looking = "looking for"
示例#4
0
class Trasmission(QMainWindow):
    def __init__(self, parent, tmodel):
        QMainWindow.__init__(self, parent)
        self.ui = Ui_TrasmissionWindow()
        self.ui.setupUi(self)
        self.tmodel = tmodel

        # Initialize the matplotlib window and the toolbar
        self.mpl_window = MatplotlibWidget()
        self.ui.verticalLayout_2.addWidget(self.mpl_window)
        self.toolbar = NavigationToolbar(self.mpl_window, self)
        self.ui.verticalLayout_2.addWidget(self.toolbar)

        # Initialize the color column
        self.color_list = generate_colors(self.tmodel.num_analites)
        self.color_col = ColorColumn(self.ui.wid_column,
                                     self.tmodel.num_teo_plates,
                                     self.tmodel.num_analites, self.color_list,
                                     self.tmodel.current_state[0], 380, 300)

        # Simulation
        self.timer = QTimer()
        self.timer.timeout.connect(self.timeout)
        self.ui.pb_exec.clicked.connect(self.start_stop)
        self.running = False

    def start_stop(self):
        if self.running:
            self.running = False
            self.timer.stop()
            self.ui.pb_exec.setText("Ejecutar")

        else:  # not running now
            self.running = True
            self.timer.start()
            self.ui.pb_exec.setText("Detener")

    def timeout(self):
        self.tmodel.update(1)
        temp = self.tmodel.current_state[0].copy()
        self.color_col.update_conc(temp, (self.tmodel.count_iter < 10))
        self.color_col.repaint()
        self.plot()
        if self.tmodel.finished:
            self.timer.stop()

    def plot(self):
        self.mpl_window.axes.hold(False)
        self.mpl_window.axes.axis = ([1, self.tmodel.num_teo_plates, 0, 100])
        x = np.linspace(0, self.tmodel.num_teo_plates,
                        self.tmodel.num_teo_plates)
        y = self.tmodel.current_state[0]

        for i in np.arange(self.tmodel.num_analites):
            self.mpl_window.axes.set_xlabel(
                _translate("Numero de platos teoricos",
                           "Numero de platos teoricos", None))
            self.mpl_window.axes.set_ylabel(
                _translate("Intensidad de la senal", "Intensidad de la senal",
                           None))
            self.mpl_window.axes.plot(x,
                                      y[i],
                                      color2str(self.color_list[i]),
                                      label=str(chr(65 + i)))
            self.mpl_window.axes.hold(True)

        self.mpl_window.axes.grid()
        self.mpl_window.axes.legend()
        self.mpl_window.draw()
示例#5
0
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        # set up the appearance of our ui, button names, locations etc
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(1084, 901)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.RawPlot = MatplotlibWidget(self.centralwidget)
        self.RawPlot.setGeometry(QtCore.QRect(10, 10, 521, 421))
        self.RawPlot.setObjectName(_fromUtf8("RawPlot"))
        self.Go = QtGui.QPushButton(self.centralwidget)
        self.Go.setGeometry(QtCore.QRect(240, 470, 75, 23))
        self.Go.setObjectName(_fromUtf8("Go"))
        self.LoadData = QtGui.QPushButton(self.centralwidget)
        self.LoadData.setGeometry(QtCore.QRect(10, 470, 101, 23))
        self.LoadData.setObjectName(_fromUtf8("LoadData"))
        self.PlayBack = QtGui.QPushButton(self.centralwidget)
        self.PlayBack.setGeometry(QtCore.QRect(120, 470, 111, 23))
        self.PlayBack.setObjectName(_fromUtf8("PlayBack"))
        self.Save = QtGui.QPushButton(self.centralwidget)
        self.Save.setGeometry(QtCore.QRect(320, 470, 91, 23))
        self.Save.setObjectName(_fromUtf8("Save"))
        self.FundamentalFrequenncyPlot = MatplotlibWidget(self.centralwidget)
        self.FundamentalFrequenncyPlot.setGeometry(
            QtCore.QRect(540, 10, 141, 421))
        self.FundamentalFrequenncyPlot.setObjectName(
            _fromUtf8("FundamentalFrequenncyPlot"))
        self.FormantPlot = MatplotlibWidget(self.centralwidget)
        self.FormantPlot.setGeometry(QtCore.QRect(540, 440, 521, 421))
        self.FormantPlot.setObjectName(_fromUtf8("FormantPlot"))
        self.Stop = QtGui.QPushButton(self.centralwidget)
        self.Stop.setGeometry(QtCore.QRect(240, 500, 75, 23))
        self.Stop.setObjectName(_fromUtf8("Stop"))
        self.SaveFormants = QtGui.QPushButton(self.centralwidget)
        self.SaveFormants.setGeometry(QtCore.QRect(320, 500, 91, 23))
        self.SaveFormants.setObjectName(_fromUtf8("SaveFormants"))
        self.SavePitch = QtGui.QPushButton(self.centralwidget)
        self.SavePitch.setGeometry(QtCore.QRect(320, 530, 91, 23))
        self.SavePitch.setObjectName(_fromUtf8("SavePitch"))
        self.VocalTractPlot = MatplotlibWidget(self.centralwidget)
        self.VocalTractPlot.setGeometry(QtCore.QRect(690, 10, 141, 421))
        self.VocalTractPlot.setObjectName(_fromUtf8("VocalTractPlot"))
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1084, 21))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        MainWindow.setStatusBar(self.statusbar)
        self.myCallback = QtGui.QAction(MainWindow)
        self.myCallback.setObjectName(_fromUtf8("myCallback"))

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

        # set up button callbacks
        self.Go.clicked.connect(self.GoRun)
        self.LoadData.clicked.connect(self.Load)
        self.PlayBack.clicked.connect(self.Playback)
        self.Save.clicked.connect(self.SaveRecording)
        self.Stop.clicked.connect(self.StopRun)
        self.SaveFormants.clicked.connect(self.SaveF)
        self.SavePitch.clicked.connect(self.SaveP)

        # set up some vriables
        self.Recording = np.zeros(100000, dtype=np.int16)
        self.Status = False
        self.fs = 44100
        self.Formants = np.zeros((100, 5), dtype=np.float32)
        self.FormantTime = np.zeros(100, dtype=np.float32)
        self.Pitch = np.zeros(100, dtype=np.float32)
        self.PitchTime = np.zeros(100, dtype=np.float32)

        # set up axes labels etc
        ax = self.RawPlot.figure.add_subplot(111)
        ax.set_title('Raw Waveform')
        ax.set_xlabel('Time (s)')
        ax.set_ylabel('amplitude')
        f0ax = self.FundamentalFrequenncyPlot.figure.add_subplot(111)
        f0ax.tick_params(axis='x',
                         which='both',
                         bottom=False,
                         top=False,
                         labelbottom=False)
        f0ax.set_position([0.35, 0.05, 0.6, 0.93])
        f0ax.set_ylabel('Fundamental Frequency (Hz)')
        f0ax.set_ylim((0, 500))
        f0ax.set_xlim((0, 0.8))
        formantAx = self.FormantPlot.figure.add_subplot(111)
        formantAx.set_title('Power Spectrum - Formants')
        formantAx.set_xlabel('Frequency (Hz)')
        formantAx.set_ylabel('Power (dB)')
        formantAx.set_ylim((-100, 75))
        formantAx.set_xlim((0, 5000))
        tractAx = self.VocalTractPlot.figure.add_subplot(111)
        tractAx.tick_params(axis='x',
                            which='both',
                            bottom=False,
                            top=False,
                            labelbottom=False)
        tractAx.set_position([0.35, 0.05, 0.6, 0.93])
        tractAx.set_ylabel('Vocal Tract Length (cm)')
        tractAx.set_ylim((0, 25))
        tractAx.set_xlim((0, 0.8))

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
        self.Go.setText(_translate("MainWindow", "Go", None))
        self.LoadData.setText(
            _translate("MainWindow", "Load Existing Data", None))
        self.PlayBack.setText(
            _translate("MainWindow", "Playback Recording", None))
        self.Save.setText(_translate("MainWindow", "Save .wav", None))
        self.Stop.setText(_translate("MainWindow", "Stop", None))
        self.SaveFormants.setText(
            _translate("MainWindow", "Save Formants", None))
        self.SavePitch.setText(_translate("MainWindow", "Save Pitch", None))
        self.myCallback.setText(_translate("MainWindow", "Test", None))

    def StopRun(self):
        #stop recording/playback
        self.Status = False

    def SaveF(self):
        # save formants
        root = Tk()
        path = tkFileDialog.asksaveasfilename()  #choose file name
        if not path:
            print('Invalid filename')
            root.destroy()
            return False
        #write to csv
        with open(path, 'w') as csvfile:
            FormantWriter = csv.writer(csvfile,
                                       delimiter=',',
                                       lineterminator='\n')
            FormantWriter.writerow([
                'time(s)', 'f1 (Hz)', 'f2 (Hz)', 'f3 (Hz)', 'f4 (Hz)',
                'f5 (Hz)'
            ])
            for i in range(len(self.FormantTime)):
                FormantWriter.writerow(
                    np.concatenate((self.FormantTime[i], self.Formants[i, :]),
                                   axis=None))
        #close stuff
        print('Formant CSV save successful')
        root.destroy()
        return True

    def SaveP(self):
        #save Pitch
        root = Tk()
        path = tkFileDialog.asksaveasfilename()  #choose file to save to
        if not path:
            print('Invalid filename')
            root.destroy()
            return False
        #write to csv
        with open(path, 'w') as csvfile:
            PitchWriter = csv.writer(csvfile,
                                     delimiter=',',
                                     lineterminator='\n')
            PitchWriter.writerow(['time(s)', 'Pitch (Hz)'])
            for i in range(len(self.PitchTime)):
                PitchWriter.writerow(
                    np.concatenate((self.PitchTime[i], self.Pitch[i]),
                                   axis=None))
        #close stuff
        print('Pitch CSV save successful')
        root.destroy()
        return True

    def GoRun(self):  #main button callback for collecting new data
        self.Status = True
        self.fs = 44100  #set sample rate, default to 44100
        iters = 1000  # (mostly) deprecated
        chunkSize = 8192  #number of samples to read in at once
        windowSize = 3  #number of seconds to plot at once
        numSamples = iters * chunkSize

        #set up an audio stream
        p = pyaudio.PyAudio()
        audioStream = p.open(format=pyaudio.paInt16,
                             channels=1,
                             rate=self.fs,
                             input=True,
                             frames_per_buffer=chunkSize)

        #empty out the recording
        self.Recording = np.zeros(numSamples, dtype=np.int16)
        self.Formants = np.zeros((100, 5), dtype=np.float32)
        self.FormantTime = np.zeros(100, dtype=np.float32)
        self.Pitch = np.zeros(100, dtype=np.float32)
        self.PitchTime = np.zeros(100, dtype=np.float32)
        FormantCount = 0
        PitchCount = 0

        #set up our axes
        ax = self.RawPlot.figure.add_subplot(111)
        f0ax = self.FundamentalFrequenncyPlot.figure.add_subplot(111)
        f0ax.tick_params(axis='x',
                         which='both',
                         bottom=False,
                         top=False,
                         labelbottom=False)
        f0ax.set_position([0.35, 0.05, 0.6, 0.93])
        formantAx = self.FormantPlot.figure.add_subplot(111)
        tractAx = self.VocalTractPlot.figure.add_subplot(111)
        tractAx.tick_params(axis='x',
                            which='both',
                            bottom=False,
                            top=False,
                            labelbottom=False)
        tractAx.set_position([0.35, 0.05, 0.6, 0.93])
        tractAx.set_ylabel('Vocal Tract Length (cm)')
        tractAx.set_ylim((0, 25))
        tractAx.set_xlim((0, 0.8))

        c = 34300  # speed of sound in cm/s
        maxPitchLag = 3
        maxVocalLag = 3
        ds_rate = 3
        #set up time vector
        print('Beginning New Recording')
        time = np.linspace(0, numSamples / self.fs, numSamples)
        i = 0
        try:  #using try/except to enable keyboard interrupt
            start = ti.time()
            while self.Status:  #keep going forever, or until keyboard interrupt
                t = (i + 1) * chunkSize

                if t > len(self.Recording
                           ):  # add space to the recording in necessary
                    extraSpace = np.zeros(numSamples, dtype=np.int16)
                    self.Recording = np.concatenate(
                        [self.Recording, extraSpace], axis=None)
                    time = np.linspace(0,
                                       len(self.Recording) / self.fs,
                                       len(self.Recording))

                # pull a chunk from our audio stream
                data = PyAudioTest.getChunk(chunkSize, audioStream, Random=0)
                data_ds = data[0:chunkSize:ds_rate]  # downsample of data
                # its generally a good idea to lowpass filter before downsampling,
                # but to save computational time this is skipped here.
                # our data is ~mostly~ band-limited, so I don't expect this to be huge problem

                # add chunk to our recording
                self.Recording[i * chunkSize:(i + 1) * chunkSize] = data

                # get f0 and update f0 plot
                # use my hack method for getting f0
                #clipData = PyAudioTest.centerClip(data)
                #acf = PyAudioTest.autocorr(clipData)
                #f0 = PyAudioTest.getF0(acf, self.fs)

                # use yin implementation instead
                # yin's original implementation called for filtering,
                # which we have not yet implemented for computational reasons
                data_hamming = data * np.hamming(chunkSize)
                df = yin.differenceFunction(data_hamming, chunkSize,
                                            self.fs / 75)
                cmndf = yin.cumulativeMeanNormalizedDifferenceFunction(
                    df, len(df))
                f0 = yin.getPitch(cmndf,
                                  self.fs / 500,
                                  self.fs / 75,
                                  harmo_th=0.35)

                if f0:  # if f0 is detected, update our graph
                    # store ot pitch and time
                    self.Pitch[PitchCount] = 1.0 * self.fs / f0
                    self.PitchTime[PitchCount] = 1.0 * (
                        t - chunkSize / 2) / self.fs
                    PitchCount += 1
                    # add space if needed
                    if PitchCount >= len(self.PitchTime):
                        self.Pitch = np.concatenate(
                            (self.Pitch, np.zeros(200, dtype=np.float32)))
                        self.PitchTime = np.concatenate(
                            (self.PitchTime, np.zeros(200, dtype=np.float32)))

                    #get pitches from the last 3 seconds
                    RecentPitches = []
                    pitchIDX = PitchCount - 1
                    while self.PitchTime[pitchIDX] >= 1.0 * (
                            t - chunkSize /
                            2) / self.fs - maxPitchLag and pitchIDX >= 0:
                        RecentPitches.append(self.Pitch[pitchIDX])
                        pitchIDX -= 1

                    #get mean and std
                    meanPitch = np.mean(RecentPitches)
                    if len(RecentPitches) == 1:
                        stdPitch = 25
                    else:
                        stdPitch = np.std(RecentPitches)

                    #plot
                    f0ax.bar([0], [2.0 * stdPitch],
                             bottom=[meanPitch - stdPitch])
                    f0ax.set_ylabel('Fundamental Frequency (Hz)')
                    f0ax.set_ylim((0, 500))
                    f0ax.set_xlim((0, 0.8))
                    self.FundamentalFrequenncyPlot.draw()

                formantAx.clear()
                formantAx.hold(True)
                if f0:  # if f0 is detected search for formants
                    #make PSD
                    fBins, PSD = sp.signal.periodogram(data_ds,
                                                       self.fs / ds_rate)
                    PSD = 20 * np.log10(PSD)  #convert to dB
                    try:
                        Formants = FormantFinder.findFormantsLPC(
                            data_ds, self.fs /
                            ds_rate)  # look for formants using LPC method
                        for f in range(
                                len(Formants
                                    )):  # plot the formants as  vertical lines
                            formantAx.plot([Formants[f], Formants[f]],
                                           [-100, 75],
                                           color='red')

                        formantAx.plot(fBins, PSD)
                        formantAx.set_title('Power Spectrum - Formants')
                        formantAx.set_xlabel('Frequency (Hz)')
                        formantAx.set_ylabel('Power (dB)')
                        formantAx.set_ylim((-90, 90))
                        formantAx.set_xlim((0, 5000))
                        '''
                        formantAx.bar(range(len(Formants)), Formants)
                        formantAx.set_xlabel('Formant number')
                        formantAx.set_ylabel('Frequency (Hz)')
                        formantAx.set_title('Formants Frequencies')
                        formantAx.set_xlim((0, 4.8))
                        formantAx.set_ylim((0, 5000))
                        formantAx.set_xticks([0.4, 1.4, 2.4, 3.4, 4.4])
                        formantAx.set_xticklabels(['F1', 'F2', 'F3', 'F4', 'F5'])
                        '''
                        self.FormantPlot.draw()
                        formantAx.hold(False)

                        #store Formants
                        if len(Formants) >= 5:
                            self.Formants[FormantCount, 0:5] = Formants[0:5]
                        else:
                            self.Formants[FormantCount,
                                          0:len(Formants)] = Formants
                        self.FormantTime[FormantCount] = 1.0 * (
                            t - chunkSize / 2) / self.fs
                        FormantCount += 1
                        # add space if needed
                        if FormantCount >= len(self.FormantTime):
                            self.Formants = np.concatenate(
                                (self.Formants,
                                 np.zeros((200, 5), dtype=np.float32)))
                            self.FormantTime = np.concatenate(
                                (self.FormantTime,
                                 np.zeros(200, dtype=np.float32)))

                        #detect recent vocal tract lengths
                        RecentTractLength = []
                        tractIDX = FormantCount - 1
                        while self.FormantTime[tractIDX] >= 1.0 * (
                                t - chunkSize /
                                2) / self.fs - maxVocalLag and tractIDX >= 0:
                            RecentTractLength.append(
                                FormantFinder.getVocalTractLength(
                                    self.Formants[tractIDX, :],
                                    c,
                                    method='lammert'))
                            tractIDX -= 1

                        # get mean, std
                        meanTractLength = np.median(RecentTractLength)
                        if len(RecentTractLength) == 1:
                            stdTractLength = 2
                        else:
                            stdTractLength = np.std(RecentTractLength)

                        # plot bar
                        tractAx.bar([0], [2 * stdTractLength],
                                    bottom=[meanTractLength - stdTractLength])
                        tractAx.set_ylabel('Vocal Tract Length (cm)')
                        tractAx.set_ylim((0, 25))
                        tractAx.set_xlim((0, 0.8))
                        self.VocalTractPlot.draw()

                    except (RuntimeError
                            ):  #formant detection can throw errors sometimes
                        Formants = np.zeros(3)

                else:  # if no f0, basically do nothing
                    fBins = np.linspace(0, self.fs / 2, 10)
                    PSD = np.zeros(10)

                #update our raw data plot, but only everyother chunk, because its time consuming
                if t > windowSize * self.fs and i % 3 == 0:
                    ax.plot(time[t - windowSize * self.fs:t],
                            self.Recording[t - windowSize * self.fs:t])
                    ax.set_title('Raw Waveform')
                    ax.set_xlabel('Time (s)')
                    ax.set_ylabel('amplitude')
                    self.RawPlot.draw()
                i += 1

                #check for incoming button clicks i.e. stop button
                QtCore.QCoreApplication.processEvents()

        except (
                KeyboardInterrupt, SystemExit
        ):  # in case of a keyboard interrupt or system exit, clean house
            self.FormantPlot.draw()
            self.RawPlot.draw()
            self.FundamentalFrequenncyPlot.draw()
            self.Pitch = self.Pitch[0:PitchCount]
            self.PitchTime = self.PitchTime[0:PitchCount]
            self.Formants = self.Formants[0:FormantCount, :]
            self.FormantTime = self.FormantTime[0:FormantCount]
            print('Recording Completed')
            self.Recording = self.Recording[0:t]
            print('recorded time is')
            print(1.0 * t / self.fs)
            print('elapsed time is:')
            print(ti.time() - start)
            return True

        self.Pitch = self.Pitch[0:PitchCount]
        self.PitchTime = self.PitchTime[0:PitchCount]
        self.Formants = self.Formants[0:FormantCount, :]
        self.FormantTime = self.FormantTime[0:FormantCount]
        print('Recording Completed')
        self.Recording = self.Recording[0:t]
        print('recorded time is')
        print(1.0 * t / self.fs)
        print('elapsed time is:')
        print(ti.time() - start)
        return True

    def SaveRecording(self):
        # open a save dialog so the user can select a file name
        root = Tk()
        path = tkFileDialog.asksaveasfilename()
        if not path:
            print('Invalid filename')
            root.destroy()
            return False
        # set file parameters
        wavFile = wave.open(path, 'w')
        wavFile.setnchannels(1)
        wavFile.setsampwidth(2)
        wavFile.setframerate(self.fs)
        #write data to file
        wavFile.writeframesraw(np.ndarray.tobytes(self.Recording))
        #close everything
        wavFile.close()
        root.destroy()
        print('Save Successful')
        return True

    def Load(self):
        # open file finder dialog UI
        root = Tk()
        root.filename = tkFileDialog.askopenfilename()
        if not root.filename:
            print('Invalid file')
            root.destroy()
            return False

        print(root.filename)
        # read the selected file
        audioFile = wave.openfp(root.filename, 'rb')
        self.fs = audioFile.getframerate()  #get fs
        n = audioFile.getnframes()  # get length
        data = np.frombuffer(audioFile.readframes(n), dtype=np.int16)
        self.Recording = data  # instert audio into our recording
        print(self.Recording)
        print("Recording Loaded successfully")
        root.destroy()
        return True

    def Playback(
        self
    ):  # similar to Go, but uses data from Load instead of collecting new data
        self.Status = True
        chunkSize = 8192
        windowSize = 3
        p = pyaudio.PyAudio()
        audioStream = p.open(format=pyaudio.paInt16,
                             channels=1,
                             rate=self.fs,
                             input=True,
                             frames_per_buffer=chunkSize)

        numSamples = len(self.Recording)
        self.Formants = np.zeros((100, 5), dtype=np.float32)
        self.FormantTime = np.zeros(100, dtype=np.float32)
        self.Pitch = np.zeros(100, dtype=np.float32)
        self.PitchTime = np.zeros(100, dtype=np.float32)
        PitchCount = 0
        FormantCount = 0

        ax = self.RawPlot.figure.add_subplot(111)

        f0ax = self.FundamentalFrequenncyPlot.figure.add_subplot(111)
        f0ax.tick_params(axis='x',
                         which='both',
                         bottom=False,
                         top=False,
                         labelbottom=False)
        f0ax.set_position([0.35, 0.05, 0.6, 0.93])
        tractAx = self.VocalTractPlot.figure.add_subplot(111)
        tractAx.tick_params(axis='x',
                            which='both',
                            bottom=False,
                            top=False,
                            labelbottom=False)
        tractAx.set_position([0.35, 0.05, 0.6, 0.93])
        tractAx.set_ylabel('Vocal Tract Length (cm)')
        tractAx.set_ylim((0, 25))
        tractAx.set_xlim((0, 0.8))

        formantAx = self.FormantPlot.figure.add_subplot(111)
        maxPitchLag = 3
        maxVocalLag = 3

        ds_rate = 3

        c = 34300  # speed of sound in cm/s

        Count = 0
        t = 0
        print('Beginning Playback')
        time = np.linspace(0, numSamples / self.fs, numSamples)
        try:
            start = ti.time()
            while t < numSamples - chunkSize and self.Status:
                t += chunkSize
                data = PyAudioTest.getChunk(chunkSize, audioStream, Random=0)
                data = self.Recording[t - chunkSize:t]
                data_ds = data[0:chunkSize:ds_rate]

                # use yin implementation
                data_hamming = data * np.hamming(chunkSize)
                df = yin.differenceFunction(data_hamming, chunkSize,
                                            self.fs / 75)
                cmndf = yin.cumulativeMeanNormalizedDifferenceFunction(
                    df, len(df))
                f0 = yin.getPitch(cmndf,
                                  self.fs / 500,
                                  self.fs / 75,
                                  harmo_th=0.35)

                if f0:
                    # store ot pitch and time
                    self.Pitch[PitchCount] = 1.0 * self.fs / f0
                    self.PitchTime[PitchCount] = 1.0 * (
                        t - chunkSize / 2) / self.fs
                    PitchCount += 1
                    # add space if needed
                    if PitchCount >= len(self.PitchTime):
                        self.Pitch = np.concatenate(
                            (self.Pitch, np.zeros(200, dtype=np.float32)))
                        self.PitchTime = np.concatenate(
                            (self.PitchTime, np.zeros(200, dtype=np.float32)))

                    RecentPitches = []
                    pitchIDX = PitchCount - 1
                    while self.PitchTime[pitchIDX] >= 1.0 * (
                            t - chunkSize /
                            2) / self.fs - maxPitchLag and pitchIDX >= 0:
                        RecentPitches.append(self.Pitch[pitchIDX])
                        pitchIDX -= 1

                    meanPitch = np.mean(RecentPitches)
                    if len(RecentPitches) == 1:
                        stdPitch = 25
                    else:
                        stdPitch = np.std(RecentPitches)
                    f0ax.bar([0], [2.0 * stdPitch],
                             bottom=[meanPitch - stdPitch])
                    f0ax.set_ylabel('Fundamental Frequency (Hz)')
                    f0ax.set_ylim((0, 500))
                    f0ax.set_xlim((0, 0.8))

                    self.FundamentalFrequenncyPlot.draw()

                # use my terrible gaussian estimation formant finder
                formantAx.clear()
                formantAx.hold(True)
                if f0:
                    fBins, PSD = sp.signal.periodogram(data_ds,
                                                       self.fs / ds_rate)
                    PSD = 20 * np.log10(PSD)
                    try:
                        Formants = FormantFinder.findFormantsLPC(
                            data_ds, self.fs / ds_rate)

                        for f in range(len(Formants)):
                            formantAx.plot([Formants[f], Formants[f]],
                                           [-100, 75],
                                           color='red')

                        formantAx.plot(fBins, PSD)
                        formantAx.set_title('Power Spectrum - Formants')
                        formantAx.set_xlabel('Frequency (Hz)')
                        formantAx.set_ylabel('Power (dB)')
                        formantAx.set_ylim((-90, 90))
                        formantAx.set_xlim((0, 5000))
                        '''
                        formantAx.bar(range(len(Formants)), Formants)
                        formantAx.set_xlabel('Formant number')
                        formantAx.set_ylabel('Frequency (Hz)')
                        formantAx.set_title('Formants Frequencies')
                        formantAx.set_xlim((0, 4.8))
                        formantAx.set_ylim((0, 5000))
                        formantAx.set_xticks([0.4, 1.4, 2.4, 3.4, 4.4])
                        formantAx.set_xticklabels(['F1', 'F2', 'F3', 'F4', 'F5'])
                        '''
                        self.FormantPlot.draw()
                        formantAx.hold(False)

                        if len(Formants) >= 5:
                            self.Formants[FormantCount, 0:5] = Formants[0:5]
                        else:
                            self.Formants[FormantCount,
                                          0:len(Formants)] = Formants
                        self.FormantTime[FormantCount] = 1.0 * (
                            t - chunkSize / 2) / self.fs
                        FormantCount += 1
                        # add space if needed
                        if FormantCount >= len(self.FormantTime):
                            self.Formants = np.concatenate(
                                (self.Formants,
                                 np.zeros((200, 5), dtype=np.float32)))
                            self.FormantTime = np.concatenate(
                                (self.FormantTime,
                                 np.zeros(200, dtype=np.float32)))

                        RecentTractLength = []
                        tractIDX = FormantCount - 1
                        while self.FormantTime[tractIDX] >= 1.0 * (
                                t - chunkSize /
                                2) / self.fs - maxVocalLag and tractIDX >= 0:
                            RecentTractLength.append(
                                FormantFinder.getVocalTractLength(
                                    self.Formants[tractIDX, :],
                                    c,
                                    method='lammert'))
                            tractIDX -= 1

                        meanTractLength = np.median(RecentTractLength)
                        if len(RecentTractLength) == 1:
                            stdTractLength = 2
                        else:
                            stdTractLength = np.std(RecentTractLength)
                        #TractLength = FormantFinder.getVocalTractLength(Formants, c)
                        tractAx.bar([0], [2 * stdTractLength],
                                    bottom=[meanTractLength - stdTractLength])
                        #tractAx.bar([0], [TractLength])
                        tractAx.set_ylabel('Vocal Tract Length (cm)')
                        tractAx.set_ylim((0, 25))
                        tractAx.set_xlim((0, 0.8))
                        self.VocalTractPlot.draw()

                    except (RuntimeError):
                        Formants = np.zeros(3)

                else:
                    fBins = np.linspace(0, self.fs / 2, 10)
                    PSD = np.zeros(10)

                Count += 1
                if t > windowSize * self.fs and Count % 3 == 0:
                    ax.plot(time[t - windowSize * self.fs:t],
                            self.Recording[t - windowSize * self.fs:t])
                    plt.xlim(t / self.fs - windowSize, t / self.fs + 1)
                    ax.set_xlabel('Time (s)')
                    ax.set_ylabel('amplitude')
                    ax.set_title('Raw Waveform')
                    self.RawPlot.draw()

                QtCore.QCoreApplication.processEvents()

        except (KeyboardInterrupt, SystemExit):
            self.FormantPlot.draw()
            self.RawPlot.draw()
            self.FundamentalFrequenncyPlot.draw()
            self.Pitch = self.Pitch[0:PitchCount]
            self.PitchTime = self.PitchTime[0:PitchCount]
            self.Formants = self.Formants[0:FormantCount, :]
            self.FormantTime = self.FormantTime[0:FormantCount]
            print('Recording Completed')
            print('recorded time is')
            print(1.0 * t / self.fs)
            print('elapsed time is:')
            print(ti.time() - start)
            return True

        self.Pitch = self.Pitch[0:PitchCount]
        self.PitchTime = self.PitchTime[0:PitchCount]
        self.Formants = self.Formants[0:FormantCount, :]
        self.FormantTime = self.FormantTime[0:FormantCount]
        print('Recording Completed')
        print('recorded time is')
        print(1.0 * t / self.fs)
        print('elapsed time is:')
        print(ti.time() - start)
示例#6
0
class DataDisplayWidget(QtGui.QWidget):
    def __init__(self):
        super(DataDisplayWidget, self).__init__()

        # Defaults

        self.cm = 'hot'
        self.ipm = 'none'
        self.is3D = False
        self.asNewScanCallback = None

        self.xlabel = 'x'
        self.ylabel = 'y'
        self.cmapdata = numpy.zeros((32, 256), numpy.uint16)
        for i in xrange(0, 31):
            self.cmapdata[i, :] = numpy.linspace(0, 255, 256)

        #Setup UI and stuff

        self.setupUI()
        self.generateContextMenu()
        self.setupActions()
        self.registerCMs()

        self.data = numpy.zeros((128, 128), numpy.uint16)
        self.data = numpy.outer(numpy.linspace(0, numpy.sqrt(256), 128),
                                numpy.linspace(0, numpy.sqrt(256), 128))

        ltz = self.data > 0
        self.maxData = numpy.max(self.data[ltz])
        self.minData = numpy.min(self.data[ltz])

        self.setAutoscale(True)
        self._hasSelection(False)
        self._draw()

    def setupUI(self):
        self.majorLayout = QtGui.QVBoxLayout(self)
        self.dataWidget = MatplotlibWidget()
        self.dataWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)

        self.majorLayout.addWidget(self.dataWidget)

        self.cbar = MatplotlibWidget()

        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,
                                       QtGui.QSizePolicy.Maximum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.cbar.sizePolicy().hasHeightForWidth())
        self.cbar.setSizePolicy(sizePolicy)
        self.cbar.setMaximumSize(QtCore.QSize(2**15 - 1, 32))
        self.updCM()
        #        self.majorLayout.addWidget(self.cbar)

        self.minDataEdit = QtGui.QLineEdit()
        self.maxDataEdit = QtGui.QLineEdit()

        editSizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum,
                                           QtGui.QSizePolicy.Maximum)

        self.minDataEdit.setSizePolicy(editSizePolicy)
        self.maxDataEdit.setSizePolicy(editSizePolicy)
        self.minDataEdit.setMaximumSize(QtCore.QSize(128, 32))
        self.maxDataEdit.setMaximumSize(QtCore.QSize(128, 32))

        self.minDataEdit.setMinimumSize(QtCore.QSize(64, 32))
        self.maxDataEdit.setMinimumSize(QtCore.QSize(64, 32))

        self.cbarlayout = QtGui.QHBoxLayout()
        self.cbarlayout.addWidget(self.minDataEdit)
        self.cbarlayout.addWidget(self.cbar)
        self.cbarlayout.addWidget(self.maxDataEdit)

        self.majorLayout.addLayout(self.cbarlayout)
        # Expose properties of mpw

    def setupActions(self):
        self.maxDataEdit.textChanged.connect(self.maxDataChanged)
        self.minDataEdit.textChanged.connect(self.minDataChanged)
        self.dataWidget.customContextMenuRequested.connect(
            self.openContextMenu)

    def onSelect(self, eclick, erelease):
        x = numpy.min([eclick.xdata, erelease.xdata])
        y = numpy.min([eclick.ydata, erelease.ydata])

        w = abs(eclick.xdata - erelease.xdata)
        h = abs(eclick.ydata - erelease.ydata)

        try:
            self.selectionRect.remove()
        except:
            pass
        if h > 3 and w > 3:
            self.selection = {'x': x, 'y': y, 'w': w, 'h': h}
            self.selectionRect = Rectangle((x, y), w, h, fill=False)
            self.dataWidget.figure.axes[0].add_patch(self.selectionRect)
            self.dataWidget.draw()
            self._hasSelection(True)
        else:
            self._hasSelection(False)
            self.selection = {'x': None, 'y': None, 'w': None, 'h': None}

    def _hasSelection(self, yn):
        self.hasSelection = yn
        self.acAsNewScan.setEnabled(yn)

    def maxDataChanged(self, txt):
        if float(txt) >= self.minData:
            self.maxData = float(txt)
            self._draw()

    def minDataChanged(self, txt):
        if float(txt) <= self.maxData:
            self.minData = float(txt)
            self._draw()

    def setXLabel(self, xlabel):
        self.xlab = xlabel

    def setYLabel(self, ylabel):
        self.ylab = ylabel

    def update(self, data):
        self.data = data
        self._draw()

    def _draw(self, **kwargs):
        if self.is3D:
            self.draw3D()
        else:
            if (self.isAutoScale):
                idx = self.data > 0
                self.maxData = numpy.max(self.data[idx])
                self.minData = numpy.min(self.data[idx])
                print "min data is: " + str(self.minData)
                self.minDataEdit.setText(str(self.minData))
                self.maxDataEdit.setText(str(self.maxData))
            self.dataWidget.axes.imshow(self.data,
                                        cmap=self.cm,
                                        clim=(self.minData, self.maxData),
                                        interpolation=self.ipm)
            self.selector = RectangleSelector(self.dataWidget.axes,
                                              self.onSelect,
                                              button=1,
                                              useblit=True)

            self.dataWidget.draw()

    def draw3D(self):
        print "3D drawing not yet implemented"

    def openContextMenu(self, point):
        self.popMenu.exec_(self.dataWidget.mapToGlobal(point))

    def generateContextMenu(self):
        self.popMenu = QtGui.QMenu(self)
        self.acSetAutoScale = QtGui.QAction('Autoscale', self)
        self.acSetAutoScale.setCheckable(True)
        self.acSetAutoScale.setChecked(True)
        self.popMenu.addAction(self.acSetAutoScale)

        self.acSetAutoScale.toggled.connect(self.setAutoscale)

        self.acSet3D = QtGui.QAction('3D', self)
        self.acSet3D.setCheckable(True)
        self.acSet3D.setChecked(False)
        self.popMenu.addAction(self.acSet3D)

        self.acgCM = QtGui.QActionGroup(self)

        self.CMmenu = QtGui.QMenu(self)
        self.CMmenu.setTitle('Colormaps')

        for cm in ("gray|red|green|blue|red white|green white|blue white|" +
                   "cyan|magenta|cyan white|jet|" +
                   "magenta white|hot|cyan hot|afmhot|bmg").split("|"):
            ac = QtGui.QAction(cm, self.acgCM)
            ac.triggered.connect(functools.partial(self.setCM, cm))
            ac.setCheckable(True)
            if cm == self.cm:
                ac.setChecked(True)
        ip_methods = [
            'none', 'nearest', 'bilinear', 'bicubic', 'spline16', 'spline36',
            'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', 'catrom',
            'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos'
        ]

        self.acgIP = QtGui.QActionGroup(self)
        for ip in ip_methods:
            ac = QtGui.QAction(ip, self.acgIP)
            ac.triggered.connect(functools.partial(self.setIP, ip))
            ac.setCheckable(True)

            self.acgIP.addAction(ac)

        self.IPmenu = QtGui.QMenu(self)
        self.IPmenu.setTitle('Interpolation')
        self.IPmenu.addActions(self.acgIP.actions())

        self.CMmenu.addActions(self.acgCM.actions())

        self.popMenu.addSeparator()
        self.popMenu.addMenu(self.CMmenu)
        self.popMenu.addSeparator()
        self.popMenu.addMenu(self.IPmenu)

        self.acAsNewScan = QtGui.QAction("Use selection as new scan",
                                         self.popMenu)
        self.acAsNewScan.triggered.connect(self.onAsNewScan)
        self.acAsNewScan.setEnabled(False)
        self.popMenu.addSeparator()
        self.popMenu.addAction(self.acAsNewScan)

    def setIP(self, ip):
        self.ipm = ip
        self._draw()

    def setAutoscale(self, chk):
        self.isAutoScale = chk
        self.minDataEdit.setEnabled(not chk)
        self.maxDataEdit.setEnabled(not chk)

    def set3D(self, chk):
        self.is3D = chk

    def setCM(self, cm):
        self.cm = cm
        self._draw()
        self.updCM()

    def updCM(self):
        self.cbarplt = self.cbar.axes.imshow(self.cmapdata, cmap=self.cm)
        self.cbar.axes.axis('off')
        self.cbar.axes.axis('tight')
        self.cbar.draw()

    def registerCMs(self):
        cyanAndRedHot = {
            'red': (
                (0.0, 0.0, 0.0),
                (0.2, 0.0, 0.0),
                (0.2 + 0.8 / 3.0, 1.0, 1.0),
                (1.0, 1.0, 1.0),
            ),
            'green':
            ((0.0, 1.0, 1.0), (0.2, 0.0, 0.0), (0.2 + 0.8 / 3.0, 0.0, 0.0),
             (0.2 + 1.6 / 3.0, 1.0, 1.0), (1.0, 1.0, 1.0)),
            'blue':
            ((0.0, 1.0, 1.0), (0.2, 0.0, 0.0), (0.2 + 0.8 / 3.0, 0.0, 0.0),
             (0.2 + 1.6 / 3.0, 0.0, 0.0), (1.0, 1.0, 1.0))
        }
        cm = matplotlib.colors.LinearSegmentedColormap('cyan hot',
                                                       cyanAndRedHot)
        matplotlib.pyplot.register_cmap(cmap=cm)

        red = {
            'red': ((0, 0, 0), (1, 1, 1)),
            'green': ((0, 0, 0), (1, 0, 0)),
            'blue': ((0, 0, 0), (1, 0, 0)),
        }

        cm = matplotlib.colors.LinearSegmentedColormap('red', red)
        matplotlib.pyplot.register_cmap(cmap=cm)

        green = {
            'red': ((0, 0, 0), (1, 0, 0)),
            'green': ((0, 0, 0), (1, 1, 1)),
            'blue': ((0, 0, 0), (1, 0, 0)),
        }

        cm = matplotlib.colors.LinearSegmentedColormap('green', green)
        matplotlib.pyplot.register_cmap(cmap=cm)

        blue = {
            'red': ((0, 0, 0), (1, 0, 0)),
            'green': ((0, 0, 0), (1, 0, 0)),
            'blue': ((0, 0, 0), (1, 1, 1)),
        }

        cm = matplotlib.colors.LinearSegmentedColormap('blue', blue)
        matplotlib.pyplot.register_cmap(cmap=cm)

        magenta = {
            'red': ((0, 0, 0), (1, 1, 1)),
            'green': ((0, 0, 0), (1, 0, 0)),
            'blue': ((0, 0, 0), (1, 1, 1)),
        }

        cm = matplotlib.colors.LinearSegmentedColormap('magenta', magenta)
        matplotlib.pyplot.register_cmap(cmap=cm)

        cyan = {
            'red': ((0, 0, 0), (1, 0, 0)),
            'green': ((0, 0, 0), (1, 1, 1)),
            'blue': ((0, 0, 0), (1, 1, 1)),
        }

        cm = matplotlib.colors.LinearSegmentedColormap('cyan', cyan)
        matplotlib.pyplot.register_cmap(cmap=cm)

        redwhite = {
            'red': ((0, 0, 0), (.5, 1, 1), (1, 1, 1)),
            'green': ((0, 0, 0), (0.5, 0, 0), (1, 1, 1)),
            'blue': ((0, 0, 0), (0.5, 0, 0), (1, 1, 1)),
        }

        cm = matplotlib.colors.LinearSegmentedColormap('red white', redwhite)
        matplotlib.pyplot.register_cmap(cmap=cm)
        greenwhite = {
            'red': ((0, 0, 0), (.5, 0, 0), (1, 1, 1)),
            'green': ((0, 0, 0), (0.5, 1, 1), (1, 1, 1)),
            'blue': ((0, 0, 0), (0.5, 0, 0), (1, 1, 1)),
        }

        cm = matplotlib.colors.LinearSegmentedColormap('green white',
                                                       greenwhite)
        matplotlib.pyplot.register_cmap(cmap=cm)
        bluewhite = {
            'red': ((0, 0, 0), (.5, 0, 0), (1, 1, 1)),
            'green': ((0, 0, 0), (0.5, 0, 0), (1, 1, 1)),
            'blue': ((0, 0, 0), (0.5, 1, 1), (1, 1, 1)),
        }

        cm = matplotlib.colors.LinearSegmentedColormap('blue white', bluewhite)
        matplotlib.pyplot.register_cmap(cmap=cm)

        bmg = {
            'red': ((0, 0, 0), (.5, 1, 1), (1, 0, 0)),
            'green': ((0, 0, 0), (0.5, 1, 1), (1, 1, 1)),
            'blue': ((0, 0, 0), (0.5, 1, 1), (1, 0, 0)),
        }

        cm = matplotlib.colors.LinearSegmentedColormap('bmg', bmg)
        matplotlib.pyplot.register_cmap(cmap=cm)

        magentawhite = {
            'red': ((0, 0, 0), (.5, 1, 1), (1, 1, 1)),
            'green': ((0, 0, 0), (0.5, 0, 0), (1, 1, 1)),
            'blue': ((0, 0, 0), (0.5, 1, 1), (1, 1, 1)),
        }

        cm = matplotlib.colors.LinearSegmentedColormap('magenta white',
                                                       magentawhite)
        matplotlib.pyplot.register_cmap(cmap=cm)

        cyanwhite = {
            'red': ((0, 0, 0), (.5, 0, 0), (1, 1, 1)),
            'green': ((0, 0, 0), (0.5, 1, 1), (1, 1, 1)),
            'blue': ((0, 0, 0), (0.5, 1, 1), (1, 1, 1)),
        }

        cm = matplotlib.colors.LinearSegmentedColormap('cyan white', cyanwhite)
        cm.set_over((0, 0, 1))
        matplotlib.pyplot.register_cmap(cmap=cm)

    def onAsNewScan(self):
        try:
            x = int(round(self.selection['x']))
            y = int(round(self.selection['y']))
            w = int(round(self.selection['w']))
            h = int(round(self.selection['h']))
            self.asNewScanCallback(self.selection, self.data[y:y + h, x:x + w])
        except AttributeError:
            print "No Callback set for opening selection in a new scan."
            self.asNewScanCallback(self.selection, self.data[y:y + h, x:x + w])