Exemplo n.º 1
0
 def __init__(self, parent=None):
     super(Quickstart, self).__init__(parent)
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.started = False
     self.start_time = 0
     self.end_time = 0
Exemplo n.º 2
0
class Player(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.show()

        self.ui.filename_lbl.setText("Music Player")
        self.ui.actionOpen.triggered.connect(self.open_file)
        self.ui.actionExit.triggered.connect(self.exit_player)
        self.ui.play_btn.clicked.connect(self.play_music)

        self.loaded_file = False
        self.location = ''

    def open_file(self):
        filenames = QFileDialog.getOpenFileName(self, 'Open File', DIR,
                                                "Audio files (*.wav *.mp3)")
        self.location = filenames[0]
        self.loaded_file = True

    def play_music(self):
        if self.loaded_file:
            self.ui.play_btn.setEnabled(False)
            playsound(self.location)
            self.ui.play_btn.setEnabled(True)

    def exit_player(self):
        sys.exit()
Exemplo n.º 3
0
    def __init__(self, parent=None):
        super(MainUi, self).__init__(parent)

        self.ui = Ui_MainWindow()

        self.ui.setupUi(self)

        page = WebPage()
        self.ui.webView.setPage(page)

        self.loadHTMLTemplate()

        self.timer = QtCore.QTimer()

        self.ui.btnGenRoute.clicked.connect(self.callGetShape)
        self.ui.btnClearPaths.clicked.connect(self.clearPaths)
        self.ui.btnHexToggleMaps.clicked.connect(self.toggleMapsJS)

        self.ui.spinAngle.valueChanged.connect(self.paramsChanged)
        self.ui.spinWidthSize.valueChanged.connect(self.paramsChanged)

        self.connect(self.ui.actionSave_polygon_shape, SIGNAL("triggered()"),
                     self.savePolyShapeToFile)
        self.connect(self.ui.actionLoad_polygon_shape, SIGNAL("triggered()"),
                     self.loadPolyShapeFromFile)
        self.connect(self.ui.actionExit_program, SIGNAL("triggered()"),
                     self.close)
        self.connect(self.ui.actionReload_Map, SIGNAL("triggered()"),
                     self.loadHTMLTemplate)
        self.connect(self.ui.actionExport_Route, SIGNAL("triggered()"),
                     self.exportGPSroute)

        self.path_gps_json = None
        self.path_hex_gps_json = None
        self.roi_gps_json = None
Exemplo n.º 4
0
class MainWindow(qtw.QMainWindow):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.show()
Exemplo n.º 5
0
    def __init__(self):
        # Initalize parent
        QMainWindow.__init__(self)
        
        # Initalize GUI layout
        self.setWindowIcon(QtGui.QIcon('myIcon.png'))
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.eds_data = None
        self.comps = None
        self.technique = "WDS"
        self.read_counts = False
        
        self.ib = None
        self.N = 0 # N is the row_number
        
#        # pre-selection before import files
#        self.ui.elements.clicked.connect(lambda: self.elements)
#        self.ui.technique.clicked.connect(lambda: self.technique)
#        self.ui.read_counts.clicked.connect(lambda: self.read_counts)
#        self.ui.image_plot.clicked.connect(lambda: self.plotting('image'))
#        self.set_combo_Elements(self.comps)
#        self.set_combo_DataElements(self.comps)
        self.set_default_elements()
        self.ui.image_plot.clicked.connect(lambda: self.image_plots())
        self.ui.line_plot.clicked.connect(lambda: self.line_plots())
        self.ui.datashow.clicked.connect(lambda: self.show_data())
        
        self.ui.actionImport_folder.triggered.connect(lambda: self.import_message())
        self.ui.actionImport_folder.triggered.connect(lambda: self.import_data("folder"))
        self.ui.actionImport_file.triggered.connect(lambda: self.import_message())
        self.ui.actionImport_file.triggered.connect(lambda: self.import_data("file"))
        self.ui.actionExport.triggered.connect(lambda: self.export_data())
        self.ui.actionAbout.triggered.connect(self.about)
    def __init__(self):
        """
        Initialize the controller
        """
        super().__init__()

        self.view = Ui_MainWindow()  # Instantiate the view class
        self.view.setupUi(self)  # Set up the UI

        # Connect signals and slots
        # Reset button clears all input fields and the output
        self.view.reset_button.clicked.connect(self.view.value_input.clear)
        self.view.reset_button.clicked.connect(
            self.view.from_currency_input.clear)
        self.view.reset_button.clicked.connect(
            self.view.to_currency_input.clear)
        self.view.reset_button.clicked.connect(self.view.result_display.clear)

        self.view.exit_button.clicked.connect(
            self.close
        )  # Exit button closes the window (and quits the application)
        self.view.live_data.stateChanged['int'].connect(
            self.use_live_data)  # state_changed checkbox switches modes
        self.view.convert_button.clicked.connect(
            self.convert
        )  # Convert button calls convert() method of controller

        # Instantiate the model using an instance of LiveDataConverter (for using online exchange rates)
        self.model = model.MainModel(model.LiveDataConverter())
class window(QtWidgets.QMainWindow):

    def __init__(self):
        super(window, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.encoder = None
        self.digitalCryptographySystem = None
        self.ui.pushButton.clicked.connect(lambda: self.polybius_code())
        self.ui.pushButton_2.clicked.connect(lambda: self.polybius_decode())
        self.ui.pushButton_3.clicked.connect(lambda: self.digitalCryptographySystem_code())
        self.ui.pushButton_4.clicked.connect(lambda: self.digitalCryptographySystem_decode())

    def polybius_code(self):
        self.encoder = Encoder(self.ui.lineEdit.text())
        self.ui.lineEdit_3.setText(self.encoder.code())

    def polybius_decode(self):
        self.encoder.decode()
        self.ui.lineEdit_2.setText(self.encoder.decode_text)

    def digitalCryptographySystem_code(self):
        self.digitalCryptographySystem = DigitalCryptographySystem(self.ui.lineEdit_4.text())
        self.digitalCryptographySystem.code()
        self.ui.lineEdit_5.setText(self.digitalCryptographySystem.encode_text)

    def digitalCryptographySystem_decode(self):
        self.digitalCryptographySystem.decode()
        self.ui.lineEdit_6.setText(self.digitalCryptographySystem.decode_text)
Exemplo n.º 8
0
 def __init__(self, parent=None):
     self.position = 38
     self.gen = Generator()
     QtWidgets.QMainWindow.__init__(self, parent)
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.initUI()
     self.setFixedSize(self.size())
 def __init__(self):
     super(window, self).__init__()
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.encoder = None
     self.digitalCryptographySystem = None
     self.ui.pushButton.clicked.connect(lambda: self.polybius_code())
     self.ui.pushButton_2.clicked.connect(lambda: self.polybius_decode())
     self.ui.pushButton_3.clicked.connect(lambda: self.digitalCryptographySystem_code())
     self.ui.pushButton_4.clicked.connect(lambda: self.digitalCryptographySystem_decode())
Exemplo n.º 10
0
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)

        self.Files = QtGui.QStandardItemModel()
        self.converter = Converter()
        
        x = Ui_MainWindow()
        x.setupUi(self)
        
        self.connect()
        
        self.listView.setModel(self.Files)
Exemplo n.º 11
0
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.show()

        self.ui.filename_lbl.setText("Music Player")
        self.ui.actionOpen.triggered.connect(self.open_file)
        self.ui.actionExit.triggered.connect(self.exit_player)
        self.ui.play_btn.clicked.connect(self.play_music)

        self.loaded_file = False
        self.location = ''
Exemplo n.º 12
0
    def __init__(self):
        super(Ui,
              self).__init__()  # Call the inherited classes __init__ method
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setStyleSheet("QMainWindow {background: '#f0f0f0';}")
        self.statusBar = QtWidgets.QStatusBar()
        self.setStatusBar(self.statusBar)
        self.pushButton = self.ui.pushButton
        self.com_in = self.ui.com_in
        self.com_out = self.ui.com_out
        self.baud_in = self.ui.baud_in
        self.baud_out = self.ui.baud_out
        self.pitch_correction = self.ui.pitch_correction
        self.roll_correction = self.ui.roll_correction
        self.console_out = self.ui.console_out
        self.console_in = self.ui.console_in
        self.menubar = self.ui.menubar

        self.pushButton.clicked.connect(self.start)
        self.flag = True
        self.setWindowTitle('LGC TILT')
        self.pushButton.setStyleSheet(
            'QPushButton {background-color: #E7F1E1; border:  none}')
        com_list = []
        for i in serial.tools.list_ports.comports():
            com_list.append(str(i).split(" ")[0])
        sorted_list = []
        for i in range(300):
            this_com = ("COM" + str(i))
            if this_com in com_list:
                sorted_list.append(this_com)
        self.com_in.addItems(sorted_list)
        self.com_out.addItems(sorted_list)
        self.threadpool = QtCore.QThreadPool()
        self.serial_object = None
        self.settings = QtCore.QSettings(self.objectName())
        self.com_in.setCurrentIndex(self.settings.value('com_in', 0))
        self.com_out.setCurrentIndex(self.settings.value('com_out', 1))
        self.baud_in.setCurrentIndex(self.settings.value('baud_in', 2))
        self.baud_out.setCurrentIndex(self.settings.value('baud_out', 2))
        self.pitch_correction.setText(
            self.settings.value('pitch_correction', '0'))
        self.roll_correction.setText(
            self.settings.value('roll_correction', '0'))
        self.restoreGeometry(self.settings.value('geo', self.saveGeometry()))
        self.settings.setValue('com_in', self.com_in.currentIndex())
        self.worker = None
        self.menubar.setHidden(True)
        self.show()  # Show the GUI
Exemplo n.º 13
0
    def __init__(self):
        super().__init__()
        self.setting = {}
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.dir = '../../captcha'
        self.png_dict = self.load_csv()
        for name in self.list_png():
            if not name in self.png_dict:
                self.png_dict[name] = ""
        self.png_list = list(self.png_dict.keys())
        self.png_list.sort()
        self.idx = 0
        self.update_img()

        self.ui.lableLineEdit.installEventFilter(self)
Exemplo n.º 14
0
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # ====================
        # == output browser ==
        # ====================
        linePlainTextEdit = LinePlainTextEdit(self)
        outputTextBrowser = self.ui.outputTextBrowser
        self.ui.verticalLayout.replaceWidget(outputTextBrowser, linePlainTextEdit)
        self.ui.outputTextBrowser = linePlainTextEdit
        self.ui.outputTextBrowser.setReadOnly(True)
        outputTextBrowser.deleteLater()

        self.ui.outputTextBrowser.setLineWrapMode(QPlainTextEdit.NoWrap)
        scrollBar = self.ui.outputTextBrowser.verticalScrollBar()
        scrollBar.setStyleSheet("background-color: rgb(240, 240, 240);\n""color: rgb(12, 12, 12);")
        scrollBar = self.ui.outputTextBrowser.horizontalScrollBar()
        scrollBar.setStyleSheet("background-color: rgb(240, 240, 240);\n""color: rgb(12, 12, 12);")
        self.ui.outputTextBrowser.setStyleSheet("background-color: rgb(30, 30, 30);\n""color: rgb(236, 236, 236);")
        self.ui.outputTextBrowser.installEventFilter(self)
        font = QFont()
        font.setFamily("Consolas")
        font.setPointSize(14)
        self.ui.outputTextBrowser.setFont(font)
        # =============================

        self.ser = serial_port.QPySerial()
        self.ser.errorOccurred.connect(self.on_serial_errorOccurred)
        self.load_setting()
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.read_from_ser)
        self.setWindowIcon(QIcon(r':icon.ico'))
        self.setWindowTitle('ATerm '+__version__)


        buads = [9600, 115200] + self.setting['custom_baud']
        buads = [str(b) for b in sorted(list(set(buads)))]
        self.ui.baudComboBox.addItems(buads)
        self.ui.baudComboBox.setLineEdit(QLineEdit())

        self.on_refreshBtn_clicked()
Exemplo n.º 15
0
    def __init__(self, parent=None):
        self.allCSV = None

        self.plotArray = None

        self.numRow = 8
        self.numColumn = 12
        self.startWell = 1 
        self.endWell = 96
        self.umPerPixel = 0.149
      
        self.minXList = []
        self.maxXList = []
        self.minYList = []
        self.maxYList = []
       
        self.minX = None
        self.maxX = None
        self.minY= None
        self.maxY = None

        self.previousWells = [] 

        QtGui.QMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
      
        self.wellMapper = {QtCore.QString(u'0'): range(0,0),
                           QtCore.QString(u'1'): range(1,13,2) + range(49,61,2),
                           QtCore.QString(u'2'): range(2,13,2) + range(50,61,2),
                           QtCore.QString(u'3'): range(13,25,2) + range(61,73,2),
                           QtCore.QString(u'4'): range(14,25,2) + range(62,73,2),
                           QtCore.QString(u'5'): range(25,37,2) + range(73,85,2),
                           QtCore.QString(u'6'): range(26,37,2) + range(74,85,2),
                           QtCore.QString(u'7'): range(37,49,2) + range(85,97,2),
                           QtCore.QString(u'8'): range(38,49,2) + range(86,97,2),
                           True: range(1,97),
                           False: range(0,0)}
                           

         
        QtCore.QObject.connect(self.ui.comboBox, QtCore.SIGNAL('currentIndexChanged(const QString &)'), self.updateSelectedPlot) 
        QtCore.QObject.connect(self.ui.checkBox_show_all, QtCore.SIGNAL('clicked(bool)'), self.updateSelectedPlot)
        
        self.plotArray = [[None for x in range(self.numColumn)] for y in range(self.numRow)]
        
        for row in range(self.numRow):
            for column in range(self.numColumn):
                self.plotArray[row][column] = MyPlot(pg.PlotItem(title='well ' + str(row*self.numColumn + column+1)))
                self.ui.widget.addItem(self.plotArray[row][column].pgPlot)
            self.ui.widget.nextRow()
Exemplo n.º 16
0
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.theX = []
        self.ui.theY = []

        self.colors = [Red(), Blue(), Black(), Green(), Violet()]
        for item in self.colors:
            self.addComboBoxItem(item.num, item.name)

        self.ui.wybierz.clicked.connect(self.selectFile)
        self.fileSelect = QtGui.QFileDialog(self)
        self.ui.rysuj.clicked.connect(self.printChart)
        self.scene = QtGui.QGraphicsScene()
        self.ui.slupkowy.clicked.connect(self.getSelectedRadio)
        self.ui.kolowy.clicked.connect(self.getSelectedRadio)
        self.ui.liniowy.clicked.connect(self.getSelectedRadio)
        self.ui.punktowy.clicked.connect(self.getSelectedRadio)
        self.ui.slupkowy.click()
class Controller(QMainWindow):
    """
    The PyQt controller class, responsible for processing GUI events.

    This class subclasses QMainWindow to work with the layout.py file (which was created from a .ui file using pyuic5).
    Without subclassing QMainWindow, this class wouldn't have access to the GUI components (such as buttons, input
    fields etc.)
    """
    def __init__(self):
        """
        Initialize the controller
        """
        super().__init__()

        self.view = Ui_MainWindow()  # Instantiate the view class
        self.view.setupUi(self)  # Set up the UI

        # Connect signals and slots
        # Reset button clears all input fields and the output
        self.view.reset_button.clicked.connect(self.view.value_input.clear)
        self.view.reset_button.clicked.connect(
            self.view.from_currency_input.clear)
        self.view.reset_button.clicked.connect(
            self.view.to_currency_input.clear)
        self.view.reset_button.clicked.connect(self.view.result_display.clear)

        self.view.exit_button.clicked.connect(
            self.close
        )  # Exit button closes the window (and quits the application)
        self.view.live_data.stateChanged['int'].connect(
            self.use_live_data)  # state_changed checkbox switches modes
        self.view.convert_button.clicked.connect(
            self.convert
        )  # Convert button calls convert() method of controller

        # Instantiate the model using an instance of LiveDataConverter (for using online exchange rates)
        self.model = model.MainModel(model.LiveDataConverter())

    def convert(self):
        """
        Convert money from a currency to other currencies.

        This method reads the user input from the UI and converts the value from the specified base currency to all the
        specified target currencies. The result is displayed as HTML formatted text in the text field.
        """

        # Read the values from the input fields
        base_value = self.view.value_input.value()
        base_currency = self.view.from_currency_input.text().strip(
        )  # Remove leading and trailing whitespace
        target_currencies = self.view.to_currency_input.text().replace(
            " ", "")  # Remove whitespace

        try:
            # Convert to the target currencies and display the result in the TextEdit
            html_str = self.model.convert(base_value, base_currency,
                                          target_currencies)
            self.view.result_display.setHtml(html_str)
            self.view.statusBar.showMessage("Umrechnung ausgeführt")
        except RuntimeError as e:
            # Catch RuntimeErrors and display the error messages as status message
            self.view.statusBar.showMessage(str(e))
        except KeyError as e:
            # Catch KeyErrors and display the error messages as status message
            self.view.statusBar.showMessage(str(e))
        except ConnectionError as e:
            # Catch ConnectionErrors and display the error messages as status message
            self.view.statusBar.showMessage(
                "Beim Abrufen der Wechselkurse ist ein Fehler aufgetreten - bitte überprüfe deine Internetverbindung"
            )

    def use_live_data(self, checkbox_state):
        """
        Switch between using current exchange rates and offline exchange rates for conversion.

        If live data should be used, the exchange rates are retrieved from exchangeratesapi.io. The application however
        also supports using exchange rates that were cached offline. These may be not as accurate.

        :param checkbox_state: The state of the "Live Data" checkbox. Since the checkbox is not a tristate checkbox,
            there are two possible values (0 and 2). 0 (unchecked) means that the offline exchange rates should be used.
            2 (checked) means that the exchange rates should be queried from exchangeratesapi.io.
        """
        if checkbox_state == 0:
            # Switch to offline data (using an instance of OfflineConverter)
            self.model.set_converter(model.OfflineConverter())
            self.view.statusBar.showMessage(
                "Es werden Offline-Daten verwendet")

        elif checkbox_state == 2:
            # Switch to online exchange rate data (using an instance of LiveDataConverter)
            self.model.set_converter(model.LiveDataConverter())
            self.view.statusBar.showMessage(
                "Es werden aktuelle Online-Daten verwendet")
Exemplo n.º 18
0
class pyPDMtools_GUI(QMainWindow):
    def __init__(self):
        # Initalize parent
        QMainWindow.__init__(self)
        
        # Initalize GUI layout
        self.setWindowIcon(QtGui.QIcon('myIcon.png'))
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.eds_data = None
        self.comps = None
        self.technique = "WDS"
        self.read_counts = False
        
        self.ib = None
        self.N = 0 # N is the row_number
        
#        # pre-selection before import files
#        self.ui.elements.clicked.connect(lambda: self.elements)
#        self.ui.technique.clicked.connect(lambda: self.technique)
#        self.ui.read_counts.clicked.connect(lambda: self.read_counts)
#        self.ui.image_plot.clicked.connect(lambda: self.plotting('image'))
#        self.set_combo_Elements(self.comps)
#        self.set_combo_DataElements(self.comps)
        self.set_default_elements()
        self.ui.image_plot.clicked.connect(lambda: self.image_plots())
        self.ui.line_plot.clicked.connect(lambda: self.line_plots())
        self.ui.datashow.clicked.connect(lambda: self.show_data())
        
        self.ui.actionImport_folder.triggered.connect(lambda: self.import_message())
        self.ui.actionImport_folder.triggered.connect(lambda: self.import_data("folder"))
        self.ui.actionImport_file.triggered.connect(lambda: self.import_message())
        self.ui.actionImport_file.triggered.connect(lambda: self.import_data("file"))
        self.ui.actionExport.triggered.connect(lambda: self.export_data())
        self.ui.actionAbout.triggered.connect(self.about)
        
    
    def set_default_elements(self):
        self.ui.combo_E1.setCurrentIndex(5)
        self.ui.combo_E2.setCurrentIndex(6)
        self.ui.combo_E3.setCurrentIndex(7)
        
        self.ui.combo_Colormap.setCurrentIndex(1)
        
        self.ui.tableWidget_pick.setRowCount(100)
        self.ui.tableWidget_pick.setShowGrid(True)


    def set_combo_Elements(self, elems):
        """ To set the elements for mapping plot.
        """
        _translate = QtCore.QCoreApplication.translate
        self.ui.combo_Element.setItemText(0, _translate("MainWindow", "Element"))
        self.ui.combo_Element.setItemText(1, _translate("MainWindow", elems[0]))
        self.ui.combo_Element.setItemText(2, _translate("MainWindow", elems[1]))
        self.ui.combo_Element.setItemText(3, _translate("MainWindow", elems[2]))
        self.ui.combo_Element.setCurrentIndex(1)
    
    
    def set_combo_DataElements(self, elems):
        """ To set the elements for showing data
        """
        _translate = QtCore.QCoreApplication.translate
        self.ui.combo_DataElement.setItemText(0, _translate("MainWindow", "Element"))
        self.ui.combo_DataElement.setItemText(1, _translate("MainWindow", elems[0]))
        self.ui.combo_DataElement.setItemText(2, _translate("MainWindow", elems[1]))
        self.ui.combo_DataElement.setItemText(3, _translate("MainWindow", elems[2]))
        self.ui.combo_DataElement.setCurrentIndex(1)
    
    
    def import_data(self, type = "folder"):
        """ To import all comps files for each element from the folder.
        """
        # check if input elements is valid.
        self.pre_import_setting()
        
        if (not self.is_valid_elements()):
            return
        
        if type == "folder":
            path = QFileDialog.getExistingDirectory(None, "Please select a folder") 
            folder_path = str(path) + "/"
                
            self.eds_data = EDS_data(folder_path, self.comps, self.technique, read_counts = self.read_counts)
            self.statusBar().showMessage('Import folder successfully!', 2000)
        
        elif type == "file":
            # file dialog pop up, user can choose a csv or a txt file
            path, ext = QFileDialog.getOpenFileName(None, "Please select a file", "", "All Files (*);; CSV files (*.csv);; TXT files (*.txt)") 
            folder_path = str(Path(path).parent) + "\\"
            # return if there are no path or the file format is not correct
            if not (path.endswith('.csv') or path.endswith('.txt')):
                return
        
        self.after_import_setting()
    
    
    def export_data(self):
#        options = QFileDialog.Options()
#        options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getSaveFileName(self, 
                                                  "Save a data file", 
                                                  os.getcwd(), 
                                                  "csv Files (*.csv);; txt Files (*.txt);; All Files (*)", 
#                                                  options = options
                                                  )
        if fileName:
#            print(fileName)
            data_save = self.transfer_data()
            data_save.to_csv(fileName, index = False)
            self.statusBar().showMessage(f'Save data to {fileName} successfully!', 2000)
                
    def transfer_data(self):
        df = pd.DataFrame()
        row_num = self.ui.tableWidget_pick.rowCount()
        col_num = self.ui.tableWidget_pick.columnCount()
#        print(self.ui.tableWidget_pick.selectedItems())
        for col in range(col_num):
            col_name = str(self.ui.tableWidget_pick.horizontalHeaderItem(col).text())
            col_list = []
            for row in range(row_num):
                data1 = self.ui.tableWidget_pick.item(row, col)
                if data1 is not None:
                    col_list.append(float(data1.text()))
                else:
                    col_list.append(np.nan)
            df[col_name] = col_list
            
        return df
    
        
    def pre_import_setting(self):
        e1 = str(self.ui.combo_E1.currentText())
        e2 = str(self.ui.combo_E2.currentText())
        e3 = str(self.ui.combo_E3.currentText())
        self.comps = [e1, e2, e3]
        self.set_combo_Elements(self.comps)
        self.set_combo_DataElements(self.comps)
    
    
    def after_import_setting(self):
        e1 = str(self.ui.combo_E1.currentText())
        e2 = str(self.ui.combo_E2.currentText())
        e3 = str(self.ui.combo_E3.currentText())
        self.ui.tableWidget_pick.setHorizontalHeaderItem(0, QTableWidgetItem(e1))
        self.ui.tableWidget_pick.setHorizontalHeaderItem(1, QTableWidgetItem(e2))
        self.ui.tableWidget_pick.setHorizontalHeaderItem(2, QTableWidgetItem(e3))
    
    
    def show_data(self):
        """ To present data in the tabular area / table.
        """
        if (self.eds_data == None):
            text = "Please import data first, then show the comp data."
            self.ui.datashow.clicked.connect(lambda: self.message_connect(text))
            return
        
        e1 = str(self.ui.combo_E1.currentText())
        e2 = str(self.ui.combo_E2.currentText())
        e3 = str(self.ui.combo_E3.currentText())
        
        if (not self.is_valid_elements()):
            text = f"Wrong Elements selection: {e1}, {e2}, {e3}."
            self.ui.datashow.clicked.connect(lambda: self.message_connect(text))
            return
        
        current_element = str(self.ui.combo_DataElement.currentText())
        if current_element not in self.comps:
            text = f"Selected element {current_element} is not in [{e1}, {e2}, {e3}]."
            self.ui.datashow.clicked.connect(lambda: self.message_connect(text))
            return
        
        data_show = self.eds_data.data[current_element]
        num_row, num_col = data_show.shape
        self.ui.tableWidget.setColumnCount(num_col)
        self.ui.tableWidget.setRowCount(num_row)
        
        for i in range(num_row):
            for j in range(num_col):
                self.ui.tableWidget.setItem(i, j, QTableWidgetItem(str(data_show[i, j])))
        
        self.ui.tableWidget.resizeColumnsToContents()
    
    
    def message_connect(self, message_text):
        """ To show error message and remind user what to do to fix the error.
        """
        msg = QMessageBox()
        msg.setWindowTitle("Error")
        msg.setText(message_text)
#        msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)      
        msg.exec()
    
    
    def import_message(self):
        """ To show error message in importing folder/files and remind user what to do to fix the error.
        """
        if (self.is_valid_elements()): return
        
        msg = QMessageBox()
        msg.setWindowTitle("Error")
        msg.setText("Please select valid elements first.")
#        msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)      
        msg.exec()
        
    
    def closeEvent(self, event):
        """Generate 'question' dialog on clicking 'X' button in title bar.

        Reimplement the closeEvent() event handler to include a 'Question'
        dialog with options on how to proceed - Save, Close, Cancel buttons
        """        
        reply = QMessageBox.question(
            self, "Message",
            "Are you sure you want to quit?",
            QMessageBox.Save | QMessageBox.Close | QMessageBox.Cancel,
            QMessageBox.Save)

        if reply == QMessageBox.Close:
            event.accept()
        else:
            event.ignore()
    
    
    def is_valid_elements(self) -> bool:
        """ To check if the three elements are valid.
        """
        e1 = str(self.ui.combo_E1.currentText())
        e2 = str(self.ui.combo_E2.currentText())
        e3 = str(self.ui.combo_E3.currentText())
        
        if (e1 == "E1" or e2 == "E2" or e3 == "E3"): return False
        
        set1 = set({e1, e2, e3})
        if (len(set1) < 3): return False
        
        return True
        
    
    def line_plots(self):
        """
        still in test mode
        """
        fig = plt.figure(figsize=(6,6))
        ax = fig.add_subplot(111)
        ax.set_xlim([-1,6])
        ax.set_ylim([-1,6])
        ax.plot([0,1,2,3,4,5],[0,1,2,3,4,5],'o--')
        canvas = FigureCanvas(fig)
#        toolbar = NavigationToolbar(canvas, self)
        graphicscene = QtWidgets.QGraphicsScene(0, 0, 650, 610)
#        graphicscene.addWidg
        graphicscene.addWidget(canvas)
        self.ui.line.setScene(graphicscene)
#        self.ui.line.fitInView(graphicscene, True)
        self.ui.line.show()

        
    def image_plots(self):
        current_element = str(self.ui.combo_Element.currentText())
        current_cmap = str(self.ui.combo_Colormap.currentText())
        figsize = 8
        fig, ax = edsmap.colormap2d(self.eds_data.data[current_element], figsize = figsize, cmap = current_cmap, close = False)
        self.show_picked_data()
        # update N
        if (self.ib is not None):
            count = 0
            for ibs in self.ib.linebuilder:
                count += max([len(ib.coords) for ib in ibs])
            self.N += count
        print("N = ", self.N)
        self.set_image_interactive(fig, ax)
#        canvas = FigureCanvas(fig)
#        
##        toolbar = NavigationToolbar(canvas, self)
#        layout = QtWidgets.QVBoxLayout()
##        layout.addWidget(toolbar)
#        layout.addWidget(canvas)
##        self.ui.image_toolbar.setLayout(layout)
#        
##        graphicscene = QtWidgets.QGraphicsScene(0, 20, figsize / 2*100, figsize / 2*100)
##        graphicscene.addWidget(canvas)
##        self.ui.image.setScene(graphicscene)
#        self.ui.image.setLayout(layout)
##        self.setCentralWidget(widget)
##        self.ui.image.setInteractive(True)
    
    
    def show_picked_data(self):
        """ To present the picked data from interactive comp-dis profiles.
        """
        
        
    def set_image_interactive(self, fig, ax):
        self.ib = ImageBuilder(fig, ax, self.eds_data.data) #, self.N, self.ui.tableWidget_pick
        
    
    def show_figure(self, fig):
        # create a dummy figure and use its
        # manager to display "fig"
    
        dummy = plt.figure()
        new_manager = dummy.canvas.manager
        new_manager.canvas.figure = fig
        fig.set_canvas(new_manager.canvas)
    
    
    def about(self):
        QMessageBox.about(
            self,
            "About Phase Diagram Mapping",
            "<p>Map the phase diagram of ternary system based on the composition measurements form EDS/WDS mapping techniques, this app is built with:</p>"
            "<p>- PyQt</p>"
            "<p>- Qt Designer</p>"
            "<p>- Python</p>",
        )
Exemplo n.º 19
0
class AppWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # ====================
        # == output browser ==
        # ====================
        linePlainTextEdit = LinePlainTextEdit(self)
        outputTextBrowser = self.ui.outputTextBrowser
        self.ui.verticalLayout.replaceWidget(outputTextBrowser, linePlainTextEdit)
        self.ui.outputTextBrowser = linePlainTextEdit
        self.ui.outputTextBrowser.setReadOnly(True)
        outputTextBrowser.deleteLater()

        self.ui.outputTextBrowser.setLineWrapMode(QPlainTextEdit.NoWrap)
        scrollBar = self.ui.outputTextBrowser.verticalScrollBar()
        scrollBar.setStyleSheet("background-color: rgb(240, 240, 240);\n""color: rgb(12, 12, 12);")
        scrollBar = self.ui.outputTextBrowser.horizontalScrollBar()
        scrollBar.setStyleSheet("background-color: rgb(240, 240, 240);\n""color: rgb(12, 12, 12);")
        self.ui.outputTextBrowser.setStyleSheet("background-color: rgb(30, 30, 30);\n""color: rgb(236, 236, 236);")
        self.ui.outputTextBrowser.installEventFilter(self)
        font = QFont()
        font.setFamily("Consolas")
        font.setPointSize(14)
        self.ui.outputTextBrowser.setFont(font)
        # =============================

        self.ser = serial_port.QPySerial()
        self.ser.errorOccurred.connect(self.on_serial_errorOccurred)
        self.load_setting()
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.read_from_ser)
        self.setWindowIcon(QIcon(r':icon.ico'))
        self.setWindowTitle('ATerm '+__version__)


        buads = [9600, 115200] + self.setting['custom_baud']
        buads = [str(b) for b in sorted(list(set(buads)))]
        self.ui.baudComboBox.addItems(buads)
        self.ui.baudComboBox.setLineEdit(QLineEdit())

        self.on_refreshBtn_clicked()

    def closeEvent(self, event):
        self.on_connectBtn_clicked(force_off=True)
        self.save_setting()
        event.accept()

    
    def eventFilter(self, source, event):
        if event.type() == QEvent.KeyPress and source is self.ui.outputTextBrowser:
            key = event.key()
            if self.ser.is_open() and (key == Qt.Key_Enter or key == Qt.Key_Return):
                self.on_sendBtn_clicked()
            else:
                if event.key() == Qt.Key_Backspace:
                    txt = self.ui.inputLineEdit.text()[:-1]
                elif event.text() in string.printable:
                    txt = self.ui.inputLineEdit.text() + event.text()
                else:
                    txt = self.ui.inputLineEdit.text()
                self.ui.inputLineEdit.setText(txt)
            # print('key press:', (event.key(), event.text()))
        return super(AppWindow, self).eventFilter(source, event)

    def load_setting(self):
        self.setting = yaml.load(default_setting, Loader=yaml.SafeLoader)
        if os.path.isfile('setting.yaml'):
            with open('setting.yaml', 'r') as f:
                setting = yaml.load(f, Loader=yaml.SafeLoader)
            self.setting.update(setting)
    
    def save_setting(self):
        with open('setting.yaml', 'w', encoding='utf-8') as f:
            yaml.dump(self.setting, f, encoding='utf-8')

    def read_from_ser(self):
        if self.ser.in_waiting() > 0:
            text = self.ser.read(self.ser.in_waiting()).decode('ascii')
            self.append_term(text)

    def append_term(self, text):
        scrollBar = self.ui.outputTextBrowser.verticalScrollBar()
        slider_pos = scrollBar.value()
        self.ui.outputTextBrowser.moveCursor(QTextCursor.End)
        self.ui.outputTextBrowser.insertPlainText(text)
        if self.ui.autoScrollCheckBox.isChecked():
            scrollBar.setValue(scrollBar.maximum())
        else:
            scrollBar.setValue(slider_pos)

    @Slot(int)
    def on_autoScrollCheckBox_stateChanged(self, state):
        if (state == Qt.Checked):
            scrollBar = self.ui.outputTextBrowser.verticalScrollBar()
            scrollBar.setValue(scrollBar.maximum())

    @Slot()
    def on_refreshBtn_clicked(self):
        self.on_connectBtn_clicked(force_off=True)
        ports = serial.tools.list_ports.comports()
        ports = ['{} - {}'.format(device.device, device.description) for device in ports]
        self.ui.portComboBox.clear()
        self.ui.portComboBox.addItems(ports)
        for target in self.setting['priority']:
            for i, port in enumerate(ports):
                if target.lower() in port.lower():
                    self.ui.portComboBox.setCurrentIndex(i)
                    return

        # self.ui.portComboBox.view().setMinimumWidth(100)
    
    @Slot(int)
    def on_portComboBox_currentIndexChanged(self, index):
        port_name = self.ui.portComboBox.itemText(index)
        for k, v in self.setting['baud'].items():
            if k.lower() in port_name.lower():
                self.ui.baudComboBox.setCurrentIndex(0)
                self.ui.baudComboBox.setEditText(str(v))

    @Slot()
    def on_connectBtn_clicked(self, force_off=False):
        if self.ui.connectBtn.text() == 'Connect' and not force_off:
            dev = self.ui.portComboBox.currentText().split('-')[0].strip()
            baud_rate = int(self.ui.baudComboBox.currentText())
            if dev == '': return
            try:
                self.ser.open(dev, baud_rate)
            except serial.serialutil.SerialException as e:
                msg = e.args[0][0].upper() + e.args[0][1:]
                QMessageBox.critical(self,"Serial Error", msg)
                return
            self.ui.connectBtn.setText('Disconnect')
            self.timer.start(200)
            self.ui.inputLineEdit.returnPressed.connect(self.on_sendBtn_clicked)
            self.ui.sendBtn.setEnabled(True)
            self.ui.sendFileBtn.setEnabled(True)
            self.ui.portComboBox.setEnabled(False)
            self.ui.baudComboBox.setEnabled(False)
            self.ui.refreshBtn.setEnabled(False)
        else:
            self.timer.stop()
            if self.ser.is_open():
                self.ser.close()
            try: self.ui.inputLineEdit.returnPressed.disconnect()
            except: pass
            self.ui.sendBtn.setEnabled(False)
            self.ui.sendFileBtn.setEnabled(False)
            self.ui.portComboBox.setEnabled(True)
            self.ui.baudComboBox.setEnabled(True)
            self.ui.refreshBtn.setEnabled(True)
            self.ui.connectBtn.setText('Connect')

    @Slot()
    def on_sendFileBtn_clicked(self):
        path = os.getcwd()
        if 'path' in self.setting and os.path.exists(path):
            if os.path.isfile(path):
                path = os.path.dirname(self.setting['path'])
            else:
                path = self.setting['path']
        fileName = QFileDialog.getOpenFileName(parent=self, caption="Choose file", dir=path)[0]
        if os.path.isfile(fileName):
            self.setting['path'] = os.path.dirname(fileName)
            dialog = SendFileDialog(fileName, self.ser, self)
            dialog.exec_()
            # with open(fileName, 'rb') as f:
            #     self.ser.write(f.read(), 0)
            # while self.ser.out_waiting() > 0:
            #     print(self.ser.out_waiting())
            #     time.sleep(0.2)

    @Slot()
    def on_sendBtn_clicked(self):
        eol = ''
        if self.ui.EOLComboBox.currentText() == 'LF':
            eol = '\n'
        elif self.ui.EOLComboBox.currentText() == 'CR;LF':
            eol = '\r\n'
        elif self.ui.EOLComboBox.currentText() == 'CR':
            eol = '\r'
        text = self.ui.inputLineEdit.text()
        text = text + eol
        self.ser.write(text.encode('ascii'))
        self.ui.inputLineEdit.setText('')

    @Slot(int)
    def on_serial_errorOccurred(self, error):
        if serial_port.CLOSED != error:
            self.on_connectBtn_clicked(True)

    @Slot()
    def on_clearOutputBtn_clicked(self):
        self.ui.outputTextBrowser.clear()
Exemplo n.º 20
0
class MainUi(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainUi, self).__init__(parent)

        self.ui = Ui_MainWindow()

        self.ui.setupUi(self)

        page = WebPage()
        self.ui.webView.setPage(page)

        self.loadHTMLTemplate()

        self.timer = QtCore.QTimer()

        self.ui.btnGenRoute.clicked.connect(self.callGetShape)
        self.ui.btnClearPaths.clicked.connect(self.clearPaths)
        self.ui.btnHexToggleMaps.clicked.connect(self.toggleMapsJS)

        self.ui.spinAngle.valueChanged.connect(self.paramsChanged)
        self.ui.spinWidthSize.valueChanged.connect(self.paramsChanged)

        self.connect(self.ui.actionSave_polygon_shape, SIGNAL("triggered()"),
                     self.savePolyShapeToFile)
        self.connect(self.ui.actionLoad_polygon_shape, SIGNAL("triggered()"),
                     self.loadPolyShapeFromFile)
        self.connect(self.ui.actionExit_program, SIGNAL("triggered()"),
                     self.close)
        self.connect(self.ui.actionReload_Map, SIGNAL("triggered()"),
                     self.loadHTMLTemplate)
        self.connect(self.ui.actionExport_Route, SIGNAL("triggered()"),
                     self.exportGPSroute)

        self.path_gps_json = None
        self.path_hex_gps_json = None
        self.roi_gps_json = None

    def loadFinishedHtml(self):
        msg = "Map reloaded"
        print msg
        self.ui.labelStatus.setText(msg + " " + str(datetime.datetime.now()))
        pass

    def savePolyShapeToFile(self):
        self.ui.labelStatus.setText("Polygon shape saved... " +
                                    str(datetime.datetime.now()))
        if self.roi_gps_json is not None:
            with open(
                    os.path.expanduser('~') + '/.dronemapgenerator.map',
                    'w') as file:
                file.write(json.dumps(self.roi_gps_json, ensure_ascii=True))
        pass

    def loadPolyShapeFromFile(self):
        with open(os.path.expanduser('~') +
                  '/.dronemapgenerator.map') as map_file:
            data = json.load(map_file)

        json_data = json.dumps(data)
        print 'json_data', json_data
        self.ui.webView.page().mainFrame().evaluateJavaScript(
            "setROIGPS(\'{0}\');".format(json.dumps(data)))
        self.ui.labelStatus.setText("Polygon shape loaded... " +
                                    str(datetime.datetime.now()))
        pass

    def loadHTMLTemplate(self, filename='map_template.html'):
        msg = "Loading map..."
        self.ui.labelStatus.setText(msg + " " + str(datetime.datetime.now()))

        html_template = ""
        try:
            with open(filename, 'r') as template_file:
                html_template = template_file.read()
        except Exception as e:
            print "Error {0}".format(str(e))
            msg = "Error loading map: {0} : ".format(
                str(e), str(datetime.datetime.now()))
            self.ui.labelStatus.setText(msg)

        self.ui.webView.setHtml(html_template, QtCore.QUrl('qrc:/'))
        self.ui.webView.page().mainFrame().addToJavaScriptWindowObject(
            'self', self)
        self.ui.webView.loadFinished.connect(self.loadFinishedHtml)
        pass

    def clearPaths(self):
        self.path_gps_json = None
        self.addLoadingModal()
        self.ui.webView.page().mainFrame().evaluateJavaScript(
            "clearGeneratedPaths();")
        self.removeLoadingModal()
        pass

    def addLoadingModal(self):
        self.ui.webView.page().mainFrame().evaluateJavaScript(
            "addLoadingModal();")

    def removeLoadingModal(self):
        self.ui.webView.page().mainFrame().evaluateJavaScript(
            "removeLoadingModal();")

    def callGetShape(self):
        self.ui.webView.page().mainFrame().evaluateJavaScript(
            "centerOnShape();")
        self.addLoadingModal()
        self.ui.webView.page().mainFrame().evaluateJavaScript(
            "setTimeout(function(){sendShapeToQT();}, 350);")

    def paramsChanged(self, val):
        print 'paramsChanged...', val
        self.callGetShape()
        pass

    def exportGPSroute(self):
        routes = {}
        if self.path_gps_json:
            routes['magnetic'] = self.path_gps_json

        if self.path_hex_gps_json:
            for k, v in self.path_hex_gps_json.items():
                routes['aerial_' + str(k)] = v

        print 'Routes:', routes

        if len(routes.keys()) > 0:
            directory = QtGui.QFileDialog.getExistingDirectory(
                self, 'Select directory to export routes ...')
            directory = str(directory)
            print 'selected dir', directory
        else:
            self.ui.labelStatus.setText(
                "Error: No route available to export, generate one route first... "
                + str(datetime.datetime.now()))

        hex_altitude_multiplicator = 0  # at every hex drone add some meters of altitude
        for k, v in routes.items():
            filename = k + '.txt'
            filepath = os.path.join(directory, filename)
            print "Writting to file...", filepath, v

            header = "QGC WPL 110"

            # 0 : counter
            # 1 : mission start (all 0 only one set as 1)
            # 2 : type of command, 0 to set home, 3 to go to waypoint, 10 follow terrain
            # 3 : command, 16 go to waypoint, 22 takeoff, 20 RTL, 115 CONDITION-YAW, 203 trigger cam
            # 4 : time to wait at waypoint/min pitch when command=22/desired yaw when command=115
            # 5 : reach radius
            # 6 : ??
            # 7 : desired angle at waypoint. INFO: not used, use CONDITION-YAW instead
            # 8 : lat
            # 9 : lon
            # 10 : altitude

            base_srt = "{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}\t{9}\t{10}\t1"

            p_counter = 0
            gps_export_str = []
            reach_radius = 1
            desired_angle = 0
            wp_alt_type = 3

            if k is 'magnetic':
                altitude_mts = self.ui.spinAltitude.value()
                time_to_wait = self.ui.spinSeconds.value()
                desired_angle = self.ui.spinAngle.value()
                wp_alt_combo_text = self.ui.comboWPALT.currentText()
                if wp_alt_combo_text == "Follow Terrain":
                    wp_alt_type = 10
            else:
                altitude_mts = self.ui.spinHexAltitude.value(
                ) + hex_altitude_multiplicator
                time_to_wait = 0
                desired_angle = self.ui.spinHexAngle.value()
                if not (0 <= desired_angle <= 360):
                    desired_angle = self.ui.spinAngle.value()

            print "WP alt type:", wp_alt_type, wp_alt_combo_text

            for coord in v:
                print 'coord', coord
                if p_counter == 0:
                    # Set home
                    gps_export_str.append(
                        base_srt.format(p_counter, 1, 0, 16, 0, reach_radius,
                                        0, 0, coord['lat'], coord['lng'], 0,
                                        1))
                    p_counter += 1

                    # 22 Takeoff
                    gps_export_str.append(
                        base_srt.format(p_counter, 0, wp_alt_type, 22, 0,
                                        reach_radius, 0, desired_angle,
                                        coord['lat'], coord['lng'],
                                        altitude_mts, 1))
                    p_counter += 1

                    # add desired yaw
                    # http://ardupilot.org/copter/docs/mission-command-list.html#mission-command-list-condition-yaw
                    gps_export_str.append(
                        base_srt.format(p_counter, 0, wp_alt_type, 115,
                                        desired_angle, reach_radius, 0, 0,
                                        coord['lat'], coord['lng'],
                                        altitude_mts, 1))

                    p_counter += 1

                    # go to first WP
                    gps_export_str.append(
                        base_srt.format(p_counter, 0, wp_alt_type, 16, 0,
                                        reach_radius, 0, desired_angle,
                                        coord['lat'], coord['lng'],
                                        altitude_mts, 1))
                else:
                    # normal waypoint
                    gps_export_str.append(
                        base_srt.format(p_counter, 0, wp_alt_type, 16, 0,
                                        reach_radius, 0, desired_angle,
                                        coord['lat'], coord['lng'],
                                        altitude_mts, 1))

                p_counter += 1

                if time_to_wait > 0:
                    # trigger cam
                    # http://ardupilot.org/copter/docs/mission-command-list.html#do-digicam-control
                    gps_export_str.append(
                        base_srt.format(p_counter, 0, wp_alt_type, 203, 0,
                                        reach_radius, 0, 0, coord['lat'],
                                        coord['lng'], altitude_mts, 1))

                    p_counter += 1

                    # send WP with time
                    gps_export_str.append(
                        base_srt.format(p_counter, 0, wp_alt_type, 16,
                                        time_to_wait, reach_radius, 0,
                                        desired_angle, coord['lat'],
                                        coord['lng'], altitude_mts, 1))

                    p_counter += 1

            # RTL
            last_coord = v[-1]
            gps_export_str.append(
                base_srt.format(p_counter, 0, wp_alt_type, 20, 0, reach_radius,
                                0, desired_angle, last_coord['lat'],
                                last_coord['lng'], altitude_mts, 1))

            f = open(filepath, 'w')
            f.write(header)
            f.write('\n')
            for elem in gps_export_str:
                f.write(elem)
                f.write('\n')

            f.close()

            print "Route exported to ", filepath
            msg = "Route exported to " + filepath
            self.ui.labelStatus.setText(msg + " " +
                                        str(datetime.datetime.now()))

            if k is not 'magnetic':
                hex_altitude_multiplicator += self.ui.spinHexAltMult.value()

        pass

    @pyqtSlot(str)
    def QTgetPixelShape(self, vertex_list):
        print "QTgetPixelShape called"
        self.clearPaths()
        data = json.loads(str(vertex_list))
        #print type(data), data

        angle = self.ui.spinAngle.value()
        line_width = self.ui.spinWidthSize.value()
        shape = data['shape']
        wp_spacement_mode = self.ui.comboWPSequence.currentText()

        shape.append(shape[0])

        c_polygon = sim.cover_polygon.CoverPolygon(
            shape,
            line_width,
            angle,
            meter_pixel_ratio=data['meter_pixel_ratio'],
            spacement_mode=wp_spacement_mode)
        lawnmower_path = c_polygon.get_lawnmower()

        hex_r = self.ui.spinHexRadius.value()
        robot_size = self.ui.spinHexRobotNumber.value()
        hex_line_w = self.ui.spinHexWidthSize.value()
        angle = self.ui.spinHexAngle.value()

        hex_tours = None
        if robot_size > 0:
            hex_p_cover = sim.cover_hexagon.CoverHexagon(
                shape,
                hex_r,
                hex_line_w,
                angle,
                robot_size=robot_size,
                meter_pixel_ratio=data['meter_pixel_ratio'])
            hex_p_cover.get_intersecting_hexagons()
            hex_p_cover.calculate_clusters()
            hex_p_cover.optimize_tours()
            hex_tours = hex_p_cover.get_tours()

        #print "Pixel lawnmower path:", lawnmower_path

        self.generateRouteFromPixel(lawnmower_path, hex_tours)

    def generateRouteFromPixel(self, flight_plan, hex_tours):
        msg = "Generating route from a pixel flight plan coordinates ..."
        self.ui.labelStatus.setText(msg + " " + str(datetime.datetime.now()))

        json_flight_plan = json.dumps(flight_plan)
        #print "Json flight plan:", json_flight_plan

        self.ui.webView.page().mainFrame().evaluateJavaScript(
            "createFlightPlans(\'{0}\');".format(json_flight_plan))

        msg = "Route generated..."
        self.ui.labelStatus.setText(msg + " " + str(datetime.datetime.now()))

        if hex_tours is not None:
            time.sleep(1)
            msg = "Generating hex routes from a pixel flight plan coordinates ..."
            self.ui.labelStatus.setText(msg + " " +
                                        str(datetime.datetime.now()))
            lawnmower_tours = {}
            for k, v in hex_tours.items():
                print k, 'len:', len(v)
                lawn_tour = []
                for h in v:
                    lawn_tour += h.getLawnmower()

                lawnmower_tours[k] = lawn_tour

            json_flight_plan = json.dumps(lawnmower_tours)
            print "Json hexagon flight plan:", json_flight_plan

            self.ui.webView.page().mainFrame().evaluateJavaScript(
                "createHexagonFlightPlans(\'{0}\');".format(json_flight_plan))

            msg = "Hexagon route generated..."
            self.ui.labelStatus.setText(msg + " " +
                                        str(datetime.datetime.now()))

        self.removeLoadingModal()
        pass

    @pyqtSlot(str)
    def QTgetGPSPath(self, gps_list):
        print "QTgetGPSPath called"
        self.path_gps_json = None

        data = json.loads(str(gps_list))
        #print type(data), data

        self.path_gps_json = data
        pass

    @pyqtSlot(str)
    def QTgetHexGPSPath(self, gps_list):
        print "QTgetHexGPSPath called"
        self.path_hex_gps_json = None

        data = json.loads(str(gps_list))
        print type(data), data

        self.path_hex_gps_json = data
        pass

    @pyqtSlot(str)
    def QTsetRegionOfInterestGPSShape(self, gps_list):
        print "QTsetRegionOfInterestGPSShape called"

        data = json.loads(str(gps_list))
        print type(data), data

        self.roi_gps_json = data
        pass

    def toggleMapsJS(self):
        self.ui.webView.page().mainFrame().evaluateJavaScript(
            "toggleHexagonMaps();")
        pass
Exemplo n.º 21
0
    def __init__(self, main_window):
        Ui_MainWindow.__init__(self)
        self.setupUi(main_window)

        self.button_submit.clicked.connect(self.on_submit)
        self.button_search_tile.clicked.connect(self.on_file)
    def __init__(self):
        super(MyUi, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        cwd = os.getcwd()
        cwd = str(cwd)
        if os.path.isfile(cwd + "/time"):
            with open("time", "r") as outfile:  #reads current time
                history = cPickle.load(outfile)
            if (datetime.now() - history
                ).total_seconds() < 43200:  #measures if time elapse>12 hours
                print("Less than 12 hours. Loading previously saved Pickle...")
                #with open("time","w") as infile: #update time
                #cPickle.dump(datetime.now(),infile)
                #            else:
                print("More than 12 hours. Updating Pickle...")
                data = ts.get_industry_classified()
                with open("class", "w+") as outfile:
                    cPickle.dump(data, outfile)
                now = datetime.now()
                with open("time", "w+") as outfile:  #update time
                    cPickle.dump(now, outfile)

        else:
            print("No Pickle found!"
                  )  #If this is first time using tuchart in this directory
            data = df()
            data = ts.get_industry_classified()
            with open('class', 'w+') as outfile:  #records pickle
                cPickle.dump(data, outfile)
            now = datetime.now()
            with open("time", "w+") as outfile:
                cPickle.dump(now, outfile)

        with open("class", "r") as infile:  # reads current time
            series = cPickle.load(infile)
        #series = pd.read_json(cwd + "\\class.json")
        #series = ts.get_industry_classified()
        series = pd.DataFrame(series)

        curdate = time.strftime(
            "%Y/%m/%d")  # gets current time to put into dateedit
        curdateQ = QDate.fromString(curdate, "yyyy/MM/dd")

        dateobj = datetime.strptime(curdate,
                                    "%Y/%m/%d")  #converts to datetime object

        past = dateobj - timedelta(days=7)  #minus a week to start date
        pasttime = datetime.strftime(past, "%Y/%m/%d")
        pastQ = QDate.fromString(
            pasttime,
            "yyyy/MM/dd")  #convert to qtime so that widget accepts the values

        pastL = dateobj - timedelta(days=30)  # minus a month to start date
        pasttimeL = datetime.strftime(pastL, "%Y/%m/%d")
        pastQL = QDate.fromString(pasttimeL, "yyyy/MM/dd")

        np_indexes = np.array([['sh', '上证指数', '大盘指数'], ['sz', '深证成指', '大盘指数'],
                               ['hs300', '沪深300指数', '大盘指数'],
                               ['sz50', '上证50', '大盘指数'],
                               ['zxb', '中小板', '大盘指数'], ['cyb', '创业板', '大盘指数']])
        indexes = df(data=np_indexes,
                     index=range(5000, 5006),
                     columns=["code", "name", "c_name"])
        series = indexes.append(series)
        list1_bfr = series["c_name"].tolist(
        )  #Get industry categories. Filters out redundant ones
        list1 = list(set(list1_bfr))
        list1.sort(key=list1_bfr.index)
        #w = database()
        #zsparent = QTreeWidgetItem(self.ui.treeWidget)
        #zsparent.setText(0,"股票指数")
        #zsnames =["上证指数-sh","深圳成指-sz","沪深300指数-hs300","上证50-"]

        self.init_treeWidget(list1, series)

        self.ui.treeWidget.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui.treeWidget.customContextMenuRequested.connect(self.openMenu)

        #self.ui.webView.setGeometry(QtCore.QRect(0, 30,1550, 861))
        file_path = os.path.abspath(
            os.path.join(os.path.dirname(__file__),
                         "render.html"))  #path to read html file
        local_url = QUrl.fromLocalFile(file_path)
        self.ui.webView.load(local_url)
        #self.ui.commandLinkButton.setFixedSize(50, 50)
        self.ui.search_btn.clicked.connect(lambda: self.search_comp(series))
        self.ui.log_btn.clicked.connect(lambda: self.log())
        self.ui.init_code_btn.clicked.connect(
            lambda: self.code_sort_tree(series))
        self.ui.init_category_btn.clicked.connect(
            lambda: self.init_treeWidget(list1, series))

        self.ui.commandLinkButton.clicked.connect(
            self.classify)  #when the arrow button is clicked, trigger events

        #self.ui.commandLinkButton.clicked.connect(lambda action: self.classify(action, self.ui.treewidget))
        #  QSizePolicy
        try:
            retain_size = self.ui.dateEdit_2.sizePolicy()
            retain_size.setRetainSizeWhenHidden(True)
            self.ui.dateEdit_2.setSizePolicy(retain_size)
            retain_size = self.ui.comboBox.sizePolicy()
            retain_size.setRetainSizeWhenHidden(True)
            #            self.ui.comboBox.setSizePolicy(retain_size)
            retain_size = self.ui.label_2.sizePolicy()
            retain_size.setRetainSizeWhenHidden(True)
            self.ui.label_2.setSizePolicy(retain_size)
        except AttributeError:
            print("No PYQT5 Binding! Widgets might be deformed")
        self.ui.dateEdit.setDate(pastQL)
        self.ui.dateEdit_2.setDate(curdateQ)  #populate widgets
        self.ui.dateEdit.setCalendarPopup(True)
        self.ui.dateEdit_2.setCalendarPopup(True)
        self.ui.comboBox.addItems(["D"])
        self.ui.treeWidget_2.setDragDropMode(self.ui.treeWidget_2.InternalMove)
        self.ui.treeWidget_2.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui.treeWidget_2.customContextMenuRequested.connect(
            self.openWidgetMenu)
        #self.ui.toolbutton.clicked.connect(lambda action: self.graphmerge(action, CombineKeyword))
        self.ui.combobox.currentIndexChanged.connect(
            lambda: self.modifycombo(pastQL, pastQ))
Exemplo n.º 23
0
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        _dir = os.path.dirname(os.path.abspath(__file__))
        #uic.loadUi(_dir + '/' + 'layout.ui', self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.profileWidget.hide()
        self.ui.smallDataWidget.hide()
        self.ui.splitter_3.setSizes([
            self.width() * 0.7, self.width() * 0.3
        ])  # splitter between image_view/plot_widget and file list
        self.ui.splitter_2.setSizes([
            self.height() * 0.7, self.height() * 0.3
        ])  # splitter between image_view and plot widget
        self.ui.splitter.setSizes([
            self.ui.splitter.width() / 3.,
            self.ui.splitter.width() / 3.,
            self.ui.splitter.width() / 3.
        ])
        self.setAcceptDrops(True)
        self.ui.fileList.setColumnWidth(0, 200)

        self.filepath = None  # current filepath
        self.imageData = None  # original image data, 2d or 3d
        self.imageShape = None
        self.dispData = None  # 2d data for plot
        self.dispShape = None
        self.mask = None
        self.curve = None
        self.h5obj = None
        self.acceptedFileTypes = [
            u'npy', u'npz', u'h5', u'mat', u'cxi', u'tif'
        ]

        self.dispItem = self.ui.imageView.getImageItem()
        self.ringItem = pg.ScatterPlotItem()
        self.centerMarkItem = pg.ScatterPlotItem()
        self.ui.imageView.getView().addItem(self.ringItem)
        self.ui.imageView.getView().addItem(self.centerMarkItem)

        self.curveItem = PlotDataItem()
        self.ui.curveWidget.addItem(self.curveItem)
        self.ui.curveWidget.getPlotItem().setTitle(title='Curve Plot')

        # basic operation for image and curve plot
        self.showImage = True
        self.axis = 'x'
        self.frameIndex = 0
        self.maskFlag = False
        self.imageLog = False
        self.binaryFlag = False
        self.FFT = False
        self.FFTSHIFT = False
        self.dispThreshold = 0
        self.center = [0, 0]
        self.showRings = False
        self.ringRadiis = []
        self.showCurvePlot = True

        self.profileItem = PlotDataItem(pen=pg.mkPen(
            'y', width=1, style=QtCore.Qt.SolidLine),
                                        name='profile')
        self.smoothItem = PlotDataItem(pen=pg.mkPen('g',
                                                    width=2,
                                                    style=QtCore.Qt.DotLine),
                                       name='smoothed profile')
        self.thresholdItem = PlotDataItem(pen=pg.mkPen('r'),
                                          width=1,
                                          style=QtCore.Qt.DashLine,
                                          name='threshold')
        self.ui.profileWidget.addLegend()
        self.ui.profileWidget.addItem(self.profileItem)
        self.ui.profileWidget.addItem(self.smoothItem)
        self.ui.profileWidget.addItem(self.thresholdItem)
        self.ui.profileWidget.getPlotItem().setTitle(title='Profile Plot')
        # profile option
        self.showProfile = False
        self.profileType = 'radial'
        self.profileMode = 'sum'
        # extrema search
        self.extremaSearch = False
        self.extremaType = 'max'
        self.extremaWinSize = 11
        self.extremaThreshold = 1.0  # ratio compared to mean value
        # angular option
        self.angularRmin = 0.
        self.angularRmax = np.inf
        # across center line option
        self.lineAngle = 0.
        self.lineWidth = 1
        # profile smoothing
        self.smoothFlag = False
        self.smoothWinSize = 15
        self.polyOrder = 3
        # small data option
        self.smallDataItem = pg.ScatterPlotItem()
        self.ui.smallDataWidget.addItem(self.smallDataItem)
        self.ui.smallDataWidget.getPlotItem().setTitle(title='Small Data')
        self.showSmallData = False
        self.smallDataFile = None
        self.smallDataset = None
        self.smallDataSorted = False
        self.smallDataPaths = None
        self.smallDataFrames = None
        self.smallData = None
        # display option
        self.imageAutoRange = False
        self.imageAutoLevels = False
        self.imageAutoHistogramRange = True
        self.curvePlotAutoRange = True
        self.curvePlotLog = False
        self.profilePlotAutoRange = True
        self.profilePlotLog = False
        self.smallDataPlotAutoRange = True
        self.smallDataPlotLog = False

        params_list = [{
            'name':
            'Data Info',
            'type':
            'group',
            'children': [{
                'name': 'File',
                'type': 'str',
                'value': 'not set',
                'readonly': True
            }, {
                'name': 'Dataset',
                'type': 'str',
                'value': 'not set',
                'readonly': True
            }, {
                'name': 'Mask',
                'type': 'str',
                'value': 'not set',
                'readonly': True
            }, {
                'name': 'Image Shape',
                'type': 'str',
                'value': 'unknown',
                'readonly': True
            }, {
                'name': 'Image Friedel Score',
                'type': 'float',
                'readonly': True
            }, {
                'name': 'Curve Length',
                'type': 'int',
                'readonly': 'True'
            }]
        }, {
            'name':
            'Basic Operation',
            'type':
            'group',
            'children': [{
                'name':
                'Image',
                'type':
                'group',
                'children': [
                    {
                        'name': 'Axis',
                        'type': 'list',
                        'values': ['x', 'y', 'z'],
                        'value': self.axis
                    },
                    {
                        'name': 'Frame Index',
                        'type': 'int',
                        'value': self.frameIndex
                    },
                    {
                        'name': 'Apply Mask',
                        'type': 'bool',
                        'value': self.imageLog
                    },
                    {
                        'name': 'Apply Log',
                        'type': 'bool',
                        'value': self.maskFlag
                    },
                    {
                        'name': 'Apply FFT',
                        'type': 'bool',
                        'value': self.FFT
                    },
                    {
                        'name': 'Apply FFT-SHIFT',
                        'type': 'bool',
                        'value': self.FFTSHIFT
                    },
                    {
                        'name': 'Binaryzation',
                        'type': 'bool',
                        'value': self.binaryFlag
                    },
                    {
                        'name': 'Threshold',
                        'type': 'float',
                        'value': self.dispThreshold
                    },
                    {
                        'name': 'Center x',
                        'type': 'int',
                        'value': self.center[1]
                    },
                    {
                        'name': 'Center y',
                        'type': 'int',
                        'value': self.center[0]
                    },
                    {
                        'name': 'Show Rings',
                        'type': 'bool'
                    },
                    {
                        'name': 'Ring Radiis',
                        'type': 'str',
                        'value': ''
                    },
                ]
            }, {
                'name': 'Curve Plot',
                'type': 'group',
                'children': [
                    {
                        'name': 'TODO',
                        'type': 'str'
                    },
                ]
            }]
        }, {
            'name':
            'Image to Feature Profile',
            'type':
            'group',
            'children': [{
                'name': 'Show Profile',
                'type': 'bool',
                'value': self.showProfile
            }, {
                'name': 'Feature',
                'type': 'list',
                'values': ['radial', 'angular', 'across center line'],
                'value': self.profileType
            }, {
                'name': 'Profile Mode',
                'type': 'list',
                'values': ['sum', 'mean'],
                'value': self.profileMode
            }, {
                'name':
                'Angular Option',
                'type':
                'group',
                'children': [
                    {
                        'name': 'R min',
                        'type': 'float',
                        'value': self.angularRmin
                    },
                    {
                        'name': 'R max',
                        'type': 'float',
                        'value': self.angularRmax
                    },
                ]
            }, {
                'name':
                'Across Center Line Option',
                'type':
                'group',
                'children': [
                    {
                        'name': 'Angle',
                        'type': 'float',
                        'value': self.lineAngle
                    },
                    {
                        'name': 'Width/pixel',
                        'type': 'int',
                        'value': self.lineWidth
                    },
                ]
            }, {
                'name':
                'Smoothing',
                'type':
                'group',
                'children': [
                    {
                        'name': 'Enable Smoothing',
                        'type': 'bool',
                        'value': self.smoothFlag
                    },
                    {
                        'name': 'Window Size',
                        'type': 'int',
                        'value': self.smoothWinSize
                    },
                    {
                        'name': 'Poly-Order',
                        'type': 'int',
                        'value': self.polyOrder
                    },
                ]
            }, {
                'name':
                'Extrema Search',
                'type':
                'group',
                'children': [
                    {
                        'name': 'Enable Extrema Search',
                        'type': 'bool',
                        'value': self.extremaSearch
                    },
                    {
                        'name': 'Extrema Type',
                        'type': 'list',
                        'values': ['max', 'min'],
                        'value': self.extremaType
                    },
                    {
                        'name': 'Extrema WinSize',
                        'type': 'int',
                        'value': self.extremaWinSize
                    },
                    {
                        'name': 'Extrema Threshold',
                        'type': 'float',
                        'value': self.extremaThreshold
                    },
                ]
            }]
        }, {
            'name':
            'Small Data',
            'type':
            'group',
            'children': [
                {
                    'name': 'Filepath',
                    'type': 'str'
                },
                {
                    'name': 'Dataset',
                    'type': 'str'
                },
                {
                    'name': 'Show data',
                    'type': 'bool',
                    'value': self.showSmallData
                },
                {
                    'name': 'Sort',
                    'type': 'bool',
                    'value': self.smallDataSorted
                },
            ]
        }, {
            'name':
            'Display Option',
            'type':
            'group',
            'children': [
                {
                    'name':
                    'Image',
                    'type':
                    'group',
                    'children': [
                        {
                            'name': 'autoRange',
                            'type': 'bool',
                            'value': self.imageAutoRange
                        },
                        {
                            'name': 'autoLevels',
                            'type': 'bool',
                            'value': self.imageAutoLevels
                        },
                        {
                            'name': 'autoHistogramRange',
                            'type': 'bool',
                            'value': self.imageAutoHistogramRange
                        },
                    ]
                },
                {
                    'name':
                    'Curve Plot',
                    'type':
                    'group',
                    'children': [
                        {
                            'name': 'autoRange',
                            'type': 'bool',
                            'value': self.curvePlotAutoRange
                        },
                        {
                            'name': 'Log',
                            'type': 'bool',
                            'value': self.curvePlotLog
                        },
                    ]
                },
                {
                    'name':
                    'Profile Plot',
                    'type':
                    'group',
                    'children': [
                        {
                            'name': 'autoRange',
                            'type': 'bool',
                            'value': self.profilePlotAutoRange
                        },
                        {
                            'name': 'Log',
                            'type': 'bool',
                            'value': self.profilePlotLog
                        },
                    ]
                },
                {
                    'name':
                    'Small Data Plot',
                    'type':
                    'group',
                    'children': [
                        {
                            'name': 'autoRange',
                            'type': 'bool',
                            'value': self.smallDataPlotAutoRange
                        },
                        {
                            'name': 'Log',
                            'type': 'bool',
                            'value': self.smallDataPlotLog
                        },
                    ]
                },
            ]
        }]
        self.params = Parameter.create(name='params',
                                       type='group',
                                       children=params_list)
        self.ui.parameterTree.setParameters(self.params, showTop=False)

        self.ui.fileList.itemDoubleClicked.connect(self.changeDatasetSlot)
        self.ui.fileList.customContextMenuRequested.connect(
            self.showFileMenuSlot)
        self.ui.imageView.scene.sigMouseMoved.connect(self.mouseMoved)
        self.smallDataItem.sigClicked.connect(self.smallDataClicked)
        self.ui.lineEdit.returnPressed.connect(self.addFilesSlot)

        self.params.param('Basic Operation', 'Image',
                          'Axis').sigValueChanged.connect(self.axisChangedSlot)
        self.params.param('Basic Operation', 'Image',
                          'Frame Index').sigValueChanged.connect(
                              self.frameIndexChangedSlot)
        self.params.param('Basic Operation', 'Image',
                          'Apply Mask').sigValueChanged.connect(
                              self.applyMaskSlot)
        self.params.param('Basic Operation', 'Image',
                          'Apply Log').sigValueChanged.connect(
                              self.applyImageLogSlot)
        self.params.param('Basic Operation', 'Image',
                          'Binaryzation').sigValueChanged.connect(
                              self.binaryImageSlot)
        self.params.param('Basic Operation', 'Image',
                          'Apply FFT').sigValueChanged.connect(
                              self.applyFFTSlot)
        self.params.param('Basic Operation', 'Image',
                          'Apply FFT-SHIFT').sigValueChanged.connect(
                              self.applyFFTSHIFTSlot)
        self.params.param('Basic Operation', 'Image',
                          'Binaryzation').sigValueChanged.connect(
                              self.binaryImageSlot)
        self.params.param('Basic Operation', 'Image',
                          'Threshold').sigValueChanged.connect(
                              self.setDispThresholdSlot)
        self.params.param('Basic Operation', 'Image',
                          'Center x').sigValueChanged.connect(
                              self.centerXChangedSlot)
        self.params.param('Basic Operation', 'Image',
                          'Center y').sigValueChanged.connect(
                              self.centerYChangedSlot)
        self.params.param('Basic Operation', 'Image',
                          'Show Rings').sigValueChanged.connect(
                              self.showRingsSlot)
        self.params.param('Basic Operation', 'Image',
                          'Ring Radiis').sigValueChanged.connect(
                              self.ringRadiiSlot)

        self.params.param('Image to Feature Profile',
                          'Show Profile').sigValueChanged.connect(
                              self.showProfileSlot)
        self.params.param('Image to Feature Profile',
                          'Feature').sigValueChanged.connect(
                              self.setProfileTypeSlot)
        self.params.param('Image to Feature Profile',
                          'Profile Mode').sigValueChanged.connect(
                              self.setProfileModeSlot)
        self.params.param('Image to Feature Profile', 'Angular Option',
                          'R min').sigValueChanged.connect(
                              self.setAngularRminSlot)
        self.params.param('Image to Feature Profile', 'Angular Option',
                          'R max').sigValueChanged.connect(
                              self.setAngularRmaxSlot)
        self.params.param(
            'Image to Feature Profile', 'Across Center Line Option',
            'Angle').sigValueChanged.connect(self.setLineAngleSlot)
        self.params.param(
            'Image to Feature Profile', 'Across Center Line Option',
            'Width/pixel').sigValueChanged.connect(self.setLineWidthSlot)
        self.params.param('Image to Feature Profile', 'Smoothing',
                          'Enable Smoothing').sigValueChanged.connect(
                              self.setSmoothSlot)
        self.params.param('Image to Feature Profile', 'Smoothing',
                          'Window Size').sigValueChanged.connect(
                              self.setWinSizeSlot)
        self.params.param('Image to Feature Profile', 'Smoothing',
                          'Poly-Order').sigValueChanged.connect(
                              self.setPolyOrderSlot)
        self.params.param('Image to Feature Profile', 'Extrema Search',
                          'Enable Extrema Search').sigValueChanged.connect(
                              self.setExtremaSearchSlot)
        self.params.param('Image to Feature Profile', 'Extrema Search',
                          'Extrema Type').sigValueChanged.connect(
                              self.setExtremaTypeSlot)
        self.params.param('Image to Feature Profile', 'Extrema Search',
                          'Extrema WinSize').sigValueChanged.connect(
                              self.setExtremaWinSizeSlot)
        self.params.param('Image to Feature Profile', 'Extrema Search',
                          'Extrema Threshold').sigValueChanged.connect(
                              self.setExtremaThresholdSlot)

        self.params.param('Small Data', 'Filepath').sigValueChanged.connect(
            self.setSmallDataFilepathSlot)
        self.params.param('Small Data', 'Dataset').sigValueChanged.connect(
            self.setSmallDatasetSlot)
        self.params.param('Small Data', 'Show data').sigValueChanged.connect(
            self.showSmallDataSlot)
        self.params.param('Small Data', 'Sort').sigValueChanged.connect(
            self.sortSmallDataSlot)

        self.params.param('Display Option', 'Image',
                          'autoRange').sigValueChanged.connect(
                              self.imageAutoRangeSlot)
        self.params.param('Display Option', 'Image',
                          'autoLevels').sigValueChanged.connect(
                              self.imageAutoLevelsSlot)
        self.params.param('Display Option', 'Image',
                          'autoHistogramRange').sigValueChanged.connect(
                              self.imageAutoHistogramRangeSlot)
        self.params.param('Display Option', 'Curve Plot',
                          'autoRange').sigValueChanged.connect(
                              self.curvePlotAutoRangeSlot)
        self.params.param('Display Option', 'Curve Plot',
                          'Log').sigValueChanged.connect(
                              self.curvePlotLogModeSlot)
        self.params.param('Display Option', 'Profile Plot',
                          'autoRange').sigValueChanged.connect(
                              self.profilePlotAutoRangeSlot)
        self.params.param('Display Option', 'Profile Plot',
                          'Log').sigValueChanged.connect(
                              self.profilePlotLogModeSlot)
        self.params.param('Display Option', 'Small Data Plot',
                          'autoRange').sigValueChanged.connect(
                              self.smallDataPlotAutoRangeSlot)
        self.params.param('Display Option', 'Small Data Plot',
                          'Log').sigValueChanged.connect(
                              self.smallDataPlotLogModeSlot)
Exemplo n.º 24
0
from PyQt4.QtGui import *
import gnuplot_out as go
from layout import Ui_MainWindow
import lg, cfg, graphic, data, agent, auks, inout
import simple_learn as sl
import globals as gl

gl.version = "0.2.556"


def run():

    gl.test_title = "correct=" + str(cfg.correct)
    out1 = sl.run_simple_learn()

    go.output([out1[0]], "# interactions", "% correct", "agent2_test_succes")


# run()


if __name__ == "__main__":
    # run()
    app = QApplication(sys.argv)
    gl.mainwindow = graphic.GUI(gl.agent1)
    ui = Ui_MainWindow()
    ui.setupUi(gl.mainwindow)
    gl.mainwindow.layout = ui
    gl.mainwindow.show()
    sys.exit(app.exec_())
Exemplo n.º 25
0
class MainWindow(qtw.QMainWindow):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.filenames = ['', '', '']
        self.graphChannels = [
            self.ui.signal1Graph, self.ui.signal2Graph, self.ui.signal3Graph
        ]
        self.spectrogramChannels = [
            self.ui.spectrogram1Graph, self.ui.spectrogram2Graph,
            self.ui.spectrogram3Graph
        ]
        self.timers = [self.ui.timer1, self.ui.timer2, self.ui.timer3]
        self.pen = [
            pg.mkPen(color=(255, 0, 0), width=1),
            pg.mkPen(color=(0, 255, 0), width=1),
            pg.mkPen(color=(0, 0, 255), width=1)
        ]

        self.PLOT_DIR = 'Plots'
        self.PDF_DIR = 'PDFs'
        self.amplitude = [[], [], []]
        self.time = [[], [], []]

        self.upToDatePlots = [[], [], []]
        self.spectrogramData = [None, None, None]
        self.pointsToAppend = [0, 0, 0]
        self.isResumed = [False, False, False]
        self.setChannelChecked = [
            self.ui.showChannel1, self.ui.showChannel2, self.ui.showChannel3
        ]
        self.channelComponents = [
            self.ui.channel1, self.ui.channel2, self.ui.channel3
        ]

        self.CHANNEL1 = 0
        self.CHANNEL2 = 1
        self.CHANNEL3 = 2

        self.ui.showChannel1.setChecked(True)
        self.ui.showChannel2.setChecked(True)
        self.ui.showChannel3.setChecked(True)
        self.ui.channel1.show()
        self.ui.channel2.show()
        self.ui.channel3.show()

        self.ui.showChannel1.stateChanged.connect(
            lambda: self.toggle(self.CHANNEL1))
        self.ui.showChannel2.stateChanged.connect(
            lambda: self.toggle(self.CHANNEL2))
        self.ui.showChannel3.stateChanged.connect(
            lambda: self.toggle(self.CHANNEL3))

        self.ui.actionAbout.triggered.connect(lambda: self.showAbout())
        self.ui.actionExit.triggered.connect(lambda: self.close())
        self.ui.actionNew.triggered.connect(lambda: self.create_new_window())

        self.ui.actionOpenChannel1.triggered.connect(
            lambda: self.browse(self.CHANNEL1))
        self.ui.playBtn1.clicked.connect(lambda: self.play(self.CHANNEL1))
        self.ui.pauseBtn1.clicked.connect(lambda: self.pause(self.CHANNEL1))
        self.ui.focusBtn1.clicked.connect(lambda: self.graphChannels[
            self.CHANNEL1].getPlotItem().enableAutoRange())
        self.ui.zoomInBtn1.clicked.connect(lambda: self.zoomin(self.CHANNEL1))
        self.ui.zoomOutBtn1.clicked.connect(
            lambda: self.zoomout(self.CHANNEL1))
        self.ui.clearBtn1.clicked.connect(lambda: self.clear(self.CHANNEL1))

        self.ui.actionOpenChannel2.triggered.connect(
            lambda: self.browse(self.CHANNEL2))
        self.ui.playBtn2.clicked.connect(lambda: self.play(self.CHANNEL2))
        self.ui.pauseBtn2.clicked.connect(lambda: self.pause(self.CHANNEL2))
        self.ui.focusBtn2.clicked.connect(lambda: self.graphChannels[
            self.CHANNEL2].getPlotItem().enableAutoRange())
        self.ui.zoomInBtn2.clicked.connect(lambda: self.zoomin(self.CHANNEL2))
        self.ui.zoomOutBtn2.clicked.connect(
            lambda: self.zoomout(self.CHANNEL2))
        self.ui.clearBtn2.clicked.connect(lambda: self.clear(self.CHANNEL2))

        self.ui.actionOpenChannel3.triggered.connect(
            lambda: self.browse(self.CHANNEL3))
        self.ui.playBtn3.clicked.connect(lambda: self.play(self.CHANNEL3))
        self.ui.pauseBtn3.clicked.connect(lambda: self.pause(self.CHANNEL3))
        self.ui.focusBtn3.clicked.connect(lambda: self.graphChannels[
            self.CHANNEL3].getPlotItem().enableAutoRange())
        self.ui.zoomInBtn3.clicked.connect(lambda: self.zoomin(self.CHANNEL3))
        self.ui.zoomOutBtn3.clicked.connect(
            lambda: self.zoomout(self.CHANNEL3))
        self.ui.clearBtn3.clicked.connect(lambda: self.clear(self.CHANNEL3))

        self.ui.generatePDF.clicked.connect(lambda: self.generatePDF())

        self.show()

    def showAbout(self) -> None:
        self.about = About()
        self.about.show()

    def play(self, channel: int) -> None:
        if not self.amplitude[channel]:
            self.browse(channel)
        if not self.isResumed[channel]:
            self.timers[channel].start()
            self.isResumed[channel] = True

    def pause(self, channel: int) -> None:
        if not self.amplitude[channel]:
            self.browse(channel)
        if self.isResumed[channel]:
            self.timers[channel].stop()
            self.isResumed[channel] = False

    def clear(self, channel: int) -> None:
        if self.amplitude[channel]:
            self.graphChannels[channel].removeItem(self.upToDatePlots[channel])
            self.spectrogramChannels[channel].removeItem(
                self.spectrogramData[channel])
            self.timers[channel].stop()
            self.isResumed[channel] = False
            self.amplitude[channel] = []
            self.time[channel] = []
            self.upToDatePlots[channel] = []
            self.spectrogramData[channel] = None

    def toggle(self, channel: int) -> None:
        if (self.channelComponents[channel].isVisible()):
            self.channelComponents[channel].hide()
            self.setChannelChecked[channel].setChecked(False)
            self.clear(channel)
        else:
            self.setChannelChecked[channel].setChecked(True)
            self.channelComponents[channel].show()

    def create_new_window(self):
        self.newWindow = MainWindow()
        self.newWindow.show()

    def browse(self, channel: int) -> None:
        self.toggle(channel)

        # self.clear(channel)
        self.filenames[channel] = qtw.QFileDialog.getOpenFileName(
            None, 'Load Signal', './', "Raw Data(*.csv *.xls *.txt)")
        path = self.filenames[channel][0]
        self.openFile(path, channel)

    def openFile(self, path: str, channel: int) -> None:
        with open(path, 'r') as csv_file:
            csv_reader = csv.reader(csv_file, delimiter=',')
            for line in csv_reader:
                self.amplitude[channel].append(float(line[1]))
                self.time[channel].append(float(line[0]))
        self.isResumed[channel] = True

        self.plotGraph(channel)
        self.plotSpectrogram(channel)

    def plotGraph(self, channel: int) -> None:
        self.upToDatePlots[channel] = self.graphChannels[channel].plot(
            self.time[channel],
            self.amplitude[channel],
            name='CH1',
            pen=self.pen[channel])
        self.graphChannels[channel].plotItem.setLimits(
            xMin=0,
            xMax=1.0,
            yMin=min(self.amplitude[channel]),
            yMax=max(self.amplitude[channel]))

        self.pointsToAppend[channel] = 0
        self.timers[channel].setInterval(150)
        self.timers[channel].timeout.connect(lambda: self.updatePlot(channel))
        self.timers[channel].start()

    def updatePlot(self, channel: int) -> None:
        xaxis = self.time[channel][:self.pointsToAppend[channel]]
        yaxis = self.amplitude[channel][:self.pointsToAppend[channel]]
        self.pointsToAppend[channel] += 20
        if self.pointsToAppend[channel] > len(self.time[channel]):
            self.timers[channel].stop()

        if self.time[channel][self.pointsToAppend[channel]] > 1.0:
            self.graphChannels[channel].setLimits(xMax=max(xaxis, default=0))
        self.graphChannels[channel].plotItem.setXRange(
            max(xaxis, default=0) - 1.0, max(xaxis, default=0))

        self.upToDatePlots[channel].setData(xaxis, yaxis)

    def plotSpectrogram(self, channel: int) -> None:
        pyqtgraph.setConfigOptions(imageAxisOrder='row-major')
        fs = 1 / (self.time[channel][1] - self.time[channel][0])
        yaxis = np.array(self.amplitude[channel])
        f, t, Sxx = scipy.signal.spectrogram(yaxis, fs)
        self.spectrogramData[channel] = self.spectrogramChannels[
            channel].addPlot()

        # Item for displaying image data
        img = pg.ImageItem()
        self.spectrogramData[channel].addItem(img)
        # Add a histogram with which to control the gradient of the image
        hist = pg.HistogramLUTItem()
        # Link the histogram to the image
        hist.setImageItem(img)
        # If you don't add the histogram to the window, it stays invisible, but I find it useful.
        self.spectrogramChannels[channel].addItem(
            self.spectrogramData[channel])
        # Show the window
        self.spectrogramChannels[channel].show()
        # Fit the min and max levels of the histogram to the data available
        hist.setLevels(np.min(Sxx), np.max(Sxx))
        # This gradient is roughly comparable to the gradient used by Matplotlib
        # You can adjust it and then save it using hist.gradient.saveState()
        hist.gradient.restoreState({
            'mode':
            'rgb',
            'ticks': [(0.5, (0, 182, 188, 255)), (1.0, (246, 111, 0, 255)),
                      (0.0, (75, 0, 113, 255))]
        })
        # hist.gradient.showTicks(False)
        # hist.shape
        # hist.layout.setContentsMargins(0, 0, 0, 0)
        # hist.vb.setMouseEnabled(x=False, y=False)

        # hist.vb.setMenuEnabled(False)
        # hist.shape
        # Sxx contains the amplitude for each pixel
        img.setImage(Sxx)
        # Scale the X and Y Axis to time and frequency (standard is pixels)
        img.scale(t[-1] / np.size(Sxx, axis=1), f[-1] / np.size(Sxx, axis=0))
        # Limit panning/zooming to the spectrogram
        self.spectrogramData[channel].setLimits(xMin=0,
                                                xMax=t[-1],
                                                yMin=0,
                                                yMax=f[-1])
        # Add labels to the axis
        # self.spectrogramData[channel].setLabel('bottom', "Time", units='s')
        # If you include the units, Pyqtgraph automatically scales the axis and adjusts the SI prefix (in this case kHz)
        # self.spectrogramData[channel].setLabel('left', "Frequency", units='Hz')

    def zoomin(self, channel: int) -> None:
        self.graphChannels[channel].plotItem.getViewBox().scaleBy((0.75, 0.75))

    def zoomout(self, channel: int) -> None:
        self.graphChannels[channel].plotItem.getViewBox().scaleBy((1.25, 1.25))

    def generatePDF(self):
        images = [0, 0, 0]
        Idx = 0
        for channel in range(3):
            if self.amplitude[channel]:
                images[channel] = 1
                Idx += 1
            else:
                self.toggle(channel)

        if not Idx:
            qtw.QMessageBox.information(self, 'failed',
                                        'You have to plot a signal first')
            return

        try:
            shutil.rmtree(self.PLOT_DIR)
            os.mkdir(self.PLOT_DIR)
        except FileNotFoundError:
            os.mkdir(self.PLOT_DIR)

        for channel in range(3):
            if images[channel]:
                exporter = pg.exporters.ImageExporter(
                    self.graphChannels[channel].plotItem)
                exporter.parameters(
                )['width'] = self.graphChannels[channel].plotItem.width()
                exporter.export(f'{self.PLOT_DIR}/plot-{channel}.png')

                exporter = pg.exporters.ImageExporter(
                    self.spectrogramChannels[channel].scene())
                exporter.export(f'{self.PLOT_DIR}/spec-{channel}.png')

        pdf = PDF()
        plots_per_page = pdf.construct(self.PLOT_DIR)

        for elem in plots_per_page:
            pdf.print_page(elem, self.PLOT_DIR)

        now = datetime.datetime.now()
        now = f'{now:%Y-%m-%d %H-%M-%S.%f %p}'
        try:
            os.mkdir(self.PDF_DIR)
        except:
            pass
        pdf.output(f'{self.PDF_DIR}/{now}.pdf', 'F')
        try:
            shutil.rmtree(self.PLOT_DIR)
        except:
            pass

        qtw.QMessageBox.information(self, 'success', 'PDF has been created')
Exemplo n.º 26
0
class MyUi(QMainWindow):
    def __init__(self):
        super(MyUi, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        #cwd = os.getcwd()
        #cwd = str(cwd)
        #if os.path.isfile(cwd+"/time"):
        #   with open("time","r") as outfile:#reads current time
        #      history = cPickle.load(outfile)
        # if (datetime.now()-history).total_seconds()<43200: #measures if time elapse>12 hours
        #    print "Less than 12 hours. Loading previously saved Json..."
        #   with open("time","w") as infile: #update time
        #      cPickle.dump(datetime.now(),infile)

        #else:
        #   print "More than 12 hours. Updating Json..."
        #  data = ts.get_industry_classified()
        # data.to_json(cwd + "/class.json", orient="columns")#writes class data so no need to call Tushare agian
        #now = datetime.now()
        #with open("time", "w+") as outfile: #update time
        #   cPickle.dump(now, outfile)

        # else:
        #    print "No json found!"#If this is first time using tuchart in this directory
        #   data = df()
        #  data = ts.get_industry_classified()
        # print data
        # var = data.to_json(cwd+"/class.json",orient="columns")
        # with open('class.json', 'w+') as outfile: #records json
        #      json.dump(var, outfile)
        #  now = datetime.now()
        # with open("time", "w+") as outfile:
        #     cPickle.dump(now,outfile)

        #   series = pd.read_json(cwd + "\\class.json")
        series = ts.get_industry_classified()
        series = pd.DataFrame(series)
        curdate = time.strftime(
            "%Y/%m/%d")  #gets current time to put into dateedit
        dateobj = datetime.strptime(curdate,
                                    "%Y/%m/%d")  #converts to datetime object
        past = dateobj - timedelta(days=7)  #minus a week to start date
        pasttime = datetime.strftime(past, "%Y/%m/%d")
        QPast = QDate.fromString(
            pasttime,
            "yyyy/MM/dd")  #convert to qtime so that widget accepts the values
        Qcurdate = QDate.fromString(curdate, "yyyy/MM/dd")
        #print series
        list1 = series["c_name"].tolist(
        )  #Get industry categories. Filters out redundant ones
        list1 = list(set(list1))
        #w = database()
        #zsparent = QTreeWidgetItem(self.ui.treeWidget)
        #zsparent.setText(0,"股票指数")
        #zsnames =["上证指数-sh","深圳成指-sz","沪深300指数-hs300","上证50-"]

        for j in list1:
            parent = QTreeWidgetItem(
                self.ui.treeWidget)  #populate treewidget with names
            parent.setText(0, j)
            var = series.loc[series["c_name"] == j]
            list2 = var["code"].tolist()
            name = var["name"].tolist()

            #var = showcollection(i) #Display database items
            for idx, val in enumerate(list2):
                child = QTreeWidgetItem(parent)
                child.setText(0, name[idx] + "-" + str(val))
                #for i in Drag:
                #grandson = QTreeWidgetItem(child)     #Commented out because increases program response time
                #grandson.setText(0, i)
        #self.ui.treeWidget.itemDoubleClicked.connect(self.onClickItem) #Display Collection items
        self.ui.treeWidget.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui.treeWidget.customContextMenuRequested.connect(self.openMenu)

        #self.ui.widget.setGeometry(QtCore.QRect(0, 30,1550, 861))
        file_path = os.path.abspath(
            os.path.join(os.path.dirname(__file__),
                         "render.html"))  #path to read html file
        local_url = QUrl.fromLocalFile(file_path)
        self.ui.widget.load(local_url)
        self.ui.commandLinkButton.setFixedSize(50, 50)
        self.ui.commandLinkButton.clicked.connect(
            self.classify)  #when the arrow button is clicked, trigger events

        #self.ui.commandLinkButton.clicked.connect(lambda action: self.classify(action, self.ui.treewidget))
        #  QSizePolicy
        retain_size = self.ui.dateEdit_2.sizePolicy()
        retain_size.setRetainSizeWhenHidden(True)
        self.ui.dateEdit_2.setSizePolicy(retain_size)
        retain_size = self.ui.comboBox.sizePolicy()
        retain_size.setRetainSizeWhenHidden(True)
        self.ui.comboBox.setSizePolicy(retain_size)
        retain_size = self.ui.label_2.sizePolicy()
        retain_size.setRetainSizeWhenHidden(True)
        self.ui.label_2.setSizePolicy(retain_size)

        self.ui.dateEdit.setDate(QPast)
        self.ui.dateEdit_2.setDate(Qcurdate)  #populate widgets
        self.ui.dateEdit.setCalendarPopup(True)
        self.ui.dateEdit_2.setCalendarPopup(True)
        self.ui.comboBox.addItems(["D", "W", "M", "5", "15", "30", "60"])
        self.ui.treeWidget_2.setDragDropMode(self.ui.treeWidget_2.InternalMove)
        self.ui.treeWidget_2.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui.treeWidget_2.customContextMenuRequested.connect(
            self.openWidgetMenu)
        #self.ui.toolbutton.clicked.connect(lambda action: self.graphmerge(action, CombineKeyword))
        self.ui.combobox.currentIndexChanged.connect(self.modifycombo)

    def modifycombo(self):
        if self.ui.combobox.currentText() == "复权".decode(
                "utf-8"
        ):  #if 复权 is selected, clear all existing queries to avoid value conflict
            self.ui.label_2.show()
            self.ui.dateEdit_2.show()
            self.ui.comboBox.show()
            self.ui.comboBox.clear()
            self.ui.comboBox.addItems(["hfq", "qfq"])
            self.ui.treeWidget_2.clear()
        if self.ui.combobox.currentText() == "K线".decode("utf-8"):
            self.ui.label_2.show()
            self.ui.dateEdit_2.show()
            self.ui.comboBox.show()
            self.ui.comboBox.clear()
            self.ui.comboBox.addItems(["D", "W", "M", "5", "15", "30",
                                       "60"])  #same as above
            self.ui.treeWidget_2.clear()
        if self.ui.combobox.currentText() == "分笔数据".decode("utf-8"):
            self.ui.comboBox.hide()
            self.ui.label_2.hide()
            self.ui.dateEdit_2.hide()
            self.ui.treeWidget_2.clear()

    def graphmerge(self, combineKeyword):
        sth = ""
        for i in combineKeyword:
            if sth == "":
                sth = sth + i
            else:
                sth = sth + "\n" + "&" + "-" + i
        list1 = sth
        return sth
        global CombineKeyword
        CombineKeyword = []
        self.ui.listwidget.clear(
        )  #combine stuff so that different graphs can be drawn together

    def kstuff(self):
        return 0

    def openWidgetMenu(self, position):
        indexes = self.ui.treeWidget_2.selectedIndexes()
        item = self.ui.treeWidget_2.itemAt(position)
        #item = self.ui.listWidget.itemAt(position)
        if len(indexes) > 0:
            menu = QMenu()
            menu.addAction(
                QAction("Delete", menu,
                        checkable=True))  #This function is perhaps useless
            #menu.triggered.connect(self.eraseItem)
            item = self.ui.treeWidget_2.itemAt(position)
            #collec = str(item.text())
            menu.triggered.connect(
                lambda action: self.ListMethodSelected(action, item))
        menu.exec_(self.ui.treeWidget_2.viewport().mapToGlobal(position))

    def ListMethodSelected(self, action, item):
        if action.text() == "Delete":
            self.eraseItem()
        if action.text() == "Combine":
            global CombineKeyword
            collec = str(item.text())
            CombineKeyword.append(collec)  #Useless function(maybe?)
            list1 = [self.tr(collec)]
            self.ui.listwidget.addItems(list1)
            self.eraseItem()

    def methodSelected(self, action, collec):
        #print action.text() #Choice
        #if (self.ui.treewidget.count() == 5):
        #   self.ui.label.setText("Maximum number of queries")
        #   return
        #self.ui.label.setText("")
        Choice = action.text()
        Stock = collec
        #print collec  #Stock Name
        #print db_origin   #DataBase name
        #list1 = [self.tr(Stock+"-"+Choice+"-"+db_origin)]
        #self.ui.treewidget.addItems(list1)
        parent = QTreeWidgetItem(self.ui.treeWidget_2)
        parent.setText(0, Stock.decode("utf-8") + "-" + Choice)
        font = QtGui.QFont("Times", 12, QtGui.QFont.Bold)
        self.ui.treeWidget_2.setFont(font)

    def eraseItem(self):
        for x in self.ui.treeWidget_2.selectedItems(
        ):  #delete with write click menu
            #item = self.ui.treewidget.takeItem(self.ui.treewidget.currentRow())
            sip.delete(x)
            #item.delete

    def classify(self, folder):
        items = []
        startdate = self.ui.dateEdit.date()
        startdate = startdate.toPyDate()
        startdate = startdate.strftime(
            "%Y/%m/%d")  #converts date from dateedit to tushare readable date
        enddate = self.ui.dateEdit_2.date()
        enddate = enddate.toPyDate()
        enddate = enddate.strftime("%Y/%m/%d")
        option = self.ui.comboBox.currentText()
        option = str(option)
        #if (self.ui.treewidget) == 0:
        #self.ui.label.setText("Need to select at least one query")
        #return
        root = self.ui.treeWidget_2.invisibleRootItem(
        )  # This is for iterating child items
        child_count = root.childCount()
        for i in range(child_count):
            if root.child(i).child(0):
                array = []
                temp = root.child(i)
                #mergelist = self.recurse(temp,array)
                #print mergelist
                parent = root.child(i).text(0)
                mergelist = []
                for j in range(temp.childCount()):
                    while temp.child(j).childCount() != 0:
                        #self.ui.label.setText("Error: Invalid Tree!")
                        return
                    txt = temp.child(j).text(0)
                    mergelist.append(txt)
                mergelist.insert(0, parent)
                url = self.graphmerge(mergelist)
                items.append(url)
            else:
                item = root.child(i)
                url = item.text(0)
                items.append(url)
        labels = [k for k in items]
        items = ([x.encode("utf-8") for x in labels])
        width = self.ui.widget.width(
        )  #give width and height of user's screen so that graphs can be generated with dynamic size
        height = self.ui.widget.height()
        graphpage(labels, startdate, enddate, option, width,
                  height)  #labels:复权ork线or分笔 option:hfq, qfq or 15, 30, D, etc
        self.ui.widget.reload()  #refreshes webengine
        self.ui.widget.repaint()
        self.ui.widget.update()

    def openMenu(self, position):
        indexes = self.ui.treeWidget.selectedIndexes()
        item = self.ui.treeWidget.itemAt(position)

        db_origin = ""
        #if item.parent():
        #   db_origin = item.parent().text(0)
        collec = str(item.text(0).encode("utf-8"))
        if len(indexes) > 0:
            level = 0
            index = indexes[0]
            while index.parent().isValid():
                index = index.parent()
                level = level + 1
            menu = QMenu()
            #print collec, db_origin
            if level == 0:
                pass
            else:
                #keyarray = GetKeys(collec, db_origin)
                #if "Open" in keyarray:
                if self.ui.combobox.currentText() == "K线".decode("utf-8"):
                    menu.addAction(QAction("Kline", menu, checkable=True))
                    menu.addAction(QAction("Open", menu, checkable=True))
                    menu.addAction(
                        QAction("Close", menu, checkable=True)
                    )  #open up different menu with different kind of graphs
                    menu.addAction(QAction("High", menu, checkable=True))
                    menu.addAction(QAction("Low", menu, checkable=True))
                    menu.addAction(QAction("Volume", menu, checkable=True))
                    #menu.addAction(QAction("P_change", menu, checkable=True))
                    #menu.addAction(QAction("Turnover",menu,checkable=True))
                if self.ui.combobox.currentText() == "复权".decode("utf-8"):
                    menu.addAction(QAction("Kline", menu, checkable=True))
                    menu.addAction(QAction("Open", menu, checkable=True))
                    menu.addAction(QAction("Close", menu, checkable=True))
                    menu.addAction(QAction("High", menu, checkable=True))
                    menu.addAction(QAction("Low", menu, checkable=True))
                    menu.addAction(QAction("Volume", menu, checkable=True))
                    menu.addAction(QAction("Amount", menu, checkable=True))
                if self.ui.combobox.currentText() == "分笔数据".decode("utf-8"):
                    menu.addAction(QAction("分笔", menu, checkable=True))
                #for g in keyarray:
                #menu.addAction(QAction(g, menu, checkable=True))
        menu.triggered.connect(
            lambda action: self.methodSelected(action, collec))
        menu.exec_(self.ui.treeWidget.viewport().mapToGlobal(position))
Exemplo n.º 27
0
class Quickstart(QMainWindow):
    def __init__(self, parent=None):
        super(Quickstart, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.started = False
        self.start_time = 0
        self.end_time = 0

    def endAnswer(self):
        answer = self.ui.lineAnswer.text()
        len_answer = len(answer)
        if len_answer == 0:
            return
        self.end_time = datetime.now()
        take_time = self.end_time - self.start_time
        self.started = False
        self.start_time = 0
        question = self.ui.lblQuestion.text()
        len_question = len(question)
        result = ''
        wrong = 0
        for index, char in enumerate(question):
            try:
                if char == answer[index]:
                    result += colorize(char, True)
                else:
                    result += colorize('-', False)
                    wrong += 1
            except IndexError:
                result += colorize('+', False)
                wrong += 1
        if len_answer > len_question:
            result += colorize(answer[len_question:], False)
        self.ui.lineAnswer.setText('')
        self.ui.lblAnswer.setText(result)
        cpm = (len_question - wrong) / take_time.total_seconds() * 60
        self.ui.lblTime.setText('{:.0f} CPM'.format(cpm))
        acc_rate = (len_question - wrong) / len_question * 100
        self.ui.lblAccuracy.setText('{0:.2f}%'.format(acc_rate))
        self.ui.lblAnswer.setText('')
        try:
            self.ui.lblQuestion.setText(next(self.qs).text)
        except StopIteration:
            self.ui.lblQuestion.setText('Finish')
            self.ui.lineAnswer.setEnabled(False)

    def changeAnswer(self):
        if not self.started and len(self.ui.lineAnswer.text()):
            self.started = True
            self.start_time = datetime.now()
        question = self.ui.lblQuestion.text()
        answer = self.ui.lineAnswer.text()
        result = ''
        for q, a in zip(question, answer):
            if q == a:
                result += colorize(a, True)
            else:
                result += colorize(a, False)
        self.ui.lblAnswer.setText(result)
        self.ui.lblAnswer.setEnabled(True)

    def start(self):
        self.game_dlg = TopicManagerDlg(self)
        layout = QVBoxLayout()
        btnStart = QPushButton('Start')
        layout.addWidget(btnStart)
        self.game_dlg.layout.addLayout(layout)
        btnStart.clicked.connect(self.start_game)
        self.game_dlg.exec_()

    def start_game(self):
        _topic = self.game_dlg.lstTopics.currentItem().text()
        topic = session.query(Topic).filter(Topic.title == _topic).first()
        qs = topic.questions.all()
        self.game_dlg.close()
        self.qs = iter(qs)
        self.ui.lineAnswer.setEnabled(True)
        self.ui.lineAnswer.setFocus()
        self.ui.lblQuestion.setText(next(self.qs).text)

    def openManQuestionDlg(self):
        dlg = QuestionManagerDlg(self)
        dlg.exec_()
Exemplo n.º 28
0
class WykresApp(QtGui.QMainWindow):
    _singleton = None

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

        self.colors = [Red(), Blue(), Black(), Green(), Violet()]
        for item in self.colors:
            self.addComboBoxItem(item.num, item.name)

        self.ui.wybierz.clicked.connect(self.selectFile)
        self.fileSelect = QtGui.QFileDialog(self)
        self.ui.rysuj.clicked.connect(self.printChart)
        self.scene = QtGui.QGraphicsScene()
        self.ui.slupkowy.clicked.connect(self.getSelectedRadio)
        self.ui.kolowy.clicked.connect(self.getSelectedRadio)
        self.ui.liniowy.clicked.connect(self.getSelectedRadio)
        self.ui.punktowy.clicked.connect(self.getSelectedRadio)
        self.ui.slupkowy.click()

    # singleton
    def __new__(cls, *args, **kwargs):
        if not cls._singleton:
            cls._singleton = super(WykresApp, cls).__new__(cls, *args, **kwargs)
        return cls._singleton

    def changeText(self, text):
        self.ui.info.setText(text)

    def selectFile(self):
        self.fileSelect.name = self.fileSelect.getOpenFileName()
        self.ui.plik.setText(self.fileSelect.name)
        self.openFile()

    def openFile(self):
        with open(self.fileSelect.name, "r") as csvfile:
            file = csv.reader(csvfile, delimiter=',')
            for row in file:
                self.ui.theX.append(int(row[0]))
                if len(row) == 2:
                    self.ui.theY.append(int(row[1]))

    def printImage(self):
        pixmap = QtGui.QPixmap("wykres.png")
        self.ui.pole_wykresu.setScaledContents(True)
        self.ui.pole_wykresu.setPixmap(pixmap)

    def getSelectedRadio(self):
        chartType = chart()
        changeText(chartType, self)  # rejestrowanie obserwatora
        for radio in self.ui.groupBox.children():
            if radio.isChecked():
                if "kolowy" != radio.objectName():
                    chartType.setTextAndObject("Plik tekstowy, gdzie wierszem jest dwójka \n(x,y)", radio)
                else:
                    chartType.setTextAndObject("Plik tekstowy, gdzie wierszem jest dwójka \n(x, nazwa zmiennej)\n"
                                               "kolor - nie dotyczy", radio)

    def printChart(self):
        mpl.cla()
        charter = matChart()
        drawCorrectChart(charter, self.ui.selectedRadio.objectName(), self.ui.theX, self.ui.theY,
                         color=self.colors[self.ui.comboBox.currentIndex()].paramName)
        mpl.ylabel("Y")
        mpl.xlabel("X")
        mpl.savefig("wykres.png")
        self.printImage()

    def addComboBoxItem(self, num, name):
        self.ui.comboBox.addItem("")
        self.ui.comboBox.setItemText(num, _translate("MainWindow", name, None))
Exemplo n.º 29
0
class MyWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        self.allCSV = None

        self.plotArray = None

        self.numRow = 8
        self.numColumn = 12
        self.startWell = 1 
        self.endWell = 96
        self.umPerPixel = 0.149
      
        self.minXList = []
        self.maxXList = []
        self.minYList = []
        self.maxYList = []
       
        self.minX = None
        self.maxX = None
        self.minY= None
        self.maxY = None

        self.previousWells = [] 

        QtGui.QMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
      
        self.wellMapper = {QtCore.QString(u'0'): range(0,0),
                           QtCore.QString(u'1'): range(1,13,2) + range(49,61,2),
                           QtCore.QString(u'2'): range(2,13,2) + range(50,61,2),
                           QtCore.QString(u'3'): range(13,25,2) + range(61,73,2),
                           QtCore.QString(u'4'): range(14,25,2) + range(62,73,2),
                           QtCore.QString(u'5'): range(25,37,2) + range(73,85,2),
                           QtCore.QString(u'6'): range(26,37,2) + range(74,85,2),
                           QtCore.QString(u'7'): range(37,49,2) + range(85,97,2),
                           QtCore.QString(u'8'): range(38,49,2) + range(86,97,2),
                           True: range(1,97),
                           False: range(0,0)}
                           

         
        QtCore.QObject.connect(self.ui.comboBox, QtCore.SIGNAL('currentIndexChanged(const QString &)'), self.updateSelectedPlot) 
        QtCore.QObject.connect(self.ui.checkBox_show_all, QtCore.SIGNAL('clicked(bool)'), self.updateSelectedPlot)
        
        self.plotArray = [[None for x in range(self.numColumn)] for y in range(self.numRow)]
        
        for row in range(self.numRow):
            for column in range(self.numColumn):
                self.plotArray[row][column] = MyPlot(pg.PlotItem(title='well ' + str(row*self.numColumn + column+1)))
                self.ui.widget.addItem(self.plotArray[row][column].pgPlot)
            self.ui.widget.nextRow()
    
    def setDataDirectory(self, directory):
        self.allCSV= glob.glob(directory + '*.csv')

   
    def loadAllWells(self):
        for idx in range(self.startWell, self.endWell+1):
            row = (idx-1) / self.numColumn 
            column = (idx-1) % self.numColumn

            searchResult = search(self.allCSV, '_pass1_well'+str(idx)+'_')
            if(searchResult):
                if(column % 4 == 0 or column % 4 == 1):
                    self.readCurves(self.plotArray[row][column], searchResult, 'noUse', True, False)
                else:
                    self.readCurves(self.plotArray[row][column], searchResult, 'nouse', False, True)

                self.minXList.append(self.plotArray[row][column].minX)
                self.maxXList.append(self.plotArray[row][column].maxX)
                self.minYList.append(self.plotArray[row][column].minY)
                self.maxYList.append(self.plotArray[row][column].maxY)

        self.minX = min(self.minXList)
        self.maxX = max(self.maxXList)
        self.minY = min(self.minYList)
        self.maxY = max(self.maxYList)

        for x in self.plotArray:
           for y in x:
               y.pgPlot.getViewBox().setRange(xRange=(min(self.minX,self.minY), max(self.maxX, self.maxY)), yRange=(min(self.minX, self.minY), max(self.maxX, self.maxY)))
               #y.pgPlot.showGrid(True, True, 0.5)
               y.pgPlot.getViewBox().setAspectLocked(True, 1)
                

        
    def updateSelectedPlot(self, key):
        ''' Display the wells that we need and hide the rest. '''
        wells = self.wellMapper[key]
        
        if(key == False):
            wells = self.previousWells
    
        for idx in range(self.startWell, self.endWell+1):
            row = (idx-1) / self.numColumn 
            column = (idx-1) % self.numColumn
           
            if(idx in wells):
                ''' 
                # Load data if we haven't done it before 
                if(len(self.plotArray[row][column].myDataItem) == 0):
                    searchResult = search(self.allCSV, '_pass1_well'+str(idx)+'_')
                    if(searchResult):
                        if(column % 4 == 0 or column % 4 == 1):
                            self.readCurves(self.plotArray[row][column], searchResult, 'noUse', True, False)
                        else:
                            self.readCurves(self.plotArray[row][column], searchResult, 'nouse', False, True)
                ''' 
                if(self.plotArray[row][column].showing == False):
                    self.plotArray[row][column].show()

            else:
                if(self.plotArray[row][column].showing and self.ui.checkBox_show_all.isChecked() == False):
                    self.plotArray[row][column].clear()
                
        if(key != True and key != False):
            self.previousWells = wells


    def readCurves(self, myPlot, file, color, flipX=False, flipY=False, moveToOrigin=True, hasTitle=True):
        print 'Opening ' + file

        with open(file, 'rb') as csvfile:
            reader = csv.reader(csvfile, delimiter=',', skipinitialspace=True)
            if(hasTitle):
                title = reader.next()
      
            # Collect x, y coordinates for each tracker in a dictionary based on tracker id.
            idColumn = 1 
            xColumn = 2
            yColumn = 3
            trackers = defaultdict(lambda: [[],[]])
            for row in reader:
                trackers[row[idColumn]][0].append(float(row[xColumn]))
                trackers[row[idColumn]][1].append(float(row[yColumn]))

            # For each track, modify its (x,y) if we need to translate or rotate them.
            minX = sys.maxint 
            minY = sys.maxint 
            maxX = -sys.maxint 
            maxY = -sys.maxint
            firstTracker = True
            for ind, values in trackers.iteritems():
                if(moveToOrigin):
                    translateX = values[0][0]
                    translateY = values[1][0] 
                    for i, item in enumerate(values[0]):
                        values[0][i] -= translateX
                        values[1][i] -= translateY
                        values[0][i], values[1][i] = rotate(90, values[0][i], values[1][i], flipX, flipY)
                       
                        # Convert pixels to microns
                        values[0][i] *= self.umPerPixel
                        values[1][i] *= self.umPerPixel

                        if(values[0][i] < minX):
                            minX = values[0][i]
                        elif(values[0][i] > maxX):
                            maxX = values[0][i]

                        if(values[1][i] < minY):
                            minY = values[1][i]
                        elif(values[1][i] > maxY):
                            maxY = values[1][i]
                
                color = nextColor(firstTracker)
                firstTracker = False
                
                item = pg.PlotDataItem(values[0], values[1], pen=color)
                myPlot.myDataItem.append(MyDataItem(item, color))
      
        myPlot.minX = minX
        myPlot.maxX = maxX
        myPlot.minY = minY
        myPlot.maxY = maxY
Exemplo n.º 30
0
class Ui(QtWidgets.QMainWindow):
    def __init__(self):
        super(Ui,
              self).__init__()  # Call the inherited classes __init__ method
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setStyleSheet("QMainWindow {background: '#f0f0f0';}")
        self.statusBar = QtWidgets.QStatusBar()
        self.setStatusBar(self.statusBar)
        self.pushButton = self.ui.pushButton
        self.com_in = self.ui.com_in
        self.com_out = self.ui.com_out
        self.baud_in = self.ui.baud_in
        self.baud_out = self.ui.baud_out
        self.pitch_correction = self.ui.pitch_correction
        self.roll_correction = self.ui.roll_correction
        self.console_out = self.ui.console_out
        self.console_in = self.ui.console_in
        self.menubar = self.ui.menubar

        self.pushButton.clicked.connect(self.start)
        self.flag = True
        self.setWindowTitle('LGC TILT')
        self.pushButton.setStyleSheet(
            'QPushButton {background-color: #E7F1E1; border:  none}')
        com_list = []
        for i in serial.tools.list_ports.comports():
            com_list.append(str(i).split(" ")[0])
        sorted_list = []
        for i in range(300):
            this_com = ("COM" + str(i))
            if this_com in com_list:
                sorted_list.append(this_com)
        self.com_in.addItems(sorted_list)
        self.com_out.addItems(sorted_list)
        self.threadpool = QtCore.QThreadPool()
        self.serial_object = None
        self.settings = QtCore.QSettings(self.objectName())
        self.com_in.setCurrentIndex(self.settings.value('com_in', 0))
        self.com_out.setCurrentIndex(self.settings.value('com_out', 1))
        self.baud_in.setCurrentIndex(self.settings.value('baud_in', 2))
        self.baud_out.setCurrentIndex(self.settings.value('baud_out', 2))
        self.pitch_correction.setText(
            self.settings.value('pitch_correction', '0'))
        self.roll_correction.setText(
            self.settings.value('roll_correction', '0'))
        self.restoreGeometry(self.settings.value('geo', self.saveGeometry()))
        self.settings.setValue('com_in', self.com_in.currentIndex())
        self.worker = None
        self.menubar.setHidden(True)
        self.show()  # Show the GUI

    def append_output(self, s):
        if len(self.console_out.toPlainText().split('\n')) > 100:
            self.console_out.setHtml(
                self.console_out.toHtml().split('</p>', 1)[1] + s)
            self.console_out.verticalScrollBar().setValue(
                self.console_out.verticalScrollBar().maximum())
        else:
            self.console_out.append(s)

    def append_input(self, s):
        if len(self.console_in.toPlainText().split('\n')) > 100:
            self.console_in.setHtml(
                self.console_in.toHtml().split('</p>', 1)[1] + s)
            self.console_in.verticalScrollBar().setValue(
                self.console_in.verticalScrollBar().maximum())
        else:
            self.console_in.append(s)
        print(s)

    def show_message(self, e):
        self.statusBar.showMessage(str(e))

    def start(self):
        if self.flag:
            com_in = self.com_in.currentText()
            com_out = self.com_out.currentText()
            baud_in = int(self.baud_in.currentText())
            baud_out = int(self.baud_out.currentText())
            pitch_correction = float(self.pitch_correction.text())
            roll_correction = float(self.roll_correction.text())
            self.serial_object = MySerial(com_in, com_out, baud_in, baud_out,
                                          pitch_correction, roll_correction)
            self.worker = Worker(self.serial_object)
            # self.worker.on()
            self.threadpool.start(self.worker)
            self.worker.signals.data_in.connect(self.append_input)
            self.worker.signals.data_out.connect(self.append_output)
            self.worker.signals.message.connect(self.show_message)
            self.worker.signals.error.connect(self.error)
            self.off()
        else:
            self.on()

    def error(self, e):
        self.on()
        print(str(e[1]).split('(')[0])
        self.statusBar.showMessage(str(e[1]).split('(')[0])

    def on(self):
        self.worker.off()
        self.statusBar.showMessage('Ports Closed')
        self.pushButton.setText('START')
        self.com_in.setEnabled(True)
        self.com_out.setEnabled(True)
        self.baud_in.setEnabled(True)
        self.baud_out.setEnabled(True)
        self.pitch_correction.setEnabled(True)
        self.roll_correction.setEnabled(True)
        self.pushButton.setStyleSheet(
            'QPushButton {background-color: #E7F1E1; border:  none}')
        self.flag = True

    def off(self):
        self.pushButton.setText('STOP')
        self.flag = False
        self.com_in.setEnabled(False)
        self.com_out.setEnabled(False)
        self.baud_in.setEnabled(False)
        self.baud_out.setEnabled(False)
        self.pitch_correction.setEnabled(False)
        self.roll_correction.setEnabled(False)
        self.pushButton.setStyleSheet(
            'QPushButton {background-color: red; border:  none}')

    def closeEvent(self, event):
        self.settings.setValue('com_in', self.com_in.currentIndex())
        self.settings.setValue('com_out', self.com_out.currentIndex())
        self.settings.setValue('baud_in', self.baud_in.currentIndex())
        self.settings.setValue('baud_out', self.baud_out.currentIndex())
        self.settings.setValue('pitch_correction',
                               self.pitch_correction.text())
        self.settings.setValue('roll_correction', self.roll_correction.text())
        self.settings.setValue('geo', self.saveGeometry())
        if self.worker:
            self.worker.off()
        if self.serial_object:
            self.serial_object.close_it()
        self.close()
Exemplo n.º 31
0
    def __init__(self):
        super(MyUi, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        cwd = os.getcwd()
        cwd = str(cwd)
        if os.path.isfile(cwd+"/time"):
            with open("time","r") as outfile:#reads current time
                history = cPickle.load(outfile)
            if (datetime.now()-history).total_seconds()<43200: #measures if time elapse>12 hours
                print("Less than 12 hours. Loading previously saved Pickle...")
                #with open("time","w") as infile: #update time
                    #cPickle.dump(datetime.now(),infile)

            else:
                print("More than 12 hours. Updating Pickle...")
                data = ts.get_industry_classified()
                with open("class","w+") as outfile:
                    cPickle.dump(data,outfile)
                now = datetime.now()
                with open("time", "w+") as outfile: #update time
                    cPickle.dump(now, outfile)

        else:
            print("No Pickle found!") #If this is first time using tuchart in this directory
            data = df()
            data = ts.get_industry_classified()
            with open('class', 'w+') as outfile: #records pickle
                cPickle.dump(data, outfile)
            now = datetime.now()
            with open("time", "w+") as outfile:
                cPickle.dump(now,outfile)

        with open("class", "r") as infile:  # reads current time
            series = cPickle.load(infile)
        #series = pd.read_json(cwd + "\\class.json")
        #series = ts.get_industry_classified()
        series = pd.DataFrame(series)

        curdate = time.strftime("%Y/%m/%d")  # gets current time to put into dateedit
        curdateQ = QDate.fromString(curdate,"yyyy/MM/dd")

        dateobj = datetime.strptime(curdate, "%Y/%m/%d")#converts to datetime object

        past = dateobj - timedelta(days = 7)  #minus a week to start date
        pasttime = datetime.strftime(past, "%Y/%m/%d")
        pastQ = QDate.fromString(pasttime,"yyyy/MM/dd") #convert to qtime so that widget accepts the values



        pastL = dateobj - timedelta(days=30)  # minus a month to start date
        pasttimeL = datetime.strftime(pastL, "%Y/%m/%d")
        pastQL = QDate.fromString(pasttimeL, "yyyy/MM/dd")


        np_indexes = np.array([['sh', '上证指数', '大盘指数'],
                               ['sz', '深证成指', '大盘指数'],
                               ['hs300', '沪深300指数', '大盘指数'],
                               ['sz50', '上证50', '大盘指数'],
                               ['zxb', '中小板', '大盘指数'],
                               ['cyb', '创业板', '大盘指数']])
        indexes = df(data=np_indexes,
                     index=range(5000, 5006),
                     columns=["code", "name", "c_name"])
        series = indexes.append(series)
        list1_bfr = series["c_name"].tolist()  #Get industry categories. Filters out redundant ones
        list1 = list(set(list1_bfr))
        list1.sort(key=list1_bfr.index)
        #w = database()
        #zsparent = QTreeWidgetItem(self.ui.treeWidget)
        #zsparent.setText(0,"股票指数")
        #zsnames =["上证指数-sh","深圳成指-sz","沪深300指数-hs300","上证50-"]

        self.init_treeWidget(list1,series)

        self.ui.treeWidget.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui.treeWidget.customContextMenuRequested.connect(self.openMenu)

        #self.ui.webView.setGeometry(QtCore.QRect(0, 30,1550, 861))
        file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "render.html")) #path to read html file
        local_url = QUrl.fromLocalFile(file_path)
        self.ui.webView.load(local_url)
        #self.ui.commandLinkButton.setFixedSize(50, 50)
        self.ui.search_btn.clicked.connect(lambda: self.search_comp(series))
        self.ui.init_code_btn.clicked.connect(lambda: self.code_sort_tree(series))
        self.ui.init_category_btn.clicked.connect(lambda: self.init_treeWidget(list1, series))

        self.ui.commandLinkButton.clicked.connect(self.classify)  #when the arrow button is clicked, trigger events


        #self.ui.commandLinkButton.clicked.connect(lambda action: self.classify(action, self.ui.treewidget))
        #  QSizePolicy
        try:
            retain_size = self.ui.dateEdit_2.sizePolicy()
            retain_size.setRetainSizeWhenHidden(True)
            self.ui.dateEdit_2.setSizePolicy(retain_size)
            retain_size = self.ui.comboBox.sizePolicy()
            retain_size.setRetainSizeWhenHidden(True)
            self.ui.comboBox.setSizePolicy(retain_size)
            retain_size = self.ui.label_2.sizePolicy()
            retain_size.setRetainSizeWhenHidden(True)
            self.ui.label_2.setSizePolicy(retain_size)
        except AttributeError:
            print("No PYQT5 Binding! Widgets might be deformed")
        self.ui.dateEdit.setDate(pastQL)
        self.ui.dateEdit_2.setDate(curdateQ)#populate widgets
        self.ui.dateEdit.setCalendarPopup(True)
        self.ui.dateEdit_2.setCalendarPopup(True)
        self.ui.comboBox.addItems(["D", "W", "M", "5", "15", "30", "60"])
        self.ui.treeWidget_2.setDragDropMode(self.ui.treeWidget_2.InternalMove)
        self.ui.treeWidget_2.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui.treeWidget_2.customContextMenuRequested.connect(self.openWidgetMenu)
        #self.ui.toolbutton.clicked.connect(lambda action: self.graphmerge(action, CombineKeyword))
        self.ui.combobox.currentIndexChanged.connect(lambda: self.modifycombo(pastQL,pastQ))
Exemplo n.º 32
0
class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        _dir = os.path.dirname(os.path.abspath(__file__))
        #uic.loadUi(_dir + '/' + 'layout.ui', self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.profileWidget.hide()
        self.ui.smallDataWidget.hide()
        self.ui.splitter_3.setSizes([
            self.width() * 0.7, self.width() * 0.3
        ])  # splitter between image_view/plot_widget and file list
        self.ui.splitter_2.setSizes([
            self.height() * 0.7, self.height() * 0.3
        ])  # splitter between image_view and plot widget
        self.ui.splitter.setSizes([
            self.ui.splitter.width() / 3.,
            self.ui.splitter.width() / 3.,
            self.ui.splitter.width() / 3.
        ])
        self.setAcceptDrops(True)
        self.ui.fileList.setColumnWidth(0, 200)

        self.filepath = None  # current filepath
        self.imageData = None  # original image data, 2d or 3d
        self.imageShape = None
        self.dispData = None  # 2d data for plot
        self.dispShape = None
        self.mask = None
        self.curve = None
        self.h5obj = None
        self.acceptedFileTypes = [
            u'npy', u'npz', u'h5', u'mat', u'cxi', u'tif'
        ]

        self.dispItem = self.ui.imageView.getImageItem()
        self.ringItem = pg.ScatterPlotItem()
        self.centerMarkItem = pg.ScatterPlotItem()
        self.ui.imageView.getView().addItem(self.ringItem)
        self.ui.imageView.getView().addItem(self.centerMarkItem)

        self.curveItem = PlotDataItem()
        self.ui.curveWidget.addItem(self.curveItem)
        self.ui.curveWidget.getPlotItem().setTitle(title='Curve Plot')

        # basic operation for image and curve plot
        self.showImage = True
        self.axis = 'x'
        self.frameIndex = 0
        self.maskFlag = False
        self.imageLog = False
        self.binaryFlag = False
        self.FFT = False
        self.FFTSHIFT = False
        self.dispThreshold = 0
        self.center = [0, 0]
        self.showRings = False
        self.ringRadiis = []
        self.showCurvePlot = True

        self.profileItem = PlotDataItem(pen=pg.mkPen(
            'y', width=1, style=QtCore.Qt.SolidLine),
                                        name='profile')
        self.smoothItem = PlotDataItem(pen=pg.mkPen('g',
                                                    width=2,
                                                    style=QtCore.Qt.DotLine),
                                       name='smoothed profile')
        self.thresholdItem = PlotDataItem(pen=pg.mkPen('r'),
                                          width=1,
                                          style=QtCore.Qt.DashLine,
                                          name='threshold')
        self.ui.profileWidget.addLegend()
        self.ui.profileWidget.addItem(self.profileItem)
        self.ui.profileWidget.addItem(self.smoothItem)
        self.ui.profileWidget.addItem(self.thresholdItem)
        self.ui.profileWidget.getPlotItem().setTitle(title='Profile Plot')
        # profile option
        self.showProfile = False
        self.profileType = 'radial'
        self.profileMode = 'sum'
        # extrema search
        self.extremaSearch = False
        self.extremaType = 'max'
        self.extremaWinSize = 11
        self.extremaThreshold = 1.0  # ratio compared to mean value
        # angular option
        self.angularRmin = 0.
        self.angularRmax = np.inf
        # across center line option
        self.lineAngle = 0.
        self.lineWidth = 1
        # profile smoothing
        self.smoothFlag = False
        self.smoothWinSize = 15
        self.polyOrder = 3
        # small data option
        self.smallDataItem = pg.ScatterPlotItem()
        self.ui.smallDataWidget.addItem(self.smallDataItem)
        self.ui.smallDataWidget.getPlotItem().setTitle(title='Small Data')
        self.showSmallData = False
        self.smallDataFile = None
        self.smallDataset = None
        self.smallDataSorted = False
        self.smallDataPaths = None
        self.smallDataFrames = None
        self.smallData = None
        # display option
        self.imageAutoRange = False
        self.imageAutoLevels = False
        self.imageAutoHistogramRange = True
        self.curvePlotAutoRange = True
        self.curvePlotLog = False
        self.profilePlotAutoRange = True
        self.profilePlotLog = False
        self.smallDataPlotAutoRange = True
        self.smallDataPlotLog = False

        params_list = [{
            'name':
            'Data Info',
            'type':
            'group',
            'children': [{
                'name': 'File',
                'type': 'str',
                'value': 'not set',
                'readonly': True
            }, {
                'name': 'Dataset',
                'type': 'str',
                'value': 'not set',
                'readonly': True
            }, {
                'name': 'Mask',
                'type': 'str',
                'value': 'not set',
                'readonly': True
            }, {
                'name': 'Image Shape',
                'type': 'str',
                'value': 'unknown',
                'readonly': True
            }, {
                'name': 'Image Friedel Score',
                'type': 'float',
                'readonly': True
            }, {
                'name': 'Curve Length',
                'type': 'int',
                'readonly': 'True'
            }]
        }, {
            'name':
            'Basic Operation',
            'type':
            'group',
            'children': [{
                'name':
                'Image',
                'type':
                'group',
                'children': [
                    {
                        'name': 'Axis',
                        'type': 'list',
                        'values': ['x', 'y', 'z'],
                        'value': self.axis
                    },
                    {
                        'name': 'Frame Index',
                        'type': 'int',
                        'value': self.frameIndex
                    },
                    {
                        'name': 'Apply Mask',
                        'type': 'bool',
                        'value': self.imageLog
                    },
                    {
                        'name': 'Apply Log',
                        'type': 'bool',
                        'value': self.maskFlag
                    },
                    {
                        'name': 'Apply FFT',
                        'type': 'bool',
                        'value': self.FFT
                    },
                    {
                        'name': 'Apply FFT-SHIFT',
                        'type': 'bool',
                        'value': self.FFTSHIFT
                    },
                    {
                        'name': 'Binaryzation',
                        'type': 'bool',
                        'value': self.binaryFlag
                    },
                    {
                        'name': 'Threshold',
                        'type': 'float',
                        'value': self.dispThreshold
                    },
                    {
                        'name': 'Center x',
                        'type': 'int',
                        'value': self.center[1]
                    },
                    {
                        'name': 'Center y',
                        'type': 'int',
                        'value': self.center[0]
                    },
                    {
                        'name': 'Show Rings',
                        'type': 'bool'
                    },
                    {
                        'name': 'Ring Radiis',
                        'type': 'str',
                        'value': ''
                    },
                ]
            }, {
                'name': 'Curve Plot',
                'type': 'group',
                'children': [
                    {
                        'name': 'TODO',
                        'type': 'str'
                    },
                ]
            }]
        }, {
            'name':
            'Image to Feature Profile',
            'type':
            'group',
            'children': [{
                'name': 'Show Profile',
                'type': 'bool',
                'value': self.showProfile
            }, {
                'name': 'Feature',
                'type': 'list',
                'values': ['radial', 'angular', 'across center line'],
                'value': self.profileType
            }, {
                'name': 'Profile Mode',
                'type': 'list',
                'values': ['sum', 'mean'],
                'value': self.profileMode
            }, {
                'name':
                'Angular Option',
                'type':
                'group',
                'children': [
                    {
                        'name': 'R min',
                        'type': 'float',
                        'value': self.angularRmin
                    },
                    {
                        'name': 'R max',
                        'type': 'float',
                        'value': self.angularRmax
                    },
                ]
            }, {
                'name':
                'Across Center Line Option',
                'type':
                'group',
                'children': [
                    {
                        'name': 'Angle',
                        'type': 'float',
                        'value': self.lineAngle
                    },
                    {
                        'name': 'Width/pixel',
                        'type': 'int',
                        'value': self.lineWidth
                    },
                ]
            }, {
                'name':
                'Smoothing',
                'type':
                'group',
                'children': [
                    {
                        'name': 'Enable Smoothing',
                        'type': 'bool',
                        'value': self.smoothFlag
                    },
                    {
                        'name': 'Window Size',
                        'type': 'int',
                        'value': self.smoothWinSize
                    },
                    {
                        'name': 'Poly-Order',
                        'type': 'int',
                        'value': self.polyOrder
                    },
                ]
            }, {
                'name':
                'Extrema Search',
                'type':
                'group',
                'children': [
                    {
                        'name': 'Enable Extrema Search',
                        'type': 'bool',
                        'value': self.extremaSearch
                    },
                    {
                        'name': 'Extrema Type',
                        'type': 'list',
                        'values': ['max', 'min'],
                        'value': self.extremaType
                    },
                    {
                        'name': 'Extrema WinSize',
                        'type': 'int',
                        'value': self.extremaWinSize
                    },
                    {
                        'name': 'Extrema Threshold',
                        'type': 'float',
                        'value': self.extremaThreshold
                    },
                ]
            }]
        }, {
            'name':
            'Small Data',
            'type':
            'group',
            'children': [
                {
                    'name': 'Filepath',
                    'type': 'str'
                },
                {
                    'name': 'Dataset',
                    'type': 'str'
                },
                {
                    'name': 'Show data',
                    'type': 'bool',
                    'value': self.showSmallData
                },
                {
                    'name': 'Sort',
                    'type': 'bool',
                    'value': self.smallDataSorted
                },
            ]
        }, {
            'name':
            'Display Option',
            'type':
            'group',
            'children': [
                {
                    'name':
                    'Image',
                    'type':
                    'group',
                    'children': [
                        {
                            'name': 'autoRange',
                            'type': 'bool',
                            'value': self.imageAutoRange
                        },
                        {
                            'name': 'autoLevels',
                            'type': 'bool',
                            'value': self.imageAutoLevels
                        },
                        {
                            'name': 'autoHistogramRange',
                            'type': 'bool',
                            'value': self.imageAutoHistogramRange
                        },
                    ]
                },
                {
                    'name':
                    'Curve Plot',
                    'type':
                    'group',
                    'children': [
                        {
                            'name': 'autoRange',
                            'type': 'bool',
                            'value': self.curvePlotAutoRange
                        },
                        {
                            'name': 'Log',
                            'type': 'bool',
                            'value': self.curvePlotLog
                        },
                    ]
                },
                {
                    'name':
                    'Profile Plot',
                    'type':
                    'group',
                    'children': [
                        {
                            'name': 'autoRange',
                            'type': 'bool',
                            'value': self.profilePlotAutoRange
                        },
                        {
                            'name': 'Log',
                            'type': 'bool',
                            'value': self.profilePlotLog
                        },
                    ]
                },
                {
                    'name':
                    'Small Data Plot',
                    'type':
                    'group',
                    'children': [
                        {
                            'name': 'autoRange',
                            'type': 'bool',
                            'value': self.smallDataPlotAutoRange
                        },
                        {
                            'name': 'Log',
                            'type': 'bool',
                            'value': self.smallDataPlotLog
                        },
                    ]
                },
            ]
        }]
        self.params = Parameter.create(name='params',
                                       type='group',
                                       children=params_list)
        self.ui.parameterTree.setParameters(self.params, showTop=False)

        self.ui.fileList.itemDoubleClicked.connect(self.changeDatasetSlot)
        self.ui.fileList.customContextMenuRequested.connect(
            self.showFileMenuSlot)
        self.ui.imageView.scene.sigMouseMoved.connect(self.mouseMoved)
        self.smallDataItem.sigClicked.connect(self.smallDataClicked)
        self.ui.lineEdit.returnPressed.connect(self.addFilesSlot)

        self.params.param('Basic Operation', 'Image',
                          'Axis').sigValueChanged.connect(self.axisChangedSlot)
        self.params.param('Basic Operation', 'Image',
                          'Frame Index').sigValueChanged.connect(
                              self.frameIndexChangedSlot)
        self.params.param('Basic Operation', 'Image',
                          'Apply Mask').sigValueChanged.connect(
                              self.applyMaskSlot)
        self.params.param('Basic Operation', 'Image',
                          'Apply Log').sigValueChanged.connect(
                              self.applyImageLogSlot)
        self.params.param('Basic Operation', 'Image',
                          'Binaryzation').sigValueChanged.connect(
                              self.binaryImageSlot)
        self.params.param('Basic Operation', 'Image',
                          'Apply FFT').sigValueChanged.connect(
                              self.applyFFTSlot)
        self.params.param('Basic Operation', 'Image',
                          'Apply FFT-SHIFT').sigValueChanged.connect(
                              self.applyFFTSHIFTSlot)
        self.params.param('Basic Operation', 'Image',
                          'Binaryzation').sigValueChanged.connect(
                              self.binaryImageSlot)
        self.params.param('Basic Operation', 'Image',
                          'Threshold').sigValueChanged.connect(
                              self.setDispThresholdSlot)
        self.params.param('Basic Operation', 'Image',
                          'Center x').sigValueChanged.connect(
                              self.centerXChangedSlot)
        self.params.param('Basic Operation', 'Image',
                          'Center y').sigValueChanged.connect(
                              self.centerYChangedSlot)
        self.params.param('Basic Operation', 'Image',
                          'Show Rings').sigValueChanged.connect(
                              self.showRingsSlot)
        self.params.param('Basic Operation', 'Image',
                          'Ring Radiis').sigValueChanged.connect(
                              self.ringRadiiSlot)

        self.params.param('Image to Feature Profile',
                          'Show Profile').sigValueChanged.connect(
                              self.showProfileSlot)
        self.params.param('Image to Feature Profile',
                          'Feature').sigValueChanged.connect(
                              self.setProfileTypeSlot)
        self.params.param('Image to Feature Profile',
                          'Profile Mode').sigValueChanged.connect(
                              self.setProfileModeSlot)
        self.params.param('Image to Feature Profile', 'Angular Option',
                          'R min').sigValueChanged.connect(
                              self.setAngularRminSlot)
        self.params.param('Image to Feature Profile', 'Angular Option',
                          'R max').sigValueChanged.connect(
                              self.setAngularRmaxSlot)
        self.params.param(
            'Image to Feature Profile', 'Across Center Line Option',
            'Angle').sigValueChanged.connect(self.setLineAngleSlot)
        self.params.param(
            'Image to Feature Profile', 'Across Center Line Option',
            'Width/pixel').sigValueChanged.connect(self.setLineWidthSlot)
        self.params.param('Image to Feature Profile', 'Smoothing',
                          'Enable Smoothing').sigValueChanged.connect(
                              self.setSmoothSlot)
        self.params.param('Image to Feature Profile', 'Smoothing',
                          'Window Size').sigValueChanged.connect(
                              self.setWinSizeSlot)
        self.params.param('Image to Feature Profile', 'Smoothing',
                          'Poly-Order').sigValueChanged.connect(
                              self.setPolyOrderSlot)
        self.params.param('Image to Feature Profile', 'Extrema Search',
                          'Enable Extrema Search').sigValueChanged.connect(
                              self.setExtremaSearchSlot)
        self.params.param('Image to Feature Profile', 'Extrema Search',
                          'Extrema Type').sigValueChanged.connect(
                              self.setExtremaTypeSlot)
        self.params.param('Image to Feature Profile', 'Extrema Search',
                          'Extrema WinSize').sigValueChanged.connect(
                              self.setExtremaWinSizeSlot)
        self.params.param('Image to Feature Profile', 'Extrema Search',
                          'Extrema Threshold').sigValueChanged.connect(
                              self.setExtremaThresholdSlot)

        self.params.param('Small Data', 'Filepath').sigValueChanged.connect(
            self.setSmallDataFilepathSlot)
        self.params.param('Small Data', 'Dataset').sigValueChanged.connect(
            self.setSmallDatasetSlot)
        self.params.param('Small Data', 'Show data').sigValueChanged.connect(
            self.showSmallDataSlot)
        self.params.param('Small Data', 'Sort').sigValueChanged.connect(
            self.sortSmallDataSlot)

        self.params.param('Display Option', 'Image',
                          'autoRange').sigValueChanged.connect(
                              self.imageAutoRangeSlot)
        self.params.param('Display Option', 'Image',
                          'autoLevels').sigValueChanged.connect(
                              self.imageAutoLevelsSlot)
        self.params.param('Display Option', 'Image',
                          'autoHistogramRange').sigValueChanged.connect(
                              self.imageAutoHistogramRangeSlot)
        self.params.param('Display Option', 'Curve Plot',
                          'autoRange').sigValueChanged.connect(
                              self.curvePlotAutoRangeSlot)
        self.params.param('Display Option', 'Curve Plot',
                          'Log').sigValueChanged.connect(
                              self.curvePlotLogModeSlot)
        self.params.param('Display Option', 'Profile Plot',
                          'autoRange').sigValueChanged.connect(
                              self.profilePlotAutoRangeSlot)
        self.params.param('Display Option', 'Profile Plot',
                          'Log').sigValueChanged.connect(
                              self.profilePlotLogModeSlot)
        self.params.param('Display Option', 'Small Data Plot',
                          'autoRange').sigValueChanged.connect(
                              self.smallDataPlotAutoRangeSlot)
        self.params.param('Display Option', 'Small Data Plot',
                          'Log').sigValueChanged.connect(
                              self.smallDataPlotLogModeSlot)

    def addFilesSlot(self):
        filePattern = str(self.ui.lineEdit.text())
        #print_with_timestamp('file(s) pattern: %s' %filePattern)
        files = glob.glob(filePattern)
        #print_with_timestamp('adding file(s): %s \n Total Num: %d' %(str(files), len(files)))
        for i in xrange(len(files)):
            self.maybeAddFile(files[i])

    def smallDataClicked(self, _, points):
        _temp_file = '.temp.npy'
        pos = points[0].pos()
        index = int(points[0].pos()[0])
        if self.smallDataSorted:
            index = np.argsort(self.smallData)[index]
        filepath = self.smallDataPaths[index]
        frame = self.smallDataFrames[index]
        #print_with_timestamp('showing file: %s, frame: %d' %(filepath, frame))
        make_temp_file(filepath, frame, _temp_file)
        maybeExistIndex = self.ui.fileList.indexOf(_temp_file)
        if maybeExistIndex != -1:
            self.ui.fileList.takeTopLevelItem(maybeExistIndex)
        item = FileItem(filepath=_temp_file)
        self.ui.fileList.insertTopLevelItem(0, item)
        self.changeDatasetSlot(item, 0)

    def setSmallDataFilepathSlot(self, _, filepath):
        #print_with_timestamp('set filepath for small data: %s' % str(filepath))
        self.smallDataFile = filepath
        self.maybeShowSmallData()

    def setSmallDatasetSlot(self, _, dataset):
        #print_with_timestamp('set dataset for small data: %s' % str(dataset))
        self.smallDataset = dataset
        self.maybeShowSmallData()

    def showSmallDataSlot(self, _, showSmallData):
        #print_with_timestamp('set show small data: %s' % str(showSmallData))
        # self.showSmallData = showSmallData
        if showSmallData:
            self.ui.smallDataWidget.show()
        else:
            self.ui.smallDataWidget.hide()
        self.maybeShowSmallData()

    def sortSmallDataSlot(self, _, sort):
        #print_with_timestamp('set show small data sorted: %s' % str(sort))
        self.smallDataSorted = sort
        self.maybeShowSmallData()

    def dragEnterEvent(self, event):
        urls = event.mimeData().urls()
        for url in urls:
            if QtCore.QString(url.toLocalFile()).startsWith('/.file/id='):
                dropFile = getFilepathFromLocalFileID(url)
            else:
                dropFile = url.toLocalFile()
            fileInfo = QtCore.QFileInfo(dropFile)
            ext = fileInfo.suffix()
            if ext in self.acceptedFileTypes:
                event.accept()
                return None
        event.ignore()
        return None

    def dropEvent(self, event):
        urls = event.mimeData().urls()
        for url in urls:
            if QtCore.QString(url.toLocalFile()).startsWith('/.file/id='):
                dropFile = getFilepathFromLocalFileID(url)
            else:
                dropFile = url.toLocalFile()
            self.maybeAddFile(dropFile)

    def maybeAddFile(self, filepath):
        ext = QtCore.QFileInfo(filepath).suffix()
        if ext in self.acceptedFileTypes:
            maybeExistIndex = self.ui.fileList.indexOf(filepath)
            if maybeExistIndex != -1:
                self.ui.fileList.takeTopLevelItem(maybeExistIndex)
            item = FileItem(filepath=filepath)
            if item.childCount() > 0:
                self.ui.fileList.insertTopLevelItem(0, item)

    def loadData(self, filepath, datasetName):
        self.filepath = str(filepath)
        basename = os.path.basename(self.filepath)
        data = load_data(self.filepath, datasetName)
        if type(data) == list:
            if self.h5obj is not None:
                self.h5obj.close()
                self.h5obj = None
            self.h5obj = data[0]
            data = data[1]
        if len(data.shape) == 1:  # 1d curve
            if data.size == 1:  # single number
                return None
            else:
                self.curve = data
                return None
        self.imageData = data
        self.imageShape = data.shape
        _shape_str = ''
        if len(self.imageShape) == 2:
            _x, _y = self.imageShape
            _shape_str = 'x: %d, y: %d' % (_x, _y)
        elif len(self.imageShape) == 3:
            _x, _y, _z = self.imageShape
            _shape_str = 'x: %d, y: %d, z: %d' % (_x, _y, _z)
        self.params.param('Data Info', 'Image Shape').setValue(_shape_str)
        self.params.param('Data Info', 'File').setValue(basename)
        self.params.param('Data Info', 'Dataset').setValue(datasetName)
        if len(self.imageShape) == 3:
            self.dispShape = self.imageData.shape[1:3]
        else:
            self.dispShape = self.imageShape
        self.center = self.calcCenter()
        self.setCenterInfo()

    def setCenterInfo(self):
        self.params.param('Basic Operation', 'Image',
                          'Center x').setValue(self.center[0])
        self.params.param('Basic Operation', 'Image',
                          'Center y').setValue(self.center[1])

    def calcCenter(self):
        if len(self.imageShape) == 2:
            center = [self.imageShape[1] // 2, self.imageShape[0] // 2]
            return center
        assert len(self.imageShape) == 3
        if self.axis == 'x':
            center = [self.imageShape[2] // 2, self.imageShape[1] // 2]
        elif self.axis == 'y':
            center = [self.imageShape[2] // 2, self.imageShape[0] // 2]
        else:
            center = [self.imageShape[1] // 2, self.imageShape[0] // 2]
        return center

    def maybeShowSmallData(self):
        if self.showSmallData:
            if not self.ui.smallDataWidget.isVisible():
                self.ui.smallDataWidget.show()
            self.ui.smallDataWidget.setLabels(bottom='index', left='metric')
            if self.smallDataFile is not None and self.smallDataset is not None:
                paths, frames, smallData = load_smalldata(
                    self.smallDataFile, self.smallDataset)
                self.smallDataPaths = paths
                self.smallDataFrames = frames
                self.smallData = smallData
                if self.smallDataSorted:
                    index_array = np.argsort(self.smallData).astype(np.int32)
                    self.smallDataItem.setData(x=np.arange(
                        self.smallData.size),
                                               y=self.smallData[index_array])
                else:
                    self.smallDataItem.setData(x=np.arange(
                        self.smallData.size),
                                               y=self.smallData)

    def maybePlotProfile(self):
        if self.showProfile and self.dispData is not None:
            if self.mask is None:
                self.mask = np.ones_like(self.dispData)
            mask = self.mask.copy()
            if self.maskFlag == True:
                assert mask.shape == self.dispData.shape
            if self.profileType == 'radial':
                profile = calc_radial_profile(self.dispData,
                                              self.center,
                                              mask=mask,
                                              mode=self.profileMode)
            elif self.profileType == 'angular':
                annulus_mask = make_annulus(self.dispShape, self.angularRmin,
                                            self.angularRmax)
                profile = calc_angular_profile(self.dispData,
                                               self.center,
                                               mask=mask * annulus_mask,
                                               mode=self.profileMode)
            else:  # across center line
                profile = calc_across_center_line_profile(
                    self.dispData,
                    self.center,
                    angle=self.lineAngle,
                    width=self.lineWidth,
                    mask=self.mask,
                    mode=self.profileMode)
            if self.profilePlotLog == True:
                profile[profile < 1.] = 1.
            self.profileItem.setData(profile)
            if self.profileType == 'radial':
                self.ui.profileWidget.setTitle('Radial Profile')
                self.ui.profileWidget.setLabels(bottom='r/pixel')
            elif self.profileType == 'angular':
                self.ui.profileWidget.setTitle('Angular Profile')
                self.ui.profileWidget.setLabels(bottom='theta/deg')
            else:
                self.ui.profileWidget.setTitle('Across Center Line Profile')
                self.ui.profileWidget.setLabels(bottom='index/pixel')
            if self.smoothFlag == True:
                smoothed_profile = savgol_filter(profile, self.smoothWinSize,
                                                 self.polyOrder)
                if self.profilePlotLog == True:
                    smoothed_profile[smoothed_profile < 1.] = 1.
                self.smoothItem.setData(smoothed_profile)
            else:
                self.smoothItem.clear()
            profile_with_noise = profile.astype(np.float) + np.random.rand(
                profile.size
            ) * 1E-5  # add some noise to avoid same integer value in profile
            if self.extremaSearch == True:
                if self.extremaType == 'max':
                    extrema_indices = argrelmax(profile_with_noise,
                                                order=self.extremaWinSize)[0]
                else:
                    extrema_indices = argrelmin(profile_with_noise,
                                                order=self.extremaWinSize)[0]
                #print_with_timestamp('before filtered by threshold: %s' %str(extrema_indices))
                extremas = profile[extrema_indices]
                filtered_extrema_indices = extrema_indices[
                    extremas > self.extremaThreshold * profile.mean()]
                filtered_extremas = profile[filtered_extrema_indices]
                #print_with_timestamp('after filtered by threshold: %s' %(filtered_extrema_indices))
                self.thresholdItem.setData(
                    np.ones_like(profile) * profile.mean() *
                    self.extremaThreshold)
            else:
                self.thresholdItem.clear()

    def calcDispData(self):
        if self.imageData is None:
            return None
        elif len(self.imageShape) == 3:
            _x, _y, _z = self.imageShape
            if self.axis == 'x':
                if 0 <= self.frameIndex < _x:
                    dispData = self.imageData[self.frameIndex, :, :]
                else:
                    #print_with_timestamp("ERROR! Index out of range. %s axis frame %d" %(self.axis, self.frameIndex))
                    QtGui.QMessageBox.question(
                        self, 'Error',
                        "ERROR! Index out of range. %s axis frame %d" %
                        (self.axis, self.frameIndex), QtGui.QMessageBox.Ok)
                    return None
            elif self.axis == 'y':
                if 0 <= self.frameIndex < _y:
                    dispData = self.imageData[:, self.frameIndex, :]
                else:
                    #print_with_timestamp("ERROR! Index out of range. %s axis frame %d" %(self.axis, self.frameIndex))
                    QtGui.QMessageBox.question(
                        self, 'Error',
                        "ERROR! Index out of range. %s axis frame %d" %
                        (self.axis, self.frameIndex), QtGui.QMessageBox.Ok)
                    return None
            else:
                if 0 <= self.frameIndex < _z:
                    dispData = self.imageData[:, :, self.frameIndex]
                else:
                    #print_with_timestamp("ERROR! Index out of range. %s axis frame %d" %(self.axis, self.frameIndex))
                    QtGui.QMessageBox.question(
                        self, 'Error',
                        "ERROR! Index out of range. %s axis frame %d" %
                        (self.axis, self.frameIndex), QtGui.QMessageBox.Ok)
                    return None
        elif len(self.imageShape) == 2:
            dispData = self.imageData
        if isinstance(dispData, np.ndarray):
            dispData = dispData.copy()
        else:
            dispData = np.asarray(dispData).copy()
        if self.imageLog:
            dispData[dispData < 1.] = 1.
            dispData = np.log(dispData)
        if self.FFT:
            dispData = np.abs(np.fft.fft2(dispData))
        if self.FFTSHIFT:
            dispData = np.fft.fftshift(dispData)
        return dispData

    def closeEvent(self, event):
        global data_viewer_window
        reply = QtGui.QMessageBox.question(self, 'Message',
                                           "Are you sure to quit?",
                                           QtGui.QMessageBox.Yes,
                                           QtGui.QMessageBox.No)
        if reply == QtGui.QMessageBox.Yes:
            #print_with_timestamp('Bye-Bye.')
            #pg.exit()
            if self.h5obj is not None:
                self.h5obj.close()
            del data_viewer_window
            data_viewer_window = None
        else:
            event.ignore()

    def changeDatasetSlot(self, item, column):
        if isinstance(item, DatasetItem):
            datasetItem = item
            fileItem = datasetItem.parent()
        else:
            assert isinstance(item, FileItem)
            fileItem = item
            datasetItem = fileItem.child(0)
        self.loadData(fileItem.filepath,
                      datasetItem.datasetName)  # maybe 1d, 2d or 3d dataset
        self.maybeChangeCurve(name=datasetItem.datasetName)
        self.maybeChangeDisp()
        self.maybePlotProfile()

    def maybeChangeCurve(self, name=None):
        if not self.showCurvePlot or self.curve is None:
            return None
        self.curveItem.setData(self.curve)
        if name is not None:
            self.ui.curveWidget.getPlotItem().setTitle('Curve Plot -- %s' %
                                                       name)

    def maybeChangeDisp(self):
        if not self.showImage or self.imageData is None:
            return None
        dispData = self.calcDispData()
        if dispData is None:
            return None
        self.dispShape = dispData.shape
        if self.maskFlag:
            if self.mask is None:
                self.mask = np.ones(self.dispShape)
            assert self.mask.shape == self.dispShape
            dispData *= self.mask
        if self.binaryFlag:
            dispData[dispData < self.dispThreshold] = 0.
            dispData[dispData >= self.dispThreshold] = 1.
        self.dispData = dispData
        # set dispData to distItem. Note: transpose the dispData to show image with same manner in matplotlib
        self.ui.imageView.setImage(
            self.dispData.T,
            autoRange=self.imageAutoRange,
            autoLevels=self.imageAutoLevels,
            autoHistogramRange=self.imageAutoHistogramRange)
        if self.showRings:
            if len(self.ringRadiis) > 0:
                _cx = np.ones_like(self.ringRadiis) * self.center[0]
                _cy = np.ones_like(self.ringRadiis) * self.center[1]
                self.ringItem.setData(_cx,
                                      _cy,
                                      size=self.ringRadiis * 2.,
                                      symbol='o',
                                      brush=(255, 255, 255, 0),
                                      pen='r',
                                      pxMode=False)
        self.centerMarkItem.setData([self.center[0]], [self.center[1]],
                                    size=10,
                                    symbol='+',
                                    brush=(255, 255, 255, 0),
                                    pen='r',
                                    pxMode=False)
        Friedel_score = calc_Friedel_score(self.dispData,
                                           self.center,
                                           mask=self.mask,
                                           mode='relative')
        self.params.param('Data Info',
                          'Image Friedel Score').setValue(Friedel_score)

    def setLineAngleSlot(self, _, lineAngle):
        #print_with_timestamp('set line angle: %s' %str(lineAngle))
        self.lineAngle = lineAngle
        self.maybePlotProfile()

    def setLineWidthSlot(self, _, lineWidth):
        #print_with_timestamp('set line width: %s' %str(lineWidth))
        self.lineWidth = lineWidth
        self.maybePlotProfile()

    def applyImageLogSlot(self, _, imageLog):
        #print_with_timestamp('set image log: %s' %str(imageLog))
        self.imageLog = imageLog
        self.maybeChangeDisp()
        self.maybePlotProfile()

    def applyFFTSlot(self, _, FFT):
        #print_with_timestamp('set image fft: %s' %str(FFT))
        self.FFT = FFT
        self.maybeChangeDisp()
        self.maybePlotProfile()

    def applyFFTSHIFTSlot(self, _, FFTSHIFT):
        #print_with_timestamp('set image fft-shift: %s' %str(FFTSHIFT))
        self.FFTSHIFT = FFTSHIFT
        self.maybeChangeDisp()
        self.maybePlotProfile()

    def setExtremaSearchSlot(self, _, extremaSearch):
        #print_with_timestamp('set extrema search: %s' %str(extremaSearch))
        self.extremaSearch = extremaSearch
        self.maybePlotProfile()

    def setExtremaWinSizeSlot(self, _, extremaWinSize):
        #print_with_timestamp('set extrema window size: %s' %str(extremaWinSize))
        self.extremaWinSize = extremaWinSize
        self.maybePlotProfile()

    def setExtremaTypeSlot(self, _, extremaType):
        #print_with_timestamp('set extrema type: %s' %str(extremaType))
        self.extremaType = extremaType
        self.maybePlotProfile()

    def setExtremaThresholdSlot(self, _, extremaThreshold):
        #print_with_timestamp('set extrema threshold: %s' %str(extremaThreshold))
        self.extremaThreshold = extremaThreshold
        self.maybePlotProfile()

    def axisChangedSlot(self, _, axis):
        #print_with_timestamp('axis changed.')
        self.axis = axis
        self.center = self.calcCenter()
        self.setCenterInfo()
        self.maybeChangeDisp()
        self.maybePlotProfile()

    def frameIndexChangedSlot(self, _, frameIndex):
        #print_with_timestamp('frame index changed')
        self.frameIndex = frameIndex
        self.maybeChangeDisp()
        self.maybePlotProfile()

    def showProfileSlot(self, _, showProfile):
        #print_with_timestamp('show or hide radial profile changed')
        if showProfile:
            #print_with_timestamp('show profile')
            self.ui.profileWidget.show()
        else:
            self.ui.profileWidget.hide()
        self.maybePlotProfile()

    def centerXChangedSlot(self, _, centerX):
        #print_with_timestamp('center X changed')
        self.center[0] = centerX
        self.maybeChangeDisp()
        self.maybePlotProfile()

    def centerYChangedSlot(self, _, centerY):
        #print_with_timestamp('center Y changed')
        self.center[1] = centerY
        self.maybeChangeDisp()
        self.maybePlotProfile()

    def showFileMenuSlot(self, position):
        fileMenu = QtGui.QMenu()
        item = self.ui.fileList.currentItem()
        if isinstance(item, DatasetItem):
            setAsMask = fileMenu.addAction("Set As Mask")
            action = fileMenu.exec_(self.ui.fileList.mapToGlobal(position))
            if action == setAsMask:
                filepath = item.parent().filepath
                mask = load_data(filepath, item.datasetName)
                if len(mask.shape) != 2:
                    raise ValueError(
                        '%s:%s can not be used as mask. Mask data must be 2d.'
                        % (filepath, item.datasetName))
                self.mask = np.asarray(mask)
                self.params.param('Data Info', 'Mask').setValue(
                    "%s::%s" % (os.path.basename(filepath), item.datasetName))
        elif isinstance(item, FileItem):
            deleteAction = fileMenu.addAction("Delete")
            action = fileMenu.exec_(self.ui.fileList.mapToGlobal(position))
            if action == deleteAction:
                #print('deleting selected file')
                for item in self.ui.fileList.selectedItems():
                    self.ui.fileList.takeTopLevelItem(
                        self.ui.fileList.indexOfTopLevelItem(item))

    def applyMaskSlot(self, _, mask):
        #print_with_timestamp('turn on mask: %s' % str(mask))
        self.maskFlag = mask
        self.maybeChangeDisp()
        self.maybePlotProfile()

    def imageAutoRangeSlot(self, _, imageAutoRange):
        #print_with_timestamp('set image autorange: %s' % str(imageAutoRange))
        self.imageAutoRange = imageAutoRange
        self.maybeChangeDisp()

    def imageAutoLevelsSlot(self, _, imageAutoLevels):
        #print_with_timestamp('set image autolevels: %s' % str(imageAutoLevels))
        self.imageAutoLevels = imageAutoLevels
        self.maybeChangeDisp()

    def imageAutoHistogramRangeSlot(self, _, imageAutoHistogramRange):
        #print_with_timestamp('set image autohistogram: %s' % str(imageAutoHistogramRange))
        self.imageAutoHistogramRange = imageAutoHistogramRange
        self.maybeChangeDisp()

    def curvePlotAutoRangeSlot(self, _, plotAutoRange):
        #print_with_timestamp('set curve plot autorange: %s' % str(plotAutoRange))
        self.curvePlotAutoRange = plotAutoRange

    def curvePlotLogModeSlot(self, _, log):
        #print_with_timestamp('set curve plot log mode: %s' % str(log))
        if log:
            self.ui.curveWidget.setLogMode(y=True)
        else:
            self.ui.curveWidget.setLogMode(y=False)

    def profilePlotAutoRangeSlot(self, _, plotAutoRange):
        #print_with_timestamp('set profile plot autorange: %s' % str(plotAutoRange))
        if plotAutoRange:
            self.ui.profileWidget.getViewBox().enableAutoRange()
        else:
            self.ui.profileWidget.getViewBox().disableAutoRange()
        self.maybePlotProfile()

    def profilePlotLogModeSlot(self, _, log):
        #print_with_timestamp('set profile plot log mode: %s' % str(log))
        self.maybePlotProfile()
        if log:
            self.ui.profileWidget.setLogMode(y=True)
        else:
            self.ui.profileWidget.setLogMode(y=False)

    def smallDataPlotAutoRangeSlot(self, _, plotAutoRange):
        #print_with_timestamp('set small data plot autorange: %s' % str(plotAutoRange))
        if plotAutoRange:
            self.ui.smallDataWidget.getViewBox().enableAutoRange()
        else:
            self.ui.smallDataWidget.getViewBox().disableAutoRange()
        self.maybePlotProfile()

    def smallDataPlotLogModeSlot(self, _, log):
        #print_with_timestamp('set small data log mode: %s' % str(log))
        if log:
            self.ui.smallDataWidget.setLogMode(y=True)
        else:
            self.ui.smallDataWidget.setLogMode(y=False)

    def showRingsSlot(self, _, showRings):
        #print_with_timestamp('show rings: %s' %showRings)
        self.showRings = showRings
        if not self.showRings:
            self.ringItem.clear()
        self.maybeChangeDisp()

    def ringRadiiSlot(self, _, ringRadiis):
        #print_with_timestamp('set ring radiis: %s' %str(ringRadiis))
        ringRadiisStrList = ringRadiis.split()
        ringRadiis = []
        for ringRadiisStr in ringRadiisStrList:
            ringRadiis.append(float(ringRadiisStr))
        self.ringRadiis = np.asarray(ringRadiis)
        self.maybeChangeDisp()

    def setProfileTypeSlot(self, _, profileType):
        #print_with_timestamp('set profile type: %s' %str(profileType))
        self.profileType = profileType
        self.maybePlotProfile()

    def setProfileModeSlot(self, _, profileMode):
        #print_with_timestamp('set profile mode: %s' %str(profileMode))
        self.profileMode = profileMode
        self.maybePlotProfile()

    def binaryImageSlot(self, _, binaryImage):
        #print_with_timestamp('apply Binaryzation: %s' %str(binaryImage))
        self.binaryFlag = binaryImage
        self.maybeChangeDisp()
        self.maybePlotProfile()

    def setDispThresholdSlot(self, _, threshold):
        #print_with_timestamp('set disp threshold: %.1f' %threshold)
        self.dispThreshold = threshold
        self.maybeChangeDisp()
        self.maybePlotProfile()

    def setSmoothSlot(self, _, smooth):
        #print_with_timestamp('set smooth: %s' %str(smooth))
        self.smoothFlag = smooth
        self.maybeChangeDisp()
        self.maybePlotProfile()

    def setWinSizeSlot(self, _, winSize):
        winSize = winSize
        if winSize % 2 == 0:
            winSize += 1  # winSize must be odd
        #print_with_timestamp('set smooth winsize: %d' %winSize)
        self.smoothWinSize = winSize
        self.maybeChangeDisp()
        self.maybePlotProfile()

    def setPolyOrderSlot(self, _, polyOrder):
        #print_with_timestamp('set poly order: %d' %polyOrder)
        self.polyOrder = polyOrder
        self.maybeChangeDisp()
        self.maybePlotProfile()

    def setAngularRminSlot(self, _, Rmin):
        #print_with_timestamp('set angular Rmin to %.1f' %Rmin)
        self.angularRmin = Rmin
        self.maybeChangeDisp()
        self.maybePlotProfile()

    def setAngularRmaxSlot(self, _, Rmax):
        #print_with_timestamp('set angular Rmax to %.1f' %Rmax)
        self.angularRmax = Rmax
        self.maybeChangeDisp()
        self.maybePlotProfile()

    def mouseMoved(self, pos):
        if self.dispShape is None:
            return None
        mouse_point = self.ui.imageView.view.mapToView(pos)
        x, y = int(mouse_point.x()), int(mouse_point.y())
        filename = os.path.basename(str(self.filepath))
        if 0 <= x < self.dispData.shape[1] and 0 <= y < self.dispData.shape[0]:
            self.ui.statusbar.showMessage(
                "%s x:%d y:%d I:%.2E" % (filename, x, y, self.dispData[y, x]),
                5000)
        else:
            pass
Exemplo n.º 33
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.filenames = ['', '', '']
        self.graphChannels = [
            self.ui.signal1Graph, self.ui.signal2Graph, self.ui.signal3Graph
        ]
        self.spectrogramChannels = [
            self.ui.spectrogram1Graph, self.ui.spectrogram2Graph,
            self.ui.spectrogram3Graph
        ]
        self.timers = [self.ui.timer1, self.ui.timer2, self.ui.timer3]
        self.pen = [
            pg.mkPen(color=(255, 0, 0), width=1),
            pg.mkPen(color=(0, 255, 0), width=1),
            pg.mkPen(color=(0, 0, 255), width=1)
        ]

        self.PLOT_DIR = 'Plots'
        self.PDF_DIR = 'PDFs'
        self.amplitude = [[], [], []]
        self.time = [[], [], []]

        self.upToDatePlots = [[], [], []]
        self.spectrogramData = [None, None, None]
        self.pointsToAppend = [0, 0, 0]
        self.isResumed = [False, False, False]
        self.setChannelChecked = [
            self.ui.showChannel1, self.ui.showChannel2, self.ui.showChannel3
        ]
        self.channelComponents = [
            self.ui.channel1, self.ui.channel2, self.ui.channel3
        ]

        self.CHANNEL1 = 0
        self.CHANNEL2 = 1
        self.CHANNEL3 = 2

        self.ui.showChannel1.setChecked(True)
        self.ui.showChannel2.setChecked(True)
        self.ui.showChannel3.setChecked(True)
        self.ui.channel1.show()
        self.ui.channel2.show()
        self.ui.channel3.show()

        self.ui.showChannel1.stateChanged.connect(
            lambda: self.toggle(self.CHANNEL1))
        self.ui.showChannel2.stateChanged.connect(
            lambda: self.toggle(self.CHANNEL2))
        self.ui.showChannel3.stateChanged.connect(
            lambda: self.toggle(self.CHANNEL3))

        self.ui.actionAbout.triggered.connect(lambda: self.showAbout())
        self.ui.actionExit.triggered.connect(lambda: self.close())
        self.ui.actionNew.triggered.connect(lambda: self.create_new_window())

        self.ui.actionOpenChannel1.triggered.connect(
            lambda: self.browse(self.CHANNEL1))
        self.ui.playBtn1.clicked.connect(lambda: self.play(self.CHANNEL1))
        self.ui.pauseBtn1.clicked.connect(lambda: self.pause(self.CHANNEL1))
        self.ui.focusBtn1.clicked.connect(lambda: self.graphChannels[
            self.CHANNEL1].getPlotItem().enableAutoRange())
        self.ui.zoomInBtn1.clicked.connect(lambda: self.zoomin(self.CHANNEL1))
        self.ui.zoomOutBtn1.clicked.connect(
            lambda: self.zoomout(self.CHANNEL1))
        self.ui.clearBtn1.clicked.connect(lambda: self.clear(self.CHANNEL1))

        self.ui.actionOpenChannel2.triggered.connect(
            lambda: self.browse(self.CHANNEL2))
        self.ui.playBtn2.clicked.connect(lambda: self.play(self.CHANNEL2))
        self.ui.pauseBtn2.clicked.connect(lambda: self.pause(self.CHANNEL2))
        self.ui.focusBtn2.clicked.connect(lambda: self.graphChannels[
            self.CHANNEL2].getPlotItem().enableAutoRange())
        self.ui.zoomInBtn2.clicked.connect(lambda: self.zoomin(self.CHANNEL2))
        self.ui.zoomOutBtn2.clicked.connect(
            lambda: self.zoomout(self.CHANNEL2))
        self.ui.clearBtn2.clicked.connect(lambda: self.clear(self.CHANNEL2))

        self.ui.actionOpenChannel3.triggered.connect(
            lambda: self.browse(self.CHANNEL3))
        self.ui.playBtn3.clicked.connect(lambda: self.play(self.CHANNEL3))
        self.ui.pauseBtn3.clicked.connect(lambda: self.pause(self.CHANNEL3))
        self.ui.focusBtn3.clicked.connect(lambda: self.graphChannels[
            self.CHANNEL3].getPlotItem().enableAutoRange())
        self.ui.zoomInBtn3.clicked.connect(lambda: self.zoomin(self.CHANNEL3))
        self.ui.zoomOutBtn3.clicked.connect(
            lambda: self.zoomout(self.CHANNEL3))
        self.ui.clearBtn3.clicked.connect(lambda: self.clear(self.CHANNEL3))

        self.ui.generatePDF.clicked.connect(lambda: self.generatePDF())

        self.show()
Exemplo n.º 34
0
        def __init__(self):
            super().__init__()
            self.components = Ui_MainWindow()
            self.components.setupUi(self)
            self.show()
            self.components.start_button.clicked.connect(
                lambda: print(self.components.path_input.text()))
            # TODO file selector
            self.components.use_id_button.toggled.connect(lambda: print(
                'status: ' + str(self.components.use_id_button.isChecked())))

            # TODO editable elements
            # TODO group disable

            def temp():
                dl = QtWidgets.QFileDialog()
                dl.setAcceptMode(QtWidgets.QFileDialog.AcceptSave)
                dl.setNameFilter('Excel File (*.xlsx)')

                if dl.exec_():
                    filenames = dl.selectedFiles()
                    print(filenames)

            self.components.open_button.clicked.connect(temp)
            self.disable_group = [
                self.components.sheet_name_input,
                self.components.pub_title_input,
                self.components.lib_title_input,
                self.components.letter_only_button,
                self.components.no_space_button, self.components.strict_button,
                self.components.correct_color_box,
                self.components.ambiguous_color_box,
                self.components.wrong_color_box
            ]

            self.id_group = [
                self.components.pub_id_input, self.components.lib_id_input
            ]

            self.color_group = [
                self.components.correct_color_box,
                self.components.ambiguous_color_box,
                self.components.wrong_color_box
            ]

            COLOR_ITEM = [
                'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure',
                'beige', 'bisque', 'black', 'blanchedalmond', 'blue',
                'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse',
                'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson',
                'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray',
                'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta',
                'darkolivegreen', 'darkorange', 'darkorchid', 'darkred',
                'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray',
                'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink',
                'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick',
                'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro',
                'ghostwhite', 'gold', 'goldenrod', 'gray', 'green',
                'greenyellow', 'grey', 'honeydew', 'hotpink', 'indianred',
                'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush',
                'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral',
                'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen',
                'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen',
                'lightskyblue', 'lightslategray', 'lightslategrey',
                'lightsteelblue', 'lightyellow', 'lime', 'limegreen', 'linen',
                'magenta', 'maroon', 'mediumaquamarine', 'mediumblue',
                'mediumorchid', 'mediumpurple', 'mediumseagreen',
                'mediumslateblue', 'mediumspringgreen', 'mediumturquoise',
                'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose',
                'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive',
                'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod',
                'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip',
                'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple',
                'rebeccapurple', 'red', 'rosybrown', 'royalblue',
                'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell',
                'sienna', 'silver', 'skyblue', 'slateblue', 'slategray',
                'slategrey', 'snow', 'springgreen', 'steelblue', 'tan', 'teal',
                'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white',
                'whitesmoke', 'yellow', 'yellowgreen'
            ]

            for color_box in self.color_group:
                color_box.addItems(COLOR_ITEM)

            self.components.correct_color_box.setCurrentIndex(
                self.components.correct_color_box.findText('green'))
            self.components.ambiguous_color_box.setCurrentIndex(
                self.components.ambiguous_color_box.findText('yellow'))
            self.components.wrong_color_box.setCurrentIndex(
                self.components.wrong_color_box.findText('red'))

            def change_disable_status():
                dis_flag = self.components.use_user_enter_button.isChecked()
                id_flag = self.components.use_id_button.isChecked()
                for element in self.disable_group:
                    element.setDisabled(not dis_flag)

                for element in self.id_group:
                    element.setDisabled(not (id_flag and dis_flag))

            def change_id_status():
                dis_flag = self.components.use_user_enter_button.isChecked()
                id_flag = self.components.use_id_button.isChecked()

                for element in self.id_group:
                    element.setDisabled(not (id_flag and dis_flag))

            change_disable_status()

            self.components.use_user_enter_button.clicked.connect(
                change_disable_status)
            self.components.use_id_button.clicked.connect(change_id_status)

            # TODO if user use self defined data, give a warninig

            def start_helper():
                file_path = self.components.path_input.text()
class MyUi(QMainWindow):
    def __init__(self):
        super(MyUi, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        cwd = os.getcwd()
        cwd = str(cwd)
        if os.path.isfile(cwd + "/time"):
            with open("time", "r") as outfile:  #reads current time
                history = cPickle.load(outfile)
            if (datetime.now() - history
                ).total_seconds() < 43200:  #measures if time elapse>12 hours
                print("Less than 12 hours. Loading previously saved Pickle...")
                #with open("time","w") as infile: #update time
                #cPickle.dump(datetime.now(),infile)
                #            else:
                print("More than 12 hours. Updating Pickle...")
                data = ts.get_industry_classified()
                with open("class", "w+") as outfile:
                    cPickle.dump(data, outfile)
                now = datetime.now()
                with open("time", "w+") as outfile:  #update time
                    cPickle.dump(now, outfile)

        else:
            print("No Pickle found!"
                  )  #If this is first time using tuchart in this directory
            data = df()
            data = ts.get_industry_classified()
            with open('class', 'w+') as outfile:  #records pickle
                cPickle.dump(data, outfile)
            now = datetime.now()
            with open("time", "w+") as outfile:
                cPickle.dump(now, outfile)

        with open("class", "r") as infile:  # reads current time
            series = cPickle.load(infile)
        #series = pd.read_json(cwd + "\\class.json")
        #series = ts.get_industry_classified()
        series = pd.DataFrame(series)

        curdate = time.strftime(
            "%Y/%m/%d")  # gets current time to put into dateedit
        curdateQ = QDate.fromString(curdate, "yyyy/MM/dd")

        dateobj = datetime.strptime(curdate,
                                    "%Y/%m/%d")  #converts to datetime object

        past = dateobj - timedelta(days=7)  #minus a week to start date
        pasttime = datetime.strftime(past, "%Y/%m/%d")
        pastQ = QDate.fromString(
            pasttime,
            "yyyy/MM/dd")  #convert to qtime so that widget accepts the values

        pastL = dateobj - timedelta(days=30)  # minus a month to start date
        pasttimeL = datetime.strftime(pastL, "%Y/%m/%d")
        pastQL = QDate.fromString(pasttimeL, "yyyy/MM/dd")

        np_indexes = np.array([['sh', '上证指数', '大盘指数'], ['sz', '深证成指', '大盘指数'],
                               ['hs300', '沪深300指数', '大盘指数'],
                               ['sz50', '上证50', '大盘指数'],
                               ['zxb', '中小板', '大盘指数'], ['cyb', '创业板', '大盘指数']])
        indexes = df(data=np_indexes,
                     index=range(5000, 5006),
                     columns=["code", "name", "c_name"])
        series = indexes.append(series)
        list1_bfr = series["c_name"].tolist(
        )  #Get industry categories. Filters out redundant ones
        list1 = list(set(list1_bfr))
        list1.sort(key=list1_bfr.index)
        #w = database()
        #zsparent = QTreeWidgetItem(self.ui.treeWidget)
        #zsparent.setText(0,"股票指数")
        #zsnames =["上证指数-sh","深圳成指-sz","沪深300指数-hs300","上证50-"]

        self.init_treeWidget(list1, series)

        self.ui.treeWidget.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui.treeWidget.customContextMenuRequested.connect(self.openMenu)

        #self.ui.webView.setGeometry(QtCore.QRect(0, 30,1550, 861))
        file_path = os.path.abspath(
            os.path.join(os.path.dirname(__file__),
                         "render.html"))  #path to read html file
        local_url = QUrl.fromLocalFile(file_path)
        self.ui.webView.load(local_url)
        #self.ui.commandLinkButton.setFixedSize(50, 50)
        self.ui.search_btn.clicked.connect(lambda: self.search_comp(series))
        self.ui.log_btn.clicked.connect(lambda: self.log())
        self.ui.init_code_btn.clicked.connect(
            lambda: self.code_sort_tree(series))
        self.ui.init_category_btn.clicked.connect(
            lambda: self.init_treeWidget(list1, series))

        self.ui.commandLinkButton.clicked.connect(
            self.classify)  #when the arrow button is clicked, trigger events

        #self.ui.commandLinkButton.clicked.connect(lambda action: self.classify(action, self.ui.treewidget))
        #  QSizePolicy
        try:
            retain_size = self.ui.dateEdit_2.sizePolicy()
            retain_size.setRetainSizeWhenHidden(True)
            self.ui.dateEdit_2.setSizePolicy(retain_size)
            retain_size = self.ui.comboBox.sizePolicy()
            retain_size.setRetainSizeWhenHidden(True)
            #            self.ui.comboBox.setSizePolicy(retain_size)
            retain_size = self.ui.label_2.sizePolicy()
            retain_size.setRetainSizeWhenHidden(True)
            self.ui.label_2.setSizePolicy(retain_size)
        except AttributeError:
            print("No PYQT5 Binding! Widgets might be deformed")
        self.ui.dateEdit.setDate(pastQL)
        self.ui.dateEdit_2.setDate(curdateQ)  #populate widgets
        self.ui.dateEdit.setCalendarPopup(True)
        self.ui.dateEdit_2.setCalendarPopup(True)
        self.ui.comboBox.addItems(["D"])
        self.ui.treeWidget_2.setDragDropMode(self.ui.treeWidget_2.InternalMove)
        self.ui.treeWidget_2.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui.treeWidget_2.customContextMenuRequested.connect(
            self.openWidgetMenu)
        #self.ui.toolbutton.clicked.connect(lambda action: self.graphmerge(action, CombineKeyword))
        self.ui.combobox.currentIndexChanged.connect(
            lambda: self.modifycombo(pastQL, pastQ))

    def log(self):
        widget = QWidget(None)
        self.w1 = Ui_Form().setupUi(widget)
        # self.w1.pushButton.clicked.connect(self.w1.login)
        # self.w1.goregister.clicked.connect(self.w1.login)
        self.w1.show()

    def init_treeWidget(self, list1, series):
        self.ui.treeWidget.clear()
        for j in list1:
            parent = QTreeWidgetItem(
                self.ui.treeWidget)  #populate treewidget with names
            parent.setText(0, j)
            var = series.loc[series["c_name"] == j]
            list2 = var["code"].tolist()
            name = var["name"].tolist()
            #var = showcollection(i) #Display database items
            for idx, val in enumerate(list2):
                child = QTreeWidgetItem(parent)
                child.setText(0, name[idx] + "-" + str(val))
                #for i in Drag:
                #grandson = QTreeWidgetItem(child)     #Commented out because increases program response time
                #grandson.setText(0, i)
        #self.ui.treeWidget.itemDoubleClicked.connect(self.onClickItem) #Display Collection items

    def code_sort_tree(self, companies):
        self.ui.treeWidget.clear()
        sorted_comps = companies.sort_values(["code"])
        code_list = sorted_comps["code"].tolist()
        name_list = sorted_comps["name"].tolist()
        shares_parent = QTreeWidgetItem(self.ui.treeWidget)
        shares_parent.setText(0, "个股行情")
        for idx, val in enumerate(code_list):
            child = QTreeWidgetItem(shares_parent)
            child.setText(0, name_list[idx] + "-" + str(val))
        self.ui.treeWidget.expandToDepth(0)

    def search_comp(self, companies):
        self.ui.treeWidget.clear()
        text = self.ui.search_lineEdit.text()
        print(text)
        filtered_codes = companies[companies['code'].str.contains(text)]
        filtered_names = companies[companies['name'].str.contains(text)]
        filtered_comps = filtered_codes.append(filtered_names)
        code_list = filtered_comps["code"].tolist()
        name_list = filtered_comps["name"].tolist()
        parent = QTreeWidgetItem(self.ui.treeWidget)
        parent.setText(0, "搜索结果")
        for idx, val in enumerate(code_list):
            child = QTreeWidgetItem(parent)
            child.setText(0, name_list[idx] + "-" + str(val))
        self.ui.treeWidget.expandToDepth(0)

    def modifycombo(self, pastQL, pastQ):
        if self.ui.combobox.currentText() == u"回测分析系统":
            self.ui.label_2.show()
            self.ui.dateEdit_2.show()
            self.ui.dateEdit.setDate(pastQL)
            self.ui.interval_label.show()
            self.ui.comboBox.hide()
            self.ui.comboBox.clear()
            self.ui.comboBox.addItems(["D"])  #same as above
            self.ui.treeWidget_2.clear()
        if self.ui.combobox.currentText() == u"获取历史K线":
            self.ui.label_2.show()
            self.ui.dateEdit_2.show()
            self.ui.dateEdit.setDate(pastQL)
            self.ui.interval_label.show()
            self.ui.comboBox.show()
            self.ui.comboBox.clear()
            self.ui.comboBox.addItems(["D", "W", "M", "5", "15", "30",
                                       "60"])  #same as above
            self.ui.treeWidget_2.clear()
        if self.ui.combobox.currentText(
        ) == u"获取复权数据":  #if 复权 is selected, clear all existing queries to avoid value conflict
            self.ui.label_2.show()
            self.ui.dateEdit_2.show()
            self.ui.dateEdit.setDate(pastQL)
            self.ui.interval_label.show()
            self.ui.comboBox.show()
            self.ui.comboBox.clear()
            self.ui.comboBox.addItems(["hfq", "qfq"])
            self.ui.treeWidget_2.clear()

        if self.ui.combobox.currentText() == u"获取分笔数据":
            self.ui.interval_label.hide()
            self.ui.comboBox.hide()
            self.ui.label_2.hide()
            self.ui.dateEdit_2.hide()
            self.ui.dateEdit.setDate(pastQ)
            self.ui.treeWidget_2.clear()
        if self.ui.combobox.currentText() == u"获取历史分钟数据":
            self.ui.interval_label.hide()
            self.ui.comboBox.show()
            self.ui.comboBox.clear()
            self.ui.comboBox.addItems(
                ["1min", "5min", "15min", "30min", "60min"])
            self.ui.label_2.hide()
            self.ui.dateEdit_2.hide()
            self.ui.dateEdit.setDate(pastQ)
            self.ui.treeWidget_2.clear()
        if self.ui.combobox.currentText() == u"分析十大股东":
            self.ui.interval_label.hide()
            self.ui.comboBox.hide()
            self.ui.label_2.hide()
            self.ui.dateEdit_2.hide()
            self.ui.treeWidget_2.clear()

    def openMenu(self, position):
        indexes = self.ui.treeWidget.selectedIndexes()
        item = self.ui.treeWidget.itemAt(position)
        db_origin = ""
        #if item.parent():
        #   db_origin = item.parent().text(0)
        collec = str(item.text(0).encode("utf-8"))
        if len(indexes) > 0:
            level = 0
            index = indexes[0]
            while index.parent().isValid():
                index = index.parent()
                level = level + 1
            menu = QMenu()
            #print((collec, db_origin))
            if level == 0:
                pass
            else:
                #keyarray = GetKeys(collec, db_origin)
                #if "Open" in keyarray:
                if self.ui.combobox.currentText() == u"回测分析系统":
                    menu.addAction(QAction("ATP model", menu, checkable=True))
                if self.ui.combobox.currentText() == u"获取历史K线":
                    menu.addAction(QAction("Kline", menu, checkable=True))
                    menu.addAction(QAction("Open", menu, checkable=True))
                    menu.addAction(
                        QAction("Close", menu, checkable=True)
                    )  #open up different menu with different kind of graphs
                    menu.addAction(QAction("High", menu, checkable=True))
                    menu.addAction(QAction("Low", menu, checkable=True))
                    menu.addAction(QAction("Volume", menu, checkable=True))
                    #menu.addAction(QAction("P_change", menu, checkable=True))
                    #menu.addAction(QAction("Turnover",menu,checkable=True))
                if self.ui.combobox.currentText() == u"获取复权数据":
                    menu.addAction(QAction("Kline", menu, checkable=True))
                    menu.addAction(QAction("Open", menu, checkable=True))
                    menu.addAction(QAction("Close", menu, checkable=True))
                    menu.addAction(QAction("High", menu, checkable=True))
                    menu.addAction(QAction("Low", menu, checkable=True))
                    menu.addAction(QAction("Volume", menu, checkable=True))
                    menu.addAction(QAction("Amount", menu, checkable=True))
                if self.ui.combobox.currentText() == u"获取分笔数据":
                    menu.addAction(QAction("分笔", menu, checkable=True))
                if self.ui.combobox.currentText() == u"获取历史分钟数据":
                    menu.addAction(QAction("Kline", menu, checkable=True))
                    menu.addAction(QAction("Open", menu, checkable=True))
                    menu.addAction(QAction("Close", menu, checkable=True))
                    menu.addAction(QAction("High", menu, checkable=True))
                    menu.addAction(QAction("Low", menu, checkable=True))
                    menu.addAction(QAction("Volume", menu, checkable=True))
                    menu.addAction(QAction("Amount", menu, checkable=True))
                if self.ui.combobox.currentText() == u"分析十大股东":
                    menu.addAction(QAction("季度饼图", menu, checkable=True))
                    #menu.addAction(QAction("持股比例", menu, checkable=True))
                #for g in keyarray:
                #menu.addAction(QAction(g, menu, checkable=True))
        menu.triggered.connect(
            lambda action: self.methodSelected(action, collec))
        menu.exec_(self.ui.treeWidget.viewport().mapToGlobal(position))

    def methodSelected(self, action, collec):
        # print(action.text()) #Choice
        # if (self.ui.treewidget.count() == 5):
        #   self.ui.label.setText("Maximum number of queries")
        #   return
        # self.ui.label.setText("")
        Choice = action.text()
        Stock = collec
        # print(collec)  #Stock Name
        # print(db_origin)  #DataBase name
        # list1 = [self.tr(Stock+"-"+Choice+"-"+db_origin)]
        # self.ui.treewidget.addItems(list1)
        parent = QTreeWidgetItem(self.ui.treeWidget_2)
        parent.setText(0, Stock.decode("utf-8") + "-" + Choice)

    def openWidgetMenu(self, position):
        indexes = self.ui.treeWidget_2.selectedIndexes()
        item = self.ui.treeWidget_2.itemAt(position)
        if item == None:
            return
        #item = self.ui.listWidget.itemAt(position)
        if len(indexes) > 0:
            menu = QMenu()
            menu.addAction(
                QAction("Delete", menu,
                        checkable=True))  #This function is perhaps useless
            #menu.triggered.connect(self.eraseItem)
            item = self.ui.treeWidget_2.itemAt(position)
            #collec = str(item.text())
            menu.triggered.connect(
                lambda action: self.ListMethodSelected(action, item))
        menu.exec_(self.ui.treeWidget_2.viewport().mapToGlobal(position))

    def ListMethodSelected(self, action, item):
        if action.text() == "Delete":
            self.eraseItem()
        if action.text() == "Combine":
            global CombineKeyword
            collec = str(item.text())
            CombineKeyword.append(collec)  #Useless function(maybe?)
            list1 = [self.tr(collec)]
            self.ui.listwidget.addItems(list1)
            self.eraseItem()

    def eraseItem(self):
        for x in self.ui.treeWidget_2.selectedItems(
        ):  #delete with write click menu
            #item = self.ui.treewidget.takeItem(self.ui.treewidget.currentRow())
            sip.delete(x)
            #item.delete

    def classify(self, folder):

        startdate = self.ui.dateEdit.date()
        startdate = startdate.toPyDate()
        startdate = startdate.strftime(
            "%Y/%m/%d")  #converts date from dateedit to tushare readable date
        enddate = self.ui.dateEdit_2.date()
        enddate = enddate.toPyDate()
        enddate = enddate.strftime("%Y/%m/%d")
        option = self.ui.comboBox.currentText()
        option = str(option)
        #if (self.ui.treewidget) == 0:
        #self.ui.label.setText("Need to select at least one query")
        #return
        root = self.ui.treeWidget_2.invisibleRootItem(
        )  # This is for iterating child items
        child_count = root.childCount()
        texts = []
        if child_count == 0:
            return
        for i in range(child_count):
            item = root.child(i)
            text = item.text(0)  #with 3 part'stock_name'+'-'+'code'+'-'+action
            texts.append(text)
        labels = [k for k in texts]
        #items = ([x.encode("utf-8") for x in labels])
        width = self.ui.webView.width(
        )  #give width and height of user's screen so that graphs can be generated with dynamic size
        height = self.ui.webView.height()
        display(labels, startdate, enddate, option, width,
                height)  #labels:复权ork线or分笔 option:hfq, qfq or 15, 30, D, etc
        self.ui.webView.reload()  #refreshes webengine
        self.ui.webView.repaint()
        self.ui.webView.update()

    def graphmerge(self, combineKeyword):
        sth = ""
        for i in combineKeyword:
            if sth == "":
                sth = sth + i
            else:
                sth = sth + "\n" + "&" + "-" + i
        list1 = sth
        return sth
        global CombineKeyword
        CombineKeyword = []
        self.ui.listwidget.clear(
        )  #combine stuff so that different graphs can be drawn together
Exemplo n.º 36
0
class MyWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        self.position = 38
        self.gen = Generator()
        QtWidgets.QMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.initUI()
        self.setFixedSize(self.size())

    def initUI(self):
        self.ui.browse.triggered.connect(lambda: fa.get_files(self))
        self.bind_fields()
        self.bind_last_change()
        self.ui.help.clicked.connect(self.display_help)
        self.ui.calculate.clicked.connect(lambda: self.gen.calculate(self))
        self.ui.save.clicked.connect(lambda: fa.save_file(self))
        self.ui.plot.clicked.connect(self.plot_diagram)

    def plot_diagram(self):
        self.window = QtWidgets.QMainWindow()
        self.ui2 = Ui_Dialog()
        self.ui2.setupUi(self.window, self.gen)
        self.window.show()
        self.window.setFixedSize(self.window.size())

    def closeEvent(self, event):
        self.close()
        try:
            self.window.close()
            self.ui2.window.close()
        except Exception:
            pass

    def bind_fields(self):
        self.ui.Sn.textChanged.connect(self.gen.set_Sn)
        self.ui.Sb.textChanged.connect(self.gen.set_Sb)
        self.ui.Ub.textChanged.connect(self.gen.set_Ub)
        self.ui.Xd.textChanged.connect(self.gen.set_Xd)
        self.ui.Xq.textChanged.connect(self.gen.set_Xq)
        self.ui.Xd1.textChanged.connect(self.gen.set_Xd1)
        self.ui.Xq1.textChanged.connect(self.gen.set_Xq1)
        self.ui.Xd2.textChanged.connect(self.gen.set_Xd2)
        self.ui.Xq2.textChanged.connect(self.gen.set_Xq2)
        self.ui.S2.textChanged.connect(self.gen.set_S2)
        self.ui.Ug.textChanged.connect(self.gen.set_Ug)
        self.ui.Zb.textChanged.connect(self.gen.set_Zb)
        self.ui.Ib.textChanged.connect(self.gen.set_Ib)
        self.ui.S2pu.textChanged.connect(self.gen.set_S2pu)
        self.ui.Ugpu.textChanged.connect(self.gen.set_Ugpu)
        self.ui.Igpu.textChanged.connect(self.gen.set_Igpu)
        self.ui.deltaIgpu.textChanged.connect(self.gen.setdelta_Igpu)
        self.ui.EQ.textChanged.connect(self.gen.set_EQ)
        self.ui.phi.textChanged.connect(self.gen.set_phi)
        self.ui.BC.textChanged.connect(self.gen.set_BC)
        self.ui.OA.textChanged.connect(self.gen.set_OA)
        self.ui.AB.textChanged.connect(self.gen.set_AB)
        self.ui.alfa.textChanged.connect(self.gen.set_alfa)
        self.ui.gamma.textChanged.connect(self.gen.set_gamma)
        self.ui.Iqpu.textChanged.connect(self.gen.set_Iqpu)
        self.ui.Idpu.textChanged.connect(self.gen.set_Idpu)
        self.ui.Uqpu.textChanged.connect(self.gen.set_Uqpu)
        self.ui.Udpu.textChanged.connect(self.gen.set_Udpu)
        self.ui.Edpu2.textChanged.connect(self.gen.set_Edpu2)
        self.ui.Eqpu2.textChanged.connect(self.gen.set_Eqpu2)
        self.ui.Edpu1.textChanged.connect(self.gen.set_Edpu1)
        self.ui.Eqpu1.textChanged.connect(self.gen.set_Eqpu1)
        self.ui.Edpu.textChanged.connect(self.gen.set_Edpu)
        self.ui.Eqpu.textChanged.connect(self.gen.set_Eqpu)
        self.ui.Epu.textChanged.connect(self.gen.set_Epu)
        self.ui.Epu1.textChanged.connect(self.gen.set_Epu1)
        self.ui.Epu2.textChanged.connect(self.gen.set_Epu2)
        self.ui.delta.textChanged.connect(self.gen.set_delta)

    def bind_last_change(self):
        self.ui.Sn.textChanged.connect(lambda: self.set_position(38))
        self.ui.comboSn.currentTextChanged.connect(
            lambda: self.set_position(38))
        self.ui.Sb.textChanged.connect(lambda: self.set_position(37))
        self.ui.comboSb.currentTextChanged.connect(
            lambda: self.set_position(37))
        self.ui.Ub.textChanged.connect(lambda: self.set_position(36))
        self.ui.comboUb.currentTextChanged.connect(
            lambda: self.set_position(36))
        self.ui.Xd.textChanged.connect(lambda: self.set_position(35))
        self.ui.Xq.textChanged.connect(lambda: self.set_position(34))
        self.ui.Xd1.textChanged.connect(lambda: self.set_position(33))
        self.ui.Xq1.textChanged.connect(lambda: self.set_position(32))
        self.ui.Xd2.textChanged.connect(lambda: self.set_position(31))
        self.ui.Xq2.textChanged.connect(lambda: self.set_position(30))
        self.ui.S2.textChanged.connect(lambda: self.set_position(29))
        self.ui.comboS2.currentTextChanged.connect(
            lambda: self.set_position(29))
        self.ui.Ug.textChanged.connect(lambda: self.set_position(28))
        self.ui.Zb.textChanged.connect(lambda: self.set_position(27))
        self.ui.Ib.textChanged.connect(lambda: self.set_position(26))
        self.ui.S2pu.textChanged.connect(lambda: self.set_position(25))
        self.ui.Ugpu.textChanged.connect(lambda: self.set_position(24))
        self.ui.Igpu.textChanged.connect(lambda: self.set_position(23))
        self.ui.deltaIgpu.textChanged.connect(lambda: self.set_position(22))
        self.ui.EQ.textChanged.connect(lambda: self.set_position(21))
        self.ui.phi.textChanged.connect(lambda: self.set_position(20))
        self.ui.BC.textChanged.connect(lambda: self.set_position(19))
        self.ui.OA.textChanged.connect(lambda: self.set_position(18))
        self.ui.AB.textChanged.connect(lambda: self.set_position(17))
        self.ui.alfa.textChanged.connect(lambda: self.set_position(16))
        self.ui.gamma.textChanged.connect(lambda: self.set_position(15))
        self.ui.Iqpu.textChanged.connect(lambda: self.set_position(14))
        self.ui.Idpu.textChanged.connect(lambda: self.set_position(13))
        self.ui.Uqpu.textChanged.connect(lambda: self.set_position(12))
        self.ui.Udpu.textChanged.connect(lambda: self.set_position(11))
        self.ui.Edpu2.textChanged.connect(lambda: self.set_position(10))
        self.ui.Eqpu2.textChanged.connect(lambda: self.set_position(9))
        self.ui.Edpu1.textChanged.connect(lambda: self.set_position(8))
        self.ui.Eqpu1.textChanged.connect(lambda: self.set_position(7))
        self.ui.Edpu.textChanged.connect(lambda: self.set_position(6))
        self.ui.Eqpu.textChanged.connect(lambda: self.set_position(5))
        self.ui.Epu.textChanged.connect(lambda: self.set_position(4))
        self.ui.Epu1.textChanged.connect(lambda: self.set_position(3))
        self.ui.Epu2.textChanged.connect(lambda: self.set_position(2))
        self.ui.delta.textChanged.connect(lambda: self.set_position(1))

    def display_help(self):
        m_box = QMessageBox()
        m_box.setIcon(QMessageBox.Information)
        m_box.setWindowTitle("Help")
        m_box.setText(
            "You can specify all the data int the file.\n"
            "The values of the parameters have to be numeric.\n"
            "For example you can't write:\n"
            "Sn = 250 MVA\n"
            "You have to write:\n"
            "Sn = 250000000\n"
            "If you want to specify parameters such as Xd', Xd'', Xq' and so on, "
            "you need to write Xd1, Xd2, Xq1 respectively. "
            "To refer to greek letters you need to give their name and subscript.\n"
            "If you are not sure what are the names of parameters, click the button "
            "\"Save to a File\" to generate a template.\n"
            "Make sure to delete the values, you don't want to specify.\n"
            "The calculations start from the last specified parameter. Previous values won't be"
            "calculated or overwritten")
        m_box.exec_()

    def set_position(self, n):
        self.position = n
Exemplo n.º 37
0
    def __init__(self):
        super(MyUi, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        #cwd = os.getcwd()
        #cwd = str(cwd)
        #if os.path.isfile(cwd+"/time"):
        #   with open("time","r") as outfile:#reads current time
        #      history = cPickle.load(outfile)
        # if (datetime.now()-history).total_seconds()<43200: #measures if time elapse>12 hours
        #    print "Less than 12 hours. Loading previously saved Json..."
        #   with open("time","w") as infile: #update time
        #      cPickle.dump(datetime.now(),infile)

        #else:
        #   print "More than 12 hours. Updating Json..."
        #  data = ts.get_industry_classified()
        # data.to_json(cwd + "/class.json", orient="columns")#writes class data so no need to call Tushare agian
        #now = datetime.now()
        #with open("time", "w+") as outfile: #update time
        #   cPickle.dump(now, outfile)

        # else:
        #    print "No json found!"#If this is first time using tuchart in this directory
        #   data = df()
        #  data = ts.get_industry_classified()
        # print data
        # var = data.to_json(cwd+"/class.json",orient="columns")
        # with open('class.json', 'w+') as outfile: #records json
        #      json.dump(var, outfile)
        #  now = datetime.now()
        # with open("time", "w+") as outfile:
        #     cPickle.dump(now,outfile)

        #   series = pd.read_json(cwd + "\\class.json")
        series = ts.get_industry_classified()
        series = pd.DataFrame(series)
        curdate = time.strftime(
            "%Y/%m/%d")  #gets current time to put into dateedit
        dateobj = datetime.strptime(curdate,
                                    "%Y/%m/%d")  #converts to datetime object
        past = dateobj - timedelta(days=7)  #minus a week to start date
        pasttime = datetime.strftime(past, "%Y/%m/%d")
        QPast = QDate.fromString(
            pasttime,
            "yyyy/MM/dd")  #convert to qtime so that widget accepts the values
        Qcurdate = QDate.fromString(curdate, "yyyy/MM/dd")
        #print series
        list1 = series["c_name"].tolist(
        )  #Get industry categories. Filters out redundant ones
        list1 = list(set(list1))
        #w = database()
        #zsparent = QTreeWidgetItem(self.ui.treeWidget)
        #zsparent.setText(0,"股票指数")
        #zsnames =["上证指数-sh","深圳成指-sz","沪深300指数-hs300","上证50-"]

        for j in list1:
            parent = QTreeWidgetItem(
                self.ui.treeWidget)  #populate treewidget with names
            parent.setText(0, j)
            var = series.loc[series["c_name"] == j]
            list2 = var["code"].tolist()
            name = var["name"].tolist()

            #var = showcollection(i) #Display database items
            for idx, val in enumerate(list2):
                child = QTreeWidgetItem(parent)
                child.setText(0, name[idx] + "-" + str(val))
                #for i in Drag:
                #grandson = QTreeWidgetItem(child)     #Commented out because increases program response time
                #grandson.setText(0, i)
        #self.ui.treeWidget.itemDoubleClicked.connect(self.onClickItem) #Display Collection items
        self.ui.treeWidget.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui.treeWidget.customContextMenuRequested.connect(self.openMenu)

        #self.ui.widget.setGeometry(QtCore.QRect(0, 30,1550, 861))
        file_path = os.path.abspath(
            os.path.join(os.path.dirname(__file__),
                         "render.html"))  #path to read html file
        local_url = QUrl.fromLocalFile(file_path)
        self.ui.widget.load(local_url)
        self.ui.commandLinkButton.setFixedSize(50, 50)
        self.ui.commandLinkButton.clicked.connect(
            self.classify)  #when the arrow button is clicked, trigger events

        #self.ui.commandLinkButton.clicked.connect(lambda action: self.classify(action, self.ui.treewidget))
        #  QSizePolicy
        retain_size = self.ui.dateEdit_2.sizePolicy()
        retain_size.setRetainSizeWhenHidden(True)
        self.ui.dateEdit_2.setSizePolicy(retain_size)
        retain_size = self.ui.comboBox.sizePolicy()
        retain_size.setRetainSizeWhenHidden(True)
        self.ui.comboBox.setSizePolicy(retain_size)
        retain_size = self.ui.label_2.sizePolicy()
        retain_size.setRetainSizeWhenHidden(True)
        self.ui.label_2.setSizePolicy(retain_size)

        self.ui.dateEdit.setDate(QPast)
        self.ui.dateEdit_2.setDate(Qcurdate)  #populate widgets
        self.ui.dateEdit.setCalendarPopup(True)
        self.ui.dateEdit_2.setCalendarPopup(True)
        self.ui.comboBox.addItems(["D", "W", "M", "5", "15", "30", "60"])
        self.ui.treeWidget_2.setDragDropMode(self.ui.treeWidget_2.InternalMove)
        self.ui.treeWidget_2.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui.treeWidget_2.customContextMenuRequested.connect(
            self.openWidgetMenu)
        #self.ui.toolbutton.clicked.connect(lambda action: self.graphmerge(action, CombineKeyword))
        self.ui.combobox.currentIndexChanged.connect(self.modifycombo)
Exemplo n.º 38
0
class MyUi(QMainWindow):
    def __init__(self):
        super(MyUi, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        cwd = os.getcwd()
        cwd = str(cwd)
        if os.path.isfile(cwd+"/time"):
            with open("time","r") as outfile:#reads current time
                history = cPickle.load(outfile)
            if (datetime.now()-history).total_seconds()<43200: #measures if time elapse>12 hours
                print("Less than 12 hours. Loading previously saved Pickle...")
                #with open("time","w") as infile: #update time
                    #cPickle.dump(datetime.now(),infile)

            else:
                print("More than 12 hours. Updating Pickle...")
                data = ts.get_industry_classified()
                with open("class","w+") as outfile:
                    cPickle.dump(data,outfile)
                now = datetime.now()
                with open("time", "w+") as outfile: #update time
                    cPickle.dump(now, outfile)

        else:
            print("No Pickle found!") #If this is first time using tuchart in this directory
            data = df()
            data = ts.get_industry_classified()
            with open('class', 'w+') as outfile: #records pickle
                cPickle.dump(data, outfile)
            now = datetime.now()
            with open("time", "w+") as outfile:
                cPickle.dump(now,outfile)

        with open("class", "r") as infile:  # reads current time
            series = cPickle.load(infile)
        #series = pd.read_json(cwd + "\\class.json")
        #series = ts.get_industry_classified()
        series = pd.DataFrame(series)

        curdate = time.strftime("%Y/%m/%d")  # gets current time to put into dateedit
        curdateQ = QDate.fromString(curdate,"yyyy/MM/dd")

        dateobj = datetime.strptime(curdate, "%Y/%m/%d")#converts to datetime object

        past = dateobj - timedelta(days = 7)  #minus a week to start date
        pasttime = datetime.strftime(past, "%Y/%m/%d")
        pastQ = QDate.fromString(pasttime,"yyyy/MM/dd") #convert to qtime so that widget accepts the values



        pastL = dateobj - timedelta(days=30)  # minus a month to start date
        pasttimeL = datetime.strftime(pastL, "%Y/%m/%d")
        pastQL = QDate.fromString(pasttimeL, "yyyy/MM/dd")


        np_indexes = np.array([['sh', '上证指数', '大盘指数'],
                               ['sz', '深证成指', '大盘指数'],
                               ['hs300', '沪深300指数', '大盘指数'],
                               ['sz50', '上证50', '大盘指数'],
                               ['zxb', '中小板', '大盘指数'],
                               ['cyb', '创业板', '大盘指数']])
        indexes = df(data=np_indexes,
                     index=range(5000, 5006),
                     columns=["code", "name", "c_name"])
        series = indexes.append(series)
        list1_bfr = series["c_name"].tolist()  #Get industry categories. Filters out redundant ones
        list1 = list(set(list1_bfr))
        list1.sort(key=list1_bfr.index)
        #w = database()
        #zsparent = QTreeWidgetItem(self.ui.treeWidget)
        #zsparent.setText(0,"股票指数")
        #zsnames =["上证指数-sh","深圳成指-sz","沪深300指数-hs300","上证50-"]

        self.init_treeWidget(list1,series)

        self.ui.treeWidget.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui.treeWidget.customContextMenuRequested.connect(self.openMenu)

        #self.ui.webView.setGeometry(QtCore.QRect(0, 30,1550, 861))
        file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "render.html")) #path to read html file
        local_url = QUrl.fromLocalFile(file_path)
        self.ui.webView.load(local_url)
        #self.ui.commandLinkButton.setFixedSize(50, 50)
        self.ui.search_btn.clicked.connect(lambda: self.search_comp(series))
        self.ui.init_code_btn.clicked.connect(lambda: self.code_sort_tree(series))
        self.ui.init_category_btn.clicked.connect(lambda: self.init_treeWidget(list1, series))

        self.ui.commandLinkButton.clicked.connect(self.classify)  #when the arrow button is clicked, trigger events


        #self.ui.commandLinkButton.clicked.connect(lambda action: self.classify(action, self.ui.treewidget))
        #  QSizePolicy
        try:
            retain_size = self.ui.dateEdit_2.sizePolicy()
            retain_size.setRetainSizeWhenHidden(True)
            self.ui.dateEdit_2.setSizePolicy(retain_size)
            retain_size = self.ui.comboBox.sizePolicy()
            retain_size.setRetainSizeWhenHidden(True)
            self.ui.comboBox.setSizePolicy(retain_size)
            retain_size = self.ui.label_2.sizePolicy()
            retain_size.setRetainSizeWhenHidden(True)
            self.ui.label_2.setSizePolicy(retain_size)
        except AttributeError:
            print("No PYQT5 Binding! Widgets might be deformed")
        self.ui.dateEdit.setDate(pastQL)
        self.ui.dateEdit_2.setDate(curdateQ)#populate widgets
        self.ui.dateEdit.setCalendarPopup(True)
        self.ui.dateEdit_2.setCalendarPopup(True)
        self.ui.comboBox.addItems(["D", "W", "M", "5", "15", "30", "60"])
        self.ui.treeWidget_2.setDragDropMode(self.ui.treeWidget_2.InternalMove)
        self.ui.treeWidget_2.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui.treeWidget_2.customContextMenuRequested.connect(self.openWidgetMenu)
        #self.ui.toolbutton.clicked.connect(lambda action: self.graphmerge(action, CombineKeyword))
        self.ui.combobox.currentIndexChanged.connect(lambda: self.modifycombo(pastQL,pastQ))

    def init_treeWidget(self, list1, series):
        self.ui.treeWidget.clear()
        for j in list1:
            parent = QTreeWidgetItem(self.ui.treeWidget)  #populate treewidget with names
            parent.setText(0,j)
            var = series.loc[series["c_name"] == j]
            list2 = var["code"].tolist()
            name = var["name"].tolist()
            #var = showcollection(i) #Display database items
            for idx,val in enumerate(list2):
                child = QTreeWidgetItem(parent)
                child.setText(0, name[idx]+"-"+str(val))
                #for i in Drag:
                    #grandson = QTreeWidgetItem(child)     #Commented out because increases program response time
                    #grandson.setText(0, i)
        #self.ui.treeWidget.itemDoubleClicked.connect(self.onClickItem) #Display Collection items

    def code_sort_tree(self, companies):
        self.ui.treeWidget.clear()
        sorted_comps = companies.sort_values(["code"])
        code_list = sorted_comps["code"].tolist()
        name_list = sorted_comps["name"].tolist()
        shares_parent = QTreeWidgetItem(self.ui.treeWidget)
        shares_parent.setText(0, "个股行情")
        for idx, val in enumerate(code_list):
            child = QTreeWidgetItem(shares_parent)
            child.setText(0, name_list[idx] + "-" + str(val))
        self.ui.treeWidget.expandToDepth(0)

    def search_comp(self, companies):
        self.ui.treeWidget.clear()
        text = self.ui.search_lineEdit.text()
        filtered_codes = companies[companies['code'].str.contains(text)]
        filtered_names = companies[companies['name'].str.contains(text)]
        filtered_comps = filtered_codes.append(filtered_names)
        code_list = filtered_comps["code"].tolist()
        name_list = filtered_comps["name"].tolist()
        parent = QTreeWidgetItem(self.ui.treeWidget)
        parent.setText(0, "搜索结果")
        for idx, val in enumerate(code_list):
            child = QTreeWidgetItem(parent)
            child.setText(0, name_list[idx] + "-" + str(val))
        self.ui.treeWidget.expandToDepth(0)


    def modifycombo(self,pastQL,pastQ):
        if self.ui.combobox.currentText()==u"复权": #if 复权 is selected, clear all existing queries to avoid value conflict
            self.ui.label_2.show()
            self.ui.dateEdit_2.show()
            self.ui.dateEdit.setDate(pastQL)
            self.ui.interval_label.show()
            self.ui.comboBox.show()
            self.ui.comboBox.clear()
            self.ui.comboBox.addItems(["hfq", "qfq"])
            self.ui.treeWidget_2.clear()
        if self.ui.combobox.currentText()==u"K线":
            self.ui.label_2.show()
            self.ui.dateEdit_2.show()
            self.ui.dateEdit.setDate(pastQL)
            self.ui.interval_label.show()
            self.ui.comboBox.show()
            self.ui.comboBox.clear()
            self.ui.comboBox.addItems(["D", "W", "M", "5", "15", "30", "60"])#same as above
            self.ui.treeWidget_2.clear()
        if self.ui.combobox.currentText()==u"分笔数据":
            self.ui.interval_label.hide()
            self.ui.comboBox.hide()
            self.ui.label_2.hide()
            self.ui.dateEdit_2.hide()
            self.ui.dateEdit.setDate(pastQ)
            self.ui.treeWidget_2.clear()
        if self.ui.combobox.currentText()==u"历史分钟":
            self.ui.interval_label.hide()
            self.ui.comboBox.show()
            self.ui.comboBox.clear()
            self.ui.comboBox.addItems(["1min","5min","15min","30min","60min"])
            self.ui.label_2.hide()
            self.ui.dateEdit_2.hide()
            self.ui.dateEdit.setDate(pastQ)
            self.ui.treeWidget_2.clear()
        if self.ui.combobox.currentText()==u"十大股东":
            self.ui.interval_label.hide()
            self.ui.comboBox.hide()
            self.ui.label_2.hide()
            self.ui.dateEdit_2.hide()
            self.ui.treeWidget_2.clear()

    def openMenu(self,position):
        indexes = self.ui.treeWidget.selectedIndexes()
        item = self.ui.treeWidget.itemAt(position)
        db_origin = ""
        #if item.parent():
         #   db_origin = item.parent().text(0)
        collec = str(item.text(0).encode("utf-8"))
        if len(indexes) > 0:
            level = 0
            index = indexes[0]
            while index.parent().isValid():
                index = index.parent()
                level = level + 1
            menu = QMenu()
            #print((collec, db_origin))
            if level ==0:
                pass
            else:
                #keyarray = GetKeys(collec, db_origin)
                #if "Open" in keyarray:
                if self.ui.combobox.currentText()==u"K线":
                    menu.addAction(QAction("Kline", menu, checkable=True))
                    menu.addAction(QAction("Open", menu, checkable=True))
                    menu.addAction(QAction("Close", menu, checkable=True))#open up different menu with different kind of graphs
                    menu.addAction(QAction("High", menu, checkable=True))
                    menu.addAction(QAction("Low", menu, checkable=True))
                    menu.addAction(QAction("Volume", menu, checkable=True))
                    #menu.addAction(QAction("P_change", menu, checkable=True))
                    #menu.addAction(QAction("Turnover",menu,checkable=True))
                if self.ui.combobox.currentText()==u"复权":
                    menu.addAction(QAction("Kline", menu, checkable=True))
                    menu.addAction(QAction("Open", menu, checkable=True))
                    menu.addAction(QAction("Close", menu, checkable=True))
                    menu.addAction(QAction("High", menu, checkable=True))
                    menu.addAction(QAction("Low", menu, checkable=True))
                    menu.addAction(QAction("Volume", menu, checkable=True))
                    menu.addAction(QAction("Amount", menu, checkable=True))
                if self.ui.combobox.currentText()==u"分笔数据":
                    menu.addAction(QAction("分笔", menu, checkable=True))
                if self.ui.combobox.currentText()==u"历史分钟":
                    menu.addAction(QAction("Kline", menu, checkable=True))
                    menu.addAction(QAction("Open", menu, checkable=True))
                    menu.addAction(QAction("Close", menu, checkable=True))
                    menu.addAction(QAction("High", menu, checkable=True))
                    menu.addAction(QAction("Low", menu, checkable=True))
                    menu.addAction(QAction("Volume", menu, checkable=True))
                    menu.addAction(QAction("Amount", menu, checkable=True))
                if self.ui.combobox.currentText()==u"十大股东":
                    menu.addAction(QAction("季度饼图", menu, checkable=True))
                    #menu.addAction(QAction("持股比例", menu, checkable=True))
                #for g in keyarray:
                #menu.addAction(QAction(g, menu, checkable=True))
        menu.triggered.connect(lambda action: self.methodSelected(action, collec))
        menu.exec_(self.ui.treeWidget.viewport().mapToGlobal(position))

    def methodSelected(self, action, collec):
        # print(action.text()) #Choice
        # if (self.ui.treewidget.count() == 5):
        #   self.ui.label.setText("Maximum number of queries")
        #   return
        # self.ui.label.setText("")
        Choice = action.text()
        Stock = collec
        # print(collec)  #Stock Name
        # print(db_origin)  #DataBase name
        # list1 = [self.tr(Stock+"-"+Choice+"-"+db_origin)]
        # self.ui.treewidget.addItems(list1)
        parent = QTreeWidgetItem(self.ui.treeWidget_2)
        parent.setText(0, Stock.decode("utf-8") + "-" + Choice)


    def openWidgetMenu(self,position):
        indexes = self.ui.treeWidget_2.selectedIndexes()
        item = self.ui.treeWidget_2.itemAt(position)
        if item == None:
            return
        #item = self.ui.listWidget.itemAt(position)
        if len(indexes) > 0:
            menu = QMenu()
            menu.addAction(QAction("Delete", menu,checkable = True))#This function is perhaps useless
            #menu.triggered.connect(self.eraseItem)
            item = self.ui.treeWidget_2.itemAt(position)
            #collec = str(item.text())
            menu.triggered.connect(lambda action: self.ListMethodSelected(action, item))
        menu.exec_(self.ui.treeWidget_2.viewport().mapToGlobal(position))

    def ListMethodSelected(self, action, item):
        if action.text() == "Delete":
            self.eraseItem()
        if action.text() == "Combine":
            global CombineKeyword
            collec = str(item.text())
            CombineKeyword.append(collec)#Useless function(maybe?)
            list1 = [self.tr(collec)]
            self.ui.listwidget.addItems(list1)
            self.eraseItem()

    def eraseItem(self):
        for x in self.ui.treeWidget_2.selectedItems():#delete with write click menu
            #item = self.ui.treewidget.takeItem(self.ui.treewidget.currentRow())
            sip.delete(x)
            #item.delete

    def classify(self, folder):

        startdate = self.ui.dateEdit.date()
        startdate = startdate.toPyDate()
        startdate = startdate.strftime("%Y/%m/%d")#converts date from dateedit to tushare readable date
        enddate = self.ui.dateEdit_2.date()
        enddate = enddate.toPyDate()
        enddate = enddate.strftime("%Y/%m/%d")
        option = self.ui.comboBox.currentText()
        option = str(option)
        #if (self.ui.treewidget) == 0:
            #self.ui.label.setText("Need to select at least one query")
            #return
        root = self.ui.treeWidget_2.invisibleRootItem()# This is for iterating child items
        child_count = root.childCount()
        texts = []
        if child_count==0:
            return
        for i in range(child_count):
            item = root.child(i)
            text = item.text(0)#with 3 part'stock_name'+'-'+'code'+'-'+action
            texts.append(text)
        labels = [k for k in texts]
        #items = ([x.encode("utf-8") for x in labels])
        width = self.ui.webView.width()#give width and height of user's screen so that graphs can be generated with dynamic size
        height = self.ui.webView.height()
        graphpage(labels, startdate,enddate,option,width, height)#labels:复权ork线or分笔 option:hfq, qfq or 15, 30, D, etc
        self.ui.webView.reload()#refreshes webengine
        self.ui.webView.repaint()
        self.ui.webView.update()

    def graphmerge(self, combineKeyword):
        sth = ""
        for i in combineKeyword:
            if sth == "":
                sth = sth + i
            else :
                sth = sth + "\n" + "&"+ "-"+i
        list1 = sth
        return sth
        global CombineKeyword
        CombineKeyword = []
        self.ui.listwidget.clear()  #combine stuff so that different graphs can be drawn together