class MyWindow(QMainWindow):

    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setInputStrings()
        self.ui.buttonCheck.clicked.connect(self.clickMethod)

    def setInputStrings(self):
        if self.ui.boxCaseSensitivity.isChecked():
            self.inputMatrix = self.ui.inputFieldMatrix.toPlainText()
            self.inputWord = self.ui.inputFieldKeyword.text()
        else:
            self.inputMatrix = self.ui.inputFieldMatrix.toPlainText().upper()
            self.inputWord = self.ui.inputFieldKeyword.text().upper()

    def clickMethod(self):
        self.setInputStrings()
        myMatrix = LetterMatrix(self.inputMatrix)
        if myMatrix.correctInput():
            wordAppearances = str(myMatrix.totalWordAppearances(self.inputWord))
            self.ui.labelOutput.setText("Das Wort wurde " + wordAppearances + " mal gefunden")
        else:
            self.ui.labelOutput.setText("Ungültige Eingabe")
Exemple #2
0
def main():
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()

    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    windowStyle.styles.dark(app)
    mw = windowStyle.window.ModernWindow(MainWindow)
    mw.setWindowTitle("Volume Buddy")

    mw.show()

    app.exec_()
Exemple #3
0
class mywindow(QtWidgets.QMainWindow):
    source = ""
    target = ""

    CURENT = 0

    def __init__(self):
        super(mywindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        #self.setAcceptDrops(True)
        #print(app.arguments())
        mywindow.source = app.arguments()[1]
        #self.ui.comboBox.addItem(app.arguments()[1])
        mywindow.target = r"\\192.168.1.170\мах"
        self.statusBar().showMessage(mywindow.target + " to " +
                                     mywindow.source)
        self.ui.Send.clicked.connect(self.SendF)

        self.ui.Cancel.clicked.connect(self.CancelF)

    def SendF(self):

        #proc = subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        #proc.wait()
        #res = proc.communicate()
        #shutil.copy(mywindow.source.replace('\\','\\'), mywindow.target.replace('\\','\\'))

        #self.statusBar().showMessage(mywindow.source + " to " + mywindow.target )
        try:
            os.system(
                'C:\\Windows\\robocopy.exe /y "{source}" "{target}" > nul'.
                format(source=mywindow.source, target=mywindow.target))
            #proc = subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        except IOError as e:
            print("Unable to copy file. %s" % e)
            exit(1)
        except:
            print("Unexpected error:", sys.exc_info())
            exit(1)
        #
        self.statusBar().showMessage("oooo")

    def CancelF(self):
        print("Exit")
        sys.exit()
Exemple #4
0
class Pencere(QMainWindow):

    def __init__(self):
        super().__init__()

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ip   = ""
        self.port = ""
        self.link = "http://aargin.com/"

    def siteyeGit_A(self):
        # Proxyyi siteden çektik, ip ve portu aldık
        # 1 https://gimmeproxy.com/api/getProxy
        # 2 https://api.getproxylist.com/proxy
        proxyCek = requests.get("https://api.getproxylist.com/proxy")
        self.ip,self.port = proxyCek.json()['ip'], str(proxyCek.json()['port'])

        self.ui.lblIp.setText("IP : "+self.ip)
        self.ui.lblPort.setText("PORT : "+self.port)
        self.ui.lblApiSite.setText("API : https://api.getproxylist.com/proxy")

        proxyAyarla(self.ip,self.port,self.link)

    def siteyeGit_M(self):
        proxyAyarla(self.ip,self.port,self.link)

    def getIp(self, ip):
        self.ip = ip
    
    def getPort(self, port):
        self.port = port
    
    def getLink1(self, link):
        self.link = link
    
    def getLink2(self, link):
        self.link = link
Exemple #5
0
class MyWork(QtWidgets.QMainWindow):
    def __init__(self):
        super(MyWork, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)  #Calls GUI.py, loads the GUI
        self.show()
class ApplicationWindow(QtWidgets.QMainWindow):
    flag = 0

    def __init__(self):
        super(ApplicationWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.actionOpen_Image.triggered.connect(self.OpenImage)
        self.ui.Combo1.currentTextChanged.connect(self.ChooseOperation)
        self.ui.comboBox_2.currentTextChanged.connect(self.KSpace)
        self.ui.comboBox.currentTextChanged.connect(self.Gradients)
        self.ui.Combo1.setCurrentIndex(0)
        self.widgets = [
            self.ui.InputImage1, self.ui.FourierInput1, self.ui.KSpace
        ]
        for i in range(len(self.widgets)):
            self.widgets[i].ui.histogram.hide()
            self.widgets[i].ui.roiBtn.hide()
            self.widgets[i].ui.menuBtn.hide()
            self.widgets[i].ui.roiPlot.hide()
        self.pen1 = pg.mkPen(color=(255, 0, 0))
        self.pen2 = pg.mkPen(color=(0, 0, 255))
        self.ui.pushButton.clicked.connect(self.ShowGraph)

    def ShowGraph(self):
        rand_Bz = np.random.randint(-3, 4, 20)
        const_Bx = [0] * 20
        const_By = [0] * 20
        const_Bz = [2] * 20
        nonUn_Bz = rand_Bz + const_Bz

        self.ui.withx.clear()
        self.ui.withy.clear()
        self.ui.withz.clear()

        self.ui.withz.plotItem.plot(nonUn_Bz, pen=self.pen1)
        self.ui.withz.setLabel('left', 'B', units='Tesla')
        self.ui.withz.setLabel('bottom', 'Z-axis')
        self.ui.withx.plotItem.plot(const_Bx, pen=self.pen2)
        self.ui.withx.setLabel('left', 'B', units='Tesla')
        self.ui.withx.setLabel('bottom', 'X-axis')
        self.ui.withy.plotItem.plot(const_By, pen=self.pen2)
        self.ui.withy.setLabel('left', 'B', units='Tesla')
        self.ui.withy.setLabel('bottom', 'Y-axis')

    def Gradients(self):
        var = np.arange(-1, 1, 0.1)
        if (str(self.ui.comboBox.currentText())) == 'Gradient Effect':
            print('Choose prope Gradient Coil')
        elif (str(self.ui.comboBox.currentText())) == 'Slice Selection':
            const_Bx = [0] * 20
            const_BxG = const_Bx + var
            self.ui.withx.clear()
            self.ui.withx.plotItem.plot(const_BxG, pen=self.pen2)
        elif (str(self.ui.comboBox.currentText())) == 'Phase Encoding':
            const_By = [0] * 20
            const_ByG = const_By + var
            self.ui.withy.clear()
            self.ui.withy.plotItem.plot(const_ByG, pen=self.pen2)
        elif (str(self.ui.comboBox.currentText())) == 'Frequency Encoding':
            const_Bz = [2] * 20
            rand_Bz = np.random.randint(-3, 4, 20)
            nonUn_Bz = rand_Bz + const_Bz
            const_BzG = nonUn_Bz + var
            self.ui.withz.clear()
            self.ui.withz.plotItem.plot(const_BzG, pen=self.pen1)

    def OpenImage(self):
        self.filePath = QtWidgets.QFileDialog.getOpenFileName(
            None, 'Open file',
            'F:\25-9\Downloads\talta tebya\Second Semester\DSP\Task2 Equalizer\TASK 2'
        )
        self.image = cv.cvtColor(cv.imread(self.filePath[0]),
                                 cv.COLOR_BGR2GRAY)
        self.ui.InputImage1.show()
        self.ui.InputImage1.setImage(self.image.T)
        self.flag = 1
        self.dft = np.fft.fft2(self.image)
        self.real = np.real(self.dft)
        self.imaginary = np.imag(self.dft)
        self.magnitude = np.abs(self.dft)
        self.phase = np.angle(self.dft)

        #K-Space Image
        self.fourier = np.fft.fft2(self.image)
        self.fourier_shift = np.fft.fftshift(self.fourier)
        self.k = np.abs(20 * np.log10(self.fourier_shift))

        #Gibb's ringing
        self.err1 = self.fourier_shift[:, 112:112 + 32]
        self.img_back1 = np.abs(np.fft.ifft2(self.err1, s=[256, 256]))

        #Ghosting
        self.err2 = self.fourier_shift.copy()
        self.err2[:, ::2] = 0.8 * self.err2[:, ::2]
        self.img_back2 = np.abs(np.fft.ifft2(self.err2))

        #T2* blurring
        self.T2star = 20  # milliseconds
        self.Ttotal = 100  # time it takes to "read" k-space
        self.N = self.fourier_shift.shape[0]  # number of pixels
        self.err3 = self.fourier_shift.copy()
        for i in range(self.err3.shape[1]):
            self.err3[:, i] = self.err3[:, i] * np.exp(
                -np.linspace(0, self.Ttotal, self.N) / self.T2star)
        self.img_back3 = np.abs(np.fft.ifft2(self.err3))
        plt.imshow(self.img_back3, cmap='gray')

    def ChooseOperation(self):
        if (str(self.ui.Combo1.currentText())) == 'FT Magnitude':
            if (self.flag == 0):
                msg = QMessageBox()
                msg.setWindowTitle("Warning")
                msg.setText("Please,choose image first")
                msg.setIcon(QMessageBox.Warning)
                x = msg.exec_()
            else:
                self.ui.FourierInput1.show()
                self.ui.FourierInput1.setImage(
                    np.fft.fftshift(20 * np.log(self.magnitude.T)))
        if (str(self.ui.Combo1.currentText())) == 'FT Phase':
            if (self.flag == 0):
                msg = QMessageBox()
                msg.setWindowTitle("Warning")
                msg.setText("Please,choose image first")
                msg.setIcon(QMessageBox.Warning)
                x = msg.exec_()
            else:
                self.ui.FourierInput1.show()
                self.ui.FourierInput1.setImage(self.phase.T)
        if (str(self.ui.Combo1.currentText())) == 'FT Real Component':
            if (self.flag == 0):
                msg = QMessageBox()
                msg.setWindowTitle("Warning")
                msg.setText("Please,choose image first")
                msg.setIcon(QMessageBox.Warning)
                x = msg.exec_()
            else:
                self.ui.FourierInput1.show()
                self.ui.FourierInput1.setImage(20 * np.log(self.real.T))
        if (str(self.ui.Combo1.currentText())) == 'FT Imaginary Component':
            if (self.flag == 0):
                msg = QMessageBox()
                msg.setWindowTitle("Warning")
                msg.setText("Please,choose image first")
                msg.setIcon(QMessageBox.Warning)
                x = msg.exec_()
            else:
                self.ui.FourierInput1.show()
                self.ui.FourierInput1.setImage(self.imaginary.T)
        if (str(self.ui.Combo1.currentText())) == 'Select an Option':
            print('Please select a proper option')

    def KSpace(self):
        if (str(self.ui.comboBox_2.currentText())) == 'Show K-Space Image':
            self.ui.KSpace.show()
            self.ui.KSpace.setImage(self.k.T)
        elif (str(self.ui.comboBox_2.currentText())) == "Show Gibb's Ringing":
            self.ui.KSpace.show()
            self.ui.KSpace.setImage(self.img_back1.T)
            msg = QMessageBox()
            msg.setWindowTitle("Definition")
            msg.setText(
                "Gibb's ringing occurs when the frequencies that are sampled in k-space are not sufficiently high "
            )
            s = msg.exec_()
        elif (str(self.ui.comboBox_2.currentText())) == 'Show Ghosting Effect':
            self.ui.KSpace.show()
            self.ui.KSpace.setImage(self.img_back2.T)
            msg = QMessageBox()
            msg.setWindowTitle("Definition")
            msg.setText(
                "Ghosting happens when even and odd k-space lines are intensity modulated differently"
            )
            s = msg.exec_()
        elif (str(self.ui.comboBox_2.currentText())) == 'Show T2* Blurring':
            self.ui.KSpace.show()
            self.ui.KSpace.setImage(self.img_back3.T)
            msg = QMessageBox()
            msg.setWindowTitle("Definition")
            msg.setText(
                "This particular artefact is due to the fact that when we acquire k-space data, the signal that we base our measurement on decays over time, with a time constant called T2*"
            )
            s = msg.exec_()
        if (str(self.ui.comboBox_2.currentText())) == 'K-Space':
            print('Please select a proper option')
class Mainwindow(QtWidgets.QMainWindow,
                 Ui_MainWindow):  #Ventana principal de la GUI
    def __init__(self, *args, **kwargs):
        #Configuration
        QtWidgets.QMainWindow.__init__(self, *args,
                                       **kwargs)  #Inicializar clases heredadas
        self.ui = Ui_MainWindow()  #Inicializamos la ventanan de la GUI
        self.ui.setupUi(self)
        #Set style
        try:
            self.real_path = os.path.dirname(os.path.abspath(__file__))
            with open(self.real_path + '/GUI_style.css') as f:
                self.setStyleSheet(f.read())
        except:
            self.real_path = os.path.dirname(sys.executable)
            with open(self.real_path + '/GUI_style.css') as f:
                self.setStyleSheet(f.read())
        #Arrow
        icon = QtGui.QIcon()
        arrow = self.real_path + '/Arrow.jpg'
        icon.addPixmap(QtGui.QPixmap(arrow), QtGui.QIcon.Normal,
                       QtGui.QIcon.Off)
        icon.addPixmap(QtGui.QPixmap(arrow), QtGui.QIcon.Normal,
                       QtGui.QIcon.On)
        self.ui.toolButton_arrow.setIcon(icon)

        #Properties
        self.main_dir = ''
        self.files = []
        self.files_order = []
        self.files_f = []
        self.filter = ["Python (*.py)", "Fortran files (*.f90)"]
        self.fcomments = 'before'
        self.terminal = True
        self.lib = ''
        self.new_folder = ''
        self.folder_path = ''
        self.interface = ''
        self.py_interface = ''
        self.module_list = []
        self.window_fmodule = ffiles.Window_fmodule(self_fparser=self)
        self.window_options = ffiles.Window_options(self_fparser=self)
        self.terminal_text = ffiles.Terminal(self_fparser=self)
        self.makefile = make.Makefile(self_fparser=self)
        self.ui.actionOpen_Directory.setShortcut("Ctrl+O")
        self.ui.actionOpen_Files.setShortcut("Ctrl+F")
        self.ui.actionOptions.setShortcut("Ctrl+T")
        self.ui.actionClear.setShortcut("Ctrl+W")

        #Connect signals
        #Use .connect(lambda: function(args)) to send extra arguments through the function
        self.ui.menuFile.triggered[QtWidgets.QAction].connect(self.action)
        self.ui.toolButton_arrow.clicked.connect(
            lambda: ffiles.select_ffiles(self))
        self.ui.pushButton_fparser.clicked.connect(
            lambda: ffiles.fortran_parser(self))
        # self.ui.combobox.signal.connect(lambda: make.function(self.ui,self.makefile))
        #self.ui.pushButton_makeOK.clicked.connect(lambda: make.selectOS(self.ui))
        self.ui.comboBox_makeFC.activated.connect(self.makefile.fcompiler)
        self.ui.pushButton_searchFC.clicked.connect(self.makefile.searchFC)
        self.ui.toolButton_lib.clicked.connect(self.makefile.searchLib)
        #self.ui.pushButton_makeOK.clicked.connect(self.makefile.properties)
        self.ui.pushButton_makeOK.clicked.connect(self.makefile.runmake)

    def action(self, selected_action):
        if selected_action.text() == 'Open Files':
            ffiles.open_files(self)
        elif selected_action.text() == 'Open Folder':
            ffiles.open_folder(self)
        elif selected_action.text() == 'Options':
            ffiles.select_options(self)
        elif selected_action.text() == 'Clear':
            ffiles.clear(self)
Exemple #8
0
class StartQT4(QtGui.QMainWindow): ### generated class
    mcu_com = communication.MCUcomm()

    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        ### link the PyQt generated file to a specific method (methods are defined below)###
        ##################<Buttons>#####################################################################
        self.ui.pushButton_connect.clicked.connect(self.connect)
        self.ui.pushButton_disconnect.clicked.connect(self.disconnect)

        self.ui.pushButton_ventilationFanON.clicked.connect(self.ventilationFanON)
        self.ui.pushButton_ventilationFanOFF.clicked.connect(self.ventilationFanOFF)
        self.ui.pushButton_circulationFanON.clicked.connect(self.circulationFanON)
        self.ui.pushButton_circulationFanOFF.clicked.connect(self.circulationFanOFF)
        self.ui.pushButton_panelLightON.clicked.connect(self.panelLightON)
        self.ui.pushButton_panelLightOFF.clicked.connect(self.panelLightOFF)
        self.ui.pushButton_humidifierON.clicked.connect(self.humidifierON)
        self.ui.pushButton_humidifierOFF.clicked.connect(self.humidifierOFF)

        self.ui.pushButton_growLightON.clicked.connect(self.growLightON)
        self.ui.pushButton_growLightOFF.clicked.connect(self.growLightOFF)
        self.ui.pushButton_heaterON.clicked.connect(self.heaterON)
        self.ui.pushButton_heaterOFF.clicked.connect(self.heaterOFF)
        self.ui.pushButton_waterPumpON.clicked.connect(self.waterPumpON)
        self.ui.pushButton_waterPumpOFF.clicked.connect(self.waterPumpOFF)
        self.ui.pushButton_airPumpON.clicked.connect(self.airPumpON)
        self.ui.pushButton_airPumpOFF.clicked.connect(self.airPumpOFF)
        ##################</Buttons>####################################################################

    #############<Methods_for_buttons>####################################################
    def connect(self):
        self.mcu_com.openMCU(str(self.ui.lineEdit.text()))
        time.sleep(2) # wait until arduino's bootloader done loading (arduino tend to auto restart each time new connection is made)
        self.periodic_sampling()

    def disconnect(self):
        self.mcu_com.closeMCU()

    def ventilationFanON(self):
        self.mcu_com.ventilationFanON()

    def ventilationFanOFF(self):
        self.mcu_com.ventilationFanOFF()

    def circulationFanON(self):
        self.mcu_com.circulationFanON()

    def circulationFanOFF(self):
        self.mcu_com.circulationFanOFF()

    def panelLightON(self):
        self.mcu_com.panelLightON()

    def panelLightOFF(self):
        self.mcu_com.panelLightOFF()

    def humidifierON(self):
        self.mcu_com.humidifierON()

    def humidifierOFF(self):
        self.mcu_com.humidifierOFF()

    def growLightON(self):
        self.mcu_com.growLightON()

    def growLightOFF(self):
        self.mcu_com.growLightOFF()

    def heaterON(self):
        self.mcu_com.heaterON()

    def heaterOFF(self):
        self.mcu_com.heaterOFF()

    def waterPumpON(self):
        self.mcu_com.waterPumpON()

    def waterPumpOFF(self):
        self.mcu_com.waterPumpOFF()

    def airPumpON(self):
        self.mcu_com.airPumpON()

    def airPumpOFF(self):
        self.mcu_com.airPumpOFF()
    #############</Methods_for_buttons>####################################################

###<display_stuffs>###
    def updateDisplays(self, a, b, c, d, e, f, g, h, i, j):
        self.ui.lcdNumber_windowSwitch.display(a)
        self.ui.lcdNumber_shellSwitch.display(b)
        self.ui.lcdNumber_waterTemperature.display(c)
        self.ui.lcdNumber_waterConductivity.display(d)
        self.ui.lcdNumber_waterpH.display(e)
        self.ui.lcdNumber_lightIntensity.display(f)
        self.ui.lcdNumber_lightPAR.display(g)
        self.ui.lcdNumber_airTemperature.display(h)
        self.ui.lcdNumber_airHumidity.display(i)
        self.ui.lcdNumber_airCO2.display(j)
###<display_stuffs>###


#######<thread>###
    def periodic_sampling_scheduler(self):
        if self.mcu_com.mcuStatus() == True:
            threading.Timer(1, self.periodic_sampling).start()  # update displays every one second


    def periodic_sampling(self):
        if self.mcu_com.mcuStatus() == True:
            receivedData = self.mcu_com.getAllSensor()
            splitData = receivedData.split(',')
            a = (splitData[0])
            b = (splitData[1])
            c = (splitData[2])
            d = (splitData[3])
            e = (splitData[4])
            f = (splitData[5])
            g = (splitData[6])
            h = (splitData[7])
            i = (splitData[8])
            j = (splitData[9])
            self.updateDisplays(a, b, c, d, e, f, g, h, i, j)
        self.periodic_sampling_scheduler()
class MyForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.PushButtonAddGold.clicked.connect(self.browse_folder)

    def browse_folder(self):
        app = QtGui.QMainWindow()
        myapp = MyWindow(self)
        myapp.show()

    def choosen(self, factory):

        directory = QtGui.QFileDialog.getOpenFileName(self)
        print(directory)
        f = open(directory)
        l = list(f.readlines())

        instance = factory.create(l)
        #self.graphvizdraw(instance)
        self.qtdraw(instance)

    def graphvizdraw(self, instance):
        d = draw()
        d.drawGraph(instance.edges, instance.tokens)

        label = self.ui.label_picture

        path = os.path.abspath('test-output/round-table.gv.pdf')
        pdf2png.gs_pdf_to_png(path, 70)
        path2 = os.path.abspath('test-output/round-table.gv.png')

        #pixmap = QtGui.QPixmap(path2)
        #label.setPixmap(pixmap)
        myPixmap = QtGui.QPixmap(path2)
       # myScaledPixmap = myPixmap.scaled(label.size())
        label.setPixmap(myPixmap)

        label.show()

    def qtdraw(self, instance):

        pixmap = QtGui.QPixmap(QtCore.QSize(400,400))
        pixmap.fill(QtGui.QColor(200,0,0))
        painter = QtGui.QPainter (pixmap)
        #gradient = QtGui.QLinearGradient(QtCore.QPoint(pixmap.rect().topLeft()),
        #                             QtCore.QPoint(pixmap.rect().bottomLeft()))
        print("painter kész")
        #gradient.setColorAt(0, QtCore.Qt.blue)
        #gradient.setColorAt(0.4, QtCore.Qt.cyan)
        #gradient.setColorAt(1, QtCore.Qt.green)

        #brush = QtGui.QBrush(gradient)
        #painter.fillRect(QtCore.QRectF(0,0,400,400), brush)
        #painter.drawText(QtCore.QRectF(0,0,400,400), QtCore.Qt.AlignCenter,
        #                  "This is az image created with QPainter and QPixmap")

        painter.setBrush(QtGui.QColor(200,200,0))
        painter.setBackground(QtGui.QColor(200,0,0))
        #painter.drawRect(110,15,540,60)
        #painter.drawEllipse(QtCore.QPoint(200, 400), 150, 40)
        painter.drawArc(20,350, 150, 40, 16*0, 16*180)
        del painter
        print("rajzoltam")
        pixmap.save("output.jpg")
        #print("mentve")

        label = self.ui.label_picture
        label.setPixmap(pixmap)
        label.show()
Exemple #10
0
class mywindow(QtWidgets.QMainWindow):
    files = ""

    CURENT = 0

    def __init__(self):
        super(mywindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setAcceptDrops(True)

        self.ui.pushB_Init2.clicked.connect(self.pushB_Init2)
        self.ui.pushB_Init12.clicked.connect(self.pushB_Init12)
        self.ui.pushB_Connect.clicked.connect(self.pushB_Connect)

        self.ui.pushB_Restart.clicked.connect(self.pushB_Restart)

        #self.ui.actionSend.triggered.connect(self.MenuSendClicked)

        #self.ui.label_1.clicked.connect(self.label_1)
        #self.ui.actionExit.triggered.connect(self.MenuExitClicked)
        #self.ui.pushButtonExit.clicked.connect(self.MenuExitClicked)
        #self.ui.pushButton.clicked.connect(self.InsertProg)
        #self.ui.tableWidget.cellClicked[int, int].connect(self.clickedRowColumn)

    def pushB_Init12(self):
        print("pushB_Init12")

        return True

    def pushB_Init2(self):
        print("pushB_Init2")

        return True

    def pushB_Connect(self):
        print("pushB_Connect")
        return True

    def pushB_Restart(self):
        print("pushB_Restart")
        return True

    def label_1(self):
        print("label_1")
        return True

    def dragEnterEvent(self, e):
        if e.mimeData().hasUrls:
            e.accept()
        else:
            e.ignore()

    def dragMoveEvent(self, e):
        if e.mimeData().hasUrls:
            e.accept()
        else:
            e.ignore()

    def dropEvent(self, e):
        f = e.mimeData().urls()
        mywindow.files = f[0].toString()
        print(mywindow.files)
        if mywindow.files[-3:] == "mp4":
            print("кто это?")
Exemple #11
0
class MainWindow(Functionalities):
    def __init__(self, path_to_patient, index_side, interactive_mode):
        self.main_win = QMainWindow()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self.main_win)

        self.path_to_patient = path_to_patient
        self.index_side = int(index_side)
        self.interactive_mode = int(interactive_mode)

        self.rel_folder = self.rel_folder()

        # Add stylesheet
        self.stylesheet_filename = '{}/UX/dark.qss'.format(self.rel_folder)
        self.loadStylesheet(self.stylesheet_filename)

        self.current_file_name = " "

        # call classes
        self.externalNeuronArray = PopUpExternalNeuronArray(self.main_win)
        self.meshRefinement = PopUpMeshRefinement(self.main_win)
        self.cpeActive = PopUpCPEActive(self.main_win)
        self.fullFieldIFFT = PopUpFullFieldIFFT(self.main_win)

        # Initializations
        # Extra Widget Group Show/Hide state
        # self.ui.widget_CPE_Active.hide()
        # self.ui.widget_Global_Rot.hide()
        if self.ui.comboBox_Spectrum_Truncation_Method.currentText(
        ) == 'No Truncation':
            self.ui.widget_Spectrum_Truncation_Method.hide()

        self.ui.stackedWidget.setCurrentIndex(0)
        # self.ui.widget_Name_Prepared_Array.hide()

        # Initial States

        # Signals to slots
        # Test function
        self.ui.checkBox_Voxel_orr_DTI.stateChanged.connect(
            lambda: self.selection_list(self.ui.checkBox_Voxel_orr_DTI))
        self.ui.checkBox_Init_Neuron_Model_Ready.stateChanged.connect(
            lambda: self.selection_list(self.ui.
                                        checkBox_Init_Neuron_Model_Ready))
        self.ui.checkBox_Init_Mesh_Ready.stateChanged.connect(
            lambda: self.selection_list(self.ui.checkBox_Init_Mesh_Ready))
        self.ui.checkBox_Adjusted_Neuron_Model_Ready.stateChanged.connect(
            lambda: self.selection_list(self.ui.
                                        checkBox_Adjusted_Neuron_Model_Ready))
        self.ui.checkBox_Signal_Generation_Ready.stateChanged.connect(
            lambda: self.selection_list(self.ui.
                                        checkBox_Signal_Generation_Ready))
        self.ui.checkBox_CSF_Mesh_Ready.stateChanged.connect(
            lambda: self.selection_list(self.ui.checkBox_CSF_Mesh_Ready))
        self.ui.checkBox_Adapted_Mesh_Ready.stateChanged.connect(
            lambda: self.selection_list(self.ui.checkBox_Adapted_Mesh_Ready))
        self.ui.checkBox_Parallel_Computing_Ready.stateChanged.connect(
            lambda: self.selection_list(self.ui.
                                        checkBox_Parallel_Computing_Ready))
        self.ui.checkBox_Parallel_Computing_Interrupted.stateChanged.connect(
            lambda: self.selection_list(self.ui.
                                        checkBox_Parallel_Computing_Ready))
        self.ui.checkBox_IFFT_Ready.stateChanged.connect(
            lambda: self.selection_list(self.ui.checkBox_IFFT_Ready))

        # Page Change
        self.ui.treeWidget_Project_Browser.itemSelectionChanged.connect(
            lambda: self.qtree_item())
        self.ui.treeWidget_Project_Browser.topLevelItem(0).setSelected(True)

        # CheckBox signal
        self.ui.checkBox_Parallel_Computing_Interrupted.stateChanged.connect(
            lambda: self.connected_check_boxes(
                self.ui.checkBox_Parallel_Computing_Interrupted, self.ui.
                checkBox_Parallel_Computing_Ready))
        self.ui.checkBox_Parallel_Computing_Ready.stateChanged.connect(
            lambda: self.connected_check_boxes(
                self.ui.checkBox_Parallel_Computing_Ready, self.ui.
                checkBox_Parallel_Computing_Interrupted))
        self.ui.checkBox_Current_Control.stateChanged.connect(
            lambda: self.disable_widget(self.ui.checkBox_Current_Control, self.
                                        ui.checkBox_CPE_Active))

        self.ui.checkBox_Neuron_Model_Array_Prepared.stateChanged.connect(
            lambda: self.show_menu_item_on_checkbox_click(
                self.ui.checkBox_Neuron_Model_Array_Prepared, self.ui.
                widget_Name_Of_External_Neuron_Array))
        self.ui.checkBox_Neuron_Model_Array_Prepared.stateChanged.connect(
            lambda: self.show_menu_item_on_checkbox_click(
                self.ui.checkBox_Neuron_Model_Array_Prepared, self.ui.
                widget_Name_Of_External_Neuron_Array_2))
        self.ui.checkBox_Neuron_Model_Array_Prepared.stateChanged.connect(
            lambda: self.show_menu_item_on_checkbox_click(
                self.ui.checkBox_Neuron_Model_Array_Prepared, self.ui.
                widget_Name_Of_External_Neuron_Array_3))
        # PopUps
        self.ui.checkBox_Neuron_Model_Array_Prepared.stateChanged.connect(
            lambda: self.pop_up_reverse(
                self.ui.checkBox_Neuron_Model_Array_Prepared, self.
                externalNeuronArray, self.main_win))
        self.ui.checkBox_Skip_Mesh_Refinement.stateChanged.connect(
            lambda: self.pop_up_reverse(self.ui.checkBox_Skip_Mesh_Refinement,
                                        self.meshRefinement, self.main_win))
        self.ui.checkBox_CPE_Active.stateChanged.connect(lambda: self.pop_up(
            self.ui.checkBox_CPE_Active, self.cpeActive, self.main_win))
        self.ui.checkBox_Full_Field_IFFT.stateChanged.connect(
            lambda: self.pop_up(self.ui.checkBox_Full_Field_IFFT, self.
                                fullFieldIFFT, self.main_win))

        # Signal to show hidden menu items
        # self.ui.lineEdit_Brain_Shape.editingFinished.connect(lambda: self.brain_shape_name_control())
        # self.ui.lineEdit_Brain_Shape.textEdited.connect(lambda: self.brain_shape_name_control())
        # self.ui.lineEdit_Brain_Shape.textChanged.connect(lambda: self.brain_shape_name_control())

        self.ui.lineEdit_Approximating_Dimensions.editingFinished.connect(
            lambda: self.check_lineedit_if_list_entered(
                self.ui.lineEdit_Approximating_Dimensions.text(), self.ui.
                lineEdit_Approximating_Dimensions))

        self.ui.lineEdit_Approx_Geometry_Center.editingFinished.connect(
            lambda: self.check_lineedit_if_list_entered(
                self.ui.lineEdit_Approx_Geometry_Center.text(), self.ui.
                lineEdit_Approx_Geometry_Center))

        self.ui.comboBox_Spectrum_Truncation_Method.currentIndexChanged.connect(
            lambda: self.show_menu_item_on_combobox_state_change(
                "No Truncation", self.ui.comboBox_Spectrum_Truncation_Method,
                self.ui.widget_Spectrum_Truncation_Method))
        self.ui.comboBox_Spectrum_Truncation_Method.currentIndexChanged.connect(
            lambda: self.spectrum_truncation_method_combobox_control())
        # self.ui.checkBox_Neuron_Model_Array_Prepared.stateChanged.connect(lambda: self.hide_menu_item_on_checkbox_click(self.ui.checkBox_Neuron_Model_Array_Prepared, self.externalNeuronArray.ui.widget_Global_Rot))
        self.ui.checkBox_Dimensions_From_MRI.stateChanged.connect(
            lambda: self.hide_menu_item_on_checkbox_click(
                self.ui.checkBox_Dimensions_From_MRI, self.ui.
                widget_Approximating_Dimensions))
        self.ui.checkBox_Dimensions_From_MRI.stateChanged.connect(
            lambda: self.hide_menu_item_on_checkbox_click(
                self.ui.checkBox_Dimensions_From_MRI, self.ui.
                widget_Approximating_Dimensions_2))
        self.ui.checkBox_Dimensions_From_MRI.stateChanged.connect(
            lambda: self.hide_menu_item_on_checkbox_click(
                self.ui.checkBox_Dimensions_From_MRI, self.ui.
                widget_Approximating_Dimensions_3))

        self.ui.checkBox_Approx_Geom_Centered_On_MRI.stateChanged.connect(
            lambda: self.hide_menu_item_on_checkbox_click(
                self.ui.checkBox_Approx_Geom_Centered_On_MRI, self.ui.
                widget_Approx_Geometry_Center))
        self.ui.checkBox_Approx_Geom_Centered_On_MRI.stateChanged.connect(
            lambda: self.hide_menu_item_on_checkbox_click(
                self.ui.checkBox_Approx_Geom_Centered_On_MRI, self.ui.
                widget_Approx_Geometry_Center_2))
        self.ui.checkBox_Approx_Geom_Centered_On_MRI.stateChanged.connect(
            lambda: self.hide_menu_item_on_checkbox_click(
                self.ui.checkBox_Approx_Geom_Centered_On_MRI, self.ui.
                widget_Approx_Geometry_Center_3))
        self.ui.checkBox_Approx_Geom_Centered_On_MRI.stateChanged.connect(
            lambda: self.ui.lineEdit_Approx_Geometry_Center.setText('0'))

        # LineEdit to List functions
        self.ui.lineEdit_N_Ranvier.editingFinished.connect(
            lambda: self.check_lineedit_if_list_entered_absolute(
                self.ui.lineEdit_N_Ranvier.text(), self.ui.lineEdit_N_Ranvier))
        self.ui.lineEdit_Fiber_Diameter.editingFinished.connect(
            lambda: self.check_lineedit_if_list_entered_absolute(
                self.ui.lineEdit_Fiber_Diameter.text(), self.ui.
                lineEdit_Fiber_Diameter))
        self.ui.lineEdit_Phi_Vector.editingFinished.connect(
            lambda: self.check_lineedit_if_list_entered(
                self.ui.lineEdit_Phi_Vector.text(), self.ui.lineEdit_Phi_Vector
            ))
        self.ui.lineEdit_Truncation_Parameter.editingFinished.connect(
            lambda: self.check_lineedit_if_value_entered(
                self.ui.lineEdit_Truncation_Parameter.text(), self.ui.
                lineEdit_Truncation_Parameter))

        # Load last saved dictionary
        self.load_last_save_state()

        # modify me!!!!!!!!!!!!!!
        self.dict_list = [
            "pop_up_control/dictionaries/dict_cpe_active.py",
            "pop_up_control/dictionaries/dict_external_neuron_array.py",
            "pop_up_control/dictionaries/dict_full_field_ifft.py",
            "pop_up_control/dictionaries/dict_mesh_refinement.py"
        ]

        # Display Images
        self.ui.pushButton_Placed_Neurons.clicked.connect(lambda: self.display(
            self.ui.label_Image_Placed_Neurons, self.path_to_patient +
            '/Images/Axon_connections.png', self.path_to_patient +
            '/Images/Placed_neurons.png'))

        self.ui.pushButton_Signal_Recovered.clicked.connect(
            lambda: self.display(
                self.ui.label_Image_Signal_Recovered, self.path_to_patient +
                '/Images/Signal_recovered_shape.png', self.path_to_patient +
                '/Images/Signal_recovered_shape.png'))
        self.ui.pushButton_CSF_Full_Refinement.clicked.connect(
            lambda: self.display(
                self.ui.label_Image_CSF_Full_Refinement, self.path_to_patient +
                '/Images/CSF_full_refinement.png', self.path_to_patient +
                '/Images/CSF_full_refinement.png'))
        self.ui.pushButton_Adapted_Mesh.clicked.connect(lambda: self.display(
            self.ui.label_Image_Adapted_Mesh, self.path_to_patient +
            '/Images/Adapted_mesh.png', self.path_to_patient +
            '/Images/Adapted_mesh.png'))
        self.ui.pushButton_Signal_Convoluted_1st_Point.clicked.connect(
            lambda: self.display(
                self.ui.label_Image_Signal_Convoluted_1st_Point, self.
                path_to_patient + '/Images/Signal_convoluted_1st_point.png',
                self.path_to_patient +
                '/Images/Signal_convoluted_1st_point.png'))
        self.ui.pushButton_Axon_Activation.clicked.connect(
            lambda: self.display(
                self.ui.label_Image_Axon_Activation, self.path_to_patient +
                '/Images/Axon_activation.png', self.path_to_patient +
                '/Images/Activated_neurons.png'))

        # Load/Save/Reset/Run to dictionary
        self.ui.pushButton_Run.clicked.connect(lambda: self.dict_write(
            self.output_dict(), self.current_file_name))
        # Modification to run a subprocess on another thread when Run button is clicked.
        self.ui.pushButton_Run.clicked.connect(lambda: self.run_thread())

        self.ui.pushButton_SaveAs.clicked.connect(lambda: self.save_as())
        self.ui.pushButton_Load.clicked.connect(lambda: self.load_dict())
        self.ui.pushButton_Reset.clicked.connect(lambda: self.reset_state())

    def show(self):
        self.main_win.show()
        if not self.interactive_mode:
            self.save_as(
                os.path.join(os.path.abspath(os.getcwd()), 'GUI_inp_dict.py'))
            self.run_thread()

    def run_command(self):
        """The subprocess takes the terminal command as a list."""
        #put a command for the "Run" button in the GUI. The command depends on whether you use Docker or not. In the former case, you have two different options: as a sudo user or not. Check the tutorial.
        dir_code = os.path.dirname(
            os.getcwd())  # OSS-DBS folder to be mount, NOT OSS_platform folder
        if sys.platform == 'linux':
            if os.environ.get('SINGULARITY_NAME'):
                output = subprocess.run(['python3', 'Launcher_OSS_lite.py'])
            else:
                output = subprocess.run([
                    'docker', 'run', '-e', 'PATIENTDIR', '--volume',
                    dir_code + ':/opt/OSS-DBS', '--volume',
                    self.path_to_patient + ':/opt/Patient', '-it', '--rm',
                    'custom_oss-dbs', 'python3', 'Launcher_OSS_lite.py'
                ])  #
        elif sys.platform == 'darwin' or sys.platform == 'win32':
            output = subprocess.run([
                'docker', 'run', '-e', 'PATIENTDIR', '--volume',
                dir_code + ':/opt/OSS-DBS', '--volume',
                self.path_to_patient + ':/opt/Patient', '-it', '--rm',
                'ningfei/oss-dbs', 'python3', 'Launcher_OSS_lite.py'
            ])
        else:
            print("The system's OS does not support OSS-DBS")
            raise SystemExit

        # does not work on macOS
        #out2 = subprocess.run(['docker','logs','OSS_container'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)  #
        #stdout_as_str = out2.stdout.decode("utf-8")

        #text_file = open(self.path_to_patient+"/Docker_log.txt", "wt")
        #n = text_file.write(stdout_as_str)
        #text_file.close()

        #print(output.returncode)

        #if not os.path.exists(self.path_to_patient+'/success.txt'):
        #    subprocess.call(['touch', self.path_to_patient+'/fail.txt'])
        #    print("Error occurred, check the terminal")
        #else:
        #    print("Simulation is completed")
        #    self.closeWindow()

        if self.index_side == 0:
            if not os.path.exists(self.path_to_patient + '/success_rh.txt'):
                subprocess.call(
                    ['touch', self.path_to_patient + '/fail_rh.txt'])
                print("Error occurred when simulating rh, check the terminal")
            else:
                print("Simulation is completed")
        else:
            if not os.path.exists(self.path_to_patient + '/success_lh.txt'):
                subprocess.call(
                    ['touch', self.path_to_patient + '/fail_lh.txt'])
                print("Error occurred when simulating lh, check the terminal")
            else:
                print("Simulation is completed")

        self.closeWindow()
        # the commands below work only with a properly installed Paraview (supporting from paraview.simple import *)

        #print(self.path_to_patient)
        #prepare screenshots
        #we need to insert the correct path here (use the already written python scripts)
        #with open(os.devnull, 'w') as FNULL: subprocess.call(['python','Visualization_files/Paraview_csv_neurons.py',self.path_to_patient], shell=True, stdout=FNULL, stderr=subprocess.STDOUT)

        # try:
        #     subprocess.run(['python','Visualization_files/Paraview_csv_neurons.py',self.path_to_patient])
        # except:
        #     subprocess.run(['python','Visualization_files/Paraview_connections_processed.py',self.path_to_patient])

        # try:
        #     subprocess.run(['python','Visualization_files/Paraview_csv_activation.py.py',self.path_to_patient])
        # except:
        #     subprocess.run(['python','Visualization_files/Paraview_connections_activation.py',self.path_to_patient])

        # subprocess.run(['python','Visualization_files/Paraview_CSFref.py',self.path_to_patient])
        # subprocess.run(['python','Visualization_files/Paraview_adapted.py',self.path_to_patient])

        #subprocess.run(['python','Visualization_files/Paraview_csv_neurons.py',self.path_to_patient])

        #subprocess.run(['xterm','-hold','-e','ls'])
        #command_to_run='gnome-terminal -- bash -c "python3 Launcher_OSS_lite.py && read"'
        #command_to_run='xterm -hold -e python3 Launcher_OSS_lite.py'
        #subprocess.run(['xterm','-hold','-e','python3','Launcher_OSS_lite.py'])
        #subprocess.run(['gnome-terminal','--execute','python3', 'Launcher_OSS_lite.py'])#
        #substitute tilda
        #subprocess.run([
        """add the command you use to run OSS-DBS here (as shown above)"""

    def run_thread(self):
        t = Thread(target=self.run_command)
        t.start()

    # Call to tree Item
    def qtree_item(self):
        if self.ui.treeWidget_Project_Browser.topLevelItem(0).isSelected():
            self.click_change_page(0)
        elif self.ui.treeWidget_Project_Browser.topLevelItem(1).isSelected():
            self.click_change_page(1)
        elif self.ui.treeWidget_Project_Browser.topLevelItem(2).isSelected():
            self.click_change_page(2)
        elif self.ui.treeWidget_Project_Browser.topLevelItem(5).isSelected():
            self.click_change_page(3)
        elif self.ui.treeWidget_Project_Browser.topLevelItem(6).isSelected():
            self.click_change_page(4)
        elif self.ui.treeWidget_Project_Browser.topLevelItem(7).isSelected():
            self.click_change_page(5)
        elif self.ui.treeWidget_Project_Browser.topLevelItem(8).isSelected():
            self.click_change_page(6)

    def click_change_page(self, page_num):
        self.ui.stackedWidget.setCurrentIndex(page_num)

    def spectrum_truncation_method_combobox_control(self):

        if self.ui.comboBox_Spectrum_Truncation_Method.currentText(
        ) == 'Octave Band Method':
            self.ui.widget_STM_1.show()
            self.ui.widget_STM_2.show()
            self.ui.widget_STM_3.show()
            self.ui.widget_STM_4.hide()
            self.ui.widget_STM_5.hide()
            self.ui.widget_STM_6.hide()
            self.ui.widget_Truncate_Already_Obtained_Full_Solution.hide()
            self.ui.widget_Truncate_Already_Obtained_Full_Solution_2.hide()
            self.ui.widget_Truncate_Already_Obtained_Full_Solution_3.hide()
        else:
            self.ui.widget_STM_1.hide()
            self.ui.widget_STM_2.hide()
            self.ui.widget_STM_3.hide()
            self.ui.widget_STM_4.show()
            self.ui.widget_STM_5.show()
            self.ui.widget_STM_6.show()
            self.ui.widget_Truncate_Already_Obtained_Full_Solution.show()
            self.ui.widget_Truncate_Already_Obtained_Full_Solution_2.show()
            self.ui.widget_Truncate_Already_Obtained_Full_Solution_3.show()

    # Selection list
    def selection_list(self, checkbox):
        vmri = self.ui.checkBox_Voxel_orr_MRI
        vdti = self.ui.checkBox_Voxel_orr_DTI
        inmr = self.ui.checkBox_Init_Neuron_Model_Ready
        imr = self.ui.checkBox_Init_Mesh_Ready
        anmr = self.ui.checkBox_Adjusted_Neuron_Model_Ready
        sgr = self.ui.checkBox_Signal_Generation_Ready
        cmr = self.ui.checkBox_CSF_Mesh_Ready
        amr = self.ui.checkBox_Adapted_Mesh_Ready
        pcr = self.ui.checkBox_Parallel_Computing_Ready
        pci = self.ui.checkBox_Parallel_Computing_Interrupted
        ifftr = self.ui.checkBox_IFFT_Ready

        full_checkbox_list = [
            vmri, vdti, inmr, anmr, sgr, cmr, amr, pcr, pci, ifftr
        ]

        vdti_L = [vmri]
        inmr_L = [vmri]
        imr_L = [vmri, inmr]
        anmr_L = [vmri, inmr, imr]
        sgr_L = [pcr, pci, ifftr]
        cmr_L = [vmri, inmr, imr, anmr, sgr]
        amr_L = [vmri, inmr, imr, anmr, cmr, sgr]
        pcr_L = [vmri, inmr, imr, anmr, cmr, amr, sgr]
        pci_L = [vmri, inmr, imr, anmr, cmr, amr, sgr]
        ifftr_L = [vmri, inmr, imr, anmr, cmr, amr, sgr, pcr]

        if checkbox == vdti:
            if checkbox.checkState() == 2:
                for x in vdti_L:
                    if x.checkState() == 0:
                        x.setCheckState(2)

        if checkbox == inmr:
            if checkbox.checkState() == 2:
                for x in inmr_L:
                    if x.checkState() == 0:
                        x.setCheckState(2)

        elif checkbox == imr:
            if checkbox.checkState() == 2:
                for x in imr_L:
                    if x.checkState() == 0:
                        x.setCheckState(2)

        elif checkbox == anmr:
            if checkbox.checkState() == 2:
                for x in anmr_L:
                    if x.checkState() == 0:
                        x.setCheckState(2)

        elif checkbox == cmr:
            if checkbox.checkState() == 2:
                for x in cmr_L:
                    if x.checkState() == 0:
                        x.setCheckState(2)

        elif checkbox == amr:
            if checkbox.checkState() == 2:
                for x in amr_L:
                    if x.checkState() == 0:
                        x.setCheckState(2)

        elif checkbox == sgr:
            if checkbox.checkState() == 0:
                for x in sgr_L:
                    x.setCheckState(0)

        elif checkbox == pcr:
            if checkbox.checkState() == 2:
                for x in pcr_L:
                    if x.checkState() == 0:
                        x.setCheckState(2)

        elif checkbox == pci:
            if checkbox.checkState() == 2:
                for x in pci_L:
                    if x.checkState() == 0:
                        x.setCheckState(2)

        elif checkbox == ifftr:
            if checkbox.checkState() == 2:
                pcr.setCheckState(2)
                pci.setCheckState(0)
                for x in ifftr_L:
                    if x.checkState() == 0:
                        x.setCheckState(2)

    def output_dict(self):
        # from pop_up_control.dictionaries import dict_cpe_active, dict_external_neuron_array, dict_full_field_ifft, \
        #     dict_mesh_refinement
        output_dict = Dictionary(self).output_dict()
        output_dict['Stim_side'] = self.index_side
        output_dict['stretch'] = self.stretch

        # # concatenate various dictionaries
        # output_dict.update(dict_cpe_active.d)
        # output_dict.update(dict_external_neuron_array.d)
        # output_dict.update(dict_full_field_ifft.d)
        # output_dict.update(dict_mesh_refinement.d)

        return output_dict

    def dict_write(self, output_dict, filename):

        if os.path.isabs(filename):
            pass
        else:
            filename = '{}/{}'.format(self.rel_folder, filename)

        if " " in filename or "default_dict.py" in filename or "last_save.py" in filename:
            self.save_as()
        else:
            with open(filename, 'w') as test_dict:
                test_dict.write(Header.header)
                test_dict.write("d = {\n")

                for x in output_dict:
                    test_dict.write("    '{}': {},\n".format(
                        x, output_dict[x]))

                # append data from other dicts
                for dict_filename in self.dict_list:
                    dict_filename = '{}/{}'.format(self.rel_folder,
                                                   dict_filename)
                    with open(dict_filename, 'r') as f:
                        content = f.read().split('{')[1].split('}')[0]
                        test_dict.write(content.strip())

                test_dict.write("}\n")

            with open("{}/GUI_tree_files/last_save.py".format(self.rel_folder),
                      'w') as last_save:
                last_save.write("d = {\n")
                for x in output_dict:
                    last_save.write("    '{}': {},\n".format(
                        x, output_dict[x]))
                last_save.write("    }\n")

            if self.interactive_mode:
                self.info(
                    "Run",
                    "Setup state has been written to {}.".format(filename))
            else:
                print("Setup state has been written to {}".format(filename))

    def save_as(self, filename=""):
        if filename == "":
            options = QFileDialog.Options()
            options |= QFileDialog.DontUseNativeDialog
            filename, _ = QFileDialog.getSaveFileName(
                None,
                "Save State",
                "",
                "All Files (*);;Text Files (*.txt)",
                options=options)

        if filename != "":
            filename = self.py_check(filename)
            if "default_dict.py" in filename or "last_save.py" in filename:
                self.info(
                    "Write Forbidden",
                    "Oops, that didn't save! It seems you attempted to write to the default dictionary."
                )
            else:
                with open(filename, 'w') as save_as_dict:
                    save_as_dict.write(Header.header)
                    save_as_dict.write("d = {\n")
                    for x in self.output_dict():
                        save_as_dict.write("    '{}': {},\n".format(
                            x,
                            self.output_dict()[x]))

                    # append data from other dicts
                    for dict_filename in self.dict_list:
                        dict_filename = '{}/{}'.format(self.rel_folder,
                                                       dict_filename)
                        with open(dict_filename, 'r') as f:
                            content = f.read().split('{')[1].split('}')[0]
                            save_as_dict.write(content.strip())

                    save_as_dict.write("}\n")

                with open(
                        "{}/GUI_tree_files/last_save.py".format(
                            self.rel_folder), 'w') as last_save:
                    last_save.write("d = {\n")
                    for x in self.output_dict():
                        last_save.write("    '{}': {},\n".format(
                            x,
                            self.output_dict()[x]))

                    # append data from other dicts
                    for dict_filename in self.dict_list:
                        dict_filename = '{}/{}'.format(self.rel_folder,
                                                       dict_filename)
                        with open(dict_filename, 'r') as f:
                            content = f.read().split('{')[1].split('}')[0]
                            last_save.write(content.strip())

                    last_save.write("}\n")

                if self.interactive_mode:
                    self.info(
                        "Run",
                        "Setup state has been written to {}.".format(filename))
                else:
                    print(
                        "Setup state has been written to {}".format(filename))
                self.set_current_file_name(filename)

    def set_load_state(self, d):
        self.stretch = d['stretch']

        # default choice of processors
        if sys.platform == 'linux':
            physical_cores = os.popen(
                """lscpu -b -p=Core,Socket | grep -v '^#' | sort -u | wc -l"""
            ).read()[:-1]
            d['number_of_processors'] = int(int(physical_cores) *
                                            0.5)  # leave some
            print("Number of cores drawn by default: ",
                  d['number_of_processors'])
        else:
            print("All cores available for Docker will be drawn")

        self.ui.checkBox_Voxel_orr_MRI.setCheckState(
            self.anti_corrector(d['voxel_arr_MRI']))
        self.ui.checkBox_Voxel_orr_DTI.setCheckState(
            ----self.anti_corrector(d['voxel_arr_DTI']))
        self.ui.checkBox_Init_Neuron_Model_Ready.setCheckState(
            self.anti_corrector(d['Init_neuron_model_ready']))
        self.ui.checkBox_Init_Mesh_Ready.setCheckState(
            self.anti_corrector(d['Init_mesh_ready']))
        self.ui.checkBox_Adjusted_Neuron_Model_Ready.setCheckState(
            self.anti_corrector(d['Adjusted_neuron_model_ready']))
        self.ui.checkBox_CSF_Mesh_Ready.setCheckState(
            self.anti_corrector(d['CSF_mesh_ready']))
        self.ui.checkBox_Adapted_Mesh_Ready.setCheckState(
            self.anti_corrector(d['Adapted_mesh_ready']))
        self.ui.checkBox_Signal_Generation_Ready.setCheckState(
            self.anti_corrector(d['signal_generation_ready']))
        self.ui.checkBox_Parallel_Computing_Ready.setCheckState(
            self.anti_corrector(d['Parallel_comp_ready']))
        self.ui.checkBox_Parallel_Computing_Interrupted.setCheckState(
            self.anti_corrector(d['Parallel_comp_interrupted']))
        self.ui.checkBox_IFFT_Ready.setCheckState(
            self.anti_corrector(d['IFFT_ready']))
        self.ui.lineEdit_MRI_Data_Name.setText(d['MRI_data_name'])
        self.ui.checkBox_MRI_m.setCheckState(self.anti_corrector(
            d['MRI_in_m']))
        self.ui.lineEdit_DTI_Data_Name.setText(d['DTI_data_name'])
        self.ui.checkBox_DTI_m.setCheckState(self.anti_corrector(
            d['DTI_in_m']))
        self.ui.doubleSpinBox_CSF_Index.setValue(d['CSF_index'])
        self.ui.doubleSpinBox_WM_Index.setValue(d['WM_index'])
        self.ui.doubleSpinBox_GM_Index.setValue(d['GM_index'])
        self.ui.comboBox_Default_Material.setCurrentIndex(
            d['default_material'] - 1)
        self.ui.comboBox_Electrode_Type.setCurrentText(d['Electrode_type'])
        self.ui.lineEdit_Brain_Shape.setText("{}".format(
            d['Brain_shape_name']))
        # self.ui.doubleSpinBox_X_Length.setValue(d['x_length'])
        # self.ui.doubleSpinBox_Y_Length.setValue(d['y_length'])
        # self.ui.doubleSpinBox_Z_Length.setValue(d['z_length'])
        self.get_lineedit_entry(d['Aprox_geometry_center'],
                                self.ui.lineEdit_Approx_Geometry_Center)
        try:
            self.get_lineedit_entry(d['Approximating_Dimensions'],
                                    self.ui.lineEdit_Approximating_Dimensions)
        except:
            pass

        self.ui.doubleSpinBox_Implantation_Coordinate_X.setValue(
            d['Implantation_coordinate_X'])
        self.ui.doubleSpinBox_Implantation_Coordinate_Y.setValue(
            d['Implantation_coordinate_Y'])
        self.ui.doubleSpinBox_Implantation_Coordinate_Z.setValue(
            d['Implantation_coordinate_Z'])
        self.ui.doubleSpinBox_2nd_Point_On_Lead_X.setValue(
            d['Second_coordinate_X'])
        self.ui.doubleSpinBox_2nd_Point_On_Lead_Y.setValue(
            d['Second_coordinate_Y'])
        self.ui.doubleSpinBox_2nd_Point_On_Lead_Z.setValue(
            d['Second_coordinate_Z'])
        self.ui.doubleSpinBox_Turn_Around_Lead_Axis.setValue(d['Rotation_Z'])
        self.ui.doubleSpinBox_Encapsulation_Thickness.setValue(
            d['encap_thickness'])
        self.ui.comboBox_Encapsulation_Tissue_Type.setCurrentIndex(
            d['encap_tissue_type'] - 1)
        self.ui.doubleSpinBox_Conductivity_Scaling.setValue(
            d['encap_scaling_cond'])
        self.ui.doubleSpinBox_Permittivity_Scaling.setValue(
            d['encap_scaling_perm'])
        self.ui.lineEdit_Pattern_Model_Name.setText("{}".format(
            d['pattern_model_name']))
        try:
            self.ui.comboBox_Axon_Model_Type.setCurrentText("{}".format(
                d['Axon_Model_Type']))
        except:
            pass
        self.ui.lineEdit_Fiber_Diameter.setText("{}".format(d['diam_fib']))
        self.ui.lineEdit_N_Ranvier.setText("{}".format(d['n_Ranvier']))
        self.ui.doubleSpinBox_V_Init.setValue(d['v_init'])
        self.ui.checkBox_Neuron_Model_Array_Prepared.setCheckState(
            self.anti_corrector(d['Neuron_model_array_prepared']))
        self.ui.lineEdit_Name_Prepared_Neuron_Array.setText("{}".format(
            d['Name_prepared_neuron_array']))
        self.externalNeuronArray.ui.checkBox_Global_Rot.setCheckState(
            self.anti_corrector(d['Global_rot']))
        if self.externalNeuronArray.ui.checkBox_Global_Rot.checkState() == 2:
            self.externalNeuronArray.ui.doubleSpinBox_X_Seed.setValue(
                d['x_seed'])
            self.externalNeuronArray.ui.doubleSpinBox_Y_Seed.setValue(
                d['y_seed'])
            self.externalNeuronArray.ui.doubleSpinBox_Z_Seed.setValue(
                d['z_seed'])
            self.externalNeuronArray.ui.spinBox_X_Steps.setValue(d['x_steps'])
            self.externalNeuronArray.ui.spinBox_Y_Steps.setValue(d['y_steps'])
            self.externalNeuronArray.ui.spinBox_Z_Steps.setValue(d['z_steps'])
            self.externalNeuronArray.ui.doubleSpinBox_X_Step.setValue(
                d['x_step'])
            self.externalNeuronArray.ui.doubleSpinBox_Y_Step.setValue(
                d['y_step'])
            self.externalNeuronArray.ui.doubleSpinBox_Z_Step.setValue(
                d['z_step'])
            self.get_lineedit_entry(
                d['alpha_array_glob'],
                self.externalNeuronArray.ui.lineEdit_Alpha_Array_Glob)
            self.get_lineedit_entry(
                d['beta_array_glob'],
                self.externalNeuronArray.ui.lineEdit_Beta_Array_Glob)
            self.get_lineedit_entry(
                d['gamma_array_glob'],
                self.externalNeuronArray.ui.lineEdit_Gamma_Array_Glob)
        else:
            self.get_lineedit_entry(
                d['X_coord_old'],
                self.externalNeuronArray.ui.lineEdit_X_Coordinate_Old)
            self.get_lineedit_entry(
                d['Y_coord_old'],
                self.externalNeuronArray.ui.lineEdit_Y_Coordinate_Old)
            self.get_lineedit_entry(
                d['Z_coord_old'],
                self.externalNeuronArray.ui.lineEdit_Z_Coordinate_Old)
            self.get_lineedit_entry(
                d['YZ_angles'], self.externalNeuronArray.ui.lineEdit_YZ_Angles)
            self.get_lineedit_entry(
                d['ZX_angles'], self.externalNeuronArray.ui.lineEdit_ZX_Angles)
            self.get_lineedit_entry(
                d['XY_angles'], self.externalNeuronArray.ui.lineEdit_XY_Angles)

        self.ui.comboBox_Laplace_Formulation.setCurrentText(d['EQS_core'])
        self.ui.checkBox_Skip_Mesh_Refinement.setCheckState(
            self.anti_corrector(d['Skip_mesh_refinement']))
        self.get_lineedit_entry(
            d['refinement_frequency'],
            self.meshRefinement.ui.lineEdit_Refinement_Frequency)
        self.meshRefinement.ui.spinBox_No_Of_Refinement_Frequencies.setValue(
            d['num_ref_freqs'])
        self.meshRefinement.ui.doubleSpinBox_Deviation_Threshold.setValue(
            d['Adaptive_frac_div'])
        self.meshRefinement.ui.doubleSpinBox_Min_Scaling.setValue(
            d['Min_Scaling'])
        self.meshRefinement.ui.doubleSpinBox_CSF_Ref_Reg.setValue(
            d['CSF_ref_reg'])
        self.meshRefinement.ui.doubleSpinBox_Rel_Div.setValue(d['rel_div'])
        self.meshRefinement.ui.doubleSpinBox_Rel_Div_Current.setValue(
            d['rel_div_current'])
        self.ui.spinBox_El_Order.setValue(d['el_order'])
        self.ui.spinBox_Number_Of_Processors.setValue(
            d['number_of_processors'])
        try:
            self.ui.checkBox_FEniCS_MPI.setCheckState(
                self.anti_corrector(d['FEniCS_MPI']))
        except:
            pass
        self.ui.checkBox_Current_Control.setCheckState(
            self.anti_corrector(d['current_control']))
        self.get_lineedit_entry(d['Phi_vector'], self.ui.lineEdit_Phi_Vector)
        try:
            self.ui.comboBox_Solver_Type.setCurrentText("{}".format(
                d['Solver_Type']))
        except:
            pass
        self.ui.doubleSpinBox_Frequency.setValue(d['freq'])
        self.ui.doubleSpinBox_T.setValue(d['T'])
        self.ui.doubleSpinBox_T_Step.setValue(d['t_step'])
        self.ui.doubleSpinBox_Signal_Shift.setValue(d['phi'])
        self.ui.comboBox_Signal_Type.setCurrentText("{}".format(
            d['Signal_type']))
        self.ui.doubleSpinBox_Amplitude_Scale.setValue(d['Ampl_scale'])
        self.ui.checkBox_CPE_Active.setCheckState(
            self.anti_corrector(d['CPE_activ']))
        self.cpeActive.ui.doubleSpinBox_Alpha.setValue(d['beta'])
        self.cpeActive.ui.doubleSpinBox_K_S.setValue(d['K_A'])
        self.cpeActive.ui.doubleSpinBox_Alpha_Ground.setValue(d['beta_ground'])
        self.cpeActive.ui.doubleSpinBox_K_S_Ground.setValue(d['K_A_ground'])
        self.ui.checkBox_Full_Field_IFFT.setCheckState(
            self.anti_corrector(d['Full_Field_IFFT']))
        self.fullFieldIFFT.ui.spinBox_T_Step_End.setValue(d['t_step_end'])
        self.fullFieldIFFT.ui.checkBox_VTA_From_DivE.setCheckState(
            self.anti_corrector(d['VTA_from_divE']))
        self.fullFieldIFFT.ui.checkBox_VTA_From_NEURON.setCheckState(
            self.anti_corrector(d['VTA_from_NEURON']))
        self.fullFieldIFFT.ui.checkBox_VTA_From_E.setCheckState(
            self.anti_corrector(d['VTA_from_E']))
        self.get_lineedit_entry(
            d['Activation_threshold_VTA'],
            self.fullFieldIFFT.ui.lineEdit_Activation_Threshold)

        self.ui.comboBox_Spectrum_Truncation_Method.setCurrentText(
            d['spectrum_trunc_method'])

        self.get_entry_truncation_parameter(
            d['trunc_param'], self.ui.comboBox_Spectrum_Truncation_Method,
            self.ui.lineEdit_Truncation_Parameter,
            self.ui.spinBox_Truncation_Parameter)

        self.ui.checkBox_Truncate_The_Obtained_Full_Solution.setCheckState(
            self.anti_corrector(d['Truncate_the_obtained_full_solution']))
        #self.ui.checkBox_Show_Paraview_Screenshots.setCheckState(self.anti_corrector(d['Show_paraview_screenshots']))

        self.ui.checkBox_external_grounding.setCheckState(
            self.anti_corrector(d['external_grounding']))

        # save sub dictionaries
        self.cpeActive.saveDict()
        self.meshRefinement.saveDict()
        self.fullFieldIFFT.saveDict()
        self.externalNeuronArray.saveDict()

    def load_dict(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog

        filename, _ = QFileDialog.getOpenFileName(
            None,
            "Load State",
            "",
            "All Files (*);;Text Files (*.txt)",
            options=options)
        if filename:
            with open(filename, 'r') as f:
                num = f.read().find('{')
                f.seek(num)
                content = f.read()
                d = ast.literal_eval(content.strip())
                self.set_load_state(d)

            self.info("Run",
                      "{} has been loaded successfully.".format(filename))
            self.set_current_file_name(filename)

    def reset_state(self):
        filename = "{}/GUI_tree_files/default_dict.py".format(self.rel_folder)
        with open(filename, 'r') as f:
            num = f.read().find('{')
            f.seek(num)
            content = f.read()
            d = ast.literal_eval(content.strip())
            self.set_load_state(d)
        # self.set_current_file_name(filename)

        # Display Images
        self.display(self.ui.label_Image_Placed_Neurons,
                     '{}/icons/image_placeholder.png'.format(self.rel_folder),
                     '{}/icons/image_placeholder.png'.format(self.rel_folder),
                     2)
        self.display(self.ui.label_Image_Signal_Recovered,
                     '{}/icons/image_placeholder.png'.format(self.rel_folder),
                     '{}/icons/image_placeholder.png'.format(self.rel_folder),
                     2)
        self.display(self.ui.label_Image_CSF_Full_Refinement,
                     '{}/icons/image_placeholder.png'.format(self.rel_folder),
                     '{}/icons/image_placeholder.png'.format(self.rel_folder),
                     2)
        self.display(self.ui.label_Image_Adapted_Mesh,
                     '{}/icons/image_placeholder.png'.format(self.rel_folder),
                     '{}/icons/image_placeholder.png'.format(self.rel_folder),
                     2)
        self.display(self.ui.label_Image_Signal_Convoluted_1st_Point,
                     '{}/icons/image_placeholder.png'.format(self.rel_folder),
                     '{}/icons/image_placeholder.png'.format(self.rel_folder),
                     2)
        self.display(self.ui.label_Image_Axon_Activation,
                     '{}/icons/image_placeholder.png'.format(self.rel_folder),
                     '{}/icons/image_placeholder.png'.format(self.rel_folder),
                     2)

    def load_last_save_state(self):
        try:
            filename = "{}/GUI_tree_files/default_dict.py".format(
                self.rel_folder)
            with open(filename, 'r') as f:
                num = f.read().find('{')
                f.seek(num)
                content = f.read()
                d = ast.literal_eval(content.strip())
                self.set_load_state(d)
            # self.info("Run", "Last save state was loaded successfully")
            # self.set_current_file_name(filename)
        except AssertionError:
            # self.info("Run", "Oopsie! There seems to have been a problem with loading the default settings")
            pass
        except ValueError:
            # self.info("Run", "Oopsie! There seems to have been a problem with loading the default settings")
            pass

        except SyntaxError:
            # self.info("Run", "Oopsie! There seems to be a syntax error with the last saved dictionary file.")
            pass

        except FileNotFoundError:
            self.info("Run",
                      "Oopsie! A default_dict.py file seems not to be found.")
            pass
        except:
            self.info(
                "Run",
                "Oopsie! There seems to have been a problem loading the last saved dictionary."
            )
Exemple #12
0
class MainWindows(QMainWindow):
    def __init__(self):
        super().__init__()
        self.gui = Ui_MainWindow()
        self.gui.setupUi(self)

        try:
            js = json.load(open('config.json', encoding='utf-8'))
            self.user_name = js['Login']['user_name']
            self.user_password = js['Login']['user_password']
            self.user_cookies = js['Login']['user_cookies']
            self.ban_status = js['Setting']['ban_status']
            self.ban_word = js['Setting']['ban_word']
            self.work_thread = js['Setting']['work_thread']
            self.download_thread = js['Setting']['download_thread']
            self.screening_criteria = js['Setting']['screening_criteria']
        except:
            self.gui.listWidget.addItem('读取配置文件失败')
            self.work = False
        else:
            self.work = True

        self._search_type = {'全年龄': 'safe', '全部': 'all', 'R18': 'r18'}

        self.gui.button_search_start.clicked.connect(self.search)
        self.gui.button_ranking_start.clicked.connect(self.ranking)

    def _search_thread(self):
        keyword = self.gui.search_tag.toPlainText()
        mode = self._search_type[self.gui.search_type.currentText()]
        start = self.gui.search_startpage.toPlainText()
        finish = self.gui.search_finishpage.toPlainText()
        if keyword != '' and mode != '' and start != '' and finish != '':
            try:
                if int(finish) >= int(start):
                    all_time = 0
                    pixix = Pixiv(self.user_cookies)
                    for i in range(int(start), int(finish) + 1):
                        self.gui.listWidget.addItem(
                            '正在爬取第{0}页......'.format(i))
                        time1 = time.time()
                        pics = pixix.search(keyword=keyword,
                                            mode=mode,
                                            search_page=i)
                        if pics != []:
                            new_data = pixix.screen(self.screening_criteria,
                                                    pics['data'],
                                                    self.work_thread)
                            pixix.download(freq=self.download_thread,
                                           data=new_data,
                                           path=pics['path'])
                            time2 = time.time()
                            self.gui.listWidget.addItem(
                                '第{0}页完成,用时{1}秒'.format(
                                    i, round(time2 - time1), 2))
                            all_time = all_time + time2 - time1
                        else:
                            self.gui.listWidget.addItem('第{0}页为空'.format(i))
                    self.gui.listWidget.addItem('{0}到{1}页已完成,共用时{2}秒'.format(
                        start, finish, round(all_time, 2)))
                else:
                    self.gui.listWidget.addItem('Error:开始页数不能大于结束页数')
            except ValueError:
                self.gui.listWidget.addItem('Error:请输入数字')
        else:
            self.gui.listWidget.addItem('Error:请输入')

    def search(self):
        if self.work:
            pixiv = Pixiv(self.user_cookies)
            if pixiv.login_status():
                thread = threading.Thread(target=self._search_thread)
                thread.start()
            else:
                self.gui.listWidget.addItem('Error:登录失效')
        else:
            self.gui.listWidget.addItem('读取配置文件出错,无法运行')

    def _ranking_thread(self):
        ranking_type = {
            '今日普通': 'daily',
            '本周普通': 'weekly',
            '本月普通': 'monthly',
            '新人普通': 'rookie',
            '原创普通': 'original',
            '受男性欢迎普通': 'male',
            '受女性欢迎普通': 'female',
            '今日R18': 'daily_r18',
            '本周R18': 'weekly_r18',
            '本月R18': 'monthly_r18',
            '新人R18': 'rookie_r18',
            '原创R18': 'original_r18',
            '受男性欢迎R18': 'male_r18',
            '受女性欢迎R18': 'female_r18'
        }
        mode = ranking_type[self.gui.ranking_type.currentText() +
                            self.gui.ranking_type2.currentText()]
        date = self.gui.ranking_date.toPlainText()
        if mode not in ['weekly_r18', 'monthly_r18', 'monthly', 'weekly']:
            try:
                int(date)
            except ValueError:
                self.gui.listWidget.addItem('Error:请输入数字')
            else:
                pixiv = Pixiv(self.user_cookies)
                time1 = time.time()
                self.gui.listWidget.addItem('正在搜索...')
                pics = pixiv.ranking_list(mode=mode, date=date)
                if pics != []:
                    new_data = pixiv.screen(self.screening_criteria,
                                            pics['data'], self.work_thread)
                    time2 = time.time()
                    self.gui.listWidget.addItem('搜索完成,用时{0}秒'.format(
                        round(time2 - time1, 2)))
                    self.gui.listWidget.addItem('正在下载...')
                    time1 = time.time()
                    pixiv.download(freq=self.download_thread,
                                   data=new_data,
                                   path=pics['path'])
                    time2 = time.time()
                    self.gui.listWidget.addItem('下载完成,用时{0}秒'.format(
                        round(time2 - time1, 2)))
                else:
                    self.gui.listWidget.addItem('内容为空!')
        else:
            pixiv = Pixiv(self.user_cookies)
            pics = pixiv.ranking_list(mode=mode, date=date)
            if pics != []:
                new_data = pixiv.screen(self.screening_criteria, pics['data'],
                                        self.work_thread)
                self.gui.listWidget.addItem('正在下载...')
                pixiv.download(freq=self.download_thread,
                               data=new_data,
                               path=pics['path'])
            else:
                self.gui.listWidget.addItem('内容为空!')

    def ranking(self):
        if self.work:
            pixiv = Pixiv(self.user_cookies)
            if pixiv.login_status():
                thread = threading.Thread(target=self._ranking_thread)
                thread.start()
            else:
                self.gui.listWidget.addItem('Error:登录失效')
        else:
            self.gui.listWidget.addItem('读取配置文件出错,无法运行')
Exemple #13
0
class Editor(QMainWindow):
    def __init__(self):
        super(Editor, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.main_text.setText('Hello!')

        self.ui.menu_save.triggered.connect(self.save)
        self.ui.menu_open.triggered.connect(self.open)
        self.ui.menu_print.triggered.connect(self.print_file)
        self.ui.menu_print_preview.triggered.connect(self.print_preview)
        self.ui.menu_export_pdf.triggered.connect(self.export_pdf)

        self.text_weight = lambda: QFont.Bold if self.ui.bold_checkBox.isChecked(
        ) else 0

        self.ui.color_change_button.clicked.connect(self.change_font_color)

        self.ui.left_alignment.triggered.connect(
            lambda: self.ui.main_text.setAlignment(Qt.AlignLeft))

        self.ui.center_alignment.triggered.connect(
            lambda: self.ui.main_text.setAlignment(Qt.AlignCenter))

        self.ui.right_alignment.triggered.connect(
            lambda: self.ui.main_text.setAlignment(Qt.AlignRight))

        self.ui.justify_alignment.triggered.connect(
            lambda: self.ui.main_text.setAlignment(Qt.AlignJustify))

        self.ui.bold_checkBox.toggled.connect(
            lambda: self.ui.main_text.setFontWeight(self.text_weight()))

        self.ui.italic_checkBox.toggled.connect(
            lambda: self.ui.main_text.setFontItalic(self.ui.italic_checkBox.
                                                    isChecked()))

        self.ui.underline_checkBox.toggled.connect(
            lambda: self.ui.main_text.setFontUnderline(
                self.ui.underline_checkBox.isChecked()))

        self.ui.font_size_spinBox.valueChanged.connect(
            lambda: self.ui.main_text.setFontPointSize(
                self.ui.font_size_spinBox.value()))

        self.ui.select_font_box.currentFontChanged.connect(self.change_font)

    def change_font_color(self):
        color = QColorDialog.getColor()
        if color.isValid():
            self.ui.main_text.setTextColor(color)
            self.ui.color_change_button.setStyleSheet(
                "background-color: {}".format(color.name()))

    def change_font(self):
        self.ui.main_text.setCurrentFont(self.ui.select_font_box.currentFont())
        self.ui.main_text.setFontPointSize(self.ui.font_size_spinBox.value())
        self.ui.main_text.setFontWeight(self.text_weight())
        self.ui.main_text.setFontItalic(self.ui.italic_checkBox.isChecked())
        self.ui.main_text.setFontUnderline(
            self.ui.underline_checkBox.isChecked())

    def save(self):
        file_name, _ = QFileDialog.getSaveFileName(
            self, 'Save file', '',
            'HTML (*.html, *htm); Text documents (*.txt)')
        if file_name:
            text = self.ui.main_text.toHtml() if os.path.splitext(file_name)[1] in ['.html', '.htm'] \
                else self.ui.main_text.toPlainText()
            try:
                with open(file_name, 'w') as f:
                    f.write(text)
            except UnicodeEncodeError:
                return

    def open(self):
        file_name = QFileDialog.getOpenFileName(self, 'Open File')[0]
        if file_name != '':
            with open(file_name, 'r') as file:
                self.ui.main_text.setText(file.read())

    def print_file(self):
        printer = QPrinter(QPrinter.HighResolution)
        dialog = QPrintDialog(printer, self)

        if dialog.exec_() == QPrintDialog.Accepted:
            self.ui.main_text.print_(printer)

    def print_preview(self):
        printer = QPrinter(QPrinter.HighResolution)
        preview_dialog = QPrintPreviewDialog(printer, self)
        preview_dialog.paintRequested.connect(
            lambda: self.ui.main_text.print_(printer))
        preview_dialog.exec_()

    def export_pdf(self):
        fn, _ = QFileDialog.getSaveFileName(self, 'Export to PDF', '',
                                            'PDF files (.pdf) ;; All Files')
        if fn != '':
            if QFileInfo(fn).suffix() == '':
                fn += '.pdf'
            printer = QPrinter(QPrinter.HighResolution)
            printer.setOutputFormat(QPrinter.PdfFormat)
            printer.setOutputFileName(fn)
            self.ui.main_text.document().print_(printer)
Exemple #14
0
class DPR(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        # call the parent class's constructor
        QtWidgets.QMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.pushButton_1.clicked.connect(self.select_file)
        self.ui.pushButton_2.clicked.connect(self.run_datapoints)
        self.ui.dateEdit_1.setDateTime(QtCore.QDateTime.currentDateTime())
        self.ui.dateEdit_2.setDateTime(QtCore.QDateTime.currentDateTime())
        self.ui.dateEdit_1.dateChanged.connect(self.update_date)
        self.ui.radioButton_1.setChecked(True)
        self.ui.radioButton_4.setChecked(True)
        self.ui.pushButton_3.clicked.connect(self.run_regression)
        self.ui.lineEdit_3.setText("5")
        self.ui.lineEdit_4.setText("10")
        self.ui.pushButton_4.clicked.connect(self.write_excel)
        self.ui.graphicsView_1.hide()
        self.ui.graphicsView_2.hide()
        self.MessageBox = ctypes.windll.user32.MessageBoxW

    # after first date edit is changed, update second date edit to be a year later
    def update_date(self):
        get_date = self.ui.dateEdit_1.date().toString("yyyy-M-d")
        new_datetime = pd.to_datetime(get_date) + relativedelta(months=+12)
        change_datetime = QtCore.QDateTime.fromString(str(new_datetime),
                                                      "yyyy-M-d hh:mm:ss")
        self.ui.dateEdit_2.setDateTime(change_datetime)

    # check if file is selected
    def select_file(self):
        filename, _ = QtWidgets.QFileDialog.getOpenFileName(
            None, "Select File", "", "Text Files (*.txt)")
        if filename:
            # outputs
            self.ui.lineEdit_1.setText(filename)
            self.filename = filename

    def run_datapoints(self):
        delimiter = str(self.ui.comboBox_1.currentText())
        has_headers = self.ui.checkBox_1.isChecked()

        if self.ui.lineEdit_1.text() == "":
            self.MessageBox(None, "No file selected.", "File Error", 0)
            return

        try:
            data = self.prepare_data(delimiter, has_headers)
        except pd.errors.EmptyDataError:
            self.MessageBox(None, "No data in file.", "Empty Data Error", 0)
            return

        if data is 0:
            self.MessageBox(None,
                            "Problem reading file. Check header declaration.",
                            "Attribute Error", 0)
            return
        elif data is 1:
            self.MessageBox(None, "Column 1 should be date type.",
                            "Attribute Error", 0)
            return
        elif data is 2:
            self.MessageBox(None, "Column 2 should be date type.",
                            "Attribute Error", 0)
            return
        elif data is 3:
            self.MessageBox(None, "Column 3 should be currency.",
                            "Attribute Error", 0)
            return

        # disable calculate button
        self.ui.pushButton_2.setEnabled(False)

        start_date = pd.to_datetime(
            self.ui.dateEdit_1.date().toString("M/d/yyyy"))
        end_date = pd.to_datetime(
            self.ui.dateEdit_2.date().toString("M/d/yyyy"))
        pb_inc = (
            end_date - start_date
        ).days + 36  #number of items in the 2 loops in datapoints fxs

        if self.ui.radioButton_1.isChecked():
            option = "option1"
        elif self.ui.radioButton_2.isChecked():
            option = "option2"
        else:
            option = "option3"

        self.worker_thread = DataPointsWorkThread(data, start_date, end_date,
                                                  pb_inc, option)
        self.worker_thread.signal.connect(self.display_datapoints)
        self.worker_thread.signal_pb.connect(self.update_progressbar)
        self.worker_thread.start()

    def update_progressbar(self, pb_update):
        self.ui.progressBar_1.setValue(pb_update)

    # construct raw data dataframe from file data
    def prepare_data(self, delimiter, has_headers):

        if delimiter == "Tab Delimited":
            sep = "\t"
        elif delimiter == 'Comma Delimited':
            sep = ","
        elif delimiter == 'Pipe Delimited':
            sep = "|"

        if has_headers:  # data file has headers
            try:
                data = pd.read_csv(self.filename,
                                   skiprows=1,
                                   sep=sep,
                                   header=None)
            except AttributeError:
                return 0
        else:  # data file does not have headers
            try:
                data = pd.read_csv(self.filename, sep=sep, header=None)
            except AttributeError:
                return 0

        data.columns = ["a", "b", "c"]

        try:
            data['a'] = pd.to_datetime(data['a'])
        except ValueError:
            return 1

        try:
            data['b'] = pd.to_datetime(data['b'])
        except ValueError:
            return 2

        try:
            data['c'] = data['c'].replace('[\$,]', '',
                                          regex=True).astype(float)
        except ValueError:
            return 3

        return data

    # display dataframe with more specific headers
    def display_datapoints(self, dp_output):
        self.df = dp_output["df"]
        self.x = dp_output["x"]
        self.y = dp_output["y"]
        self.DOI = dp_output["DOI"]
        self.DOI_dollars = dp_output["DOI_dollars"]

        df = self.df
        x = self.x
        y = self.y
        DOI = self.DOI
        DOI_dollars = self.DOI_dollars

        # update progress bar
        self.ui.progressBar_1.setValue(100)

        # graph plot
        self.ui.graphicsView_1.canvas.ax.clear()  # clear if already drawn
        self.ui.graphicsView_1.canvas.ax.plot(x, y, '-', color="orange")
        self.ui.graphicsView_1.canvas.ax.set_xlabel('Time', fontsize=8.0)
        self.ui.graphicsView_1.canvas.ax.set_ylabel('Sum', fontsize=8.0)
        self.ui.graphicsView_1.canvas.draw()  # needed for the first drawing
        for ytick in self.ui.graphicsView_1.canvas.ax.get_yticklabels():
            ytick.set_fontsize(8.0)
        for xtick in self.ui.graphicsView_1.canvas.ax.get_xticklabels():
            xtick.set_fontsize(8.0)

        fmt = '${x:,.0f}'
        tick = mtick.StrMethodFormatter(fmt)
        self.ui.graphicsView_1.canvas.ax.yaxis.set_major_formatter(tick)

        self.ui.graphicsView_1.canvas.draw()  # needed for updated figures
        self.ui.graphicsView_1.show()
        self.ui.lineEdit_2.setText(DOI)
        self.ui.lineEdit.setText(DOI_dollars)

        # enable calculate button
        self.ui.pushButton_2.setEnabled(True)

        # table
        df.columns = ["Date Range Start", "Date Range End", "Sum"]
        model = PandasModel(df)
        self.ui.tableView_1.setModel(model)

    def run_regression(self):
        x = self.x
        y = self.y
        try:
            df = self.df
        except AttributeError:
            self.MessageBox(None, "No datapoints have been calculated.",
                            "Attribute Error", 0)
            return

        max_segments = int(self.ui.lineEdit_3.text())
        max_iter = int(self.ui.lineEdit_4.text())
        isnt_discretized = self.ui.radioButton_4.isChecked()

        # disable calculate button
        self.ui.pushButton_3.setEnabled(False)

        self.ui.progressBar_2.setRange(0, 0)
        self.worker_thread = RegressionWorkThread(x, y, df, max_segments,
                                                  max_iter, isnt_discretized)
        self.worker_thread.signal.connect(self.display_regression)
        self.worker_thread.start()

    def display_regression(self, regression_output):
        # instance variables for excel output
        self.df_output = regression_output["df"]
        self.df_regress_stats = regression_output["df_regress_stats"]
        self.df_anova = regression_output["df_anova"]
        self.df_coef = regression_output["df_coef"]
        self.plt = regression_output["plt"]

        # update progress bar
        self.ui.progressBar_2.setRange(0, 100)
        self.ui.progressBar_2.setValue(100)

        # graph plot
        self.ui.graphicsView_2.canvas.ax.clear()  # clear if already drawn
        self.ui.graphicsView_2.canvas.ax.plot(regression_output["x"],
                                              regression_output["y"],
                                              '-',
                                              color="orange")
        self.ui.graphicsView_2.canvas.ax.plot(regression_output["xHat"],
                                              regression_output["yHat"],
                                              '--',
                                              color="royalblue")
        self.ui.graphicsView_2.canvas.ax.set_xlabel('Time', fontsize=8.0)
        self.ui.graphicsView_2.canvas.ax.set_ylabel('Sum', fontsize=8.0)
        self.ui.graphicsView_2.canvas.draw()
        for ytick in self.ui.graphicsView_2.canvas.ax.get_yticklabels():
            ytick.set_fontsize(8.0)
        for xtick in self.ui.graphicsView_2.canvas.ax.get_xticklabels():
            xtick.set_fontsize(8.0)

        fmt = '${x:,.0f}'
        tick = mtick.StrMethodFormatter(fmt)
        self.ui.graphicsView_2.canvas.ax.yaxis.set_major_formatter(tick)

        self.ui.graphicsView_2.canvas.draw()
        self.ui.graphicsView_2.show()

        # provide number of segments from model
        self.ui.lineEdit_5.setText(regression_output["num_segments"])

        # provide function value from model
        self.ui.lineEdit_6.setText(regression_output["func_value"])

        # display regression statistics
        model_regress_stats = PandasModel(
            regression_output["df_regress_stats"])
        self.ui.tableView_2.setModel(model_regress_stats)

        # display ANOVA statistics
        model_anova = PandasModel(regression_output["df_anova"])
        self.ui.tableView_3.setModel(model_anova)

        # display coefficients table
        model_coef = PandasModel(regression_output["df_coef"])
        self.ui.tableView_4.setModel(model_coef)

        # enable calculate button
        self.ui.pushButton_3.setEnabled(True)

    def write_excel(self):
        try:
            df_output = self.df_output
        except AttributeError:
            self.MessageBox(None, "No datapoints have been calculated.",
                            "Attribute Error", 0)
            return

        df_regress_stats = self.df_regress_stats
        df_anova = self.df_anova
        df_coef = self.df_coef
        plt = self.plt

        # prompt for save file path and name, default is desktop
        desktop = os.path.join(os.path.join(os.path.expanduser('~')),
                               'Desktop')
        fileout, _ = QtWidgets.QFileDialog.getSaveFileName(
            None, "Save File", desktop, "Excel File (*xlsx)")

        if fileout:
            # append .xlsx to file name
            if fileout.endswith(".xlsx"):
                fileout = fileout
            else:
                fileout += ".xlsx"

            # split path into basepath and file name
            head, tail = os.path.split(fileout)

            # save figure to be overwritten each iteration in project folder
            plt.savefig("myplot.png", dpi=100)

            # rename column headers
            df_output = df_output.rename(index=str,
                                         columns={
                                             "C": "Sum",
                                             "col4": "Estimate (y-prediction)"
                                         })

            # write dataframes to an input excel file to be overwritten each iteration in project folder
            num_columns = len(df_output.columns)
            writer = pd.ExcelWriter('input.xlsx', engine='xlsxwriter')
            df_output.to_excel(writer, sheet_name='Sheet1', index=False)
            df_regress_stats.to_excel(writer,
                                      sheet_name='Sheet1',
                                      startrow=30,
                                      startcol=num_columns + 1,
                                      index=False)
            df_anova.to_excel(writer,
                              sheet_name="Sheet1",
                              startrow=38,
                              startcol=num_columns + 1,
                              index=False)
            df_coef.to_excel(writer,
                             sheet_name='Sheet1',
                             startrow=43,
                             startcol=num_columns + 1,
                             index=False)
            writer.save()

            # open input excel file, do formatting, add plot, save file as output
            wb = openpyxl.load_workbook("input.xlsx")
            ws = wb.active
            ws.merge_cells('A1:B1')
            ws.cell(row=1, column=1).value = "Service Date Range"
            img = openpyxl.drawing.image.Image("myplot.png")
            ws.add_image(img, 'M1')
            wb.save(fileout)
            wb.close()
Exemple #15
0
class ApplicationWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(ApplicationWindow, self).__init__()
        pg.setConfigOption('background', '042629')

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.InputViewerArray = [
            self.ui.ImageOneview, self.ui.ImageTwoView,
            self.ui.ImageOneComponent, self.ui.ImageTwoComponent,
            self.ui.ModifiedOne, self.ui.ModifiefTwo
        ]
        for i in range(len(self.ui.InputViewerArray)):
            self.ui.InputViewerArray[i].getPlotItem().hideAxis('left')
            self.ui.InputViewerArray[i].getPlotItem().hideAxis('bottom')

        self.ImageOneChoice = True
        self.ImageObject = [0, 0]
        self.ImageDrawArray = [0, 0]
        self.ImageArray = [0, 0]
        self.FilePathArray = [0, 0]
        self.ui.ComponentOneChoice.currentTextChanged.connect(self.ComboValues)
        self.ui.Browser.clicked.connect(self.Browse)
        self.ui.DrawComboArray = [
            self.ui.ImageOneViewChoice, self.ui.ImageTwoViewChoice
        ]
        self.ui.SlidersArray = [self.ui.MixerSliderOne, self.ui.MixerSliderTwo]
        self.ui.TextArray = [self.ui.SliderOneValue, self.ui.SliderTwoValue]
        self.ui.ImageOneViewChoice.currentTextChanged.connect(
            lambda: self.Draw(0, 0, 0, 2, None))
        self.ui.ImageTwoViewChoice.currentTextChanged.connect(
            lambda: self.Draw(1, 1, 0, 3, None))
        self.ui.MixerSliderOne.valueChanged.connect(
            lambda: self.SlidersValue(0))
        self.ui.MixerSliderTwo.valueChanged.connect(
            lambda: self.SlidersValue(1))
        for i in range(2):
            self.ui.ImageMixerOneChoice.model().item(i + 1).setEnabled(False)
            self.ui.ImageMixerTwoChoice.model().item(i + 1).setEnabled(False)
#-------------------------------------------------ApplicationWindow--------------------------------------------------------------

#-------------------------------------------------Browse------------------------------------------------------------------------

    def Browse(self):
        #Image Loading
        filePaths = QtWidgets.QFileDialog.getOpenFileNames(
            self, 'Choose image file', "~/Desktop", "*.jpg")
        for filePath in filePaths:
            for f in filePath:

                if f == '*' or f == None:
                    break

                if self.ImageOneChoice == True:
                    i = 0
                elif self.ImageOneChoice == False:
                    i = 1
                    self.ImageOneChoice = True

                self.ImageObject = ImageModel(f)

                self.FilePathArray[i] = f
    # Size Checking and Image Analysis
            try:
                if i == 1:
                    Check = self.ImageArray[0].EqualSizeCheck(self.ImageObject)
                    if Check == True:
                        self.ui.WarningTabOne.setText(
                            "Error: The 2 Images Must Be Same Size- Reload Image 2 Again"
                        )
                        self.ImageOneChoice = False
                    else:
                        self.ImageArray[i] = self.ImageObject
                        self.ui.WarningTabOne.setText(
                            "Perfection! Images loaded Successfully,Now You can View any componet you want"
                        )
                        logging.info(
                            'User Loaded similar sized Images Successfully and ready to proceed'
                        )
                        self.ImageDrawArray[i] = pg.ImageItem(
                            np.asarray(Image.open(f)))
                        self.ImageDrawArray[i].rotate(270)
                        self.ui.InputViewerArray[i].addItem(
                            self.ImageDrawArray[i])
                        self.ImageOneChoice = False
                        self.ui.ImageMixerOneChoice.model().item(2).setEnabled(
                            True)
                        self.ui.ImageMixerTwoChoice.model().item(2).setEnabled(
                            True)
                elif i == 0:
                    self.ImageArray[i] = self.ImageObject
                    self.ui.WarningTabOne.setText(
                        "Great image one is loaded Successfully")
                    self.ImageDrawArray[i] = pg.ImageItem(
                        np.asarray(Image.open(f)))
                    self.ImageDrawArray[i].rotate(270)
                    self.ui.InputViewerArray[i].addItem(self.ImageDrawArray[i])
                    self.ImageOneChoice = False
                    self.ui.ImageMixerOneChoice.model().item(1).setEnabled(
                        True)
                    self.ui.ImageMixerTwoChoice.model().item(1).setEnabled(
                        True)
            except:
                logging.info(
                    'Somthing Went Wrong with Size Checking, Check if you loaded to images first!'
                )

    #Image Drawing

#-------------------------------------------------Browse------------------------------------------------------------------------

#-------------------------------------------------Draw------------------------------------------------------------------------

    def Draw(self, ImageChoice, ComboChoice, DrawingOption, GraphChoice, img):
        try:
            if DrawingOption == 0:
                check = self.ui.DrawComboArray[ComboChoice].currentText()
                if check == "Phase":
                    Drawable = pg.ImageItem(self.ImageArray[ImageChoice].phase)
                elif check == "Mag":
                    Drawable = pg.ImageItem(
                        self.ImageArray[ImageChoice].magnitude)
                elif check == "Img":
                    Drawable = pg.ImageItem(
                        self.ImageArray[ImageChoice].imaginary)
                elif check == "Real":
                    Drawable = pg.ImageItem(self.ImageArray[ImageChoice].real)
                self.ui.InputViewerArray[GraphChoice].addItem(Drawable)
                logging.info('Drawing has been done Successfully')
            elif DrawingOption == 1:
                Drawable = pg.ImageItem(img)
                Drawable.rotate(270)

                if GraphChoice == 0:
                    self.ui.ModifiedOne.addItem(Drawable)
                    logging.info(
                        'Hooraayy- Output one has been mixed Successfully ')
                    self.ui.WarningTabTwo.setText(
                        "Perfection! Output one has been Generated Successfully"
                    )
                elif GraphChoice == 1:
                    self.ui.ModifiefTwo.addItem(Drawable)
                    logging.info(
                        'Hooraayy- Output two has been mixed Successfully ')
                    self.ui.WarningTabTwo.setText(
                        "Perfection! Output two has been Generated Successfully"
                    )
        except:
            logging.info(
                'Somthing went wrong with drawing your image object- it may be broken :( '
            )
            self.ui.WarningTabTwo.setText(
                "Somthing went wrong with drawing your image object- it may be broken :("
            )
#-------------------------------------------------Draw------------------------------------------------------------------------

#-------------------------------------------------SlidersValue----------------------------------------------------------------

    def SlidersValue(self, componentChoosen):
        try:
            self.ui.TextArray[componentChoosen].setText(
                str(self.ui.SlidersArray[componentChoosen].value()))
            ModeIndex = "NULL"  # Set To Nothing Until Both componets are choosen
            CallerIndix = 0  #By default
            Picture = self.ui.ImageMixerOneChoice.currentText()

            if Picture == "ImageOne":
                PicIndix = 0
            elif Picture == "ImageTwo":
                PicIndix = 1
            CallerObj = self.ui.ImageMixerTwoChoice.currentText()
            if CallerObj == "ImageOne":
                CallerIndix = 0
            elif CallerObj == "ImageTwo":
                CallerIndix = 1

            componentOne = self.ui.ComponentOneChoice.currentText()
            componentTwo = self.ui.ComponentTwoChocie.currentText()
            if componentOne == "Mag" or componentOne == "UniMag":
                ModeIndex = Modes.magnitudeAndPhase
                Mag_Real_Indix = 0
                Phase_Imag_Indox = 1

            elif componentOne == "Phase" or componentOne == "UniPhase":

                ModeIndex = Modes.magnitudeAndPhase

                Mag_Real_Indix = 1
                Phase_Imag_Indox = 0

            elif componentOne == "Real":
                ModeIndex = Modes.realAndImaginary
                Mag_Real_Indix = 0
                Phase_Imag_Indox = 1

            elif componentOne == "Imag":
                ModeIndex = Modes.realAndImaginary
                Mag_Real_Indix = 1
                Phase_Imag_Indox = 0

            (Mag_Real_Ratio) = float(
                self.ui.SlidersArray[Mag_Real_Indix].value()) / 100
            (Phase_Imag_Ratio) = float(
                self.ui.SlidersArray[Phase_Imag_Indox].value()) / 100

            OutPutCheck = self.ui.OutputChoice.currentText()
            TempImage = ImageModel((self.FilePathArray[0]))
            TempCaller = ImageModel((self.FilePathArray[1]))

            if OutPutCheck == "OutPutOne":
                if componentOne == "UniMag" or componentTwo == "UniMag":
                    TempImage.magnitude = np.ones(
                        self.ImageArray[PicIndix].magnitude.shape)
                    TempCaller.magnitude = np.ones(
                        self.ImageArray[CallerIndix].magnitude.shape)
                if componentOne == "UniPhase" or componentTwo == "UniPhase":
                    TempImage.phase = np.zeros(
                        self.ImageArray[PicIndix].phase.shape)
                    TempCaller.phase = np.zeros(
                        self.ImageArray[CallerIndix].phase.shape)
                if componentOne == "UniMag" or componentTwo == "UniMag" or componentOne == "UniPhase" or componentTwo == "UniPhase":
                    OutputImageOne = TempCaller.mix(TempImage, Mag_Real_Ratio,
                                                    Phase_Imag_Ratio,
                                                    ModeIndex)
                else:
                    OutputImageOne = self.ImageArray[CallerIndix].mix(
                        self.ImageArray[PicIndix], Mag_Real_Ratio,
                        Phase_Imag_Ratio, ModeIndex)

                logging.info(
                    'Output one generated and ready to be sent to drawing function!'
                )
                self.Draw(0, 0, 1, 0, OutputImageOne)

            elif OutPutCheck == "OutputTwo":
                if componentOne == "UniMag" or componentTwo == "UniMag":
                    TempImage.magnitude = np.ones(
                        self.ImageArray[PicIndix].magnitude.shape)
                    TempCaller.magnitude = np.ones(
                        self.ImageArray[CallerIndix].magnitude.shape)
                if componentOne == "UniPhase" or componentTwo == "UniPhase":
                    TempImage.phase = np.zeros(
                        self.ImageArray[PicIndix].phase.shape)
                    TempCaller.phase = np.zeros(
                        self.ImageArray[CallerIndix].phase.shape)
                if componentOne == "UniMag" or componentTwo == "UniMag" or componentOne == "UniPhase" or componentTwo == "UniPhase":
                    OutputImageOne = TempCaller.mix(TempImage, Mag_Real_Ratio,
                                                    Phase_Imag_Ratio,
                                                    ModeIndex)
                else:
                    OutputImageOne = self.ImageArray[CallerIndix].mix(
                        self.ImageArray[PicIndix], Mag_Real_Ratio,
                        Phase_Imag_Ratio, ModeIndex)
                logging.info(
                    'Output two generated and ready to be sent to drawing function!'
                )
                self.Draw(0, 0, 1, 1, OutputImageOne)
        except:

            logging.info(
                'Somthing went wrong with slider values function or mixer')

#-------------------------------------------------SlidersValue----------------------------------------------------------------
#-------------------------------------------------Combo Values----------------------------------------------------------------

    def ComboValues(self):
        self.ui.ComponentTwoChocie.setCurrentIndex(0)
        for i in range(7):
            self.ui.ComponentTwoChocie.model().item(i).setEnabled(False)

        componentOne = self.ui.ComponentOneChoice.currentText()
        if componentOne == "Mag" or componentOne == "UniMag":
            self.ui.ComponentTwoChocie.model().item(2).setEnabled(True)
            self.ui.ComponentTwoChocie.model().item(6).setEnabled(True)
            logging.info(
                'Mag or Uni mag is choosen for component one and enabling only phase or uni phase for component two'
            )
        elif componentOne == "Phase" or componentOne == "UniPhase":

            self.ui.ComponentTwoChocie.model().item(1).setEnabled(True)
            self.ui.ComponentTwoChocie.model().item(5).setEnabled(True)
            logging.info(
                'Phase or Uni Phase is choosen for component one and enabling only Mag or uni Mag for component two'
            )

        elif componentOne == "Real":

            self.ui.ComponentTwoChocie.model().item(4).setEnabled(True)
            logging.info(
                'Real is choosen for component one and enabling only Imaginary for component two'
            )
        elif componentOne == "Imag":
            logging.info(
                'Imaginary is choosen for component one and enabling only Real for component two'
            )
            self.ui.ComponentTwoChocie.model().item(3).setEnabled(True)
Exemple #16
0
class MainApp:
    def __init__(self):
        self.img_path = None
        self.privKey = None
        self.pubKey = None
        self.curve = None

        self.init_ui()

    def init_ui(self):
        self.app = QtWidgets.QApplication(sys.argv)
        self.MainWindow = QtWidgets.QMainWindow()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self.MainWindow)

    def init_listeners(self):
        self.ui.pushButtonUploadPlain.clicked.connect(self.upload_plain_image)
        self.ui.pushButtonUploadEnc.clicked.connect(self.upload_enc_image)
        self.ui.pushButtonEncrypt.clicked.connect(self.encrypt_file)
        self.ui.pushButtonDecrypt.clicked.connect(self.decrypt_file)

    def upload_plain_image(self):
        dlg = QFileDialog()
        if dlg.exec_():
            path = dlg.selectedFiles()[0]
            self.img_path = path
            self.ui.lineEditPlainImgPath.setText(path)

            image = Image.open(path)
            image.show()

    def upload_enc_image(self):
        dlg = QFileDialog()
        if dlg.exec_():
            path = dlg.selectedFiles()[0]
            self.img_path = path
            self.ui.lineEditEncImgPath.setText(path)

    def init_curve(self):
        self.curve = registry.get_curve('brainpoolP256r1')

        if os.path.exists(KEY_FILE):
            key_file = open(KEY_FILE, 'rb')
            keys = pickle.load(key_file)
            self.pubKey = keys[0]
            self.privKey = keys[1]
        else:

            self.privKey = secrets.randbelow(self.curve.field.n)
            self.pubKey = self.privKey * self.curve.g

            keys = [self.pubKey, self.privKey]
            key_file = open(KEY_FILE, 'wb')
            pickle.dump(keys, key_file)

    def encrypt_file(self):
        if self.img_path:
            with open(self.img_path, "rb") as image_file:

                encoded_string = base64.b64encode(image_file.read())

                self.init_curve()

                encryptedMsg = SafeEC.encrypt_ECC(self.curve, encoded_string,
                                                  self.pubKey)

                enc_file = open('encrypted.dat', 'wb')
                pickle.dump(encryptedMsg, enc_file)
                self.show_message("Encrypted")

                file_name = os.path.basename(self.img_path)
                s_mail = self.ui.lineEditUsername.text()
                s_pwd = self.ui.lineEditPassword.text()
                r_mail = self.ui.lineEditMail.text()
                mail(r_mail, file_name, s_mail, s_pwd)

        else:
            self.show_error("No file selected!")

    def decrypt_file(self):
        if self.img_path:
            with open(self.img_path, "rb") as image_file:
                # unpickler = pickle.Unpickler(image_file)
                # encryptedMsg = unpickler.load()
                encryptedMsg = pickle.load(image_file)
                self.init_curve()

                decryptedMsg = SafeEC.decrypt_ECC(encryptedMsg, self.privKey)

                dec_file = open(DEC_FILE, 'wb')
                dec_file.write(base64.b64decode(decryptedMsg))
                dec_file.flush()
                dec_file.close()

                image = Image.open(DEC_FILE)
                image.show()

                self.show_error("Decrypted")

        else:
            self.show_error("No file selected!")

    def show_error(self, msg):
        print(msg)
        error_dialog = QtWidgets.QErrorMessage()
        error_dialog.showMessage(msg)

    def show_message(self, msg):
        print(msg)
        error_dialog = QtWidgets.QErrorMessage()
        error_dialog.showMessage(msg)

    def start(self):
        self.ui.setupUi(self.MainWindow)
        self.init_listeners()
        self.MainWindow.show()
        sys.exit(self.app.exec_())
Exemple #17
0
class ApplicationWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(ApplicationWindow,self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.actionOpen_Image.triggered.connect(self.OpenImage)
        self.ui.Combo1.currentTextChanged.connect(self.ChooseOperation)
        self.ui.comboBox.currentTextChanged.connect(self.Gradients)
        self.ui.Combo1.setCurrentIndex(0)
        self.widgets = [self.ui.InputImage1,self.ui.FourierInput1]
        for i in range(len(self.widgets)):
            self.widgets[i].ui.histogram.hide()
            self.widgets[i].ui.roiBtn.hide()
            self.widgets[i].ui.menuBtn.hide()
            self.widgets[i].ui.roiPlot.hide()
        self.pen1 = pg.mkPen(color=(255, 0, 0))
        self.pen2 = pg.mkPen(color=(0, 0, 255))
        self.ui.pushButton.clicked.connect(self.ShowGraph)

    def ShowGraph (self):
        np.random.seed(42)
        rand_Bz = np.random.randint(-3,4,20)
        
        const_Bx = [0]*20
        const_By = [0]*20
        const_Bz = [2]*20
        nonUn_Bz = rand_Bz + const_Bz

        self.ui.withx.clear()
        self.ui.withy.clear()
        self.ui.withz.clear()

        self.ui.withz.plotItem.plot(nonUn_Bz,pen=self.pen1)
        self.ui.withz.setLabel('left', 'B', units='Tesla')
        self.ui.withz.setLabel('bottom', 'Z-axis')
        self.ui.withx.plotItem.plot(const_Bx,pen=self.pen2)
        self.ui.withx.setLabel('left', 'B', units='Tesla')
        self.ui.withx.setLabel('bottom', 'X-axis')
        self.ui.withy.plotItem.plot(const_By,pen=self.pen2)
        self.ui.withy.setLabel('left', 'B', units='Tesla')
        self.ui.withy.setLabel('bottom', 'Y-axis')


    def Gradients (self):
        var = np.arange(-1,1,0.1)
        if (str(self.ui.comboBox.currentText())) == 'Gradient Effect':
            print('Choose prope Gradient Coil')
        elif (str(self.ui.comboBox.currentText())) == 'Slice Selection':
            const_Bx = [0]*20
            const_BxG = const_Bx + var
            self.ui.withx.clear()
            self.ui.withx.plotItem.plot(const_BxG,pen=self.pen2)
        elif (str(self.ui.comboBox.currentText())) == 'Phase Encoding':
            const_By = [0]*20
            const_ByG = const_By + var
            self.ui.withy.clear()
            self.ui.withy.plotItem.plot(const_ByG,pen=self.pen2)
        elif (str(self.ui.comboBox.currentText())) == 'Frequency Encoding':
            const_Bz = [2]*20
            rand_Bz = np.random.randint(-3,4,20)
            nonUn_Bz = rand_Bz + const_Bz
            const_BzG = nonUn_Bz + var
            self.ui.withz.clear()
            self.ui.withz.plotItem.plot(const_BzG,pen=self.pen1)


    def OpenImage(self):
        self.filePath = QtWidgets.QFileDialog.getOpenFileName(None, 'Open file', 'F:\25-9\Downloads\talta tebya\Second Semester\DSP\Task2 Equalizer\TASK 2')
        self.image = cv.cvtColor(cv.imread(self.filePath[0]),cv.COLOR_BGR2GRAY)
        self.ui.InputImage1.show()
        self.ui.InputImage1.setImage(self.image.T)

        self.dft = np.fft.fft2(self.image)
        self.real = np.real(self.dft)
        self.imaginary = np.imag(self.dft)
        self.magnitude = np.abs(self.dft)
        self.phase = np.angle(self.dft)

    def ChooseOperation(self):
        if (str(self.ui.Combo1.currentText())) == 'FT Magnitude':
            self.ui.FourierInput1.show()
            self.ui.FourierInput1.setImage(np.fft.fftshift(20 * np.log(self.magnitude.T)))
        elif (str(self.ui.Combo1.currentText())) == 'FT Phase':
            self.ui.FourierInput1.show()
            self.ui.FourierInput1.setImage(self.phase.T)
        elif (str(self.ui.Combo1.currentText())) == 'FT Real Component':
            self.ui.FourierInput1.show()
            self.ui.FourierInput1.setImage(20 * np.log(self.real.T))
        elif (str(self.ui.Combo1.currentText())) == 'FT Imaginary Component':
            self.ui.FourierInput1.show()
            self.ui.FourierInput1.setImage(self.imaginary.T)
        if (str(self.ui.Combo1.currentText())) == 'Select an Option':
            print('Please select a proper option')
class MyWindowClass(QMainWindow):
    def __init__(self, parent=None):
        super(self.__class__, self).__init__()
        self.car = None
        self.rps_counter = None

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.forwardBtn.clicked.connect(self.forward_clicked)
        self.ui.backBtn.clicked.connect(self.backward_clicked)
        self.ui.leftBtn.clicked.connect(self.left_clicked)
        self.ui.rightBtn.clicked.connect(self.right_clicked)
        self.ui.stopBtn.clicked.connect(self.stop_clicked)
        self.ui.startButton.clicked.connect(self.start_clicked)

        self.ui.actionOpen_Writer.triggered.connect(self.open_writer)
        self.ui.actionExit.triggered.connect(self.exit)
        self.ui.actionAbout.triggered.connect(self.about)

        self.img_left = self.ui.img_left
        self.img_right = self.ui.img_right
        self.img_center = self.ui.img_center

        self.camera_label = {
            'camera_r': self.img_left,
            'camera_c': self.img_center,
            'camera_l': self.img_right
        }

        self.sensor_label = {
            'left': self.ui.sensor_left,
            'center': self.ui.sensor_center,
            'right': self.ui.sensor_right
        }

        self.add_log("DrivingMatter GUI Started.")
        self.show_image()

    def open_writer(self):
        self.add_log("OpenWriter called")
        self.writer = Writer(self.car)
        self.writer.setWindowTitle('Driving Matter - Writer')
        self.writer.show()

    def exit(self):
        self.add_log("Exit called")

    def about(self):
        self.add_log("About called")

    def add_log(self, message):
        from datetime import datetime
        message = str(
            datetime.now().strftime('%Y-%m-%d %H:%M:%S')) + ": " + message
        self.ui.logdata.appendPlainText(message)

        #scroll log textedit to bottom
        self.ui.logdata.verticalScrollBar().setValue(
            self.ui.logdata.verticalScrollBar().maximum())

    def load_car(self):
        ip, okPressed = QInputDialog.getText(self, "Car IP Address",
                                             "Enter IP Address",
                                             QLineEdit.Normal, "192.168.137.2")
        if okPressed:
            try:
                socket.inet_aton(ip)  # throw exception in invalid ip

                car_link = "ws://{}:{}".format(ip, "8000")

                action_link = "{}/action".format(car_link)
                state_link = "{}/state".format(car_link)

                self.add_log("Action Link: " + action_link)
                self.add_log("State Link: " + state_link)

                self.car = Car(action_link, url_state=state_link)
                self.rps_counter = RPSCounter()
                self.car.set_state_callback(self._handle_dataset_response)

                self.ui.startButton.setText('Started')
            except socket.error:
                pass  # leave the condition
        else:
            self.ui.startButton.setText('Start')
            self.ui.startButton.setEnabled(False)

    def stop_clicked(self):
        self.car.stop()

    def backward_clicked(self):
        self.add_log("Car::backward()")
        self.car.backward()

    def right_clicked(self):
        self.add_log("Car::right()")
        self.car.forwardRight()

    def left_clicked(self):
        self.add_log("Car::left()")
        self.car.forwardLeft()

    def forward_clicked(self):
        self.add_log("Car::forward()")
        self.car.forward()

    def start_clicked(self):
        global running
        running = True
        self.ui.startButton.setEnabled(False)
        self.ui.startButton.setText('Starting...')
        self.load_car()

    def show_image(self):
        qim = QtGui.QImage("../images/no-image.png")  # PNG only
        qim = qim.scaled(200,
                         200,
                         aspectRatioMode=QtCore.Qt.KeepAspectRatio,
                         transformMode=QtCore.Qt.SmoothTransformation)
        self.ui.img_left.setPixmap(QtGui.QPixmap.fromImage(qim))
        self.ui.img_right.setPixmap(QtGui.QPixmap.fromImage(qim))
        self.ui.img_center.setPixmap(QtGui.QPixmap.fromImage(qim))
        self.ui.img_left.adjustSize()

        self.add_log("Showing default images.")

    def _handle_dataset_response(self, data, ws):
        current_datavector = json.loads(data)

        pc_rps = self.rps_counter.get()

        #logger.debug("PC RPS: " + str(pc_rps) + "\n\nCar RPS: " + str(car_rps) + "\n\nTotal: " + str(total_requests))
        sensors = current_datavector['sensors']

        for key, value in sensors.items():
            self.sensor_label[key].setText(str(value))

            if value:
                self.sensor_label[key].setStyleSheet('color: red')
            else:
                self.sensor_label[key].setStyleSheet('color: green')

        camera_names = [
            key for key in current_datavector if key.startswith('camera')
        ]
        for name in camera_names:
            frame_data = current_datavector[name]  # [type, array, shape]

            frame = BytesIO(base64.decodestring(frame_data.encode("utf-8")))
            frame = np.asarray(Image.open(frame))

            qim = QtGui.QImage(
                frame.data, frame.shape[1], frame.shape[0], frame.strides[0],
                QImage.Format_RGB888)  # https://gist.github.com/smex/5287589
            qim = qim.scaled(200,
                             200,
                             aspectRatioMode=QtCore.Qt.KeepAspectRatio,
                             transformMode=QtCore.Qt.SmoothTransformation)

            self.camera_label[name].setPixmap(QtGui.QPixmap.fromImage(qim))
            self.camera_label[name].adjustSize()

            self.add_log("Received dataset. RPS: " + str(int(pc_rps)))
class ApplicationWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(ApplicationWindow, self).__init__()

        self.ui = Ui_MainWindow()

        #intialize memebers of class plot_data that contains all the functions
        #and the variables needed for plotting to avoid repeativness
        self.Ugraph_1 = Plot_Data()

        #Empty arrays used in singular-import function
        self.Empty_X = []
        self.Empty_Y = []

        #Toggles for the exception handling of pressing start button and crashing before any graph is drawn, used in import
        self.HasEntered1stView = 0

        pg.setConfigOption('background', 'w')

        self.ui.setupUi(self)

        self.ui.StartButton.clicked.connect(self.Startplot)

        self.ui.StopButton.clicked.connect(self.Stop_1)

        self.ui.HideButton.clicked.connect(self.Hide)

        self.ui.ExitButton.clicked.connect(self.Exit)

        self.ui.EmptyButton.clicked.connect(self.Empty)

    def Plot_1(self):
        if self.Ugraph_1.Plot_Stop == 1 and self.HasEntered1stView == 1:
            self.Ugraph_1.Start()
            self.Startplot()
        elif self.HasEntered1stView == 1:
            self.Ugraph_1.Start()

    def Stop_1(self):
        self.Ugraph_1.Stop()

    def Graph1(self):
        #print(self.Ugraph_1.data_Y)
        #(self.Ugraph_1.data_X)

        self.ui.GraphicsView.plot(self.Ugraph_1.data_X,
                                  self.Ugraph_1.data_Y,
                                  pen='r')

        if len(self.Ugraph_1.data_X) > 2:
            self.ui.GraphicsView.setXRange(
                self.Ugraph_1.data_X[-1] -
                (self.Ugraph_1.data_X[1] - self.Ugraph_1.data_X[0]) * 100,
                self.Ugraph_1.data_X[-1])
            min_y = np.amin(self.Ugraph_1.data_Y)
            max_y = np.amax(self.Ugraph_1.data_Y)
            self.ui.GraphicsView.plotItem.getViewBox().setLimits(
                xMin=self.Ugraph_1.data_X[0],
                xMax=self.Ugraph_1.data_X[-1],
                yMin=min_y - min_y * 0.1,
                yMax=max_y + max_y * 0.1)

        QtCore.QCoreApplication.processEvents()
        #self.Ugraph_1.data_stop = self.Ugraph_1.data_stop + 10S
        # if self.Ugraph_1.data_stop >= len(self.Ugraph_1.data_X):
        #     self.Ugraph_1.data_stop = 0
        #     self.Ugraph_1.Stop()

    def Hide(self):
        self.Ugraph_1.Stop()
        self.ui.GraphicsView.clear()

    def Empty(self):
        self.Hide()
        self.Ugraph_1.Empty()

        self.HasEntered1stView = 0
        self.Ugraph_1.GraphIsWav = 0

    def Startplot(self):
        self.Ugraph_1.Plot_Stop = 0
        self.getdatafromserial()

    def getdatafromserial(self):

        threshold = 514.0
        oldvalue = 0
        newvalue = 0

        reading123 = 0
        oldmillis = 0
        newmillis = 0
        timings = [0] * 16

        self.HasEntered1stView = 1

        #insert ur COM here
        ser = Serial('COM15')
        ser.flushInput()

        while self.Ugraph_1.Plot_Stop == 0:
            try:
                ser_bytes = ser.readline()
                decoded_bytes = float(ser_bytes[0:len(ser_bytes) -
                                                2].decode("utf-8"))
            except:
                print("Keyboard Interrupt")
                break

            oldvalue = newvalue
            newvalue = 0

            for i in range(16):  # Average over 16 measurements
                newvalue += decoded_bytes

            newvalue = newvalue / 16

            self.Ugraph_1.data_X.append(
                reading123
            )  #self.Ugraph_1.data_X.append((time.strftime("%H:%M:%S", time.localtime()))) #np.append(self.Ugraph_1.data_X,((time.strftime("%H:%M:%S", time.localtime()))))
            reading123 += 1
            self.Ugraph_1.data_Y.append(
                newvalue)  #np.append(self.Ugraph_1.data_Y,newvalue)
            self.Graph1()

            # find triggering edge
            if oldvalue < threshold and newvalue >= threshold:
                oldmillis = newmillis
                newmillis = time.time() * 1000
                # fill in the current time difference  a ringbuffer
                timings.append((int)(newmillis - oldmillis))
                if len(timings) > 16:
                    timings.pop(0)  #filling queue of time differences
                totalmillis = 0
                # calculate average of the last 16 time differences
                for i in range(16):
                    totalmillis += timings[i]

                # calculate heart rate
                heartrate = 60000 // (totalmillis / 16)

                if heartrate > 40 and heartrate < 130:
                    print(heartrate)
                else:
                    print("Measuring Heart rate")

            QtCore.QCoreApplication.processEvents()

    def Exit(self):
        sys.exit()
Exemple #20
0
from GUI import Ui_MainWindow
from PyQt5 import QtGui, QtWidgets

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    glFormat = QtGui.QSurfaceFormat()
    ui = Ui_MainWindow()
    ui.setupUi(glFormat, MainWindow)
    MainWindow.show()
    code = app.exec_()
    sys.exit(code)
Exemple #21
0
class StartQT4(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        ##################Buttons#######################################################################
        self.ui.pushButton.clicked.connect(self.calculate)
        ##################Buttons#######################################################################

    def calculate(self):
        Vnom = float(self.ui.lineEdit_1.text())
        stallTorque = float(self.ui.lineEdit_2.text())
        motor_ESR = float(self.ui.lineEdit_3.text())
        NL_Curr = float(self.ui.lineEdit_4.text())
        NL_RPM = float(self.ui.lineEdit_5.text())

        spoolDiam = float(self.ui.lineEdit_6.text())
        inputVolt = float(self.ui.lineEdit_7.text())
        PWM_DC = float(self.ui.lineEdit_8.text())
        batt_Ah = float(self.ui.lineEdit_9.text())
        torque_load = float(self.ui.lineEdit_10.text())
        gear_ratio = float(self.ui.lineEdit_21.text())

        #v/rpm
        bemf_const = (Vnom - (motor_ESR * NL_Curr)) / NL_RPM

        #rpm/v (not sure which one to use)
        motor_kv = 1 / bemf_const
        motor_kv = NL_RPM / Vnom

        effective_voltage = inputVolt * PWM_DC / 100.0
        self.ui.lineEdit_13.setText(str(effective_voltage))

        max_torque = stallTorque * effective_voltage / Vnom
        self.ui.lineEdit_11.setText(str(max_torque * gear_ratio))

        shaft_torque = max_torque * torque_load / 100.0
        self.ui.lineEdit_12.setText(str(shaft_torque * gear_ratio))

        #help! this need fixing
        shaft_rpm = (motor_kv *
                     effective_voltage) - (NL_RPM / stallTorque) * shaft_torque
        self.ui.lineEdit_19.setText(str(shaft_rpm / gear_ratio))

        travel_speed = shaft_rpm * 60.0 * 2.0 * 3.14159265359 * spoolDiam / 1000.0
        self.ui.lineEdit_20.setText(str(travel_speed / gear_ratio))

        #current eqn
        i_mot = (effective_voltage - (bemf_const * shaft_rpm)) / motor_ESR
        self.ui.lineEdit_14.setText(str(i_mot))

        power_in = effective_voltage * i_mot
        self.ui.lineEdit_16.setText(str(power_in))

        power_out = shaft_torque * shaft_rpm / 60.0 * 2.0 * 3.14159265359
        self.ui.lineEdit_17.setText(str(power_out))

        efficiency = power_out / power_in * 100
        self.ui.lineEdit_18.setText(str(efficiency))

        runtime_hour = (inputVolt * batt_Ah) / (effective_voltage * i_mot)
        self.ui.lineEdit_15.setText(str(runtime_hour))

        cable_stress = shaft_torque * gear_ratio / (spoolDiam / 2)
        statmsg =  "Cable stress = " + str(round(cable_stress,2)) + "N/m^2 # "  + \
   "Distance travelled/minute = " + str(round(travel_speed*1000.0/60.0/gear_ratio, 2)) + "m # " + \
   "Cable Force = " + str(round(cable_stress/9.80665, 2)) + "kg # " + \
   "Total distance travelled with the battery = " + str(round(travel_speed*runtime_hour/gear_ratio, 2)) + "km"
        self.ui.statusbar.showMessage(statmsg)
Exemple #22
0
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
from GUI import Ui_MainWindow as UIM

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = UIM()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())
Exemple #23
0
class ApplicationWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(ApplicationWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setFixedSize(1500, 930)
        
    ##############  UI control lists  ##############
        self.imageViews = [self.ui.graphicsView , self.ui.graphicsView_2 ] 
        self.legend = [0, 0, 0] # guard for legend overaddition

        for image in self.imageViews : ## hide unwanted options
            image.ui.histogram.hide()
            image.ui.roiBtn.hide()
            image.ui.menuBtn.hide()
            image.ui.roiPlot.hide()

    ############# initialize fourier #############
        self.originalImage0 = cv.cvtColor(cv.imread('images/Brain2.png'),cv.COLOR_BGR2GRAY)
        #plot original
        self.imageViews[0].show()
        self.imageViews[0].setImage(self.originalImage0.T)

        #plot fourier
        self.imageViews[1].show()
        self.imageViews[1].setImage(fourier(self.originalImage0).T)
    ####################################
        #self.axes1 = self.ui.graphicsView1.figure.add_subplot(111, title="$M_x/M_o$ vs time")
        #self.axes2 = self.ui.graphicsView2.figure.add_subplot(111)
        #self.axes3 = self.ui.graphicsView3.figure.add_subplot(111)
        
    ##############  UI Signals  ##############
        self.ui.pushButton.clicked.connect(lambda: self.plotEffect())
        self.ui.pushButton_2.clicked.connect(lambda : self.plotFourier())
        
    ##########################################
    

    

    def plotFourier(self) :
        
        """[summary] : plots : original image, it's fourier transform
        """     
        #Read the image file 
        fname = QtGui.QFileDialog.getOpenFileName( self, 'choose the image', os.getenv('HOME') ,"Images (*.png *.xpm *.jpg)" )
        self.path = fname[0] 
        #Assertion for path errors
        if self.path =="" :
            return
        #convert image to grey Scale
        self.originalImage = cv.cvtColor(cv.imread(self.path),cv.COLOR_BGR2GRAY)
        #plot original
        self.imageViews[0].show()
        self.imageViews[0].setImage(self.originalImage.T)

        #plot fourier
        self.imageViews[1].show()
        self.imageViews[1].setImage(fourier(self.originalImage).T)
        return None
    
    


    def plotEffect(self):
        print("Drawing curves")
            
        B = 1.5
        BPositive = 2.5
        BNegative = 0.5
        gyroRatio = 42
        w = gyroRatio * B
        wPositive = gyroRatio * BPositive
        wNegative = gyroRatio * BNegative
        T1 = 490/1000
        T2 = 43/1000
        t = np.arange(start=0, stop=10, step=0.0001)

        omega = 2*np.pi*w*t
        omegaPositive = 2*np.pi*wPositive*t + np.pi/8
        omegaNegative = 2*np.pi*wNegative*t - np.pi/8


        Mx = np.exp(-1*t/T2)*np.sin(omega)
        MxPositive = np.exp(-1*t/T2)*np.sin(omegaPositive)
        MxNegative = np.exp(-1*t/T2)*np.sin(omegaNegative)


        My = np.exp(-1*t/T2)*np.cos(omega)
        MyPositive = np.exp(-1*t/T2)*np.cos(omegaPositive)
        MyNegative = np.exp(-1*t/T2)*np.cos(omegaNegative)


        Mxy = np.sqrt(Mx**2 + My**2)
        MxyPositive = np.sqrt(MxPositive**2 + MyPositive**2)
        MxyNegative = np.sqrt(MxNegative**2 + MyNegative**2)
        
        self.axes1 = self.ui.graphicsView1.figure.add_subplot(111, title="$M_x/M_o$ vs time",xlabel="time",ylabel="$M_x/M_o$")
        self.axes1.plot(t[:1000], Mx[:1000], 'r', label="No Noise")
        self.axes1.plot(t[:1000], MxPositive[:1000], 'b', label="Positive Noise")
        self.axes1.plot(t[:1000], MxNegative[:1000], 'y', label="Negative Noise")
        if self.legend[0] == 0:
            self.axes1.legend()
            self.legend[0] += 1


        self.axes2 = self.ui.graphicsView2.figure.add_subplot(111,title="$M_y/M_o$ vs time",xlabel="time",ylabel="$M_y/M_o$")
        self.axes2.plot(t[:1000], My[:1000], 'r', label="No Noise")
        self.axes2.plot(t[:1000], MyPositive[:1000], 'b', label="Positive Noise")
        self.axes2.plot(t[:1000], MyNegative[:1000], 'y', label="Negative Noise")
        if self.legend[1] == 0:
            self.axes2.legend()
            self.legend[1] = 1

        self.axes3 = self.ui.graphicsView3.figure.add_subplot(111,title="$M_{xy}$ in X-Y Plane",xlabel="$M_x/M_o$",ylabel="$M_y/M_o$")
        self.axes3.plot(Mx, My, 'r', label="No Noise")
        self.axes3.plot(MxPositive, MyPositive, 'b', label="Positive Noise")
        self.axes3.plot(MxNegative, MyNegative, 'y', label="Negative Noise")
        if self.legend[2] == 0:
            self.axes3.legend()
            self.legend[2] = 1

        self.axes1.figure.canvas.draw()
        self.axes2.figure.canvas.draw()
        self.axes3.figure.canvas.draw()