Ejemplo n.º 1
0
 def __init__(self):
     super(mywindow, self).__init__()
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.ui.textBrowser.setText("PyScripts")
     self.ui.listWidget.addItem("PyScripts")
     self.ui.pushButton.clicked.connect(self.test)
Ejemplo n.º 2
0
class mywindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(mywindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.textBrowser.setText("PyScripts")
        self.ui.listWidget.addItem("PyScripts")
        self.ui.pushButton.clicked.connect(self.test)

    def test(self):
        self.ui.listWidget.clear()
        a = start()
        b = "Белинвестбанк:", a[0], "Нейронная сеть:", a[1], "Альфа-Банк:", a[
            2], "Нейронная сеть:", a[3], "Нацбанк:", a[
                4], "Нейронная сеть:", a[5]
        self.ui.textBrowser.setText(str(b))

        cur = con.cursor()
        cur.execute("SELECT * FROM `test`")
        rows = cur.fetchall()
        for row in rows:
            if self.ui.checkBox.isChecked():
                self.ui.listWidget.addItem("Белинвестбанк: " + str(row[0]) +
                                           ";    Прогноз нейронной сети: " +
                                           str("%.3f" % row[1]))
            if self.ui.checkBox_2.isChecked():
                self.ui.listWidget.addItem(
                    "Альфа-Банк: " + str(row[2]) +
                    ";         Прогноз нейронной сети: " +
                    str("%.2f" % row[3]))
            if self.ui.checkBox_3.isChecked():
                self.ui.listWidget.addItem(
                    "Нацбанк: " + str(row[4]) +
                    ";               Прогноз нейронной сети: " +
                    str("%.2f" % row[3]))
Ejemplo n.º 3
0
class Ui(QtWidgets.QMainWindow):
    def __init__(self, parent=None, **kwargs):
        # super().__init__(parent, **kwargs)
        # uic.loadUi("test.ui", self)
        # self.show()
        super(Ui, self).__init__(parent, **kwargs)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        # self.showFullScreen()

        self.ui.pbExit.clicked.connect(self.exit)
        self.ui.pbReboot.clicked.connect(self.reboot)
        self.ui.pbShutdown.clicked.connect(self.shutdown)

        self.ui.tabTempData = PlotWindow()

        self.show()

    def exit(self):
        sys.exit()

    def reboot(self):
        os.system("sudo shutdown -r now")

    def shutdown(self):
        os.system("sudo shutdown -P now")
Ejemplo n.º 4
0
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()  # the ui file here
        self.ui.setupUi(self)
        self.statusBar().showMessage('ready')
        self.setWindowTitle('ipad database')

        # q_widget for plot

        # self.toolbar1 = NavigationToolbar(self.canvas1, self)

        grid = QtGui.QGridLayout()
        self.ui.plt_widget.setLayout(grid)

        self.figure1 = plt.figure(figsize=(15, 5))
        self.canvas1 = FigureCanvas(self.figure1)

        grid.addWidget(self.canvas1, 1, 0, 1, 2)

        # layout1 = QtGui.QVBoxLayout()
        # layout1.addWidget(self.toolbar1)
        # layout1.addWidget(self.canvas1)

        # self.ui.plt_widget.setLayout(layout1)
        self.num_rep_init()
Ejemplo n.º 5
0
    def __init__(self, app):
        """
            Initializes all needed variables
        """
        super(MyWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.carolbtn.clicked.connect(self.carolclicked)
        self.ui.jinglebtn.clicked.connect(self.jingleclicked)
        self.ui.littlebtn.clicked.connect(self.littleclicked)
        self.ui.pausebtn.clicked.connect(self.pauseClicked)
        self.ui.exitbtn.clicked.connect(self.exitclicked)
        self.ui.tempoSlider.valueChanged[int].connect(self.updateTempo)

        self.setSongPlaying(False)  #Initialize Song Stopper
        self.isPaused = False
        self.progress = 0
        self.currentTempo = 290

        self.threadpool = QThreadPool()
        self.win = self
        self.app = app

        self.ui.progressBar.setVisible(False)
Ejemplo n.º 6
0
 def __init__(self, parent=None):
     QtGui.QWidget.__init__(self, parent)
     self.ui = Ui_MainWindow()
     self.ui.StartUi(self)
     self.shift = 0
     self.HOST = socket.gethostname()
     self.PORT = 0x1234
     self.MSGSIZE = 16384
     self.ifStart = False
     self.startime = 0
     self.timepassed = 0
     self.original = 0
     QtCore.QObject.connect(self.ui.originalBtn,
                            QtCore.SIGNAL(_fromUtf8("clicked()")),
                            self.Initial)
     QtCore.QObject.connect(self.ui.shiftUpBtn,
                            QtCore.SIGNAL(_fromUtf8("clicked()")),
                            self.Shiftup)
     QtCore.QObject.connect(self.ui.shiftDownBtn,
                            QtCore.SIGNAL(_fromUtf8("clicked()")),
                            self.Shiftdown)
     QtCore.QObject.connect(self.ui.Exit,
                            QtCore.SIGNAL(_fromUtf8("clicked()")),
                            self.close_application)
     QtCore.QObject.connect(self.ui.Clear,
                            QtCore.SIGNAL(_fromUtf8("clicked()")),
                            self.clear)
     self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.s.connect((self.HOST, self.PORT))
     self.sendMsg = ""
Ejemplo n.º 7
0
 def __init__(self):
     super(MyWindow, self).__init__()
     self.setGeometry(200, 200, 300, 300)
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.ui.littlebtn.clicked.connect(self.littleclicked)
     self.ui.jinglebtn.clicked.connect(self.jingleclicked)
     self.ui.carolbtn.clicked.connect(self.carolclicked)
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.pushButton.pressed.connect(self.button)

    def button(self):
        self.ui.label_3.setText('123')
Ejemplo n.º 9
0
    def __init__(self):
        super(mywindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        #  изменяем шрифт и размер надписи
        self.ui.label.setFont(QtGui.QFont('Arial', 20))

        # изменить геометрию
        self.ui.label.setGeometry(QtCore.QRect(210, 210, 600, 200))

        self.ui.label.setText("Бамоновка - помойка!")
Ejemplo n.º 10
0
Archivo: 0920.py Proyecto: hyxcj/0919
 def __init__(self, parent=None):
     super().__init__(parent)  # 调用父类构造函数,创建窗体
     self.ui = Ui_MainWindow()  # 创建UI对象
     self.ui.setupUi(self)  # 构造UI界面
     self.setWindowTitle("hyx")
     mplStyle.use("classic")  # 使用样式,必须在绘图之前调用,修改字体后才可显示汉字
     mpl.rcParams['font.sans-serif'] = ['KaiTi', 'SimHei'
                                        ]  # 显示汉字为 楷体, 汉字不支持 粗体,斜体等设置
     mpl.rcParams['font.size'] = 12
     ##  Windows自带的一些字体
     ##  黑体:SimHei 宋体:SimSun 新宋体:NSimSun 仿宋:FangSong  楷体:KaiTi
     mpl.rcParams['axes.unicode_minus'] = False  # 减号unicode编码
     self.data = []
     self.__createFigure()  # 创建Figure和FigureCanvas对象,初始化界面
Ejemplo n.º 11
0
    def __init__(self, parent=None, **kwargs):
        # super().__init__(parent, **kwargs)
        # uic.loadUi("test.ui", self)
        # self.show()
        super(Ui, self).__init__(parent, **kwargs)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        # self.showFullScreen()

        self.ui.pbExit.clicked.connect(self.exit)
        self.ui.pbReboot.clicked.connect(self.reboot)
        self.ui.pbShutdown.clicked.connect(self.shutdown)

        self.ui.tabTempData = PlotWindow()

        self.show()
Ejemplo n.º 12
0
class MyWindow(QMainWindow):
    def __init__(self):
        super(MyWindow, self).__init__()
        self.setGeometry(200, 200, 300, 300)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.littlebtn.clicked.connect(self.littleclicked)
        self.ui.jinglebtn.clicked.connect(self.jingleclicked)
        self.ui.carolbtn.clicked.connect(self.carolclicked)

    def carolclicked(self):
        print("Carol button was clicked")

    def jingleclicked(self):
        print("Jingle button was clicked")

    def littleclicked(self):
        print("Little button was clicked")
Ejemplo n.º 13
0
class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.dbCon = DB_manager.DatabaseUtility("autoswitch", "boards")

    def FillTable(self):
        col = self.dbCon.GetColumns("boards")  #self.dbu.GetColumns()
        #table = self.dbcon.GetTable()

        headerlbl = []
        for c in range(len(col)):
            headerlbl.append(col[c][0])

        self.ui.tableWidget.setColumnCount(len(headerlbl))
        self.ui.tableWidget.setHorizontalHeaderLabels(headerlbl)
        self.ui.tableWidget.clear()
        '''
Ejemplo n.º 14
0
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Create combo box for Col1
        combo_box_1 = QtWidgets.QComboBox()
        combo_box_1.addItems(['Item 1', 'Item 2', 'Item 3'])
        combo_box_1.currentIndexChanged[str].connect(self.print_selected_text)
        self.ui.tab_1_table.setCellWidget(0, 0, combo_box_1)

        # Connect add row buttons to functions
        self.ui.add_tab_1_button.clicked.connect(self.add_row)

        ### Test section ###
        # Create combo box for Col2
        self.combo_box_2 = QtWidgets.QComboBox()
        self.ui.tab_1_table.setCellWidget(0, 1, self.combo_box_2)
        self.combo_box_2.addItems(['Item A', 'Item B', 'Item C'])
        self.combo_box_2.currentIndexChanged[str].connect(
            self.print_selected_text)
        ##################

    def add_row(self):
        """Add row and insert combo box in column.."""

        rowPos = self.ui.tab_1_table.rowCount()

        # Create new instance of a combo boxes
        new_combo_box_1 = QtWidgets.QComboBox()
        new_combo_box_1.addItems(['Item 1', 'Item 2', 'Item 3'])
        new_combo_box_1.currentIndexChanged[str].connect(
            self.print_selected_text)

        # Insert new row and add combo boxes
        self.ui.tab_1_table.insertRow(rowPos)
        self.ui.tab_1_table.setCellWidget(rowPos, 0, new_combo_box_1)

    def print_selected_text(self, text):
        """Test function to see if cell text will be printed whenever it changes."""
        print(text)
Ejemplo n.º 15
0
    def __init__(self):
        super().__init__()
        #loadUi('test.ui', self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        #init Bottons
        self.ui.call_xls.clicked.connect(self.csv)
        self.ui.call_dia_classi.clicked.connect(self.read_classi)
        self.ui.call_dia_train.clicked.connect(self.read_train)
        self.ui.call_dia_val.clicked.connect(self.read_val)
        self.ui.call_dialog.clicked.connect(self.read_meas)
        self.ui.call_dialog_3.clicked.connect(self.read_meas_2)
        self.ui.call_vz.clicked.connect(self.choose_dir)
        self.ui.call_start_meas.clicked.connect(self.meas_start)
        self.ui.call_stop_meas.clicked.connect(self.stop_con)
        self.ui.call_start_classi.clicked.connect(self.start_classi)
        self.ui.call_save_feature.clicked.connect(self.feat_extra)
        self.ui.call_dia_test.clicked.connect(self.read_test)
        self.ui.call_com.clicked.connect(self.start_thread)
Ejemplo n.º 16
0
    def __init__(self, app):
        """
            Initializes all needed variables
        """
        super(MyWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.carolbtn.clicked.connect(self.carolclicked)
        self.ui.jinglebtn.clicked.connect(self.jingleclicked)
        self.ui.littlebtn.clicked.connect(self.littleclicked)
        self.ui.pausebtn.clicked.connect(self.pauseClicked)
        self.ui.playbtn.clicked.connect(self.playClicked)
        self.ui.exitbtn.clicked.connect(self.exitclicked)

        self.setSongPlaying(False)#Initialize Song Stopper
        self.isPaused = False

        self.threadpool = QThreadPool()
        self.win = self
        self.app = app
Ejemplo n.º 17
0
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Create combo box for Col1
        combo_box_1 = QtWidgets.QComboBox()
        combo_box_1.addItems(['Item 1', 'Item 2', 'Item 3'])
        combo_box_1.currentIndexChanged[str].connect(self.print_selected_text)
        self.ui.tab_1_table.setCellWidget(0, 0, combo_box_1)

        # Connect add row buttons to functions
        self.ui.add_tab_1_button.clicked.connect(self.add_row)

        ### Test section ###
        # Create combo box for Col2
        self.combo_box_2 = QtWidgets.QComboBox()
        self.ui.tab_1_table.setCellWidget(0, 1, self.combo_box_2)
        self.combo_box_2.addItems(['Item A', 'Item B', 'Item C'])
        self.combo_box_2.currentIndexChanged[str].connect(
            self.print_selected_text)
Ejemplo n.º 18
0
 def __init__(self):
     super(mywindow, self).__init__()
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.ui.PlusButt.clicked.connect(self.AddEntry)
     self.ui.AddButton.clicked.connect(self.EditEntry)
     self.ui.DelButt.clicked.connect(self.DeleteEntry)
     self.ui.SentimientosColor.clicked.connect(self.ColorPick)
     self.ui.SentimientosAdd.clicked.connect(self.AddFeeling)
     self.ui.Menu.clicked.connect(self.MenuTravel)
     self.ui.MenuCon.setEnabled(False)
     self.ui.PerfilCon.setEnabled(False)
     self.ui.tabWidget.setCurrentIndex(0)
     self.ui.SentimientosColor.setStyleSheet("background-color: white")
     self.ui.SentimientosDrop.activated.connect(self.LoadFeeling)
     self.ui.SentimientosDropEdic.activated.connect(self.LoadFeeling)
     self.ui.SentimientosRemove.clicked.connect(self.DeleteFeeling)
     self.ui.BackMenu.clicked.connect(self.BackMenu)
     self.ui.Perfil.clicked.connect(self.GoPerfil)
     self.ui.BackPerfil.clicked.connect(self.BackPerfil)
     self.ReloadFeelings()
     self.LoadFeeling()
     self.CargarEntradas()
Ejemplo n.º 19
0
import sys
from test import Ui_MainWindow
from PyQt4 import QtGui


if __name__ =="__main__":
    app=QtGui.QApplication(sys.argv)
    win=Ui_MainWindow()
    win.show()
    sys.exit(app.exec_())
Ejemplo n.º 20
0
class AppWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        #loadUi('test.ui', self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        #init Bottons
        self.ui.call_xls.clicked.connect(self.csv)
        self.ui.call_dia_classi.clicked.connect(self.read_classi)
        self.ui.call_dia_train.clicked.connect(self.read_train)
        self.ui.call_dia_val.clicked.connect(self.read_val)
        self.ui.call_dialog.clicked.connect(self.read_meas)
        self.ui.call_dialog_3.clicked.connect(self.read_meas_2)
        self.ui.call_vz.clicked.connect(self.choose_dir)
        self.ui.call_start_meas.clicked.connect(self.meas_start)
        self.ui.call_stop_meas.clicked.connect(self.stop_con)
        self.ui.call_start_classi.clicked.connect(self.start_classi)
        self.ui.call_save_feature.clicked.connect(self.feat_extra)
        self.ui.call_dia_test.clicked.connect(self.read_test)
        self.ui.call_com.clicked.connect(self.start_thread)


    @pyqtSlot()

    def meas_start(self):
        #if self.ui.ad_ver.text.isempty or self.ui.ad_name_meas.isempyty:
        #    self.ui.msg_text.setText("no path selcted")
        #elif self.ui.ad_val_meas.isempty:
        #    self.ui.msg_text.setText("no num of cycle set")
        #else:
            # Variables
            ip_adress = '192.168.128.1'
            file_path = str(self.ui.ad_ver.text())+'/'+str(self.ui.ad_name_meas.text())+'.csv'
            num_of_cycle = int(self.ui.ad_val_meas.text())
            buff_array = ''
            buff_np = np.zeros((num_of_cycle, 16384), float)

            # inizilation trigger
            rp_s = scpi.scpi(host=ip_adress)

            rp_s.tx_txt('ACQ:DEC 64')
            rp_s.tx_txt('ACQ:TRIG:LEVEL -21')
            rp_s.tx_txt('ACQ:TRIG:DLY 12192')
            rp_s.tx_txt('ACQ:START')
            rp_s.tx_txt('ACQ:TRIG EXT_NE')

            # wait untill trigger is activated
            while 1:
                rp_s.tx_txt('ACQ:TRIG:STAT?')
                if rp_s.rx_txt() == 'TD':
                    break
            for x in range(num_of_cycle):
                # collecting all 16xxx values and save and convert
                rp_s.tx_txt('ACQ:SOUR1:DATA?')
                buff_string = rp_s.rx_txt()
                buff_string = buff_string.strip('{}\n\r').replace("  ", "")
                buff = np.fromstring(buff_string, sep=',')
                buff = np.round(buff, 3)
                buff_np[x:] = buff

            np.savetxt(file_path, buff_np, delimiter=';', fmt='%.3f')
            print('done')


    def start_thread(self):
        t1 = threading.Thread(target=self.com_start)
      #  t2 = threading.Thread(target=self.w.show)
       # t2.start()

        t1.start()

    def com_start(self):
        path = open('path.txt', 'r')
        path = path.read()
        # path = 'C:\Users\dennis\Documents\red_pitaya\plink.exe [email protected] -ssh -pw root -m "config.txt"'
        print(path)
        os.system(path)

    def csv(self):

        file = QFileDialog.getOpenFileName(self, "Choose ultra sonic data from Labview", "",
                                           "All Files (*);;XLS Files (*.xls)")
        # open the data
        file_str = open(file[0], 'r')
        file = file_str.read()

       # self.ui.ad_xls.setText(file_str)

        # replace the tabstop with a simikolon
        file_new = file.replace('\t', ';')
        file_new = file_new.replace(',', '.')
        file_new = file_new.replace('"', '')
        # file_new = file_new.replace('\r\n', ';')
        name = file_str.name
        len(name)
      #  print(file_new)

        # generate a new dataname with csv
        new = name.replace('xls', 'csv')

        # open and write new file with the replaced simikolon
        new_file = open(new, 'w+')
        new_file.write(file_new)

        # close all data
        new_file.close()
        file_str.close()

        self.ui.ad_xls.setText(new)

    def read_train(self):

        file = QFileDialog.getOpenFileName(self, "read train Data", "",
                                           "All Files (*);;CSV File (*.csv)")
        self.ui.ad_train.setText(file[0])

    def read_val(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        file = QFileDialog.getOpenFileName(self, "QFileDialog.getOpenFileName()", "",
                                           "All Files (*);;CSV File (*.csv)", options=options)
        self.ui.ad_val.setText(file[0])

    def read_classi(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        file = QFileDialog.getOpenFileName(self, "QFileDialog.getOpenFileName()", "",
                                           "All Files (*);;CSV File (*.csv)", options=options)
        self.ui.ad_classi.setText(file[0])

    def read_meas(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        file = QFileDialog.getOpenFileName(self, "QFileDialog.getOpenFileName()", "",
                                           "All Files (*);;CSV File (*.csv)", options=options)
        self.ui.ad_meas.setText(file[0])

    def read_test(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        file = QFileDialog.getOpenFileName(self, "QFileDialog.getOpenFileName()", "",
                                           "All Files (*);;CSV File (*.csv)", options=options)
        self.ui.ad_test.setText(file[0])

    def read_meas_2(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        file = QFileDialog.getOpenFileName(self, "QFileDialog.getOpenFileName()", "",
                                           "All Files (*);;CSV File (*.csv)", options=options)
        self.ui.ad_meas_3.setText(file[0])

    def choose_dir(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        file = str(QFileDialog.getExistingDirectory(self, "Select Directory"))
        print(file)

        self.ui.ad_ver.setText(file)






    def stop_con(self):
        path = open('path1.txt', 'r')
        path = path.read()
        # path = 'C:\Users\dennis\Documents\red_pitaya\plink.exe [email protected] -ssh -pw root -m "config.txt"'
        print(path)
        os.system(path)

    def start_classi(self):
        path_test = self.ui.ad_test.text()
        path_train = self.ui.ad_train.text()
        path_val = self.ui.ad_val.text()

        if  path_train == "" or path_val == "" or path_test == "":
            self.ui.msg_text.setText("path not complett")
        elif self.ui.check_svm.isChecked():
            df0 = np.loadtxt(path_test, delimiter=";")
            df1 = np.loadtxt(path_train, delimiter=";")
            df2 = np.loadtxt(path_val, delimiter=";")
            # variables
            size0 = df0.shape
            input0 = size0[1] - 1
            size1 = df1.shape
            input1 = size1[1] - 1
            size2 = df2.shape
            input2 = size2[1] - 1

            # split input and output
            X0 = df1[:, 0:input0]
            Y0 = df1[:, input0]
            X1 = df1[:, 0:input1]
            Y1 = df1[:, input1]
            X2 = df2[:, 0:input2]
            Y2 = df2[:, input2]

            #svm
            model = svm.SVC(kernel='linear', decision_function_shape='ovr', C=0.01)
            model.fit(X1, Y1)


            # file creation
          #  new_file = open(r'svm_classi.txt', 'w+')
           # new_file.write(string_bayes)
            #new_file.close()

            predicted = model.predict(X0)

            score = model.score(X2, Y2)
            #self.ui.msg_text.setText(predicted, score)
            print(predicted, score)


        elif self.ui.check_neuro.isChecked():
            df0 = np.loadtxt(path_test, delimiter=";")
            df1 = np.loadtxt(path_train, delimiter=";")
            df2 = np.loadtxt(path_val, delimiter=";")
            # variables
            size0 = df0.shape
            input0 = size0[1] - 1
            size1 = df1.shape
            input1 = size1[1] - 1
            size2 = df2.shape
            input2 = size2[1] - 1

            # split input and output
            X0 = df1[:, 0:input0]
            Y0 = df1[:, input0]
            X1 = df1[:, 0:input1]
            Y1 = df1[:, input1]
            X2 = df2[:, 0:input2]
            Y2 = df2[:, input2]

            # creating model
            model = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(10, 2), random_state=1)

            #string_bayes = model.get_params(deep='true')
            # file creation
            #new_file = open(r'neuro_classi.txt', 'w+')
            #new_file.write(string_bayes)
            #new_file.close()

            model.fit(X1, Y1)

            predicted = model.predict(X0)

            score = model.score(X2, Y2)
            print(predicted, score)
            #self.ui.msg_text.setText(score)

        elif self.ui.check_bayes.isChecked():
            df0 = np.loadtxt(path_test, delimiter=";")
            df1 = np.loadtxt(path_train, delimiter=";")
            df2 = np.loadtxt(path_val, delimiter=";")
            # variables
            size0 = df0.shape
            input0 = size0[1] - 1
            size1 = df1.shape
            input1 = size1[1] - 1
            size2 = df2.shape
            input2 = size2[1] - 1

            # split input and output
            X0 = df1[:, 0:input0]
            Y0 = df1[:, input0]
            X1 = df1[:, 0:input1]
            Y1 = df1[:, input1]
            X2 = df2[:, 0:input2]
            Y2 = df2[:, input2]
            # bayes classifier
            model = GaussianNB()

            model.fit(X1, Y1)




            predicted = model.predict(X0)

            score = model.score(X2, Y2)
            #self.ui.msg_text.setText(predicted, score)




            predicted = model.predict(X0)

            score = model.score(X2, Y2)
            print(predicted, score)





        else:
            self.ui.msg_text.setText("no choice of classifier")



    def feat_extra(self):
        def feature_gen(df1):
            print(df1)

            # statistische Berechnung
            df_max = max(df1)
            df_min = min(df1)
            df_peak = df_max-df_min
            df_mean = np.mean(df1)
            df_var = np.var(df1)
            df_std = np.std(df1)
            df_max_pos, _ = find_peaks(df1, height=df_max)

            # uni_vec = np.ones(0, df_num, float)
            # print(df_max, df_min, df_mean, df_var, df_std)

            # check for bad reading
            if df_mean > bad_read_value or df_num != np.size(df1):
                print("bad reading of the value")

            # Offset substraction
            df1 = df1 - df_mean

            # praparation fft analyses

            # max value in center of fft
            df_high_peak = np.argmax(df1)
            fft_start = df_high_peak - int(num_fft / 2)
            fft_end = df_high_peak + int(num_fft / 2)

            # protection for limet of dataframe value fft_end >= df_num
            if fft_end > int(df_num):
                dif_fft = fft_end - int(df_num)
                fft_start = fft_start - dif_fft
                fft_end = fft_end - dif_fft

            if fft_start < 0:
                dif_fft = fft_end - int(df_num)
                fft_start = fft_start - dif_fft
                fft_end = fft_end - dif_fft

            x_fft = np.fft.rfftfreq(num_fft, d=del_time)
            # x_fft = x_fft[fft_start:fft_end]

            # db_fft = np.log10(fft_df/np.argmax(fft_df))
            # plot for x axis fft
            # plt.plot(x_fft)
            # plt.show()

            # FFT
            df_new = df1[fft_start:fft_end] * window
            fft_df = abs(np.fft.rfft(df_new))
            fft_plot = np.copy(fft_df)

            mag = abs(20 * np.log10(fft_df))
            max_fft = max(fft_df)
            max_fft_pos = np.argmax(fft_df)
            fft_peak, _ = find_peaks(fft_df, height=max_fft)
            # fft_sample = fft_peak + fft_start
            # feature

            # distance
            distance = 18500 * del_time * (df_max_pos)

            # bandwith and center frequency
            f_center = x_fft[max_fft_pos]
            for i in range(num_fft):
                if 0.5 * max_fft > fft_df[i + max_fft_pos]:
                    f_band = x_fft[i + max_fft_pos]
                    f_band -= f_center
                    f_band = 2 * f_band
                    break

            # print "f_center = %d und f_0 = %d" % (f_center, f_band)

            # THD
            total_rms = np.sqrt(np.mean(np.abs(df1[fft_start:fft_end]) ** 2))
            under_five = np.argwhere(fft_df < 2)
            for i in range(len(under_five)):
                if under_five[i] > max_fft_pos:
                    uppermin = under_five[i]
                    lowermin = under_five[i - 1]
                    break

            fft_plot[int(lowermin):int(uppermin)] = 0.0
            noise_df = np.fft.irfft(fft_df)
            noise_rms = np.sqrt(np.mean(np.abs(noise_df) ** 2))
            THDN = noise_rms / total_rms
            print("THD+N:     %.4f%% or %.1f dB" % (THDN * 100, 20 * np.log10(THDN)))

            #

            # Num of Peaks
            num_peak, _ = find_peaks(df1, height=peak_high)
            num_peak_num = np.size(num_peak)

            return (THDN, f_center, f_band, max_fft, df_var, df_std, df_peak)
        # define Variabels
        df_num = 16384.0
        sam_fre = 1900000.0
        del_time = 1.0 / sam_fre
        sum_df = 0.0
        num_fft = 4098
        peak_high = 0.05
        end_x_axis = del_time * df_num
        x_time = np.linspace(0.0, end_x_axis, df_num)
        bad_read_value = 0.05
        delay = 4000  # sampels
        window = hann(num_fft)
        # window = hann(int(df_num))

        path = self.ui.ad_meas.text()

        df_ob = np.loadtxt(path, delimiter=";")
        size_ob = df_ob.shape
        feature_ob = np.zeros((size_ob[0], 7))

        for i in range(size_ob[0]):
            df1 = df_ob[i]
            feature_ob[i:] = feature_gen(df1)
        colum_one = np.ones(size_ob[0])
        data_ob = np.column_stack((feature_ob, colum_one))

        fileName, _ = QFileDialog.getSaveFileName(self, "QFileDialog.getSaveFileName()", "",
                                                      "All Files (*);;csv Files (*.csv)")
        np.savetxt(str(fileName), data_ob, delimiter=";")


        path_per = self.ui.ad_meas_3.text()


        df_per = np.loadtxt(path_per, delimiter=";")

        size_per = df_per.shape
        feature_per = np.zeros((size_per[0], 7))
        for i in range(size_per[0]):
            df1 = df_per[i]
            feature_per[i:] = feature_gen(df1)
        colum_zero = np.zeros(size_per[0])
        data_per = np.column_stack((feature_per, colum_zero))

        fileName_2, _ = QFileDialog.getSaveFileName(self, "QFileDialog.getSaveFileName()", "",
                                                  "All Files (*);;csv Files (*.csv)")
        np.savetxt(str(fileName_2), data_per, delimiter=";")


        data_all = np.concatenate((data_ob, data_per), axis=0)
        fileName_3, _ = QFileDialog.getSaveFileName(self, "QFileDialog.getSaveFileName()", "",
                                                    "All Files (*);;csv Files (*.csv)")
        np.savetxt(str(fileName_3), data_all, delimiter=";")


        print(feature_per, feature_ob)
Ejemplo n.º 21
0
class mywindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(mywindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.PlusButt.clicked.connect(self.AddEntry)
        self.ui.AddButton.clicked.connect(self.EditEntry)
        self.ui.DelButt.clicked.connect(self.DeleteEntry)
        self.ui.SentimientosColor.clicked.connect(self.ColorPick)
        self.ui.SentimientosAdd.clicked.connect(self.AddFeeling)
        self.ui.Menu.clicked.connect(self.MenuTravel)
        self.ui.MenuCon.setEnabled(False)
        self.ui.PerfilCon.setEnabled(False)
        self.ui.tabWidget.setCurrentIndex(0)
        self.ui.SentimientosColor.setStyleSheet("background-color: white")
        self.ui.SentimientosDrop.activated.connect(self.LoadFeeling)
        self.ui.SentimientosDropEdic.activated.connect(self.LoadFeeling)
        self.ui.SentimientosRemove.clicked.connect(self.DeleteFeeling)
        self.ui.BackMenu.clicked.connect(self.BackMenu)
        self.ui.Perfil.clicked.connect(self.GoPerfil)
        self.ui.BackPerfil.clicked.connect(self.BackPerfil)
        self.ReloadFeelings()
        self.LoadFeeling()
        self.CargarEntradas()

    def EnterEntry(self, ID):
        global EditingEntry
        print(ID)
        if (EditingEntry != ID):
            self.CleanText()
        if (self.ui.Entrada.isEnabled != True):
            self.ui.Entrada.setEnabled(True)
        try:
            self.LeerEntrada(int(ID))
        except:
            pass
        self.ui.tabWidget.setCurrentIndex(1)
        EditingEntry = ID

    def AddEntry(self):
        layout = self.ui.scrollAreaContent.layout()
        button = QtWidgets.QPushButton(date.today().__str__())
        button.setMinimumSize(0, 76)
        global EntryCount
        global Entries
        button.setProperty("ID", EntryCount)
        button.setProperty("Data", date.today().__str__())
        EntryCount += 1
        layout.addWidget(button)
        Entries.append(button)
        button.clicked.connect(lambda: self.EnterEntry(button.property("ID")))
        color = self.ui.SentimientosColor.palette().color(1).name()
        button.setStyleSheet("background-color: " + color)
        self.EnterEntry(int(button.property("ID")))
        self.ui.Lista.setEnabled(False)
        self.CleanText()

    def EditEntry(self):
        self.ui.Lista.setEnabled(True)
        global EditingEntry
        global Entries
        for button in Entries:
            if (button.property("ID") == EditingEntry):
                button.setText(date.today().__str__() + "  " +
                               self.ui.TituloEdit.text())
                self.ui.tabWidget.setCurrentIndex(0)
                self.ui.Entrada.setEnabled(False)
                self.ActualizaGuardar(button.property("ID"),
                                      button.property("Data"))
                color = self.ui.ColorEdit.palette().color(1).name()
                button.setStyleSheet("background-color: " + color)
        for item in Entries:
            layout = self.ui.scrollAreaContent.layout()
            layout.removeWidget(item)
        for entry in Entries:
            EntriesID.append(entry.property("ID"))
        EntriesID.sort(reverse=True)
        for button in EntriesID:
            for item in Entries:
                if (item.property("ID") == button):
                    layout = self.ui.scrollAreaContent.layout()
                    layout.addWidget(item)
        self.CleanText()

    def GoPerfil(self):
        self.ui.PerfilCon.setEnabled(True)
        self.ui.tabWidget.setCurrentIndex(3)
        self.ui.Lista.setEnabled(False)
        self.ReloadFeelings()

    def BackPerfil(self):
        self.ui.tabWidget.setCurrentIndex(0)
        self.ui.PerfilCon.setEnabled(False)
        self.ui.Lista.setEnabled(True)

    def MenuTravel(self):
        self.ui.MenuCon.setEnabled(True)
        self.ui.tabWidget.setCurrentIndex(2)
        self.ui.Lista.setEnabled(False)

    def BackMenu(self):
        self.ui.tabWidget.setCurrentIndex(0)
        self.ui.MenuCon.setEnabled(False)
        self.ui.Lista.setEnabled(True)

    #############################
    def ActualizaGuardar(self, ID, Data):
        try:
            cursor.execute("INSERT INTO Entradas VALUES (?,?,?,?,?,?,?);",
                           (ID, self.ui.TituloEdit.text().__str__(),
                            self.ui.SentimientosDropEdic.currentIndex(),
                            self.ui.Razon.text().__str__(),
                            self.ui.Ideas.text().__str__(),
                            self.ui.Reflexion.toPlainText().__str__(), Data))
            self.CleanText()
            db.commit()
        except:
            cursor.execute("DELETE FROM Entradas WHERE ID = (?)", (ID, ))
            db.commit()
            cursor.execute("INSERT INTO Entradas VALUES (?,?,?,?,?,?,?);",
                           (ID, self.ui.TituloEdit.text().__str__(),
                            self.ui.SentimientosDropEdic.currentIndex(),
                            self.ui.Razon.text().__str__(),
                            self.ui.Ideas.text().__str__(),
                            self.ui.Reflexion.toPlainText().__str__(), Data))
            self.CleanText()
            db.commit()

    def CargarEntradas(self):
        global EntryCount
        global Entries
        cursor.execute("SELECT * FROM Entradas")
        Entradas = cursor.fetchall()
        layout = self.ui.scrollAreaContent.layout()

        for n in Entradas:
            try:
                n = n[0]
                cursor.execute("SELECT Titulo FROM Entradas WHERE ID = (?);",
                               (n, ))
                Titulos = cursor.fetchall()
                cursor.execute("SELECT Data FROM Entradas WHERE ID = (?);",
                               (n, ))
                Dts = cursor.fetchall()
                Data = converTuple(Dts[0])
                Titulo = converTuple(Titulos[0])
                button = None
                button = QtWidgets.QPushButton(date.today().__str__())
                button.setMinimumSize(0, 76)
                button.setProperty("ID", n)
                button.setProperty("Data", Data)
                button.setText(Data + "  " + Titulo)
                Entries.append(button)
                layout.addWidget(button)
                cursor.execute("SELECT Como FROM Entradas WHERE ID = (?);",
                               (n, ))
                Como = cursor.fetchall()
                self.ui.SentimientosDrop.setCurrentIndex(int(Como[0][0]))
                text = self.ui.SentimientosDrop.currentText()
                cursor.execute(
                    "SELECT Color FROM Sentimientos WHERE Nombre = (?);",
                    (text, ))
                color = cursor.fetchall()
                color = converTuple(color[0])
                button.setStyleSheet("background-color: " + color)
                EntryCount = n + 1
            except:
                pass
        for entry in Entries:
            EntriesID.append(entry.property("ID"))
        EntriesID.sort(reverse=True)
        for button in EntriesID:
            print(button)
            for item in Entries:
                if (item.property("ID") == button):
                    layout = self.ui.scrollAreaContent.layout()
                    item.clicked.connect(
                        partial(self.EnterEntry, item.property("ID")))

    def LeerEntrada(self, ID):
        cursor.execute("SELECT * FROM Entradas WHERE ID = (?);", (ID, ))
        resultados = cursor.fetchall()
        res = int(resultados[0][2])
        self.ui.TituloEdit.setText(resultados[0][1])
        self.ui.Razon.setText(resultados[0][3])
        self.ui.Ideas.setText(resultados[0][4])
        self.ui.Reflexion.setPlainText(resultados[0][5])
        self.ui.SentimientosDropEdic.setCurrentIndex(res)

        self.LoadFeeling()

    def CleanText(self):
        self.ui.TituloEdit.setText("")
        #Vaciar Sentimiento ?
        self.ui.Razon.setText("")
        self.ui.Ideas.setText("")
        self.ui.Reflexion.setPlainText("")

    def DeleteEntry(self):
        global EditingEntry
        ID = EditingEntry
        cursor.execute("DELETE FROM Entradas WHERE ID = (?)", (ID, ))
        db.commit()
        self.CleanText()
        self.ui.tabWidget.setCurrentIndex(0)
        for item in Entries:
            if (item.property("ID") == ID):
                layout = self.ui.scrollAreaContent.layout()
                layout.removeWidget(item)
                layout.addWidget(item)
                item.deleteLater()
                item = None

    def ColorPick(self):
        color = QtWidgets.QColorDialog.getColor()
        if color.isValid():
            self.ui.SentimientosColor.setStyleSheet("background-color: " +
                                                    color.name())

    #############################
    def AddFeeling(self):
        Nombre = self.ui.SentimientosNombre.text()
        Color = self.ui.SentimientosColor.palette().color(1).name()
        try:
            cursor.execute("INSERT INTO Sentimientos VALUES (?,?);",
                           (Nombre, Color))
            db.commit()
        except:
            cursor.execute(
                "UPDATE Sentimientos SET Color = (?) WHERE Nombre = (?)", (
                    Color,
                    Nombre,
                ))
            db.commit()
        self.ReloadFeelings()

    def ReloadFeelings(self):
        try:
            Feelings.clear()
            self.ui.SentimientosDrop.clear()
            self.ui.SentimientosDropEdic.clear()
            cursor.execute("SELECT * FROM Sentimientos")
            Sentimientos = cursor.fetchall()
            for i in Sentimientos:
                self.ui.SentimientosDrop.addItem(i[0])
                self.ui.SentimientosDropEdic.addItem(i[0])
            for i in Entries:
                self.LeerEntrada(i.property("ID"))
                fln = self.ui.SentimientosDropEdic.currentText()
                color = self.ui.ColorEdit.palette().color(1).name()
                i.setStyleSheet("background-color: " + color)
                Feelings.append(fln)
            self.CleanText()
            self.MakeGraph()
        except:
            pass

    def LoadFeeling(self):
        try:
            text = self.ui.SentimientosDrop.currentText()
            self.ui.SentimientosNombre.setText(text)
            cursor.execute("SELECT Color FROM Sentimientos WHERE Nombre = (?)",
                           (text, ))
            color = cursor.fetchall()
            self.ui.SentimientosColor.setStyleSheet("background-color: " +
                                                    color[0][0])

            text = self.ui.SentimientosDropEdic.currentText()
            cursor.execute("SELECT Color FROM Sentimientos WHERE Nombre = (?)",
                           (text, ))
            color = cursor.fetchall()
            self.ui.ColorEdit.setStyleSheet("background-color: " + color[0][0])
        except:
            pass

    def DeleteFeeling(self):
        text = self.ui.SentimientosDrop.currentText()
        ent = self.ui.SentimientosDrop.currentIndex()
        cursor.execute("DELETE FROM Sentimientos WHERE Nombre = (?)", (text, ))
        db.commit()
        self.ui.SentimientosDrop.removeItem(ent)
        self.ui.SentimientosDropEdic.removeItem(ent)
        self.ui.SentimientosDrop.setCurrentIndex(ent - 1)
        self.ui.SentimientosDropEdic.setCurrentIndex(ent - 1)
        self.ReloadFeelings()
        self.LoadFeeling()

    def MakeGraph(self):
        CleanFeels = []
        NumFeels = []
        ColorFeels = []
        for i in Feelings:
            num = CleanFeels.count(i)
            if num <= 0:
                CleanFeels.append(i)
                NumFeels.append(Feelings.count(i))
        for i in CleanFeels:
            cursor.execute("SELECT Color FROM Sentimientos WHERE Nombre = (?)",
                           (i, ))
            Color = cursor.fetchall()
            ColorFeels.append(converTuple(Color[0]))
        mpl.subplot().pie(NumFeels,
                          labels=CleanFeels,
                          colors=ColorFeels,
                          shadow=True)
        mpl.suptitle('Resumen global', fontsize=16)
        mpl.savefig(path + "graph.png")
        Pixmap = QtGui.QPixmap(path + "graph.png")
        self.ui.Graphic.setPixmap(Pixmap)
        mpl.cla()
        mpl.clf()
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.pushButton.pressed.connect(self.button)
Ejemplo n.º 23
0
Archivo: 0920.py Proyecto: hyxcj/0919
class QmyMainWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)  # 调用父类构造函数,创建窗体
        self.ui = Ui_MainWindow()  # 创建UI对象
        self.ui.setupUi(self)  # 构造UI界面
        self.setWindowTitle("hyx")
        mplStyle.use("classic")  # 使用样式,必须在绘图之前调用,修改字体后才可显示汉字
        mpl.rcParams['font.sans-serif'] = ['KaiTi', 'SimHei'
                                           ]  # 显示汉字为 楷体, 汉字不支持 粗体,斜体等设置
        mpl.rcParams['font.size'] = 12
        ##  Windows自带的一些字体
        ##  黑体:SimHei 宋体:SimSun 新宋体:NSimSun 仿宋:FangSong  楷体:KaiTi
        mpl.rcParams['axes.unicode_minus'] = False  # 减号unicode编码
        self.data = []
        self.__createFigure()  # 创建Figure和FigureCanvas对象,初始化界面

    ##  ==============自定义功能函数========================
    def __createFigure(self):  # 创建面板
        self.__fig = mpl.figure.Figure()
        figCanvas = FigureCanvas(self.__fig)  # 创建FigureCanvas对象,必须传递一个Figure对象
        self.__fig.suptitle("显示", fontsize=16, fontweight='bold')  # 总的图标题
        naviToolbar = NavigationToolbar(figCanvas, self)  # 创建工具栏
        naviToolbar.setToolButtonStyle(
            Qt.ToolButtonTextUnderIcon
        )  # ToolButtonTextUnderIcon,ToolButtonTextBesideIcon

        self.addToolBar(naviToolbar)  # 添加工具栏到主窗口
        self.setCentralWidget(figCanvas)

        splitter1 = QSplitter(Qt.Vertical)
        splitter1.addWidget(self.ui.verticalLayoutWidget)
        splitter1.addWidget(self.ui.horizontalLayoutWidget)

        splitter = QSplitter(self)
        splitter.setOrientation(Qt.Horizontal)
        splitter.addWidget(splitter1)  # 左侧控制面板
        splitter.addWidget(figCanvas)  # 右侧FigureCanvas对象
        self.setCentralWidget(splitter)

    @pyqtSlot()  ##"选择初至文件"
    def on_pushButton_clicked(self):
        curPath = QDir.currentPath()  # 获取系统当前目录
        dlgTitle = "选择初至文件"  # 对话框标题
        filt = "文本文件(*.txt);;"  # 文件过滤器
        filename = QFileDialog.getOpenFileName(self, dlgTitle, curPath, filt)
        self.data = pd.read_csv(filename[0], sep='\s+')
        self.fbpath = filename[0]

    def __drawFB(self):  ##初始化绘图初至

        ax1 = self.__fig.add_subplot(1, 1, 1, label="FB")  # 子图1
        ax1.cla()
        x1 = self.data['RcvLine'] * 10000
        x2 = self.data['RcvStation']
        x = x1 + x2
        y = self.data['fb(ms)']
        # x = np.random.normal(size=1000000)
        # y = np.random.normal(size=1000000)
        ax1.scatter(x, y, c='r', marker='x', label="fb", s=4)  # 绘制一条曲线
        ax1.set_xlabel('X 轴')  # X轴标题
        ax1.set_ylabel('Y 轴')  # Y轴标题
        # ax1.set_xlim([0, 10])  # X轴坐标范围
        # ax1.set_ylim([-1.5, 1.5])  # Y轴坐标范围
        ax1.set_title("初至")
        ax1.legend()  # 自动创建图例

    @pyqtSlot()  ##点击绘制初至
    def on_pushButton_2_clicked(self):
        self.__drawFB()
        self.__fig.canvas.draw()

    @pyqtSlot()  ##"打开另一个ui,并连接新ui的信号与主窗口槽函数"
    def on_pushButton_4_clicked(self):
        self.newDialog = Qmydialog_sps()
        self.newDialog.mySignal.connect(self.__drawSPS)
        # self.newDialog.mySignal.connect(self.__drawSPS)
        self.newDialog.exec_()

    def __drawSPS(self, connect):  ##绘制sps
        portion = os.path.splitext(connect)

        # a = pd.read_csv(open(connect),header=None,sep='\s+',encoding="gbk")
        # b = pd.read_csv(open(portion[0] + '.S'),header=None,sep='\s+',encoding="gbk")
        R = sps.Sps_sr(connect)
        S = sps.Sps_sr(portion[0] + '.S')
        # print(a)
        # print(b)
        ax1 = self.__fig.add_subplot(1, 1, 1, label="sps")  # 子图1
        ax1.cla()
        # x1 = a[1]
        # x2 = b[1]
        # y1 = a[2]
        # y2 = b[2]
        ax1.scatter(R.X, R.Y, c='b', marker='x', label="R", s=0.5)  # 绘制一条曲线
        ax1.scatter(S.X, S.Y, c='r', marker='x', label="S", s=0.5)  # 绘制一条曲线
        ax1.set_xlabel('X 轴')  # X轴标题
        ax1.set_ylabel('Y 轴')  # Y轴标题
        ax1.get_xaxis().get_major_formatter().set_useOffset(False)
        # ax1.set_xlim([0, 10])  # X轴坐标范围
        # ax1.set_ylim([-1.5, 1.5])  # Y轴坐标范围
        ax1.set_title("观测系统")
        ax1.legend()  # 自动创建图例

    @pyqtSlot()  ##点击绘制sps
    def on_pushButton_7_clicked(self):
        self.__fig.canvas.draw()

    @pyqtSlot()  ##"打开一个文件"
    def on_pushButton_3_clicked(self):
        self.newDialog = Qmydialog()
        self.newDialog.show()

    @pyqtSlot()  ##输入文件号显示初至
    def on_lineEdit_returnPressed(self):
        self.danpaochuzhi()
        self.__fig.canvas.draw()

    def danpaochuzhi(self):
        ffid = int(self.ui.lineEdit.text())
        ax1 = self.__fig.add_subplot(1, 1, 1, label="FB")  # 子图1
        ax1.cla()
        with open(self.fbpath) as fb_file:
            ShotLine = []
            ShotStation = []
            ShotIdx = []
            RcvLine = []
            RcvStation = []
            FileNo = []
            ChannelNo = []
            fb = []
            Rcv = []
            Shot = []
            of = []

            for line in islice(fb_file, 1, None):
                ShotLine.append(float(line[8:15]))
                ShotStation.append(float(line[23:30]))
                ShotIdx.append(int(line[43:45]))
                RcvLine.append(float(line[53:60]))
                RcvStation.append(float(line[68:75]))
                FileNo.append(int(line[83:91]))
                ChannelNo.append(float(line[99:106]))
                fb.append(float(line[112:121]))
                Rcv.append(
                    int(float(line[53:60])) * 10000 + int(float(line[68:75])))
                Shot.append(
                    int(float(line[8:15])) * 10000 + float(line[23:30]))
                of.append(abs((float(line[68:75]) - float(line[23:30]))) * 40)

                fb_file = {
                    'ShotLine': ShotLine,
                    'ShotStation': ShotStation,
                    'ShotIdx': ShotIdx,
                    'RcvLine': RcvLine,
                    'RcvStation': RcvStation,
                    'FileNo': FileNo,
                    'ChannelNo': ChannelNo,
                    'fb': fb,
                    'Rcv': Rcv,
                    'Shot': Shot,
                    'of': of
                }
            fb_file1 = pd.DataFrame(fb_file)

            ffid_file = pd.DataFrame(np.ones(1) * ffid, columns=['FileNo'])
            fb_ffid = pd.merge(fb_file1, ffid_file, on=['FileNo'])
        ax1.scatter(fb_ffid['ChannelNo'], fb_ffid['fb'], marker='x')  # 绘制一条曲线
        ax1.get_xaxis().get_major_formatter().set_useOffset(False)
        ax1.set_title("单炮初至")
        ax1.legend()  # 自动创建图例

    @pyqtSlot()  ##下一炮
    def on_pushButton_6_clicked(self):
        n = int(self.ui.lineEdit.text())
        m = str(n + 1)
        self.ui.lineEdit.setText(m)
        self.danpaochuzhi()
        self.__fig.canvas.draw()\

    @pyqtSlot()  ##上一炮
    def on_pushButton_5_clicked(self):
        n = int(self.ui.lineEdit.text())
        m = str(n - 1)
        self.ui.lineEdit.setText(m)
        self.danpaochuzhi()
        self.__fig.canvas.draw()
Ejemplo n.º 24
0
Archivo: wow.py Proyecto: wesshih/bhb
import sys
from PyQt4.QtGui import QApplication, QMainWindow
from test import Ui_MainWindow

app = QApplication(sys.argv)
window = QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(window)

window.show()
sys.exit(app.exec_())
Ejemplo n.º 25
0
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from test import Ui_MainWindow
import matplotlib.pyplot as plt
import numpy as np
import math
import matplotlib.pyplot as plt
# Create app
app = QtWidgets.QApplication(sys.argv)

#init
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()

#hook logic
def dihtomia():
    l_wall = int(ui.lineEdit_4.text())
    r_wall = int(ui.lineEdit.text())
    a = float(ui.lineEdit_3.text())
    exp = float(ui.lineEdit_2.text())
    iter=0
    e=math.exp(1)
    while abs(l_wall-r_wall)>exp:
        deli = (l_wall+r_wall)/2
        if (3*deli-a*e**deli>0 and 3*l_wall-a*e**l_wall>0) or (3*deli-a*e**deli<0 and 3*l_wall-a*e**l_wall<0):
            iter+=1
            l_wall=deli
            x = l_wall
            print(x)
Ejemplo n.º 26
0
class MyWindow(QMainWindow):
    def __init__(self, app):
        """
            Initializes all needed variables
        """
        super(MyWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.carolbtn.clicked.connect(self.carolclicked)
        self.ui.jinglebtn.clicked.connect(self.jingleclicked)
        self.ui.littlebtn.clicked.connect(self.littleclicked)
        self.ui.pausebtn.clicked.connect(self.pauseClicked)
        self.ui.playbtn.clicked.connect(self.playClicked)
        self.ui.exitbtn.clicked.connect(self.exitclicked)

        self.setSongPlaying(False)#Initialize Song Stopper
        self.isPaused = False

        self.threadpool = QThreadPool()
        self.win = self
        self.app = app

    def exitclicked(self):
        """
            Exits the application when the exit button is clicked.
            Is connected to exitbtn
        """
        sys.exit()
    
    def afterSong(self):
        """
            Is executed after every song. Is connected to a worker signal.
        """
        #self.songselectbtnsswitch(True)
        #self.pausePlaySwitch(False)
        
    def carolclicked(self):
        """
            Handles carol of the bells song playing with worker classes, signals, and threadpools.
            Think of the worker class as a thread that happens in the background while the ui continues 
            so that pause, play, and exit to work. 
        """
        #Setup For next Song
        self.setPaused(False) #Turn Paused Off
        self.setSongPlaying(False) #Turn Song Off
        self.threadpool.waitForDone() #Wait for songs to return
        self.setSongPlaying(True) #Turn Song On

        carolsong = carol.NewCarolSong(self.win, self.app)
        self.carolWorker = Worker(carolsong.startsong) # add the function to execute to the worker class
        self.carolWorker.signals.finished.connect(self.afterSong) # function that will execute after carolWorker is done
        self.threadpool.start(self.carolWorker) # starts carolWorker with the above requirements

    def jingleclicked(self):
        """
            Handles jingle bells song playing with worker classes, signals, and threadpools.
            Think of the worker class as a thread that happens in the background while the ui continues 
            so that pause, play, and exit to work. 
        """
        #Turn All Songs Off
        self.setPaused(False) #Turn Paused Off
        self.setSongPlaying(False) #Turn Song Off
        self.threadpool.waitForDone() #Wait for songs to return
        self.setSongPlaying(True) #Turn Song On

        jinglesong = jingle.NewJingleSong(self.win, self.app)
        self.jingleWorker = Worker(jinglesong.startsong) # add the function to execute to the worker class
        self.jingleWorker.signals.finished.connect(self.afterSong) # function that will execute after carolWorker is done
        self.threadpool.start(self.jingleWorker) # starts carolWorker with the above requirements

    def littleclicked(self):
        """
            Handles little drummer boy song playing with worker classes, signals, and threadpools.
            Think of the worker class as a thread that happens in the background while the ui continues 
            so that pause, play, and exit to work. 
        """
        #Setup For next Song
        self.setPaused(False) #Turn Paused Off
        self.setSongPlaying(False) #Turn Song Off
        self.threadpool.waitForDone() #Wait for songs to return
        self.setSongPlaying(True) #Turn Song On

        drummersong = drummer.NewDrummerSong(self.win, self.app)
        self.drummerWorker = Worker(drummersong.startsong) # add the function to execute to the worker class
        self.drummerWorker.signals.finished.connect(self.afterSong) # function that will execute after carolWorker is done
        self.threadpool.start(self.drummerWorker) # starts carolWorker with the above requirements


    def pauseClicked(self):
        """
            Handles the pause functionality for the app. Could possibly be further devloped 
            to handle pause and play. Must have songs played in a worker class so that it may run in a threadpool or else
            pause functionality will disapear since the main thread will be playing the song.
        """
        self.setPaused(True) # need to set paused to true so that way the song playing knows to pause

    def playClicked(self):
        """
            Handles the play functionality for the app. Could possibly be further devloped 
            to handle pause and play. Must have songs played in a worker class so that it may run in a threadpool or else
            pause functionality will disapear since the main thread will be playing the song.
        """
        self.setPaused(False) # set paused to false so that the song currently playing knows that it is no longer paused
        self.win.updatelabel2("Play button clicked!\nResuming the song.")

    def setPaused(self, logic):
        """
            Setter for the pause variable
        """
        self.isPaused = logic
        self.pausePlaySwitch(logic)

    def getPaused(self):
        """
            Getter for the pause variable
        """
        return self.isPaused

    def getStopped(self):
        """
            Getter for the stop variable
        """
        return self.stopSong

    def setSongPlaying(self, logic):
        """
            Setter for the stop variable
        """
        self.stopSong = not logic

    def updatelabel2(self, text):
        self.ui.label2.setText(text)
        self.ui.label2.adjustSize()
    """
    def songselectbtnsswitch(self, logic):
    """
            #Switches the song list to clickable or not
    """
        self.ui.carolbtn.setEnabled(logic)
        self.ui.jinglebtn.setEnabled(logic)
        self.ui.littlebtn.setEnabled(logic)
    """

    def pausePlaySwitch(self, logic):
        """
            Switches the pause and play buttons to clickable or not
        """
        self.ui.playbtn.setEnabled(logic)
Ejemplo n.º 27
0
class StartQT5(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        QtWidgets.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
Ejemplo n.º 28
0
class QmyMainWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)  # 调用父类构造函数,创建窗体
        self.ui = Ui_MainWindow()  # 创建UI对象
        self.ui.setupUi(self)  # 构造UI界面

        self.setWindowTitle("hyx")
        mplStyle.use("classic")  # 使用样式,必须在绘图之前调用,修改字体后才可显示汉字

        mpl.rcParams['font.sans-serif'] = ['KaiTi', 'SimHei'
                                           ]  # 显示汉字为 楷体, 汉字不支持 粗体,斜体等设置
        mpl.rcParams['font.size'] = 12
        ##  Windows自带的一些字体
        ##  黑体:SimHei 宋体:SimSun 新宋体:NSimSun 仿宋:FangSong  楷体:KaiTi
        mpl.rcParams['axes.unicode_minus'] = False  # 减号unicode编码
        self.data = []
        self.data1 = Qmydialog_sps().open_sps()

        self.__createFigure()  # 创建Figure和FigureCanvas对象,初始化界面
        #self.__drawFig2X1()  # 绘图

    ##  ==============自定义功能函数========================
    def __createFigure(self):
        ##      self.__fig=mpl.figure.Figure(figsize=(8, 5),constrained_layout=True, tight_layout=None)  #单位英寸
        #self.__fig = mpl.figure.Figure(figsize=(4, 2))  #单位英寸
        self.__fig = mpl.figure.Figure()
        figCanvas = FigureCanvas(self.__fig)  # 创建FigureCanvas对象,必须传递一个Figure对象
        self.__fig.suptitle("显示", fontsize=16, fontweight='bold')  # 总的图标题
        naviToolbar = NavigationToolbar(figCanvas, self)  # 创建工具栏
        naviToolbar.setToolButtonStyle(
            Qt.ToolButtonTextUnderIcon
        )  # ToolButtonTextUnderIcon,ToolButtonTextBesideIcon

        self.addToolBar(naviToolbar)  # 添加工具栏到主窗口
        self.setCentralWidget(figCanvas)

        splitter1 = QSplitter(Qt.Vertical)
        splitter1.addWidget(self.ui.verticalLayoutWidget)
        splitter1.addWidget(self.ui.horizontalLayoutWidget)

        # splitter2 = QSplitter(Qt.Vertical)
        # splitter2.addWidget(splitter1)
        # splitter2.addWidget(bottom)

        splitter = QSplitter(self)
        splitter.setOrientation(Qt.Horizontal)
        splitter.addWidget(splitter1)  # 左侧控制面板
        splitter.addWidget(figCanvas)  # 右侧FigureCanvas对象
        self.setCentralWidget(splitter)

    def __drawFB(self):  ##初始化绘图
        ##      gs=self.__fig.add_gridspec(2,1)  #2行,1列
        ##
        ##      ax1=self.__fig.add_subplot(gs[0,0],label="sin-cos plot")  #子图1

        ax1 = self.__fig.add_subplot(1, 1, 1, label="FB")  # 子图1
        ax1.cla()
        x1 = self.data['RcvLine'] * 10000
        x2 = self.data['RcvStation']
        x = x1 + x2
        #print(x)
        y = self.data['fb(ms)']
        # x = np.random.normal(size=1000000)
        # y = np.random.normal(size=1000000)
        ax1.scatter(x, y, c='r', marker='x', label="fb", s=4)  # 绘制一条曲线
        ax1.set_xlabel('X 轴')  # X轴标题
        ax1.set_ylabel('Y 轴')  # Y轴标题
        # ax1.set_xlim([0, 10])  # X轴坐标范围
        # ax1.set_ylim([-1.5, 1.5])  # Y轴坐标范围
        ax1.set_title("初至")
        ax1.legend()  # 自动创建图例
        #self.__curAxes = ax1  # 当前操作的Axes对象

    def __drawSPS(self):  ##初始化绘图
        ax1 = self.__fig.add_subplot(1, 1, 1, label="sps")  # 子图1
        ax1.cla()
        x = self.data1['1']
        #print(x)
        y = self.data1['2']
        # x = np.random.normal(size=1000000)
        # y = np.random.normal(size=1000000)
        ax1.scatter(x, y, c='r', marker='x', label="sps", s=4)  # 绘制一条曲线
        ax1.set_xlabel('X 轴')  # X轴标题
        ax1.set_ylabel('Y 轴')  # Y轴标题
        # ax1.set_xlim([0, 10])  # X轴坐标范围
        # ax1.set_ylim([-1.5, 1.5])  # Y轴坐标范围
        ax1.set_title("观测系统")
        ax1.legend()  # 自动创建图例
        #self.__curAxes = ax1  # 当前操作的Axes对象

    @pyqtSlot()  ##子图是否可见
    def on_pushButton_2_clicked(self):

        self.__drawFB()
        self.__fig.canvas.draw()

    @pyqtSlot()  ##子图是否可见
    def on_pushButton_7_clicked(self):
        self.a = Qmydialog_sps().data
        print(self.a)
        #self.__drawSPS()
        #self.__fig.canvas.draw()

    @pyqtSlot()  ##"打开一个文件"
    def on_pushButton_clicked(self):
        curPath = QDir.currentPath()  # 获取系统当前目录
        dlgTitle = "选择一个文件"  # 对话框标题
        filt = "文本文件(*.txt);;"  # 文件过滤器

        # filename = QFileDialog.getOpenFileName(self, dlgTitle, curPath, filt)
        #self.ui.plainTextEdit.appendPlainText(filename)
        #self.ui.plainTextEdit.appendPlainText("\n" + filtUsed)

        filenam = QFileDialog()

        filenam.setFileMode(QFileDialog.AnyFile)
        #设置过滤器
        filenam.setFilter(QDir.Files)

        if filenam.exec_():
            filenames = filenam.selectedFiles()
            f = pd.read_csv(filenames[0], sep='\s+')

            # with f:
            #     data = f.read()
            #     #self.contents.setText(data)
            #     print(data)
            self.data = f
            print(self.data)
            # self.x = f['RcvStation']
            # self.y = f['fb(ms)']
            # print(self.x)
        # sx = []
        # sy = []
        # sz = []
        # sl = []
        # sp = []
        #
        # for line in filename:
        #     sx.append(float(line[47:55]))
        #     sy.append(float(line[56:65]))
        #     # sz.append(float(line[65:70]))
        #     sl.append(float(line[2:11]))
        #     sp.append(float(line[16:21]))
        # return sx, sy, sz, sl, sp
        # print(sx)

    @pyqtSlot()  ##"打开一个文件"
    def on_pushButton_3_clicked(self):
        self.newDialog = Qmydialog()
        self.newDialog.show()

    @pyqtSlot()  ##"打开一个文件"
    def on_pushButton_4_clicked(self):
        self.newDialog = Qmydialog_sps()
        self.newDialog.show()
Ejemplo n.º 29
0
 def __init__(self):
     QMainWindow.__init__(self)
     Ui_MainWindow.__init__(self)
     self.setupUi(self)
Ejemplo n.º 30
0
 def __init__(self):
     super(MainWindow, self).__init__()
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.dbCon = DB_manager.DatabaseUtility("autoswitch", "boards")
Ejemplo n.º 31
0
 def __init__(self, parent=None):
     QtWidgets.QWidget.__init__(self, parent)
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
Ejemplo n.º 32
0
class MyWindow(QMainWindow):
    def __init__(self, app):
        """
            Initializes all needed variables
        """
        super(MyWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.carolbtn.clicked.connect(self.carolclicked)
        self.ui.jinglebtn.clicked.connect(self.jingleclicked)
        self.ui.littlebtn.clicked.connect(self.littleclicked)
        self.ui.pausebtn.clicked.connect(self.pauseClicked)
        self.ui.exitbtn.clicked.connect(self.exitclicked)
        self.ui.tempoSlider.valueChanged[int].connect(self.updateTempo)

        self.setSongPlaying(False)  #Initialize Song Stopper
        self.isPaused = False
        self.progress = 0
        self.currentTempo = 290

        self.threadpool = QThreadPool()
        self.win = self
        self.app = app

        self.ui.progressBar.setVisible(False)

    def exitclicked(self):
        """
            Exits the application when the exit button is clicked.
            Is connected to exitbtn
        """
        # We need to have a class containing functions that all songs use so that we can call
        # the all function here. For now this will do.
        forPausing = music.music(self.win, self.app, "no song")
        forPausing.all(False)
        sys.exit()

    def afterSong(self):
        """
            Is executed after every song. Is connected to a worker signal.
            Right now it is not used because it causes bugs in switching songs.
        """
        #self.songselectbtnsswitch(True)
        #self.pausePlaySwitch(False)

    def carolclicked(self):
        """
            Handles carol of the bells song playing with worker classes, signals, and threadpools.
            Think of the worker class as a thread that happens in the background while the ui continues 
            so that pause, play, and exit to work. 
        """
        #Turn All Songs Off
        self.setPaused(False)  #Turn Paused Off
        self.setSongPlaying(False)  #Turn Song Off
        self.threadpool.waitForDone()  #Wait for songs to return
        self.setSongPlaying(True)  #Turn Song On
        self.ui.progressBar.setVisible(True)

        carolsong = carol.NewCarolSong(self.win, self.app)
        self.carolWorker = Worker(
            carolsong.startsong
        )  # add the function to execute to the worker class
        self.carolWorker.signals.finished.connect(
            self.afterSong
        )  # function that will execute after carolWorker is done
        self.carolWorker.signals.progress_callback.connect(
            self.updateProgressBar
        )  # function that will execute when carolWorker sends a signal
        self.threadpool.start(
            self.carolWorker)  # starts carolWorker with the above requirements
        #self.songselectbtnsswitch(True)

    def jingleclicked(self):
        """
            Handles jingle bells song playing with worker classes, signals, and threadpools.
            Think of the worker class as a thread that happens in the background while the ui continues 
            so that pause, play, and exit to work. 
        """
        #Turn All Songs Off
        #Setup For next Song
        self.setPaused(False)  #Turn Paused Off
        self.setSongPlaying(False)  #Turn Song Off
        self.threadpool.waitForDone()  #Wait for songs to return
        self.setSongPlaying(True)  #Turn Song On
        self.ui.progressBar.setVisible(True)

        jinglesong = jingle.NewJingleSong(self.win, self.app)
        self.jingleWorker = Worker(
            jinglesong.startsong
        )  # add the function to execute to the worker class
        self.jingleWorker.signals.finished.connect(
            self.afterSong
        )  # function that will execute after carolWorker is done
        self.jingleWorker.signals.progress_callback.connect(
            self.updateProgressBar
        )  # function that will execute when carolWorker sends a signal
        self.threadpool.start(
            self.jingleWorker
        )  # starts carolWorker with the above requirements

    def littleclicked(self):
        """
            Handles little drummer boy song playing with worker classes, signals, and threadpools.
            Think of the worker class as a thread that happens in the background while the ui continues 
            so that pause, play, and exit to work. 
        """
        #Setup For next Song
        self.setPaused(False)  #Turn Paused Off
        self.setSongPlaying(False)  #Turn Song Off
        self.threadpool.waitForDone()  #Wait for songs to return
        self.setSongPlaying(True)  #Turn Song On
        self.ui.progressBar.setVisible(True)

        drummersong = drummer.NewHousetopSong(self.win, self.app)
        self.drummerWorker = Worker(
            drummersong.startsong
        )  # add the function to execute to the worker class
        self.drummerWorker.signals.finished.connect(
            self.afterSong
        )  # function that will execute after carolWorker is done
        self.drummerWorker.signals.progress_callback.connect(
            self.updateProgressBar
        )  # function that will execute when carolWorker sends a signal
        self.threadpool.start(
            self.drummerWorker
        )  # starts carolWorker with the above requirements

    def pauseClicked(self):
        """
            Handles the pause functionality for the app. Could possibly be further devloped 
            to handle pause and play. Must have songs played in a worker class so that it may run in a threadpool or else
            pause functionality will disapear since the main thread will be playing the song.
        """
        self.updatelabel2('paused')
        print("\n\npause clicked\n\n")
        if self.getPaused() is True:
            self.setPaused(
                False
            )  # set paused to false so that the song currently playing knows that it is no longer paused
            self.win.updatelabel2("Play button clicked!\nResuming the song.")
        else:
            self.setPaused(
                True
            )  # need to set paused to true so that way the song playing knows to pause

    def setPaused(self, logic):
        """
            Setter for the pause variable
        """
        self.isPaused = logic

    def getPaused(self):
        """
            Getter for the pause variable
        """
        return self.isPaused

    def getStopped(self):
        """
            Getter for the stop variable
        """
        return self.stopSong

    def setSongPlaying(self, logic):
        """
            Setter for the stop variable
        """
        self.stopSong = not logic

    def setProgressBarMax(self, value):
        """
            Sets Max value for progress bar
        """
        self.ui.progressBar.setMaximum(value)

    def updateTempo(self, valueChanged):
        """
            Updates the global tempo variable and Tempo label
        """
        self.currentTempo = valueChanged
        self.ui.tempoSlider.setValue(self.currentTempo)
        self.updateTempoLabel(str(valueChanged))

    def getTempoValue(self):
        return self.currentTempo

    def updateProgressBar(self, progress_callback):
        """
            Updates progress bar with progress_callback as current value
        """
        self.ui.progressBar.setValue(progress_callback)

    def updateTempoLabel(self, text):
        self.ui.tempoLabel.setText("Tempo : " + text)
        # self.ui.tempoLabel.adjustSize()

    def updatelabel2(self, text):
        self.ui.label2.setText(text)
        self.ui.label2.adjustSize()

    def pausePlaySwitch(self, logic):
        """
            Switches the pause and play buttons to clickable or not
        """
        self.ui.pausebtn.setEnabled(logic)