Пример #1
0
 def __init__(self, parent=None):
     super(MinWindow, self).__init__(parent)
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     # self.ui.setupUi(self)
     self.center()
     self.on_draw()
     self.load_event()
Пример #2
0
 def __init__(self):
   QtGui.QMainWindow.__init__(self)
   self.ui = Ui_MainWindow()
   self.ui.setupUi(self)
   # Объявляем слоты
   # Выход из программы
   self.ui.actionExit.triggered.connect(self.close)
   # Открыть БД
   self.ui.actionDBOpen.triggered.connect(self.openDB)
   # Закрыть БД
   self.ui.actionDBClose.triggered.connect(self.closeDB)
   # Отобразить съемы пациента
   self.ui.trePatients.itemClicked.connect(self.listProbes)
   # Чекнуть пациента
   # Внимание!!! - Не очевидно.
   # Во в момент срабатывания itemChanged так же срабатывает
   # и itemClicked, однако itemChanged всегда отрабатывает
   # раньше
   self.ui.trePatients.itemChanged.connect(self.selectAllPatientProbes)
   # Чекнуть единичный съем пациента
   self.ui.treProbes.itemChanged.connect(self.selectProbe)
   # Выбрать всех
   self.ui.actSelectAll.triggered.connect(self.selectAllProbes)
   # Экспорт
   self.ui.actionExport.triggered.connect(self.exportProbes)
   # Вывести окошко 'О программе'
   self.ui.actAboutShow.triggered.connect(self.helpAbout)
   # Выбор таба графика
   self.ui.tabWidView.currentChanged.connect(self.changeTab)
   # Щелчёк по съему в окне экспорта
   self.ui.treExportProbes.itemClicked.connect(self.selectExportPatient)
   # Кнопка "Удалить" в окне экспорта
   self.ui.btnDelElem.clicked.connect(self.delExportItems)
   # Кнопка "Очистить" в окне экспорта
   self.ui.btnClearProbes.clicked.connect(self.clearExport)
   # Кнопка сохранения изображения графика
   self.ui.butSaveImage.clicked.connect(self.saveImage)
   # Кнопка экспорта данных графика
   self.ui.butGarphExport.clicked.connect(self.exportGarph)
   # Отображение графиков по щелчку на легенде
   self.ui.qwtSegPlot.legendChecked.connect(self.showCurve)
   # Построение графика MaxMin
   self.ui.actMaxMin.triggered.connect(self.plotMaxMin)
   # Построение графика корреляции по сегментам
   self.ui.actCorrelationFi.triggered.connect(self.plotCorrelationFi)
   # Постоение графика вегетативного индекса
   self.ui.actVI.triggered.connect(self.plotVegetIndex)
   # Разворачиваем на весь экран
   self.showMaximized()
   self.graphTab = 'graph'
   self.groupVI = True
   self.statusBar().showMessage(u'Готов')
Пример #3
0
#lr.setZValue(-10)
#p8.addItem(lr)
#
#p9 = win.addPlot(title="Zoom on selected region")
#p9.plot(data2)
#def updatePlot():
#    p9.setXRange(*lr.getRegion(), padding=0)
#def updateRegion():
#    lr.setRegion(p9.getViewBox().viewRange()[0])
#lr.sigRegionChanged.connect(updatePlot)
#p9.sigXRangeChanged.connect(updateRegion)
#updatePlot()

# Enable antialiasing for prettier plots
pg.setConfigOptions(antialias=True)
ui = Ui_MainWindow()

address_book = ['*****@*****.**']
msg = MIMEMultipart()
sender = "*****@*****.**"
subject = "Testmail"
body = "This is my email body"

msg['From'] = sender
msg['To'] = ','.join(address_book)
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
text = msg.as_string()
#print text
# Send the message via our SMTP server
s = smtplib.SMTP('mail.gmx.net', 587)
    def __init__(self):
        super(MyApp,self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # set full screen
        self.showMaximized()

        # set icon
        self.setWindowIcon(QtGui.QIcon('asset/Logo.ico')) 
        self.ui.slapButton.setIcon(QtGui.QIcon('asset/slapButton.png'))
        self.ui.slapButton2.setIcon(QtGui.QIcon('asset/slapButton.png'))
        self.ui.fallButton.setIcon(QtGui.QIcon('asset/fallButton.png'))
        self.ui.saveButton.setIcon(QtGui.QIcon('asset/saveButton.png'))
        self.ui.pauseButton.setIcon(QtGui.QIcon('asset/pauseButton.png'))
        self.ui.startButton.setIcon(QtGui.QIcon('asset/startButton.png'))
        self.ui.forwardButton.setIcon(QtGui.QIcon('asset/forwardButton.png'))
        self.ui.backwardButton.setIcon(QtGui.QIcon('asset/backwardButton.png'))
        self.ui.forwardButton_graph.setIcon(QtGui.QIcon('asset/forwardButton.png'))
        self.ui.backwardButton_graph.setIcon(QtGui.QIcon('asset/backwardButton.png'))
        self.ui.forwardButton_video.setIcon(QtGui.QIcon('asset/forwardButton.png'))
        self.ui.backwardButton_video.setIcon(QtGui.QIcon('asset/backwardButton.png'))
        self.ui.matchingButton.setIcon(QtGui.QIcon('asset/matchingButton.png'))
        self.ui.fileButton.setIcon(QtGui.QIcon('asset/fileButton.png'))
        self.ui.openButton.setIcon(QtGui.QIcon('asset/openButton.png'))
        self.ui.personalButton.setIcon(QtGui.QIcon('asset/personalButton.png'))

        # set save config file (slap button and fall button)
        self.ui.slapButton.clicked.connect(self.slapButtonPressed)
        self.ui.slapButton2.clicked.connect(self.slapButton2Pressed)
        self.ui.fallButton.clicked.connect(self.fallButtonPressed)
        self.ui.saveButton.clicked.connect(self.saveButtonPressed)

        # set graph and video button (Connection)
        self.ui.pauseButton.clicked.connect(self.pauseButtonPressed)
        self.ui.startButton.clicked.connect(self.startButtonPressed)
        self.ui.forwardButton.clicked.connect(self.forwardButtonPressed)
        self.ui.backwardButton.clicked.connect(self.backwardButtonPressed)
        self.ui.matchingButton.clicked.connect(self.matchingButtonPressed)

        # For open personal data file
        self.ui.personalButton.clicked.connect(self.personalButtonPressed)
        self.ui.statusbar.showMessage("Select personal data file before opening video and graph")

        # set graph button (Connection)
        self.ui.fileButton.clicked.connect(self.fileButtonPressed)      
        self.ui.horizontalSlider_graph.sliderPressed.connect(self.horizontalSliderGraphPressed)
        self.ui.horizontalSlider_graph.sliderReleased.connect(self.horizontalSliderGraphReleased)
        self.ui.backwardButton_graph.clicked.connect(self.backwardButtonGraphPressed)
        self.ui.forwardButton_graph.clicked.connect(self.forwardButtonGraphPressed)
        self.ui.comboBox_graph.currentIndexChanged.connect(self.selectGraphChange)
        self.ui.comboBox_type.currentIndexChanged.connect(self.selectTypeChange)
        self.ui.comboBox_peak.currentIndexChanged.connect(self.selectPeakChange)

        # set graph
        layout = QVBoxLayout()
        self.figure = Figure()
        self.ui.GraphImage.canvas = FigureCanvas(self.figure)
        layout.addWidget(self.ui.GraphImage.canvas)
        self.ui.GraphImage.setLayout(layout)
        self.ax1 = self.figure.add_subplot(1,1,1)
        self.ax1.get_yaxis().set_visible(False)
        self.ax1.get_xaxis().set_visible(True)
        self.figure.subplots_adjust(left=0.001, right=0.999, top=1.0, bottom=0.1)

        # parameter graph and pointing graph
        self.isRunGraph = True # for loop
        self.isthreadActiveGraph = False # for active graph
        self.isUpdateGraph = False # for updating graph
        self.wthread2 = workerThread2(self)           
        self.wthread2.start() 
        self.frameGraphUpdate = 0
        self.maxGraphX = 40000
        self.timeGraph = 0
        self.graphUpdate = 40

        # set video
        self.ui.openButton.clicked.connect(self.openButtonPressed)
        self.ui.forwardButton_video.clicked.connect(self.forwardButtonVideoPressed)
        self.ui.backwardButton_video.clicked.connect(self.backwardButtonVideoPressed)
        self.ui.horizontalSlider_video.sliderPressed.connect(self.horizontalSliderVideoPressed)
        self.ui.horizontalSlider_video.sliderReleased.connect(self.horizontalSliderVideoReleased)
        self.ui.comboBox_video.currentIndexChanged.connect(self.selectVideoChange)

        # parameter video and pointing video
        self.isRunVideo = True # for loop
        self.resizegoing = False 
        self.isthreadActiveVideo = False # for active video
        self.isUpdateVideo = False # for updating graph
        self.wthread = workerThread(self)           
        self.wthread.start() 
        self.frameVideo = 0
        self.timeVideo = 0
        self.endframe = 1
        self.videoUpdate = 20

        # Graph and Video Connection
        self.isUpdateGV = False
        self.wthread4 = workerThread4(self)           
        self.wthread4.start() 
        self.autoData = False
        self.wthread3 = workerThread3(self)           
        self.wthread3.start() 
        self.matching = 0
class MyApp(QMainWindow):
    def __init__(self):
        super(MyApp,self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # set full screen
        self.showMaximized()

        # set icon
        self.setWindowIcon(QtGui.QIcon('asset/Logo.ico')) 
        self.ui.slapButton.setIcon(QtGui.QIcon('asset/slapButton.png'))
        self.ui.slapButton2.setIcon(QtGui.QIcon('asset/slapButton.png'))
        self.ui.fallButton.setIcon(QtGui.QIcon('asset/fallButton.png'))
        self.ui.saveButton.setIcon(QtGui.QIcon('asset/saveButton.png'))
        self.ui.pauseButton.setIcon(QtGui.QIcon('asset/pauseButton.png'))
        self.ui.startButton.setIcon(QtGui.QIcon('asset/startButton.png'))
        self.ui.forwardButton.setIcon(QtGui.QIcon('asset/forwardButton.png'))
        self.ui.backwardButton.setIcon(QtGui.QIcon('asset/backwardButton.png'))
        self.ui.forwardButton_graph.setIcon(QtGui.QIcon('asset/forwardButton.png'))
        self.ui.backwardButton_graph.setIcon(QtGui.QIcon('asset/backwardButton.png'))
        self.ui.forwardButton_video.setIcon(QtGui.QIcon('asset/forwardButton.png'))
        self.ui.backwardButton_video.setIcon(QtGui.QIcon('asset/backwardButton.png'))
        self.ui.matchingButton.setIcon(QtGui.QIcon('asset/matchingButton.png'))
        self.ui.fileButton.setIcon(QtGui.QIcon('asset/fileButton.png'))
        self.ui.openButton.setIcon(QtGui.QIcon('asset/openButton.png'))
        self.ui.personalButton.setIcon(QtGui.QIcon('asset/personalButton.png'))

        # set save config file (slap button and fall button)
        self.ui.slapButton.clicked.connect(self.slapButtonPressed)
        self.ui.slapButton2.clicked.connect(self.slapButton2Pressed)
        self.ui.fallButton.clicked.connect(self.fallButtonPressed)
        self.ui.saveButton.clicked.connect(self.saveButtonPressed)

        # set graph and video button (Connection)
        self.ui.pauseButton.clicked.connect(self.pauseButtonPressed)
        self.ui.startButton.clicked.connect(self.startButtonPressed)
        self.ui.forwardButton.clicked.connect(self.forwardButtonPressed)
        self.ui.backwardButton.clicked.connect(self.backwardButtonPressed)
        self.ui.matchingButton.clicked.connect(self.matchingButtonPressed)

        # For open personal data file
        self.ui.personalButton.clicked.connect(self.personalButtonPressed)
        self.ui.statusbar.showMessage("Select personal data file before opening video and graph")

        # set graph button (Connection)
        self.ui.fileButton.clicked.connect(self.fileButtonPressed)      
        self.ui.horizontalSlider_graph.sliderPressed.connect(self.horizontalSliderGraphPressed)
        self.ui.horizontalSlider_graph.sliderReleased.connect(self.horizontalSliderGraphReleased)
        self.ui.backwardButton_graph.clicked.connect(self.backwardButtonGraphPressed)
        self.ui.forwardButton_graph.clicked.connect(self.forwardButtonGraphPressed)
        self.ui.comboBox_graph.currentIndexChanged.connect(self.selectGraphChange)
        self.ui.comboBox_type.currentIndexChanged.connect(self.selectTypeChange)
        self.ui.comboBox_peak.currentIndexChanged.connect(self.selectPeakChange)

        # set graph
        layout = QVBoxLayout()
        self.figure = Figure()
        self.ui.GraphImage.canvas = FigureCanvas(self.figure)
        layout.addWidget(self.ui.GraphImage.canvas)
        self.ui.GraphImage.setLayout(layout)
        self.ax1 = self.figure.add_subplot(1,1,1)
        self.ax1.get_yaxis().set_visible(False)
        self.ax1.get_xaxis().set_visible(True)
        self.figure.subplots_adjust(left=0.001, right=0.999, top=1.0, bottom=0.1)

        # parameter graph and pointing graph
        self.isRunGraph = True # for loop
        self.isthreadActiveGraph = False # for active graph
        self.isUpdateGraph = False # for updating graph
        self.wthread2 = workerThread2(self)           
        self.wthread2.start() 
        self.frameGraphUpdate = 0
        self.maxGraphX = 40000
        self.timeGraph = 0
        self.graphUpdate = 40

        # set video
        self.ui.openButton.clicked.connect(self.openButtonPressed)
        self.ui.forwardButton_video.clicked.connect(self.forwardButtonVideoPressed)
        self.ui.backwardButton_video.clicked.connect(self.backwardButtonVideoPressed)
        self.ui.horizontalSlider_video.sliderPressed.connect(self.horizontalSliderVideoPressed)
        self.ui.horizontalSlider_video.sliderReleased.connect(self.horizontalSliderVideoReleased)
        self.ui.comboBox_video.currentIndexChanged.connect(self.selectVideoChange)

        # parameter video and pointing video
        self.isRunVideo = True # for loop
        self.resizegoing = False 
        self.isthreadActiveVideo = False # for active video
        self.isUpdateVideo = False # for updating graph
        self.wthread = workerThread(self)           
        self.wthread.start() 
        self.frameVideo = 0
        self.timeVideo = 0
        self.endframe = 1
        self.videoUpdate = 20

        # Graph and Video Connection
        self.isUpdateGV = False
        self.wthread4 = workerThread4(self)           
        self.wthread4.start() 
        self.autoData = False
        self.wthread3 = workerThread3(self)           
        self.wthread3.start() 
        self.matching = 0
    
    ######################### Open personal data #######################
    def personalButtonPressed(self):
        self.directory = "D:/"
        fileName = QFileDialog.getOpenFileName(None,caption="Select Personal Data File in Excel",directory="D:/")
        self.directory = os.path.dirname(fileName[0])
        if len(fileName[0])>0: 
            try:
                xls = pd.ExcelFile(fileName[0])
                self.dfPersonal = pd.read_excel(xls)
                self.ui.fileButton.setEnabled(True)
                self.ui.openButton.setEnabled(True)
                self.ui.personalButton.setEnabled(False)
                self.ui.statusbar.showMessage("Open Personal Data successfully") 
                self.successMessage("Open Personal Data successfully")
            except Exception as e:
                self.ui.statusbar.showMessage("Error::Please try again") 
                self.errorMessage(e) 
                    
    ######################### Calculate time ########################
    def calculationTime(self):
        self.timeGraph = round((self.frameGraphUpdate*0.0005),2)
        try: self.timeVideo = round((self.frameVideo/self.fps))
        except: self.timeVideo = 0
        self.ui.statusbar.showMessage("Frame of Video ::" + str(self.frameVideo+1) + "/" + str(self.endframe) +
            " (Time = " + str(datetime.timedelta(seconds=self.timeVideo)) + ") Number of Signal :: " + str(self.frameGraphUpdate+1) +
            "/"+ str(self.maxGraphX) + " (Time =" + str(self.timeGraph) + " second)")
        
    ######################### Auto run ##############################
    def pauseButtonPressed(self):
        self.autoData = False   
        # Main menu and slider
        self.ui.horizontalSlider_video.setEnabled(True) 
        self.ui.startButton.setEnabled(True)
        self.ui.slapButton.setEnabled(True)
        self.ui.slapButton2.setEnabled(True)
        self.ui.fallButton.setEnabled(True)
        self.ui.forwardButton.setEnabled(True)
        self.ui.backwardButton.setEnabled(True)
        self.ui.matchingButton.setEnabled(True)
        # if matching button was clicked
        if self.matching == 1:
            # For video     
            self.ui.forwardButton_video.setEnabled(False)
            self.ui.backwardButton_video.setEnabled(False)
            self.ui.openButton.setEnabled(False)
            self.ui.comboBox_video.setEnabled(False)
            # For graph
            self.ui.forwardButton_graph.setEnabled(False)
            self.ui.backwardButton_graph.setEnabled(False)
            self.ui.fileButton.setEnabled(False)
            self.ui.horizontalSlider_graph.setEnabled(False) 
            self.ui.comboBox_graph.setEnabled(True)
            self.ui.comboBox_type.setEnabled(True)
            self.ui.comboBox_peak.setEnabled(True)
        else: # if matching button was not clicked
            # For video     
            self.ui.forwardButton_video.setEnabled(True)
            self.ui.backwardButton_video.setEnabled(True)
            self.ui.openButton.setEnabled(True)
            self.ui.comboBox_video.setEnabled(True)
            # For graph
            self.ui.forwardButton_graph.setEnabled(True)
            self.ui.backwardButton_graph.setEnabled(True)
            self.ui.fileButton.setEnabled(True)
            self.ui.comboBox_graph.setEnabled(True)
            self.ui.comboBox_type.setEnabled(True)
            self.ui.comboBox_peak.setEnabled(True)
            self.ui.horizontalSlider_graph.setEnabled(True) 

    def startButtonPressed(self):
        if self.isthreadActiveVideo and self.isthreadActiveGraph:
            self.autoData = True
            # For video 
            self.ui.forwardButton_video.setEnabled(False)
            self.ui.backwardButton_video.setEnabled(False)
            self.ui.fileButton.setEnabled(False)
            self.ui.openButton.setEnabled(False)
            self.ui.horizontalSlider_video.setEnabled(False)
            self.ui.comboBox_video.setEnabled(False)
            # For graph
            self.ui.forwardButton_graph.setEnabled(False)
            self.ui.backwardButton_graph.setEnabled(False)
            self.ui.fileButton.setEnabled(False)
            self.ui.openButton.setEnabled(False)
            self.ui.horizontalSlider_graph.setEnabled(False)
            self.ui.comboBox_graph.setEnabled(False)
            self.ui.comboBox_type.setEnabled(False)
            self.ui.comboBox_peak.setEnabled(False)
            # For main menu
            self.ui.fallButton.setEnabled(False)
            self.ui.slapButton.setEnabled(False)
            self.ui.slapButton2.setEnabled(False)
            self.ui.startButton.setEnabled(False)
            self.ui.forwardButton.setEnabled(False)
            self.ui.backwardButton.setEnabled(False)
            self.ui.matchingButton.setEnabled(False)

    def backwardButtonPressed(self):
        if self.frameGraphUpdate-(self.graphUpdate*3) >= 0 and self.frameVideo-(self.videoUpdate*3) >= 0:
            self.frameGraphUpdate -= self.graphUpdate*3
            self.ui.horizontalSlider_graph.setValue(self.frameGraphUpdate)
            self.frameVideo -= self.videoUpdate*3
            self.ui.horizontalSlider_video.setValue(self.frameVideo)
            self.isUpdateGV = True
            self.ui.backwardButton.setEnabled(False)
            self.ui.forwardButton.setEnabled(False)
        else:
            pass

    def forwardButtonPressed(self):
        if self.frameGraphUpdate+(self.graphUpdate*3) <= self.maxGraphX and self.frameVideo+(self.videoUpdate*3) <= self.endframe:
            self.frameGraphUpdate += self.graphUpdate*3
            self.ui.horizontalSlider_graph.setValue(self.frameGraphUpdate)
            self.frameVideo += self.videoUpdate*3
            self.ui.horizontalSlider_video.setValue(self.frameVideo)
            self.isUpdateGV = True
            self.ui.backwardButton.setEnabled(False)
            self.ui.forwardButton.setEnabled(False)
        else:
            pass

    def matchingButtonPressed(self):
        if self.matching == 0:
            self.matching = 1
            self.ui.matchingButton.setStyleSheet("background-color: #7EA6BF")
            self.ui.horizontalSlider_graph.setEnabled(False)
            self.ui.forwardButton_graph.setEnabled(False)
            self.ui.backwardButton_graph.setEnabled(False)
            self.ui.forwardButton_video.setEnabled(False)
            self.ui.backwardButton_video.setEnabled(False)
            self.ui.openButton.setEnabled(False)
            self.ui.fileButton.setEnabled(False)
            self.ui.comboBox_video.setEnabled(False)
            self.matchVideo = self.ui.horizontalSlider_video.value()
            self.matchGraph = self.ui.horizontalSlider_graph.value()
        elif self.matching == 1:
            self.matching = 0
            self.ui.matchingButton.setStyleSheet("background-color: light gray")
            self.ui.horizontalSlider_graph.setEnabled(True)
            self.ui.forwardButton_graph.setEnabled(True)
            self.ui.backwardButton_graph.setEnabled(True)
            self.ui.forwardButton_video.setEnabled(True)
            self.ui.backwardButton_video.setEnabled(True)
            self.ui.openButton.setEnabled(True)
            self.ui.fileButton.setEnabled(True)
            self.ui.forwardButton.setEnabled(True)
            self.ui.backwardButton.setEnabled(True)
            self.ui.comboBox_video.setEnabled(True)
    
    ######################### Message Box ##############################
    def errorMessage(self,message):
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Critical)
        msg.setText("Error")
        msg.setInformativeText(str(message))
        msg.setWindowTitle("Error")
        msg.exec_()      
    
    def successMessage(self,message):
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Information)
        msg.setText("Success")
        msg.setInformativeText(str(message))
        msg.setWindowTitle("Success")
        msg.exec_()  

    ######################### Save config ##############################
    def fallButtonPressed(self):
        # set name for saving file
        wordG = self.fileGraph.split('/')
        NewwordG = wordG[len(wordG)-1].split('.')
        fileNameG = NewwordG[0]
        # set directory
        directory = ""
        for i in range(len(wordG)-1):
            directory = directory + wordG[i] + "/"
        directory = directory + "/Database"
        if not os.path.exists(directory):
            os.makedirs(directory)
        # set file name
        filename = directory+"/"+str(fileNameG)+"(time).config"
        # Save 
        config = ConfigObj(filename, encoding='utf8')
        config.filename = filename
        config["Fall-Video"] = str(datetime.timedelta(seconds=self.timeVideo))
        self.falltime = self.timeStamp[self.frameGraphUpdate]
        config["Fall-Graph"] = str(self.falltime)
        config.write()
        self.ui.statusbar.showMessage("Save successfully - Fall-Video = " +str(datetime.timedelta(seconds=self.timeVideo))+ 
            ", Fall-Graph = " +str(self.timeGraph)+ " second") 
        self.successMessage("Save successfully - Fall-Video = " +str(datetime.timedelta(seconds=self.timeVideo))+ 
            ", Fall-Graph = " +str(self.timeGraph)+ " second")
        self.ui.saveButton.setEnabled(True)

    def slapButtonPressed(self):
        # set name for saving file
        wordG = self.fileGraph.split('/')
        NewwordG = wordG[len(wordG)-1].split('.')
        fileNameG = NewwordG[0]
        # set directory
        directory = ""
        for i in range(len(wordG)-1):
            directory = directory + wordG[i] + "/"
        directory = directory + "/Database"
        if not os.path.exists(directory):
            os.makedirs(directory)
        # set file name
        filename = directory+"/"+str(fileNameG)+"(time).config"
        # Save 
        config = ConfigObj(filename, encoding='utf8')
        config.filename = filename
        config["Slap1-Video"] = str(datetime.timedelta(seconds=self.timeVideo))
        self.slaptime1 = self.timeStamp[self.frameGraphUpdate]
        config["Slap1-Graph"] = str(self.slaptime2)
        config.write()
        self.ui.statusbar.showMessage("Save successfully - Slap1-Video = " +str(datetime.timedelta(seconds=self.timeVideo))+
            ", Slap1-Graph = " +str(self.timeGraph)+ " second") 
        self.successMessage("Save successfully - Slap1-Video = " +str(datetime.timedelta(seconds=self.timeVideo))+
            ", Slap1-Graph = " +str(self.timeGraph)+ " second") 

    def slapButton2Pressed(self):
        # set name for saving file
        wordG = self.fileGraph.split('/')
        NewwordG = wordG[len(wordG)-1].split('.')
        fileNameG = NewwordG[0]
        # set directory
        directory = ""
        for i in range(len(wordG)-1):
            directory = directory + wordG[i] + "/"
        directory = directory + "/Database"
        if not os.path.exists(directory):
            os.makedirs(directory)
        # set file name
        filename = directory+"/"+str(fileNameG)+"(time).config"
        # Save 
        config = ConfigObj(filename, encoding='utf8')
        config.filename = filename
        config["Slap2-Video"] = str(datetime.timedelta(seconds=self.timeVideo))
        self.slaptime2 = self.timeStamp[self.frameGraphUpdate]
        config["Slap2-Graph"] = str(self.slaptime2)
        config.write()
        self.ui.statusbar.showMessage("Save successfully - Slap2-Video = " +str(datetime.timedelta(seconds=self.timeVideo))+
            ", Slap2-Graph = " +str(self.timeGraph)+ " second")  
        self.successMessage("Save successfully - Slap2-Video = " +str(datetime.timedelta(seconds=self.timeVideo))+
            ", Slap2-Graph = " +str(self.timeGraph)+ " second") 
    
    def saveButtonPressed(self):
        position = int(self.df[self.df['TimeStamp']==self.falltime]['TimestampCounter'].values)
        datacrop = 200 #mS
        pos1 = position-(datacrop*2)
        pos2 = position-(datacrop*4)
        pos3 = position-(datacrop*10)
        pos0 = position+(datacrop*6)
        #define Label 
        self.df['Label'] = 0
        self.df['Label'][pos2:pos1] = 1
        self.df['Label'][pos1:position] = 2
        self.df['Label'][position:pos0] = 3
        # cut data
        try: 
            self.df.drop(self.df.index[pos0::], inplace=True)
            self.df.drop(self.df.index[0:pos3], inplace=True)
            self.df.drop(columns=['Real_Time'], inplace=True)
            # set name for saving file
            wordV = self.fileVideo.split('/')
            NewwordV = wordV[len(wordV)-1].split('.')
            fileNameV = NewwordV[0]
            wordG = self.fileGraph.split('/')
            NewwordG = wordG[len(wordG)-1].split('.')
            fileNameG = NewwordG[0]
            # set personal parameter
            try: 
                splitFileNameG = fileNameG.split('_')
                participant_ID = splitFileNameG[1]
                for i in range(len(self.dfPersonal.Participant_ID)):
                    if self.dfPersonal.Participant_ID[i].find(participant_ID)>-1:
                        participant_BMI = self.dfPersonal.BMI[i]
                        self.df['BMI'] = participant_BMI
                        participant_SexM = self.dfPersonal.Sex_M[i]
                        self.df['SEXM'] = participant_SexM
                        participant_SexF = self.dfPersonal.Sex_F[i]
                        self.df['SEXF'] = participant_SexF
                        participant_Active = self.dfPersonal.Active[i]
                        self.df['Active'] = participant_Active
            except: pass
            # set directory
            directory = ""
            for i in range(len(wordG)-1):
                directory = directory + wordG[i] + "/"
            directory = directory + "/Database"
            if not os.path.exists(directory):
                os.makedirs(directory)
            # set file name
            filename = directory+"/"+str(fileNameG)+"(Cropped).csv"
            self.df.to_csv(filename) 
            self.successMessage("Save CSV file successfully")
            self.ui.saveButton.setEnabled(False)
        except Exception as e:
            #self.errorMessage("Please click save slapping 2 button before click this button") 
            self.errorMessage(e) 

    ######################### Graph ##############################
    def backwardButtonGraphPressed(self):
        if self.frameGraphUpdate-self.graphUpdate >= 0:
            self.frameGraphUpdate -= self.graphUpdate
            self.ui.horizontalSlider_graph.setValue(self.frameGraphUpdate)
            self.isUpdateGraph = True
            self.ui.backwardButton_graph.setEnabled(False)
            self.ui.forwardButton_graph.setEnabled(False)
        else:
            self.frameGraphUpdate = 0
            self.ui.horizontalSlider_graph.setValue(self.frameGraphUpdate)
            self.isUpdateGraph = True
            self.ui.backwardButton_graph.setEnabled(False)
            self.ui.forwardButton_graph.setEnabled(False)

    def forwardButtonGraphPressed(self):
        if self.frameGraphUpdate+self.graphUpdate < self.maxGraphX:
            self.frameGraphUpdate += self.graphUpdate
            self.ui.horizontalSlider_graph.setValue(self.frameGraphUpdate)
            self.isUpdateGraph = True
            self.ui.backwardButton_graph.setEnabled(False)
            self.ui.forwardButton_graph.setEnabled(False)
        else:
            self.frameGraphUpdate = self.maxGraphX - 1
            self.ui.horizontalSlider_graph.setValue(self.frameGraphUpdate)
            self.isUpdateGraph = True
            self.ui.backwardButton_graph.setEnabled(False)
            self.ui.forwardButton_graph.setEnabled(False)
    
    def selectGraphChange(self):
        self.setGraphX()
        self.ax1.lines.remove(self.ax1.lines[4])
        if self.ui.comboBox_type.currentIndex() == 0:
            self.ax1.plot([self.data[self.frameGraphUpdate,10],self.data[self.frameGraphUpdate,10]],[-10,10],'Gray',linewidth=2.0) 
        elif self.ui.comboBox_type.currentIndex() == 1:
            self.ax1.plot([self.data[self.frameGraphUpdate,10],self.data[self.frameGraphUpdate,10]],[-100,100],'Gray',linewidth=2.0) 
        self.ui.GraphImage.canvas.draw()
    
    def selectTypeChange(self):
        self.draw()
    
    def selectPeakChange(self):
        if self.ui.comboBox_peak.currentIndex() == 0: pass
        else: 
            pos = self.listPeak[self.ui.comboBox_peak.currentIndex()-1]
            if self.matching == 0:
                self.ui.horizontalSlider_graph.setValue(pos)
                self.frameGraphUpdate = self.ui.horizontalSlider_graph.value()
                self.sliderbusyGraph = False
                self.isUpdateGraph = True
            elif self.matching == 1:
                current = pos - self.matchGraph
                self.frameGraphUpdate = pos
                self.ui.horizontalSlider_graph.setValue(self.frameGraphUpdate)
                self.frameVideo = int(round(self.matchVideo + (current*(self.videoUpdate/self.graphUpdate))))
                self.ui.horizontalSlider_video.setValue(self.frameVideo)
                self.isUpdateGV = True
                self.sliderbusyVideo = False
    
    def setGraphX(self):
        if self.ui.comboBox_graph.currentIndex() == 1:
            if self.frameGraphUpdate >= 0 and self.frameGraphUpdate < 2000: self.ax1.set_xlim(0,1)
            elif self.frameGraphUpdate >= 2000 and self.frameGraphUpdate < 4000: self.ax1.set_xlim(1,2)
            elif self.frameGraphUpdate >= 4000 and self.frameGraphUpdate < 6000: self.ax1.set_xlim(2,3)
            elif self.frameGraphUpdate >= 6000 and self.frameGraphUpdate < 8000: self.ax1.set_xlim(3,4)
            elif self.frameGraphUpdate >= 8000 and self.frameGraphUpdate < 10000: self.ax1.set_xlim(4,5)
            elif self.frameGraphUpdate >= 10000 and self.frameGraphUpdate < 12000: self.ax1.set_xlim(5,6)
            elif self.frameGraphUpdate >= 12000 and self.frameGraphUpdate < 14000: self.ax1.set_xlim(6,7)
            elif self.frameGraphUpdate >= 14000 and self.frameGraphUpdate < 16000: self.ax1.set_xlim(7,8)
            elif self.frameGraphUpdate >= 16000 and self.frameGraphUpdate < 18000: self.ax1.set_xlim(8,9)
            elif self.frameGraphUpdate >= 18000 and self.frameGraphUpdate < 20000: self.ax1.set_xlim(9,10)
            elif self.frameGraphUpdate >= 20000 and self.frameGraphUpdate < 22000: self.ax1.set_xlim(10,11)
            elif self.frameGraphUpdate >= 22000 and self.frameGraphUpdate < 24000: self.ax1.set_xlim(11,12)
            elif self.frameGraphUpdate >= 24000 and self.frameGraphUpdate < 26000: self.ax1.set_xlim(12,13)
            elif self.frameGraphUpdate >= 26000 and self.frameGraphUpdate < 28000: self.ax1.set_xlim(13,14)
            elif self.frameGraphUpdate >= 28000 and self.frameGraphUpdate < 30000: self.ax1.set_xlim(14,15)
            elif self.frameGraphUpdate >= 30000 and self.frameGraphUpdate < 32000: self.ax1.set_xlim(15,16)
            elif self.frameGraphUpdate >= 32000 and self.frameGraphUpdate < 34000: self.ax1.set_xlim(16,17)
            elif self.frameGraphUpdate >= 34000 and self.frameGraphUpdate < 36000: self.ax1.set_xlim(17,18)
            elif self.frameGraphUpdate >= 36000 and self.frameGraphUpdate < 38000: self.ax1.set_xlim(18,19)
            elif self.frameGraphUpdate >= 38000 and self.frameGraphUpdate < 40000: self.ax1.set_xlim(19,20)
        elif self.ui.comboBox_graph.currentIndex() == 2:
            if self.frameGraphUpdate >= 0 and self.frameGraphUpdate < 10000: self.ax1.set_xlim(0,5)
            elif self.frameGraphUpdate >= 10000 and self.frameGraphUpdate < 20000: self.ax1.set_xlim(5,10)
            elif self.frameGraphUpdate >= 20000 and self.frameGraphUpdate < 30000: self.ax1.set_xlim(10,15)
            elif self.frameGraphUpdate >= 30000 and self.frameGraphUpdate < 40000: self.ax1.set_xlim(15,20)
        else:
            self.ax1.set_xlim(0,20)

    def horizontalSliderGraphPressed(self):
        self.sliderbusyGraph = True
    
    def horizontalSliderGraphReleased(self):
        self.frameGraphUpdate = self.ui.horizontalSlider_graph.value()
        self.ui.backwardButton_graph.setEnabled(False)
        self.ui.forwardButton_graph.setEnabled(False)
        self.sliderbusyGraph = False
        self.isUpdateGraph = True
    
    def fileButtonPressed(self):
        fileName = QFileDialog.getOpenFileName(None,caption="Select Data File in CSV File",directory=self.directory)
        self.directory = os.path.dirname(fileName[0])
        if len(fileName[0])>0:
            try:
                try:
                    self.data = pd.read_csv(fileName[0], converters={"TimestampCounter": lambda x: int(x, 16),
                                                                    "TimeStamp": lambda x: int(x, 16)/1000000,           # convert column Timestamp to 
                                                                    "Ax": lambda x: self.twos_comp(int(x, 16), 16)*(1/2048),  # convert data with two complement  * +-16G scale 
                                                                    "Ay": lambda x: self.twos_comp(int(x, 16), 16)*(1/2048),  # convert data with two complement  * +-16G scale 
                                                                    "Az": lambda x: self.twos_comp(int(x, 16), 16)*(1/2048),  # convert data with two complement  * +-16G scale 
                                                                    "Gx": lambda x: self.twos_comp(int(x, 16), 16)/131,       # convert data with two complement  * +-2000 scale 
                                                                    "Gy": lambda x: self.twos_comp(int(x, 16), 16)/131,       # convert data with two complement  * +-2000 scale 
                                                                    "Gz": lambda x: self.twos_comp(int(x, 16), 16)/131})      # convert data with two complement  * +-2000 scale 
                    self.df = self.data.copy()
                    self.df['rss_A'] =  np.sqrt((self.df.Ax*self.df.Ax)+(self.df.Ay*self.df.Ay)+(self.df.Az*self.df.Az)) # add rss acc signals to dataframe  
                    self.df['rss_G'] =  np.sqrt((self.df.Gx*self.df.Gx)+(self.df.Gy*self.df.Gy)+(self.df.Gz*self.df.Gz)) # add rss gyro signals to dataframe
                    self.df['Real_Time'] = (self.df.TimestampCounter*0.0005)
                    self.df['Deg_saggital'] = np.arctan(self.df['Az']/self.df['Ay'])*(180/math.pi)
                    self.df['Deg_Frontal'] = np.arctan(self.df['Ax']/self.df['Ay'])*(180/math.pi)
                    self.timeStamp = self.df["TimeStamp"]
                    self.df = self.df.round({'Ax': 3,'Ay': 3,'Az': 3,'Gx': 3,'Gy': 3,'Gz': 3,'rss_A': 3,'rss_G': 3}) # roundup data     
                    self.frameGraphUpdate = 0
                    self.draw()  
                except Exception as e: 
                    self.data = pd.read_csv(fileName[0])
                    self.df = self.data.copy()
                    self.df['Real_Time'] = (self.df.TimestampCounter*0.0005)
                    self.df['Deg_saggital'] = np.arctan(self.df['Az']/self.df['Ay'])*(180/math.pi)
                    self.df['Deg_Frontal'] = np.arctan(self.df['Ax']/self.df['Ay'])*(180/math.pi)
                    self.timeStamp = self.df["TimeStamp"]
                    self.df = self.df.round({'Ax': 3,'Ay': 3,'Az': 3,'Gx': 3,'Gy': 3,'Gz': 3,'rss_A': 3,'rss_G': 3}) # roundup data     
                    self.frameGraphUpdate = 0
                    self.draw()  
                # Setting parameters
                self.slaptime1 = None
                self.slaptime2 = None
                self.falltime = None
                # setting button and status bar
                self.findPeak()
                self.fileGraph = fileName[0]
                self.ui.statusbar.showMessage("File Graph:: " + self.fileGraph)  
                self.ui.comboBox_graph.setCurrentIndex(0)
                self.ui.comboBox_peak.setCurrentIndex(0)
                self.ui.horizontalSlider_graph.setValue(self.frameGraphUpdate)
                self.ui.forwardButton_graph.setEnabled(True)
                self.ui.backwardButton_graph.setEnabled(True)
                self.ui.horizontalSlider_graph.setEnabled(True)
                self.ui.comboBox_graph.setEnabled(True)
                self.ui.comboBox_type.setEnabled(True)
                self.ui.comboBox_peak.setEnabled(True)
                self.isthreadActiveGraph = True
                if self.isthreadActiveVideo and self.isthreadActiveGraph:
                    self.ui.startButton.setEnabled(True)
                    self.ui.pauseButton.setEnabled(True)
                    self.ui.fallButton.setEnabled(True)
                    self.ui.slapButton.setEnabled(True)
                    self.ui.slapButton2.setEnabled(True)
                    self.ui.forwardButton.setEnabled(True)
                    self.ui.backwardButton.setEnabled(True)
                    self.ui.matchingButton.setEnabled(True)
            except Exception as e:  
                self.ui.statusbar.showMessage("Error::Please try again") 
                self.errorMessage(e)     

    def draw(self):  
        self.ax1.clear() 
        self.data = self.df.values[:,0:11]
        if self.ui.comboBox_type.currentIndex() == 0:
            self.ax1.plot(self.data[:,10],self.data[:,2],'y') # Ax
            self.ax1.plot(self.data[:,10],self.data[:,3],'r') # Ay
            self.ax1.plot(self.data[:,10],self.data[:,4],'g') # Az
            self.ax1.plot(self.data[:,10],self.data[:,8],'b') # rss_A
            self.ax1.set_ylim(-10, 10)
            self.setGraphX()
            self.ui.horizontalSlider_graph.setMaximum(self.maxGraphX-1)
            self.ax1.plot([self.data[self.frameGraphUpdate,10],self.data[self.frameGraphUpdate,-1]],[-10,10],'Gray',linewidth=2.0)
        elif self.ui.comboBox_type.currentIndex() == 1:
            self.ax1.plot(self.data[:,10],self.data[:,5],'y') # Gx
            self.ax1.plot(self.data[:,10],self.data[:,6],'r') # Gy
            self.ax1.plot(self.data[:,10],self.data[:,7],'g') # Gz
            self.ax1.plot(self.data[:,10],self.data[:,9],'b') # rss_G
            self.ax1.set_ylim(-100, 100)
            self.setGraphX()
            self.ui.horizontalSlider_graph.setMaximum(self.maxGraphX-1)
            self.ax1.plot([self.data[self.frameGraphUpdate,10],self.data[self.frameGraphUpdate,-1]],[-100,100],'Gray',linewidth=2.0)    
        self.ui.GraphImage.canvas.draw()

    def findPeak(self):
        final_list = [] 
        N = 5
        A = np.array((self.data[:,8]))
        peaks, _ = find_peaks(A,distance=200)    
        list1 = peaks.tolist()
        for i in range(0, N):  
            max1 = 0
            for j in range(len(list1)):      
                if A[list1[j]] > max1: 
                    max1 = A[list1[j]]
                    position = list1[j]
            list1.remove(position) 
            final_list.append(position) 
        self.listPeak = final_list
    
    def twos_comp(self, val, bits):                                                      
        """compute the 2's complement of int value val"""                          
        if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255
            val = val - (1 << bits)        # compute negative value                
        return val                         # return positive value as is  

    ######################### Video ##############################
    def openButtonPressed(self):
        try:
            fileName = QFileDialog.getOpenFileName(None,caption="Select Video File",directory=self.directory)
            self.directory = os.path.dirname(fileName[0])
            if len(fileName[0])>0:
                self.cap = cv2.VideoCapture(fileName[0])
                self.isthreadActiveVideo = True
            else:
                self.isthreadActiveVideo = False
                return
            self.length = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
            self.fps = self.cap.get(cv2.CAP_PROP_FPS)
            # set fps specific for updating video
            if round(self.fps) == 50: self.ui.comboBox_video.setCurrentIndex(1)
            elif round(self.fps) == 30: self.ui.comboBox_video.setCurrentIndex(2)
            else: self.ui.comboBox_video.setCurrentIndex(0)
            self.setVideo() 
            self.ui.horizontalSlider_video.setMaximum(self.endframe-1)
            self.cap.set(1,self.stframe)
            ret, frame = self.cap.read()
            self.frameVideo = self.stframe
            self.ui.horizontalSlider_video.setValue(self.frameVideo)
            self.limg = frame
            self.frameHeight = frame.shape[0]
            self.frameWidth = frame.shape[1]
            self.on_zoomfit_clicked()
            nchannel = frame.shape[2]
            limg2 = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)  
            timg = cv2.resize(limg2,(int(self.scaleFactor*limg2.shape[1]),int(self.scaleFactor*limg2.shape[0]))) 
            limage = QtGui.QImage(timg.data, timg.shape[1], timg.shape[0], nchannel*timg.shape[1], QtGui.QImage.Format_RGB888)  
            self.ui.VideoImage.setPixmap(QtGui.QPixmap(limage))
            self.ui.forwardButton_video.setEnabled(True)
            self.ui.backwardButton_video.setEnabled(True)
            self.ui.horizontalSlider_video.setEnabled(True)
            self.ui.comboBox_video.setEnabled(True)
            self.ui.statusbar.showMessage("File Video:: " + str(fileName[0])) 
            self.fileVideo = fileName[0]
            if self.isthreadActiveGraph and self.isthreadActiveVideo:
                self.ui.startButton.setEnabled(True)
                self.ui.pauseButton.setEnabled(True)
                self.ui.fallButton.setEnabled(True)
                self.ui.slapButton.setEnabled(True)
                self.ui.slapButton2.setEnabled(True)
                self.ui.forwardButton.setEnabled(True)
                self.ui.backwardButton.setEnabled(True)
                self.ui.matchingButton.setEnabled(True)
        except Exception as e:
            self.ui.statusbar.showMessage("Error::Please try again") 
            self.errorMessage(e)       
    
    def on_zoomfit_clicked(self): # for fitting frame of window   
        self.resizegoing = True
        a = self.ui.VideoImage.size()
        if a.width()/self.frameWidth < a.height()/self.frameHeight:
            self.scaleFactor = a.width()/self.frameWidth
            self.startx = 0
            self.starty = (a.height() - self.scaleFactor * self.frameHeight) / 2
        else:
            self.scaleFactor=1.0*a.height()/self.frameHeight
            self.starty = 0
            self.startx = (a.width() - self.scaleFactor * self.frameWidth) / 2
        sleep(0.2)
        self.resizegoing = False
    
    def setVideo(self):
        if self.ui.comboBox_video.currentIndex() == 1:
            self.graphUpdate = 40
            self.videoUpdate = 20
            self.stframe = int(0)    
            self.endframe = int(self.length) 
        elif self.ui.comboBox_video.currentIndex() == 2:
            self.graphUpdate = 32
            self.videoUpdate = 4
            self.stframe = int(0)    
            self.endframe = int(self.length-8) 
        else:
            self.graphUpdate = 40
            self.videoUpdate = 20
            self.stframe = int(0)    
            self.endframe = int(self.length) 

    def forwardButtonVideoPressed(self):
        if self.frameVideo+self.videoUpdate < self.endframe:
            self.frameVideo+=self.videoUpdate
            self.ui.horizontalSlider_video.setValue(self.frameVideo)
            self.isUpdateVideo = True
            self.ui.backwardButton_video.setEnabled(False)
            self.ui.forwardButton_video.setEnabled(False)
        else:
            self.frameVideo = self.endframe - 1
            self.ui.horizontalSlider_video.setValue(self.frameVideo+1)
            self.isUpdateVideo = True
            self.ui.backwardButton_video.setEnabled(False)
            self.ui.forwardButton_video.setEnabled(False)

    def backwardButtonVideoPressed(self):
        if self.frameVideo-self.videoUpdate > 0:
            self.frameVideo -= self.videoUpdate
            self.ui.horizontalSlider_video.setValue(self.frameVideo)
            self.isUpdateVideo = True
            self.ui.backwardButton_video.setEnabled(False)
            self.ui.forwardButton_video.setEnabled(False)
        else:
            self.frameVideo = self.stframe
            self.ui.horizontalSlider_video.setValue(self.frameVideo)
            self.isUpdateVideo = True
            self.ui.backwardButton_video.setEnabled(False)
            self.ui.forwardButton_video.setEnabled(False)

    def selectVideoChange(self):
        self.setVideo()

    def horizontalSliderVideoPressed(self):
        self.sliderbusyVideo = True

    def horizontalSliderVideoReleased(self):
        self.frameVideo = self.ui.horizontalSlider_video.value()
        if self.matching == 0:
            self.ui.backwardButton_video.setEnabled(False)
            self.ui.forwardButton_video.setEnabled(False)
            self.isUpdateVideo = True
            self.sliderbusyVideo = False
        elif self.matching == 1:
            current = self.frameVideo - self.matchVideo
            self.frameGraphUpdate = round(self.matchGraph + (current*(self.graphUpdate/self.videoUpdate)))
            if self.frameGraphUpdate < 0: self.frameGraphUpdate = 0
            elif self.frameGraphUpdate > self.maxGraphX: self.frameGraphUpdate = self.maxGraphX - 1
            self.ui.horizontalSlider_graph.setValue(self.frameGraphUpdate)
            self.isUpdateGV = True
            self.sliderbusyVideo = False
Пример #6
0
from PyQt5 import QtWidgets
from   MainForm import  Ui_MainWindow

def test(text):
    print( 'text')

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui=Ui_MainWindow()
    Ui_MainWindow.setupUi(ui,MainWindow)
    MainWindow.show()
    QtWidgets.QApplication.processEvents()
    ###################
    # app.installEventFilter(MainWindow)
    sys.exit(app.exec_())
Пример #7
0
class MinWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MinWindow, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        # self.ui.setupUi(self)
        self.center()
        self.on_draw()
        self.load_event()

    def on_draw(self):
        self.draw_all_stack_tab()
        self.set_all_stack_tab_toolbar()
        pass

    def load_event(self):
        self.event_with_buttons()
        pass

    def draw_all_stack_tab(self):
        # 绘制所有图像
        # 添加到stack_tabWidget上

        # 创建matplot画布
        self.tab1 = PlotCanvas(self, width=9, height=6, dpi=100)
        self.tab2 = PlotCanvas(self, width=9, height=6, dpi=100)
        self.tab3 = PlotCanvas(self, width=9, height=6, dpi=100)
        # mpl.draw_one_line()

        # 加载数据
        # 在不同的画布上画出来
        # 将所有f分页加入到tabWidget上
        lines = load_all_lines()

        self.tab1.draw_one_line(lines[0])
        self.tab2.draw_one_line(lines[1])
        self.tab3.draw_one_line(lines[2])

        # 将所有的tab添加到stack_tabWidget上
        self.ui.stack_tabWidget.addTab(self.tab1, 'td=0.12')
        self.ui.stack_tabWidget.addTab(self.tab2, 'td=0.144')
        self.ui.stack_tabWidget.addTab(self.tab3, 'td=0.176')
        pass

    def set_all_stack_tab_toolbar(self):
        # 添加图像的工具栏 所有的工具栏用容器toolbar_stackedWidget保存
        self.tab1_ntb = NavigationToolbar(self.tab1, self.ui.page)  # 添加完整的 toolbar
        self.tab2_ntb = NavigationToolbar(self.tab2, self.ui.page)  # 添加完整的 toolbar
        self.tab3_ntb = NavigationToolbar(self.tab3, self.ui.page)  # 添加完整的 toolbar

        self.tab1.mpl_nav_toolbar = self.tab1_ntb
        self.tab2.mpl_nav_toolbar = self.tab2_ntb
        self.tab3.mpl_nav_toolbar = self.tab3_ntb
        # log('设置了的')
        # 隐藏当前的toolbar
        self.tab1_ntb.hide()
        self.tab2_ntb.hide()
        self.tab3_ntb.hide()

    def set_button_tip(self, button, tip=None):
        # 设置左下角显示button 的提示
        if tip is not None:
            button.setToolTip(tip)
            button.setStatusTip(tip)
        pass

    def event_with_buttons(self):
        # button绑定事件
        # self.ui.reset_Button.clocked()
        # 点击按钮 保存当前图像
        self.ui.save_pushButton.clicked.connect(self.toolbar_save_plot)

        self.ui.reset_Button.clicked.connect(self.toolbar_home)

        self.ui.forward_Button.clicked.connect(self.toolbar_forward)

        self.ui.back_Button.clicked.connect(self.toolbar_back)
        self.ui.zoom_pushButton.clicked.connect(self.toolbar_zoom)
        self.ui.pan_pushButton.clicked.connect(self.toolbar_pan)

        self.set_button_tip(self.ui.save_pushButton, '点击保存 快捷键Ctrl + S')
        self.set_button_tip(self.ui.reset_Button, '显示图像最初的样子')

        self.set_button_tip(self.ui.forward_Button, '返回上一步图像')
        self.set_button_tip(self.ui.back_Button, '返回下一步图像')
        self.set_button_tip(self.ui.zoom_pushButton, '选中放大图像')
        self.set_button_tip(self.ui.pan_pushButton, '选中图像 可拖动查看细节')



        # 给菜单按钮添加绑定事件
        # QtCore.QMetaObject.connectSlotsByName(self)
        save_file_action = self.create_action("&保存图像",
                                              shortcut="Ctrl+S", slot=self.toolbar_save_plot,
                                              tip="Save the plot")
        quit_action = self.create_action("&Quit", slot=self.close,
                                         shortcut="Ctrl+Q", tip="Close the application")

        self.add_actions(self.ui.file_menu,
                         (save_file_action, None, quit_action))
        pass

    def toolbar_set_curt(self):
        # self.ui.stack_tabWidget.currentWidget().mpl_nav_toolbar

        pass

    def create_action(self, text, slot=None, shortcut=None,
                      icon=None, tip=None, checkable=False,
                      signal="triggered()"):
        # 创建事件
        action = QAction(text, self)
        if icon is not None:
            # action.setIcon(QIcon(":/%s.png" % button_icon))
            pass
        if shortcut is not None:
            action.setShortcut(shortcut)
        if tip is not None:
            action.setToolTip(tip)
            # bottons = QPushButton(text, self)
            # bottons.setti
            action.setStatusTip(tip)
        if slot is not None:
            action.triggered.connect(slot)
        if checkable:
            action.setCheckable(True)
        return action

    def add_actions(self, target, actions):
        # 添加事件
        for action in actions:
            if action is None:
                target.addSeparator()
            else:
                target.addAction(action)

    def center(self):
        # 设置主窗口在屏幕中间
        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        # from utils import log
        # log('screen.width ({})  size.width({})'.format(screen.width(), size.width()))
        self.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2)

    def toolbar_save_plot(self):
        # 保存当前图像
        log('点击了保存')
        # 给button设置tips

        self.ui.stack_tabWidget.currentWidget().mpl_nav_toolbar.save_figure()
        # log('点击了保存啊')
        pass

    def toolbar_zoom(self):
        # 放大当前图像
        log('点击了放大')
        self.ui.stack_tabWidget.currentWidget().mpl_nav_toolbar.zoom()

    def toolbar_back(self):
        # 显示前一步操作的图像
        log("点击了前进")
        self.ui.stack_tabWidget.currentWidget().mpl_nav_toolbar.back()

    def toolbar_forward(self):
        # 显示前一步操作的图像
        log("点击了上一步")
        self.ui.stack_tabWidget.currentWidget().mpl_nav_toolbar.forward()

    def toolbar_edit_parameters(self):
        # 编辑图像的参数

        self.ui.stack_tabWidget.currentWidget().mpl_nav_toolbar.edit_parameters()

    def toolbar_pan(self):
        #
        self.ui.stack_tabWidget.currentWidget().mpl_nav_toolbar.pan()

    def toolbar_edit_parameters(self):
        self.ui.stack_tabWidget.currentWidget().mpl_nav_toolbar.edit_parameters()

    def toolbar_home(self):
        log('点击了重置')
        self.ui.stack_tabWidget.currentWidget().mpl_nav_toolbar.home()
Пример #8
0
class Main(QtGui.QMainWindow):
  def __init__(self):
    QtGui.QMainWindow.__init__(self)
    self.ui = Ui_MainWindow()
    self.ui.setupUi(self)
    # Объявляем слоты
    # Выход из программы
    self.ui.actionExit.triggered.connect(self.close)
    # Открыть БД
    self.ui.actionDBOpen.triggered.connect(self.openDB)
    # Закрыть БД
    self.ui.actionDBClose.triggered.connect(self.closeDB)
    # Отобразить съемы пациента
    self.ui.trePatients.itemClicked.connect(self.listProbes)
    # Чекнуть пациента
    # Внимание!!! - Не очевидно.
    # Во в момент срабатывания itemChanged так же срабатывает
    # и itemClicked, однако itemChanged всегда отрабатывает
    # раньше
    self.ui.trePatients.itemChanged.connect(self.selectAllPatientProbes)
    # Чекнуть единичный съем пациента
    self.ui.treProbes.itemChanged.connect(self.selectProbe)
    # Выбрать всех
    self.ui.actSelectAll.triggered.connect(self.selectAllProbes)
    # Экспорт
    self.ui.actionExport.triggered.connect(self.exportProbes)
    # Вывести окошко 'О программе'
    self.ui.actAboutShow.triggered.connect(self.helpAbout)
    # Выбор таба графика
    self.ui.tabWidView.currentChanged.connect(self.changeTab)
    # Щелчёк по съему в окне экспорта
    self.ui.treExportProbes.itemClicked.connect(self.selectExportPatient)
    # Кнопка "Удалить" в окне экспорта
    self.ui.btnDelElem.clicked.connect(self.delExportItems)
    # Кнопка "Очистить" в окне экспорта
    self.ui.btnClearProbes.clicked.connect(self.clearExport)
    # Кнопка сохранения изображения графика
    self.ui.butSaveImage.clicked.connect(self.saveImage)
    # Кнопка экспорта данных графика
    self.ui.butGarphExport.clicked.connect(self.exportGarph)
    # Отображение графиков по щелчку на легенде
    self.ui.qwtSegPlot.legendChecked.connect(self.showCurve)
    # Построение графика MaxMin
    self.ui.actMaxMin.triggered.connect(self.plotMaxMin)
    # Построение графика корреляции по сегментам
    self.ui.actCorrelationFi.triggered.connect(self.plotCorrelationFi)
    # Постоение графика вегетативного индекса
    self.ui.actVI.triggered.connect(self.plotVegetIndex)
    # Разворачиваем на весь экран
    self.showMaximized()
    self.graphTab = 'graph'
    self.groupVI = True
    self.statusBar().showMessage(u'Готов')

  def openDB(self):
    '''
    Открыть БД и отобразить список пациентов
    '''
    # Подчищаем старые данные
    self.closeDB()
    # Создаём новый список экспортных пациентов
    self.patLst = pr.ExportProbes()
    # Получаем имя базы в системной кодировке
    filename = pu.convert(QtGui.QFileDialog.getOpenFileName(self,
                                                            u'Выберете файл базы данных',
                                                            QtCore.QDir.homePath(),
                                                            u"Базы данных (*.gdb *.GDB)"))
    if filename != '':
      # Подключаемся к базе
      global base
      try:
        base = db.DBAccess(filename)
        # Получаем список пациентов
        patients = base.getAllPatients()
        # Выводим его
        for id in patients.keys():
          # Порядок полей: ID, ФИО, дата рождения, пол
          item = QtGui.QTreeWidgetItem([ str(id), patients[id][0], str(patients[id][1]), patients[id][2] ])
          item.setCheckState(0, QtCore.Qt.Unchecked)
          self.ui.trePatients.addTopLevelItem(item)
        self.statusBar().showMessage(u'База данных загружена. Найдено ' + str(len(patients)) + u' пациентов.')
      except UnicodeDecodeError:
        self.statusBar().showMessage(u'Ошибка: слишком длинный путь до базы данных.')

  def closeDB(self):
    '''
    Закрыть БД
    '''
    base = None
    # Очищаем элементы формы
    self.ui.treProbes.clear()
    self.ui.trePatients.clear()
    self.ui.treExportProbes.clear()
    # Очищаем список экспортных пациентов
    self.patLst = None
    self.statusBar().showMessage(u'База данных закрыта')

  def listProbes(self, patient):
    '''
    Отобразить съемы выбранного пациента
    '''
    # Получаем Id текущего пациента из виджета списка пациентов
    id = patient.text(0)
    # Сохранить Id текущего пациента в список экспортных пациентов для
    # последующего формирования элементов списка
    self.patLst.putID(id)
    # Очищаем лист съемов
    self.ui.treProbes.clear()
    # Запрашиваем из базы все съемы пациента с данным Id
    probes = base.getPatientInfoDate(id)
    # Получаем список съемов, уже присутствующих в списке экспорта
    chkLst = self.patLst.getCheckedProbes(id)
    # Выводим полученные данные в виджет вывода съемов
    for date in probes.keys():
      item = QtGui.QTreeWidgetItem([ date, str(len(probes[date])) ])
      childNum = 0
      allDateCheck = True
      for probe in probes[date].keys():
        item.addChild(QtGui.QTreeWidgetItem([ probe, probes[date][probe] ]))
        # Если съем присутствует в списке на экспорт
        if chkLst.has_key(probe):
          # Отмечаем его галочкой
          item.child(childNum).setCheckState(0, QtCore.Qt.Checked)
        else:
          # Иначе снимаем галочку
          item.child(childNum).setCheckState(0, QtCore.Qt.Unchecked)
          # И отмечаем всю дату как не выбранную
          allDateCheck = False
        childNum += 1
      self.ui.treProbes.addTopLevelItem(item)
      if allDateCheck:
        item.setCheckState(0, QtCore.Qt.Checked)
      else:
        item.setCheckState(0, QtCore.Qt.Unchecked)

  def selectAllProbes(self):
    """
    Отметить всех пациентов из списка пациентов, как приготовленных
    на экспорт.
    """
    self.statusBar().showMessage(u'Внимание: при больших размерах БД операция может занять длительное время.')
    # Получаем список всех пациентов
    for itemN in xrange(self.ui.trePatients.topLevelItemCount()):
      # Получаем единичный съём
      item = self.ui.trePatients.topLevelItem(itemN)
      # Отмечаем его галочкой
      item.setCheckState(0, QtCore.Qt.Checked)
      # Внимание!!! Далее - не очевидно.
      # после отмечания галочкой происходит срабатывания сигнала
      # trePatients.itemChanged и вызывается его обработчик.
    # selectAllProbes()

  def selectAllPatientProbes(self, patient):
    """
    Отметить все съемы данного пациента, как приготовленные на экспорт.
    """
    # Получаем ID пациента
    id = patient.text(0)
    # Если галочку установили
    if patient.checkState(0):
      # Запрашиваем из базы все съемы пациента с данным Id
      probes = base.getPatientInfo(id)
      # Заносим все съёмы пациента в список экспорта
      self.patLst.reSetProbes(id, probes)
    # Если галочку сняли
    else:
      # Очищаем список экспорта данного пациента
      self.patLst.reSetProbes(id, None)
    # Перезагружаем виджет со списком экспорта
    self.refreshExportList()
    # selectAllPatientProbes()

  def selectProbe(self, probe):
    """
    Отметить единичный элемент в дереве съёмов
    """
    # Если элемент является съёмом
    if probe.childCount() == 0:
      # Получаем ID текущего пациента
      id = self.patLst.getID()
      # Меняем статус съема (выбран/не выбран)
      self.patLst.changeProbeStatus(id, str(probe.text(0)), probe.text(1))
      # Перезагружаем виджет со списком экспорта
      self.refreshExportList()
    # Если элемент является группой съёмов
    else:
      # Получаем свежеустановленный статус (отмечено/снято)
      state = probe.checkState(0)
      # Для всех потомков поддерева
      for i in xrange(probe.childCount()):
        # Устанавливаем тот же статус
        probe.child(i).setCheckState(0, state)
    # selectProbe()

  def refreshExportList(self):
    '''
    Перезагрузить список экспортных съемов.
    '''
    # Очищаем виджет экспортных съёмов
    self.ui.treExportProbes.clear()
    # Получаем список съемов, приготовленнных к экспорту
    exportLst = self.patLst.getAllProbes()
    # Выводим экспортные съёмы
    if exportLst:
      for patient in exportLst.keys():
        for date in exportLst[patient].keys():
          item = QtGui.QTreeWidgetItem([patient, base.getPatientName(patient), date, exportLst[patient][date] ])
          self.ui.treExportProbes.addTopLevelItem(item)
    # refreshExportList()

  def exportProbes(self):
    '''
    Экспортирование съемов
    '''
    # Запрашиваем дирректорию сохраниения съемов в системной кодировке
    dirName = pu.convert(QtGui.QFileDialog.getExistingDirectory(self,
                                                                u'Выберете дирректорию сохранения'))
    if dirName != '':
      # Получаем список съемов, приготовленнных к экспорту
      exportLst = self.patLst.getAllProbes()
      # Для каждого пациента в списке экспортных съемов
      for patient in exportLst.keys():
        # Для каждого съема конкретного пациента
        for date in exportLst[patient].keys():
          # Получаем дату съема
          trueDate = datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
          # преобразуем её в строку особого вида
          dateStr = trueDate.strftime('%Y-%m-%d-%H-%M-%S')
          # Получаем Ф.И.О пациента в нужной кодировке
          patientName = pu.convert(base.getPatientName(patient))
          # Суммируем полученные ранее переменные в полное имя файла
          fileName = os.path.join(dirName, patientName + '_' + dateStr + '.txt')
          # Открываем файл на запись
          tmpFile = open(fileName, "w")
          # Получаем матрицы съема
          lMatr, rMatr = base.getMatrix(patient, date)
          # Пишем матрицы по очереди в файл (Формат Новосибирска)
          for i in xrange(35):
            for j in xrange(24):
              tmpFile.write(str(lMatr[i][j]))
              tmpFile.write('; ')
            tmpFile.write('\n')
          for i in xrange(35):
            for j in xrange(24):
              tmpFile.write(str(rMatr[i][j]))
              tmpFile.write('; ')
            tmpFile.write('\n')
          # Закрываем файл
          tmpFile.close()
      # Информируем пользователя
      self.statusBar().showMessage(u'Экспорт прошёл успешно')
    # exportProbes()

  def selectExportPatient(self, probe):
    '''
    Выбрать съем из списка экспорта для обработки
    '''
    if self.graphTab == 'seg':
      self.plotSegment()
    elif self.graphTab == 'func':
      pass
    elif self.graphTab == 'graph':
      pass
#    elif self.graphTab == 'matr':    
    # selectExportPatient()

  def saveImage(self):
    '''
    Сохранение графика в изображение
    '''
    if self.graphTab == 'seg':
      plot = self.ui.qwtSegPlot
    elif self.graphTab == 'func':
      plot = self.ui.qwtFuncPlot
    elif self.graphTab == 'graph':
      plot = self.ui.qwtGraphPlot
#    elif self.graphTab == 'matr':
    # Получаем имя изображения в системной кодировке
    filename = QtGui.QFileDialog.getSaveFileName(self,
                                                 u'Выберете файл изображения',
                                                 QtCore.QDir.homePath(),
                                                 u"Изображение (*.png *.PNG)")
    if filename != '':
      Qt.QPixmap.grabWidget(plot).save(filename, 'PNG')
      # Информируем пользователя
      self.statusBar().showMessage(u'Изображение сохранено')

  def exportGarph(self):
    '''
    Сохранение данных графика во внешний файл
    '''
    pass

  def delExportItems(self):
    '''
    Удаление выделенных элементов списка экспорта
    '''
    if not self.ui.treExportProbes.selectedIndexes():
      return
    # Удаляем выбранные итемы
    for index in self.ui.treExportProbes.selectedItems():
      self.patLst.changeProbeStatus(index.text(0), str(index.text(2)), index.text(3))
    # Перезагружаем виджет со списком экспорта
    self.refreshExportList()
  # delExportItems()

  def changeTab(self):
    """
    Смена таба с графиком
    """
    if self.ui.tabWidView.currentIndex() == 1:
      self.graphTab = 'seg'
      self.plotSegment()
    if self.ui.tabWidView.currentIndex() == 2:
      self.graphTab = 'func'
    if self.ui.tabWidView.currentIndex() == 0:
      self.graphTab = 'matr'
    if self.ui.tabWidView.currentIndex() == 3:
      self.graphTab = 'graph'

  #changeTab()

  def showCurve(self, item, on):
    """
    Включить/отключить отображение графика
    """
    if self.graphTab == 'seg':
      plot = self.ui.qwtSegPlot
    elif self.graphTab == 'func':
      plot = self.ui.qwtFuncPlot
    elif self.graphTab == 'graph':
      plot = self.ui.qwtGraphPlot
    else:
      return
    item.setVisible(on)
    widget = plot.legend().find(item)
    if isinstance(widget, Qwt.Qwt.QwtLegendItem):
      widget.setChecked(on)
    plot.replot()

  # showCurve()

  def clearExport(self):
    '''
    Очистка списка экспорта
    '''
    self.ui.treExportProbes.clear()
    # Создаём новый список экспортных пациентов
    self.patLst = pr.ExportProbes()
    # clearExport()


  def plotMaxMin(self):
    '''
    Постоение графика Max-min
    '''
    # Если выделена не однастрока (4 поля)
    if len(self.ui.treExportProbes.selectedIndexes()) != 4:
      self.statusBar().showMessage(u'Пациент не выбран')
      return
    for index in self.ui.treExportProbes.selectedItems():
      # Получаем матрицы съема
      lMatr, rMatr = base.getMatrix(index.text(0), str(index.text(2)))
    # Расчитываем MaxMin для каждого полушария
    lMaxMin = MathFunc.MaxMin(lMatr)
    rMaxMin = MathFunc.MaxMin(rMatr)
    # подготавливаем холст
    gf.preparePlot(self.ui.qwtGraphPlot, u'Max-Min')
    gf.setAxis(self.ui.qwtGraphPlot)
    # markers (Вертикальны разделители)
    gf.plotVFuncMarkers(self.ui.qwtGraphPlot)
    # Построение графика левого полушария
    curve = Qwt.QwtPlotCurve(u'Левое полушарие')
    curve.attach(self.ui.qwtGraphPlot)
    curve.setRenderHint(Qwt.QwtPlotItem.RenderAntialiased)
    curve.setPen(Qt.QPen(Qt.Qt.black, 2, Qt.Qt.DotLine))
    curve.setData(range(0, 35), lMaxMin)
    # Построение графика правого полушария
    curve = Qwt.QwtPlotCurve(u'Правое полушарие')
    curve.attach(self.ui.qwtGraphPlot)
    curve.setRenderHint(Qwt.QwtPlotItem.RenderAntialiased)
    curve.setPen(Qt.QPen(Qt.Qt.black, 2))
    curve.setData(range(0, 35), rMaxMin)
    # Выводим график
    self.ui.qwtGraphPlot.replot()
    # plotMaxMin()

  def plotCorrelationFi(self):
    """
    Построение графика корреляции левого и правого полушария по сегментам
    """
    # Если выделена не однастрока (4 поля)
    if len(self.ui.treExportProbes.selectedIndexes()) != 4:
      self.statusBar().showMessage(u'Пациент не выбран')
      return
    for index in self.ui.treExportProbes.selectedItems():
      # Получаем матрицы съема
      lMatr, rMatr = base.getMatrix(index.text(0), str(index.text(2)))
    # Получаем матрицу корреляции
    corrMtrx = MathFunc.CorrelationSegI(lMatr, rMatr)
    # подготавливаем холст
    gf.preparePlot(self.ui.qwtGraphPlot, u'Корреляция Seg(L,R)')
    gf.setAxis(self.ui.qwtGraphPlot)
    # markers (Вертикальны разделители)
    gf.plotVFuncMarkers(self.ui.qwtGraphPlot)
    # ось абцисс
    gf.plotAbciss(self.ui.qwtGraphPlot)
    # Построение графика правого полушария
    curve = Qwt.QwtPlotCurve(u'Корреляция Seg(L,R)')
    curve.attach(self.ui.qwtGraphPlot)
    curve.setRenderHint(Qwt.QwtPlotItem.RenderAntialiased)
    curve.setPen(Qt.QPen(Qt.Qt.black, 2))
    curve.setData(range(0, 35), corrMtrx)
    # Выводим график
    self.ui.qwtGraphPlot.replot()


  def plotVegetIndex(self):
    """
    Построение вегетативного индекса (ВИ)
    """
    if not self.ui.treExportProbes.selectedIndexes():
      return
    srcVI = []
    rezVI = []
    rezDat = []
    # Перебираем все выделенные item-ы
    for index in self.ui.treExportProbes.selectedItems():
      # Получаем матрицы съема
      lMatr, rMatr = base.getMatrix(index.text(0), str(index.text(2)))
      # Расчитываем MaxMin для каждого полушария
      lMaxMin = MathFunc.MaxMin(lMatr)
      rMaxMin = MathFunc.MaxMin(rMatr)
      # Расчитываем ВИ и заносим его в список исходных ВИ
      VI = MathFunc.VegetIndex(lMaxMin, rMaxMin)
      srcVI.append([index.text(2), VI]) #extend
    # Сортируем по дате
    srcVI.sort()
    # Если выставлена группировка индексов по времени и дате
    if self.groupVI:
      # Номер группы
      group = 0
      # Число индексов в группе
      div = 1
      # Предыдущий обрабатываемый ВИ
      oldVI = 0
      for i in xrange(len(srcVI)):
        # Если первый элемент в массиве
        # то добавляем его в первую группу
        if oldVI == 0:
          rezVI.append(srcVI[i][1])
          rezDat.append(srcVI[i][0])
        else:
          d1 = datetime.datetime.strptime(str(srcVI[i][0]), '%Y-%m-%d %H:%M:%S')
          d2 = datetime.datetime.strptime(str(oldVI[0]), '%Y-%m-%d %H:%M:%S')
          diff = d1 - d2
          # Если разница по времени между съемами >= 7 минут (3 мин на
          # съем и 3 на тупняк между съемами)
          if diff.seconds / 60 >= 7:
            # Делим уже сложенные ВИ на их количество
            rezVI[group] = rezVI[group] / div
            # Формируем красивую дату с числом индексов
            d1 = datetime.datetime.strptime(str(rezDat[group]), '%Y-%m-%d %H:%M:%S')
            rezDat[group] = d1.strftime('%d.%m.%y %H:%M ') + '(' + str(div) + ')'
            # Добавляем текущий индекс в новую группу
            group = group + 1
            rezVI.append(srcVI[i][1])
            rezDat.append(srcVI[i][0])
            div = 1
          # Иначе суммируем текущий индекс с существующей суммой
          else:
            rezVI[group] = rezVI[group] + srcVI[i][1]
            div = div + 1
        oldVI = srcVI[i]
      # Завершающий расчёт
      else:
        # Делим уже сложенные ВИ на их количество
        rezVI[group] = rezVI[group] / div
        # Формируем красивую дату с числом индексов
        d1 = datetime.datetime.strptime(str(rezDat[group]), '%Y-%m-%d %H:%M:%S')
        rezDat[group] = d1.strftime('%d.%m.%y %H:%M ') + '(' + str(div) + ')'
    # Если группировка не выставлена
    else:
      for i in xrange(len(srcVI)):
        rezVI.append(srcVI[i][1])
        d1 = datetime.datetime.strptime(str(srcVI[i][0]), '%Y-%m-%d %H:%M:%S')
        rezDat.append(d1.strftime('%d.%m.%y %H:%M '))
    # Расчёт среднего ВИ (отрисовывается отдельно)
    sum = 0
    for i in xrange(len(rezVI)):
      sum = sum + rezVI[i]
    mean = sum / float(len(rezVI))
    # Расчёт максимального ВИ + 20%(для масштабирования)
    maxVI = 0
    for i in rezVI:
      if i > maxVI:
        maxVI = i
    if maxVI < 2.5:
      maxVI = 2.5
    maxVI = maxVI + maxVI * 0.2
    # Построение графика ВИ
    # подготавливаем холст
    gf.preparePlot(self.ui.qwtGraphPlot, u'Вегетативный индекс', leg = 'no')
    gf.setAxis(self.ui.qwtGraphPlot, 'index', rezDat, rezVI, maxVI)
    # График ВИ
    curve = Qwt.QwtPlotCurve(u'ВИ')
    curve.attach(self.ui.qwtGraphPlot)
    curve.setPen(Qt.QPen(Qt.Qt.black, 20))
    curve.setData(range(len(rezVI)), rezVI)
    curve.setStyle(Qwt.Qwt.QwtPlotCurve.Sticks)
    # Построение границ нормы
    gf.plotNormBorders(self.ui.qwtGraphPlot, 2.5, 0.5, mean)
    # Выводим график
    self.ui.qwtGraphPlot.replot()

  def plotSegment(self):
    """
    Построение по сегментам
    """
    cols = {'C1':Qt.Qt.black, 'C2-3':Qt.Qt.red, 'C4-5':Qt.Qt.blue,
            'C6':Qt.Qt.black, 'C7-8':Qt.Qt.red, 'Th1':Qt.Qt.blue,
            'Th2':Qt.Qt.black, 'Th3-4':Qt.Qt.red, 'Th5':Qt.Qt.blue,
            'Th6':Qt.Qt.black, 'Th7':Qt.Qt.red, 'Th8-9':Qt.Qt.blue,
            'Th10':Qt.Qt.black, 'Th11':Qt.Qt.red, 'Th12':Qt.Qt.blue,
            'L1':Qt.Qt.black, 'L2':Qt.Qt.red, 'L3':Qt.Qt.blue,
            'L4':Qt.Qt.black, 'L5':Qt.Qt.red, 'S1':Qt.Qt.blue,
            'S2':Qt.Qt.black, 'S3-4':Qt.Qt.red, 'K-S5':Qt.Qt.blue}

    # Если выделена не однастрока (4 поля)
    if len(self.ui.treExportProbes.selectedIndexes()) != 4:
      return
    # подготавливаем холст
    gf.preparePlot(self.ui.qwtSegPlot, u'Сегмент', leg = 'check')
    gf.setAxis(self.ui.qwtSegPlot)
    # markers (Вертикальны разделители)
    gf.plotVFuncMarkers(self.ui.qwtSegPlot)
    # Расчёт значений
    for index in self.ui.treExportProbes.selectedItems():
      # Получаем матрицы съема
      lMatr, rMatr = base.getMatrix(index.text(0), str(index.text(2)))
    # Получаем словарь сегментов для каждого полушария
    lSeg = MathFunc.Segment(lMatr)
    rSeg = MathFunc.Segment(rMatr)
    # Создаём словари curve
    curvL = {}
    curvR = {}
    # Строим графики по сементам
    for key in lSeg.keys():
      # Левое полушарие
      curvL[key] = Qwt.QwtPlotCurve(key)
      curvL[key].attach(self.ui.qwtSegPlot)
      curvL[key].setRenderHint(Qwt.QwtPlotItem.RenderAntialiased)
      curvL[key].setPen(Qt.QPen(cols[key], 2, Qt.Qt.DotLine))
      curvL[key].setData(range(len(lSeg[key])), lSeg[key])
      self.showCurve(curvL[key], False)
      # Правое полушарие
      curvR[key] = Qwt.QwtPlotCurve(key)
      curvR[key].attach(self.ui.qwtSegPlot)
      curvR[key].setRenderHint(Qwt.QwtPlotItem.RenderAntialiased)
      curvR[key].setPen(Qt.QPen(cols[key], 2))
      curvR[key].setData(range(len(rSeg[key])), rSeg[key])
      self.showCurve(curvR[key], False)
    # Выводим график
    self.showCurve(curvL['C1'], True)
    self.showCurve(curvR['C1'], True)
    self.ui.qwtSegPlot.replot()
  # plotSegment()

  def helpAbout(self):
    '''
    Отобразить окошко About
    '''
    QtGui.QMessageBox.about(self, "About Converter",
                            u"""<b>MEGI Converter</b> v %s
                            <p>Copyright &copy; 2010 Neurocyb.
                            All rights reserved.
                            <p>Приложение для конвертирования БД МЭГИ в
                            открытые форматы.
                            <p>Python %s - Qt %s - PyQt %s on %s
                            """ % (__version__, platform.python_version(),
                            QtCore.QT_VERSION_STR, QtCore.PYQT_VERSION_STR,
                            platform.system())
                            )
Пример #9
0
    def __init__(self):
        super(MainForm, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        layout = QVBoxLayout()

        self.figure = Figure()
        self.ui.bottomImage.canvas = FigureCanvas(self.figure)

        layout.addWidget(self.ui.bottomImage.canvas)
        self.ui.bottomImage.setLayout(layout)

        self.ax1 = self.figure.add_subplot(1, 1, 1)  #, projection='3d')

        self.ax1.get_yaxis().set_visible(False)
        self.ax1.get_xaxis().set_visible(True)

        self.figure.subplots_adjust(left=0.001,
                                    right=0.999,
                                    top=1.0,
                                    bottom=0.1)

        self.scaleFactor = 1.0
        self.frameID = 0
        self.strt = 0
        self.isRun = True
        self.resizegoing = False
        self.sliderbusy = False
        self.sliderbusy2 = False
        self.linebusy = False
        self.template = np.zeros((1, 1, 1))
        self.ui.openButton.clicked.connect(self.openButtonPressed)
        self.ui.startButton.clicked.connect(self.startButtonPressed)
        self.ui.fileButton.clicked.connect(self.fileButtonPressed)
        self.ui.horizontalSlider.sliderPressed.connect(
            self.horizontalSliderPressed)
        self.ui.horizontalSlider.sliderReleased.connect(
            self.horizontalSliderReleased)
        self.ui.horizontalSlider.valueChanged.connect(
            self.slider_value_changed)

        self.ui.pauseButton.clicked.connect(self.pauseButtonPressed)
        #self.ui.MainWindow.

        self.resized.connect(self._on_resized)
        #self.keypressed.connect(self._key_pressed)
        self.startx = 0
        self.starty = 0
        self.isvideo = False
        self.isdata = False

        self.isbusy = 0
        self.frameHeight = 1
        self.frameWidth = 1
        self.limg = np.zeros((1, 1, 1))
        self.tracker = None
        self.cap = None
        self.timer = None

        self.ui.statusbar.showMessage("Select Data File First")
        self.isthreadActive = False

        self.wthread = workerThread(self)
        self.wthread.updatedM.connect(self.horizontalSliderSet)
        self.wthread.start()

        self.wthread2 = workerThread2(self)
        #self.wthread2.updatedLine.connect(self.lineSliderSet)
        self.wthread2.start()

        klistener = pynput.keyboard.Listener(
            on_press=self.on_press)  #,on_release=self.on_release)
        klistener.start()
Пример #10
0
class MainForm(QMainWindow):

    resized = QtCore.pyqtSignal()

    #keypressed = QtCore.pyqtSignal()

    def __init__(self):
        super(MainForm, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        layout = QVBoxLayout()

        self.figure = Figure()
        self.ui.bottomImage.canvas = FigureCanvas(self.figure)

        layout.addWidget(self.ui.bottomImage.canvas)
        self.ui.bottomImage.setLayout(layout)

        self.ax1 = self.figure.add_subplot(1, 1, 1)  #, projection='3d')

        self.ax1.get_yaxis().set_visible(False)
        self.ax1.get_xaxis().set_visible(True)

        self.figure.subplots_adjust(left=0.001,
                                    right=0.999,
                                    top=1.0,
                                    bottom=0.1)

        self.scaleFactor = 1.0
        self.frameID = 0
        self.strt = 0
        self.isRun = True
        self.resizegoing = False
        self.sliderbusy = False
        self.sliderbusy2 = False
        self.linebusy = False
        self.template = np.zeros((1, 1, 1))
        self.ui.openButton.clicked.connect(self.openButtonPressed)
        self.ui.startButton.clicked.connect(self.startButtonPressed)
        self.ui.fileButton.clicked.connect(self.fileButtonPressed)
        self.ui.horizontalSlider.sliderPressed.connect(
            self.horizontalSliderPressed)
        self.ui.horizontalSlider.sliderReleased.connect(
            self.horizontalSliderReleased)
        self.ui.horizontalSlider.valueChanged.connect(
            self.slider_value_changed)

        self.ui.pauseButton.clicked.connect(self.pauseButtonPressed)
        #self.ui.MainWindow.

        self.resized.connect(self._on_resized)
        #self.keypressed.connect(self._key_pressed)
        self.startx = 0
        self.starty = 0
        self.isvideo = False
        self.isdata = False

        self.isbusy = 0
        self.frameHeight = 1
        self.frameWidth = 1
        self.limg = np.zeros((1, 1, 1))
        self.tracker = None
        self.cap = None
        self.timer = None

        self.ui.statusbar.showMessage("Select Data File First")
        self.isthreadActive = False

        self.wthread = workerThread(self)
        self.wthread.updatedM.connect(self.horizontalSliderSet)
        self.wthread.start()

        self.wthread2 = workerThread2(self)
        #self.wthread2.updatedLine.connect(self.lineSliderSet)
        self.wthread2.start()

        klistener = pynput.keyboard.Listener(
            on_press=self.on_press)  #,on_release=self.on_release)
        klistener.start()

        #self.keythread=MyWidget(self)

    #def on_release(self,key):
    #    if self.isRun:
    #        if key==pynput.keyboard.Key.left:
    #            print('left')
    #            #self.horizontalSliderIncrease(1)
    #        elif key==pynput.keyboard.Key.right:
    #            print('right')
    #            #self.horizontalSliderIncrease(-1)

    def on_press(self, key):
        if self.isRun:
            if pynput.keyboard.Key.space == key:
                if self.ui.pauseButton.isEnabled():
                    self.pauseButtonPressed()
                else:
                    while (self.sliderbusy == True
                           or self.resizegoing == True):
                        sleep(0.1)
                    self.startButtonPressed()

    def slider_value_changed(self):
        if not self.isthreadActive:
            #print('slidervalue change')
            self.horizontalSliderIncrease(0)

    def horizontalSliderIncrease(self, val):
        if self.sliderbusy or self.resizegoing:
            return
        self.sliderbusy = True
        #print(self.ui.horizontalSlider.value())
        #self.ui.horizontalSlider.setValue(self.ui.horizontalSlider.value()+val)
        #print(self.frameID)
        self.frameID = self.stframe + self.ui.horizontalSlider.value() - 1
        #print(self.frameID)
        #self.drawmin=1
        if self.ui.startButton.isEnabled():
            self.cap.set(cv2.CAP_PROP_POS_FRAMES, self.frameID)
            ret, frame = self.cap.read()
            self.limg = frame
            #self.on_zoomfit_clicked()
            nchannel = frame.shape[2]
            limg2 = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
            timg = cv2.resize(limg2, (int(self.scaleFactor * limg2.shape[1]),
                                      int(self.scaleFactor * limg2.shape[0])))
            limage = QtGui.QImage(timg.data, timg.shape[1], timg.shape[0],
                                  nchannel * timg.shape[1],
                                  QtGui.QImage.Format_RGB888)
            self.ui.LeftImage.setPixmap(QtGui.QPixmap(limage))
            self.lineSliderSet(self.frameID)

        self.sliderbusy = False

    def updateFrame(self):
        self.frameID += 1

    def lineSliderSet(self, cnt):
        if cnt + 1 - self.stframe > self.ui.horizontalSlider.maximum():
            return

        self.linebusy = True
        pdraw = self.drawmin

        self.drawmin -= 20
        if self.drawmin < 1:
            self.drawmin = 1
        while (cnt + 1) / self.fps > self.data.values[self.drawmin, 1]:
            self.drawmin += 1
        if not self.drawmin == pdraw or pdraw == 1:

            wr = ref(self.ax1.lines[5])
            self.ax1.lines.remove(wr())
            self.ui.bottomImage.canvas.draw()
            self.ax1.plot([
                self.data.values[self.drawmin, 1],
                self.data.values[self.drawmin, 1]
            ], [0, 3.4],
                          'k',
                          linewidth=2.0)
            self.ui.bottomImage.canvas.draw()

        tsec = cnt / self.fps
        tmin = int(tsec / 60)
        ttsec = int(tsec - 60 * tmin)
        ksec = tsec - 60 * tmin - ttsec

        self.ui.statusbar.showMessage("Frame Time: " + str(tmin).zfill(2) +
                                      ":" + str(ttsec).zfill(2) + ":" +
                                      str(int(ksec * 100)))

        self.linebusy = False

    def horizontalSliderSet(self, cnt):
        if cnt + 1 - self.stframe > self.ui.horizontalSlider.maximum(
        ) or self.sliderbusy or self.resizegoing:
            return
        self.sliderbusy2 = True
        self.ui.horizontalSlider.setValue(cnt + 1 - self.stframe)
        tsec = cnt / self.fps
        tmin = int(tsec / 60)
        ttsec = int(tsec - 60 * tmin)
        ksec = tsec - 60 * tmin - ttsec

        self.ui.statusbar.showMessage("Frame Time: " + str(tmin).zfill(2) +
                                      ":" + str(ttsec).zfill(2) + ":" +
                                      str(int(ksec * 100)))
        self.sliderbusy2 = False

    def horizontalSliderPressed(self):
        self.sliderbusy = True

    def horizontalSliderReleased(self):
        self.frameID = self.stframe + self.ui.horizontalSlider.value() - 1

        self.drawmin = 1
        if self.ui.startButton.isEnabled():
            self.cap.set(cv2.CAP_PROP_POS_FRAMES, self.frameID)
            ret, frame = self.cap.read()
            self.limg = frame
            self.on_zoomfit_clicked()
            nchannel = frame.shape[2]
            limg2 = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
            timg = cv2.resize(limg2, (int(self.scaleFactor * limg2.shape[1]),
                                      int(self.scaleFactor * limg2.shape[0])))
            limage = QtGui.QImage(timg.data, timg.shape[1], timg.shape[0],
                                  nchannel * timg.shape[1],
                                  QtGui.QImage.Format_RGB888)
            self.ui.LeftImage.setPixmap(QtGui.QPixmap(limage))
            self.lineSliderSet(self.frameID)

        self.sliderbusy = False

    def resizeEvent(self, event):
        self.resized.emit()
        return super(MainForm, self).resizeEvent(event)

    def _on_resized(self):
        self.on_zoomfit_clicked()

    def on_zoomfit_clicked(self):

        self.resizegoing = True
        a = self.ui.LeftImage.size()
        if a.width() / self.frameWidth < a.height() / self.frameHeight:
            self.scaleFactor = a.width() / self.frameWidth
            self.startx = 0
            self.starty = (a.height() -
                           self.scaleFactor * self.frameHeight) / 2
        else:
            self.scaleFactor = 1.0 * a.height() / self.frameHeight
            self.starty = 0
            self.startx = (a.width() -
                           self.scaleFactor * self.frameWidth) / 2.0
        sleep(0.2)
        self.resizegoing = False

    def openButtonPressed(self):
        if self.isthreadActive:
            return
        try:
            fileName = QFileDialog.getOpenFileName(
                None,
                caption="Select Video File",
                directory=QtCore.QDir.currentPath())
            if len(fileName[0]) > 0:
                self.cap = cv2.VideoCapture(fileName[0])
                self.isvideo = True
            else:
                return

            length = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
            self.fps = self.cap.get(cv2.CAP_PROP_FPS)

            self.stframe = int(self.data.values[1, 1] * self.fps)
            self.endframe = int(self.data.values[-1, 1] * self.fps)

            self.ui.horizontalSlider.setMaximum(self.endframe - self.stframe)

            self.cap.set(1, self.stframe)
            ret, frame = self.cap.read()
            self.drawmin = 1
            self.frameID = self.stframe
            self.limg = frame
            self.frameHeight = frame.shape[0]
            self.frameWidth = frame.shape[1]
            self.on_zoomfit_clicked()

            nchannel = frame.shape[2]
            limg2 = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)

            timg = cv2.resize(limg2, (int(self.scaleFactor * limg2.shape[1]),
                                      int(self.scaleFactor * limg2.shape[0])))
            limage = QtGui.QImage(timg.data, timg.shape[1], timg.shape[0],
                                  nchannel * timg.shape[1],
                                  QtGui.QImage.Format_RGB888)
            self.ui.LeftImage.setPixmap(QtGui.QPixmap(limage))

            self.ui.statusbar.showMessage(
                "Ready to Start, or redefine data or video")
            self.ui.startButton.setEnabled(True)
            self.ui.pauseButton.setEnabled(False)
            self.ui.horizontalSlider.setEnabled(True)
        except:
            pass

    def fileButtonPressed(self):
        fileName = QFileDialog.getOpenFileName(
            None,
            caption="Select Data File in Excel",
            directory=QtCore.QDir.currentPath())
        if len(fileName[0]) > 0:
            try:
                book = load_workbook(fileName[0])
                ws = book.active
                self.data = pd.DataFrame(ws.values)
                self.isdata = True
                self.draw()
                self.ui.statusbar.showMessage("Select Video File")
                self.ui.openButton.setEnabled(True)
            except:
                pass

        else:
            return

    def draw(self):

        self.ax1.clear()
        #self.ax.axis('off')

        data = self.data.values[1:, 1:5]
        data[:, 1] = (data[:, 1] - data[:, 1].min()) / (data[:, 1].max() -
                                                        data[:, 1].min())
        data[:, 2] = (data[:, 2] - data[:, 2].min()) / (data[:, 2].max() -
                                                        data[:, 2].min())
        data[:, 3] = (data[:, 3] - data[:, 3].min()) / (data[:, 3].max() -
                                                        data[:, 3].min())
        #self.ax.set_xlim([-0.5,0.5])
        self.ax1.set_ylim([0, 3.6])
        #self.ax.set_zlim([-0.5,0.5])
        self.ax1.plot(data[:, 0],
                      data[:, 1] + 2.3,
                      'y',
                      label=self.data.values[0, 2])
        self.ax1.plot(data[:, 0],
                      data[:, 2] + 1.2,
                      'r',
                      label=self.data.values[0, 3])
        self.ax1.plot(data[:, 0],
                      data[:, 3] + 0.1,
                      'g',
                      label=self.data.values[0, 4])

        self.ax1.plot(data[:, 0], 1.15 * np.ones(data[:, 0].shape), 'k')
        self.ax1.plot(data[:, 0], 2.25 * np.ones(data[:, 0].shape), 'k')

        self.ax1.set_xlim([self.data.values[1, 1], self.data.values[-1, 1]])

        self.ax1.plot([self.data.values[1, 1], self.data.values[1, 1]],
                      [0, 3.4],
                      'k',
                      linewidth=2.0)

        start, end = self.ax1.get_xlim()
        self.ax1.xaxis.set_ticks(np.arange(start + 1, end - 1, 5))
        self.ax1.legend(loc='best', framealpha=0.1, ncol=3)

        self.ui.bottomImage.canvas.draw()

    def startButtonPressed(self):

        if self.isthreadActive:
            return

        self.ui.startButton.setEnabled(False)

        if self.ui.timeComboBox.currentIndex() == 0:
            self.timer = perpetualTimer(1.0 / self.fps, self.updateFrame)
            self.timer.start()
        else:
            self.timer = None

        self.ui.pauseButton.setEnabled(True)
        self.isthreadActive = True

    def pauseButtonPressed(self):

        if not self.isthreadActive:
            return
        self.ui.startButton.setEnabled(True)
        self.ui.pauseButton.setEnabled(False)
        if not self.timer is None:
            self.timer.cancel()
        self.isthreadActive = False
Пример #11
0
"""
增强型奥拉 II Python ver.
20200906

主入口部分

"""

from PyQt5.QtWidgets import QApplication

import sys

import Base
from MainForm import Ui_MainWindow

#启动主窗体
if __name__ == "__main__":
    app = QApplication(sys.argv)
    main_window = Ui_MainWindow()
    main_window.setupUi(main_window)
    main_window.show()
    Base.log("启动主窗体")
    sys.exit(app.exec_())
Пример #12
0
class MainForm(QMainWindow):

    resized = QtCore.pyqtSignal()
    #keypressed = QtCore.pyqtSignal()

    def __init__(self):
        super(MainForm,self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        
        layout = QVBoxLayout()
        
        self.figure = Figure()
        self.ui.bottomImage.canvas = FigureCanvas(self.figure)

        layout.addWidget(self.ui.bottomImage.canvas)        
        self.ui.bottomImage.setLayout(layout)

        self.ax1 = self.figure.add_subplot(1,1,1 )#, projection='3d')
        
        self.ax1.get_yaxis().set_visible(False)
        self.ax1.get_xaxis().set_visible(True)
        
        self.figure.subplots_adjust(left=0.001, right=0.999, top=1.0, bottom=0.1)



        self.scaleFactor=1.0
        self.frameID=0        
        self.strt=0
        self.isRun=True
        self.resizegoing=False
        self.sliderbusy=False
        self.sliderbusy2=False
        self.linebusy=False
        self.template=np.zeros((1,1,1))
        self.ui.openButton.clicked.connect(self.openButtonPressed)
        self.ui.startButton.clicked.connect(self.startButtonPressed)   
        self.ui.fileButton.clicked.connect(self.fileButtonPressed)      
        self.ui.horizontalSlider.sliderPressed.connect(self.horizontalSliderPressed)
        self.ui.horizontalSlider.sliderReleased.connect(self.horizontalSliderReleased)
        self.ui.horizontalSlider.valueChanged.connect(self.slider_value_changed)
        self.fps = 20

        # processed frames


        self.ui.pauseButton.clicked.connect(self.pauseButtonPressed)
        #self.ui.MainWindow.
        
        self.resized.connect(self._on_resized)
        #self.keypressed.connect(self._key_pressed)
        self.startx=0
        self.starty=0
        self.isvideo=False
        self.isdata=False

        
        

        self.isbusy=0
        self.frameHeight=1
        self.frameWidth=1
        self.limg=np.zeros((1,1,1))
        self.tracker=None
        self.cap=None
        self.timer=None

       
        self.ui.statusbar.showMessage("Select a video for analysis")
        self.isthreadActive=False

        self.wthread = workerThread(self)        
        self.wthread.updatedM.connect(self.horizontalSliderSet)        
        self.wthread.start()  

        self.wthread2 = workerThread2(self)        
        #self.wthread2.updatedLine.connect(self.lineSliderSet)       
        self.wthread2.start() 

        klistener=pynput.keyboard.Listener(on_press=self.on_press) #,on_release=self.on_release)
        klistener.start()

        #self.keythread=MyWidget(self)


    #def on_release(self,key):
    #    if self.isRun:
    #        if key==pynput.keyboard.Key.left:
    #            print('left')
    #            #self.horizontalSliderIncrease(1)
    #        elif key==pynput.keyboard.Key.right:
    #            print('right')
    #            #self.horizontalSliderIncrease(-1)

    def on_press(self,key):        
         if self.isRun:            
            if pynput.keyboard.Key.space==key: 
                if self.ui.pauseButton.isEnabled():
                    self.pauseButtonPressed()
                else:
                    while (self.sliderbusy==True or self.resizegoing==True):
                        sleep(0.1)
                    self.startButtonPressed()

    def slider_value_changed(self):        
        if not self.isthreadActive:
            #print('slidervalue change')
            self.horizontalSliderIncrease(0)
           
    def horizontalSliderIncrease(self,val):
        if self.sliderbusy or self.resizegoing:        
            return
        self.sliderbusy=True
        #print(self.ui.horizontalSlider.value())
        #self.ui.horizontalSlider.setValue(self.ui.horizontalSlider.value()+val)
        #print(self.frameID)
        self.frameID=self.stframe + self.ui.horizontalSlider.value()-1  
        #print(self.frameID)     
        #self.drawmin=1
        if self.ui.startButton.isEnabled():
                      
            if proc_frames.get(self.frameID) is not None:
                frame = proc_frames[self.frameID]
            else: 
                self.cap.set(cv2.CAP_PROP_POS_FRAMES,self.frameID)        
                ret, frame = self.cap.read()
            self.limg=frame            
            #self.on_zoomfit_clicked()
            nchannel=frame.shape[2]
            limg2 = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)                  
            timg=cv2.resize(limg2,(int(self.scaleFactor*limg2.shape[1]),int(self.scaleFactor*limg2.shape[0]))) 
            limage = QtGui.QImage(timg.data, timg.shape[1], timg.shape[0], nchannel*timg.shape[1], QtGui.QImage.Format_RGB888)  
            self.ui.LeftImage.setPixmap(QtGui.QPixmap(limage))
            self.lineSliderSet(self.frameID)

        self.sliderbusy=False   

    def updateFrame(self):
            self.frameID+=1
            
    def lineSliderSet(self,cnt):
        if cnt+1-self.stframe>self.ui.horizontalSlider.maximum():
            return

        self.linebusy=True
        pdraw=self.drawmin

        self.drawmin-=20
        if self.drawmin<1:
            self.drawmin=1
        while (cnt+1)/self.fps>self.data.values[self.drawmin,1]:
            self.drawmin+=1
        if not self.drawmin==pdraw or pdraw==1:     
           
            wr = ref(self.ax1.lines[-1])
            self.ax1.lines.remove(wr())
            self.ui.bottomImage.canvas.draw()
            self.ax1.plot([self.data.values[self.drawmin,1],self.data.values[self.drawmin,1]],[0,20],'k',linewidth=2.0)
            self.ui.bottomImage.canvas.draw()

        tsec=cnt/self.fps
        tmin=int(tsec/60)
        ttsec=int(tsec-60*tmin)
        ksec=tsec-60*tmin-ttsec
                

        self.ui.statusbar.showMessage("To analyze a frame, press Process Frame and wait")

        self.linebusy=False

    def horizontalSliderSet(self,cnt):
        if cnt+1-self.stframe>self.ui.horizontalSlider.maximum() or self.sliderbusy or self.resizegoing:
            return
        self.sliderbusy2=True        
        self.ui.horizontalSlider.setValue(cnt+1-self.stframe)  
        tsec=cnt/self.fps
        tmin=int(tsec/60)
        ttsec=int(tsec-60*tmin)
        ksec=tsec-60*tmin-ttsec
                

        self.ui.statusbar.showMessage("To analyze a frame, press Process Frame and wait")      
        self.sliderbusy2=False
        
    
    def horizontalSliderPressed(self):
        self.sliderbusy=True

    def horizontalSliderReleased(self):
        self.frameID=self.stframe + self.ui.horizontalSlider.value()-1
        
        self.drawmin=1
        if self.ui.startButton.isEnabled():
            print(type(proc_frames.get(self.frameID)))
            print(proc_frames.get(self.frameID))
            if proc_frames.get(self.frameID) is not None:
                frame = proc_frames[self.frameID]
            else:
                self.cap.set(cv2.CAP_PROP_POS_FRAMES,self.frameID)           
                ret, frame = self.cap.read()


            # real time update
            print(self.frameID)
            
            self.limg=frame            
            self.on_zoomfit_clicked()
            nchannel=frame.shape[2]
            limg2 = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)                  
            timg=cv2.resize(limg2,(int(self.scaleFactor*limg2.shape[1]),int(self.scaleFactor*limg2.shape[0]))) 
            limage = QtGui.QImage(timg.data, timg.shape[1], timg.shape[0], nchannel*timg.shape[1], QtGui.QImage.Format_RGB888)  
            self.ui.LeftImage.setPixmap(QtGui.QPixmap(limage))
            self.lineSliderSet(self.frameID)

        self.sliderbusy=False

    def resizeEvent(self, event):
        self.resized.emit()
        return super(MainForm, self).resizeEvent(event)

    def _on_resized(self):
        self.on_zoomfit_clicked()
   

    def on_zoomfit_clicked(self):        

        self.resizegoing=True
        a=self.ui.LeftImage.size()
        if a.width()/self.frameWidth < a.height()/self.frameHeight:
            self.scaleFactor=a.width()/self.frameWidth
            self.startx=0
            self.starty= (a.height() - self.scaleFactor * self.frameHeight)/2
        else:
            self.scaleFactor=1.0*a.height()/self.frameHeight
            self.starty=0
            self.startx= (a.width() - self.scaleFactor * self.frameWidth)/2.0
        sleep(0.2)
        self.resizegoing=False

    def openButtonPressed(self):
        if self.isthreadActive:
            return

        self.ui.statusbar.showMessage("Wait while our machine learning model processes the video") 

        self.pe = PoseEstimationModel('model.h5') # https://www.dropbox.com/s/llpxd14is7gyj0z/model.h5
        self.pemodel = self.pe.create_model() # create the model

        self.processor = PoseEstimationProcessing()

        



        import time
        import random
        import json


        # random processing


        self.cap.set(cv2.CAP_PROP_POS_FRAMES,self.frameID)           
        ret, frame = self.cap.read()
        a = cv2.resize(frame, (224,224))
        shared_pts = self.processor.shared_points(self.pemodel, a)

        print(type(shared_pts))
        
        a = plot_circles(a, shared_pts)

        a2 = cv2.resize(a, (self.frameWidth, self.frameHeight))
        proc_frames[self.frameID] = a2[:]
        print('Updated %d'%(self.frameID))
        print(proc_frames[self.frameID])

        # log generation


        with open('logs.db', 'a') as outfile:
            outfile.write("frame_no: %d frame_pts_data: "%(self.frameID))
            outfile.write(str(shared_pts))

        self.limg= a2       
        self.on_zoomfit_clicked()
        nchannel=a2.shape[2]
        limg2 = cv2.cvtColor(a2, cv2.COLOR_RGB2BGR)                  
        timg=cv2.resize(limg2,(int(self.scaleFactor*limg2.shape[1]),int(self.scaleFactor*limg2.shape[0]))) 
        limage = QtGui.QImage(timg.data, timg.shape[1], timg.shape[0], nchannel*timg.shape[1], QtGui.QImage.Format_RGB888)  
        self.ui.LeftImage.setPixmap(QtGui.QPixmap(limage))
        self.lineSliderSet(self.frameID)





    def fileButtonPressed(self):

        fileName = QFileDialog.getOpenFileName(None,caption="Select Video File",directory=QtCore.QDir.currentPath())
        try:
            print('1')

            if len(fileName[0])>0:
                self.cap = cv2.VideoCapture(fileName[0])
                self.isvideo=True
            else:
                print('No video updated')
                return

            # cnt = 0
            # test_cap = cv2.VideoCapture(fileName[0])
            # rett, framet = test_cap.read()
            # out_img = framet
            # n_im = 0
            # while(rett):
            #     rett, framet = test_cap.read()
            #     if cnt%20 == 0:
            #         out_img = np.concatenate((out_img,framet), axis=1)
            #         n_im += 1
                
            #     if n_im == 15:
            #         break
                
            #     cnt += 1

            # frame_bar = out_img # cv2.resize(out_img, (100,20))

            print('2')

            length = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
            print(length)
            self.fps = self.cap.get(cv2.CAP_PROP_FPS)
            print('FPS:')
            print(self.fps)


            print('3')

            self.data = pd.read_excel('output.xlsx')  
            self.stframe=int(20.125*self.fps)    
            self.endframe=int(89*self.fps)  

            self.ui.horizontalSlider.setMaximum(self.endframe-self.stframe)

            self.cap.set(1,self.stframe)
            ret, frame=self.cap.read()



            print('4')
            self.drawmin=1
            self.frameID=self.stframe
            self.limg=frame
            print('5')
            self.frameHeight=frame.shape[0]
            self.frameWidth=frame.shape[1] 
            self.on_zoomfit_clicked()

            print('6')

            nchannel=frame.shape[2]
            limg2 = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)  
                    
            timg=cv2.resize(limg2,(int(self.scaleFactor*limg2.shape[1]),int(self.scaleFactor*limg2.shape[0]))) 
            limage = QtGui.QImage(timg.data, timg.shape[1], timg.shape[0], nchannel*timg.shape[1], QtGui.QImage.Format_RGB888)  
            self.ui.LeftImage.setPixmap(QtGui.QPixmap(limage))

            self.ui.statusbar.showMessage("Ready to Start, or redefine data or video") 
            self.ui.startButton.setEnabled(True)
            self.ui.pauseButton.setEnabled(False)
            self.ui.horizontalSlider.setEnabled(True)


                    



            print(self.stframe)
            print(self.endframe)

            print(self.data)       
            self.isdata=True      
            self.draw()  
            self.ui.statusbar.showMessage("Select Video File")  
            self.ui.openButton.setEnabled(True)
        except Exception as e: print(e)

        # fileName = QFileDialog.getOpenFileName(None,caption="Select Data File in Excel",directory=QtCore.QDir.currentPath())
        # if len(fileName[0])>0:
        #  try:
        #    book = load_workbook(fileName[0])
        #    ws = book.active
        #    self.data = pd.DataFrame(ws.values)     
        #    print(self.data)       
        #    self.isdata=True      
        #    self.draw()  
        #    self.ui.statusbar.showMessage("Select Video File")  
        #    self.ui.openButton.setEnabled(True)
        #  except:
        #    pass

        # else:
        #    return

    def draw(self):              
        
        self.ax1.clear()        
        #self.ax.axis('off')
        
        data=self.data.values[1:,1:5]
        data[:,1]= (data[:,1]-data[:,1].min())/(data[:,1].max()-data[:,1].min())
        data[:,2]= (data[:,2]-data[:,2].min())/(data[:,2].max()-data[:,2].min())
        data[:,3]= (data[:,3]-data[:,3].min())/(data[:,3].max()-data[:,3].min())
        #self.ax.set_xlim([-0.5,0.5])
        self.ax1.set_ylim([0,20])
        #self.ax1.imshow(frame_bar) 
        #xi = cv2.imread('icon.png')
        #xi = cv2.resize(xi, (100,5))
        
        #self.ax.set_zlim([-0.5,0.5])
        self.ax1.plot([1,2,3],[4,5,6],'y',label=self.data.values[0,2])
        self.ax1.plot([1,2,3],[4,5,6],'r',label=self.data.values[0,3])
        #self.ax1.plot(data[:,0],data[:,3]+0.1,'g',label=self.data.values[0,4])
        self.ax1.plot([1,2,3],[4,5,6],'g',label=self.data.values[0,4])

        self.ax1.plot([0,1] ,[1,1],'k')
        self.ax1.plot([0,1] ,[1,1],'k')
        

        self.ax1.set_xlim([20,86])       

        self.ax1.plot([self.data.values[1,1],self.data.values[1,1]],[0,20],'k',linewidth=2.0)   
        
  
        start, end = self.ax1.get_xlim()
        self.ax1.xaxis.set_ticks([])        
        #self.ax1.legend(loc='best',  framealpha=0.1,ncol=3)
  
        
        self.ui.bottomImage.canvas.draw()

    def startButtonPressed(self):         
        
        if self.isthreadActive:
            return             
                     

        self.ui.startButton.setEnabled(False)
        print(len(proc_frames))

        if self.ui.timeComboBox.currentIndex()==0:
            self.timer = perpetualTimer(1.0/self.fps,self.updateFrame)
            self.timer.start()
        else:
            self.timer=None
        
        self.ui.pauseButton.setEnabled(True)
        self.isthreadActive=True

    def pauseButtonPressed(self):        

         if not self.isthreadActive:
            return 
         self.ui.startButton.setEnabled(True)         
         self.ui.pauseButton.setEnabled(False)
         if not self.timer is None:
            self.timer.cancel()
         self.isthreadActive=False