Ejemplo n.º 1
0
    def __init__(self):
        # Create Application Instance
        app = QtWidgets.QApplication(sys.argv)

        # Create new main_window Instance
        self.main_window = QtWidgets.QMainWindow()

        # Create a ui instance to reference from the View
        # and pass in the main_window as an argument to update the
        # main window remotely
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self.main_window)

        self.date_dict = {}

        # call functions to process events
        self.trigger_date_change()
        self.trigger_search_bar_used()
        self.trigger_recent_stock_selection()
        self.trigger_search_button()
        self.trigger_import_date()
        self.trigger_click_on_cell_row()

        # Show main_window and execute application
        self.main_window.show()
        sys.exit(app.exec_())
Ejemplo n.º 2
0
    def __init__(self, inController, inModel, parent=None):
        """
        Конструктор принимает ссылки на модель и контроллер.
        """
        super(QMainWindow, self).__init__(parent)
        self.mController = inController
        self.mModel = inModel

        # подключаем визуальное представление
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # регистрируем представление в качестве наблюдателя
        self.mModel.addObserver(self)

        # устанавливаем валидаторы полей ввода данных
        self.ui.le_c.setValidator(QDoubleValidator())
        self.ui.le_d.setValidator(QDoubleValidator())

        # связываем событие завершения редактирования с методом контроллера
        '''self.connectNotify(self.ui.le_c, pyqtSignal("editingFinished()"),
                     self.mController.setC)
        self.connectNotify(self.ui.le_d, pyqtSignal("editingFinished()"),
                     self.mController.setD)'''
        self.ui.le_c.editingFinished.connect(self.mController.setC)
        self.ui.le_d.editingFinished.connect(self.mController.setD)
Ejemplo n.º 3
0
    def __init__(self, inController, parent=None):
        super(QMainWindow, self).__init__(parent)
        self.mController = inController

        #Визуальное представление
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        #Добавляем обработчики событий
        self.ui.add_class.clicked.connect(self.add_class)
        self.ui.Learn.clicked.connect(self.learn_clicked)
        self.ui.Hebb.clicked.connect(self.learn_alg)
        self.ui.LMS.clicked.connect(self.learn_alg)
        self.ui.polar.clicked.connect(self.signal_changed)
        self.ui.biPolar.clicked.connect(self.signal_changed)
        self.ui.bipolar_lbl.clicked.connect(self.lbl_type_changed)
        self.ui.binary_lbl.clicked.connect(self.lbl_type_changed)
        self.ui.tabWidget.currentChanged.connect(self.tab_changed)
        self.ui.test_btn.clicked.connect(self.test_clicked)
        self.ui.setBias.clicked.connect(self.set_bias)

        self.treeSettings()
        self.ui.img_1.setScaledContents(True)
        self.ui.img_2.setScaledContents(True)
        self.ui.img_3.setScaledContents(True)
        self.current_test_id = 0

        self.img1 = None
        self.img2 = None

        self.active_class_item = None
        self.connect(self.ui.data_tree,
                     SIGNAL("itemClicked(QTreeWidgetItem*, int)"),
                     self.onClickItem)
        self.connect(self.ui.activation, SIGNAL("activated(const QString&)"),
                     self.activation_changed)

        validator = QtGui.QDoubleValidator()
        self.ui.bias.setValidator(validator)

        self.mController.modelIsChanged(
            self.ui.tabWidget.currentWidget().objectName())
        act_functions = [
            'Бинарный порог', 'Биполярный порог', 'Радиально-симметричная'
        ]
        self.ui.activation.addItems(act_functions)
        self.params = {
            'Signal': '',
            'Learn': '',
            'Label': '',
            'Neurons': '',
            'Activation': '',
            'Bias': '',
            'Function param': '',
        }
Ejemplo n.º 4
0
    def __init__(self, inController, inModel, inModel2, parent=None):
        """
        Конструктор принимает ссылки на модель и контроллер.
        """
        # SIGNAL = pyqtSignal
        super(QMainWindow, self).__init__(parent)
        self.mController = inController
        self.mModel = inModel
        self.mModel2 = inModel2

        # подключаем визуальное представление
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.initUI()
        self.modelIsChanged()
Ejemplo n.º 5
0
class CplusDView(QMainWindow, CplusDObserver, metaclass=CplusDMeta):
    """
    Класс отвечающий за визуальное представление CplusDModel.
    """
    def __init__(self, inController, inModel, parent=None):
        """
        Конструктор принимает ссылки на модель и контроллер.
        """
        super(QMainWindow, self).__init__(parent)
        self.mController = inController
        self.mModel = inModel

        # подключаем визуальное представление
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # регистрируем представление в качестве наблюдателя
        self.mModel.addObserver(self)

        # устанавливаем валидаторы полей ввода данных
        self.ui.le_c.setValidator(QDoubleValidator())
        self.ui.le_d.setValidator(QDoubleValidator())

        # связываем событие завершения редактирования с методом контроллера
        '''self.connectNotify(self.ui.le_c, pyqtSignal("editingFinished()"),
                     self.mController.setC)
        self.connectNotify(self.ui.le_d, pyqtSignal("editingFinished()"),
                     self.mController.setD)'''
        self.ui.le_c.editingFinished.connect(self.mController.setC)
        self.ui.le_d.editingFinished.connect(self.mController.setD)

    def modelIsChanged(self):
        """
        Метод вызывается при изменении модели.
        Запрашивает и отображает значение суммы.
        """
        sum = str(self.mModel.sum)
        self.ui.le_result.setText(sum)
Ejemplo n.º 6
0
class MainWindow(QMainWindow, ABC, metaclass=Meta):
    def __init__(self, inController, inModel, inModel2, parent=None):
        """
        Конструктор принимает ссылки на модель и контроллер.
        """
        # SIGNAL = pyqtSignal
        super(QMainWindow, self).__init__(parent)
        self.mController = inController
        self.mModel = inModel
        self.mModel2 = inModel2

        # подключаем визуальное представление
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.initUI()
        self.modelIsChanged()

    def initUI(self):
        self.ui.pushButton_0.clicked.connect(self.mController.percent_many_ruble)
        self.ui.pushButton_1.clicked.connect(self.mController.odd_many_ruble)
        self.ui.pushButton_2.clicked.connect(self.mController.add_many_ruble)
        self.ui.pushButton_3.clicked.connect(self.mController.change_many_ruble)
        self.ui.pushButton_4.clicked.connect(self.mController.percent_many_dollar)
        self.ui.pushButton_5.clicked.connect(self.mController.odd_many_dollar)
        self.ui.pushButton_6.clicked.connect(self.mController.add_many_dollar)
        self.ui.pushButton_7.clicked.connect(self.mController.change_many_dollar)

    def modelIsChanged(self):
        sum1 = str(int(self.mModel.many))
        sum2 = str(int(self.mModel.few))
        sum = sum1 + "," + sum2
        sum3 = str(int(self.mModel2.many))
        sum4 = str(int(self.mModel2.few))
        sum5 = sum3 + ',' + sum4
        self.ui.rubles.setText(sum)
        self.ui.dollars.setText(sum5)
Ejemplo n.º 7
0
class NNView(QMainWindow, NNModelObserver, metaclass=NNMeta):
    def __init__(self, inController, parent=None):
        super(QMainWindow, self).__init__(parent)
        self.mController = inController

        #Визуальное представление
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        #Добавляем обработчики событий
        self.ui.add_class.clicked.connect(self.add_class)
        self.ui.Learn.clicked.connect(self.learn_clicked)
        self.ui.Hebb.clicked.connect(self.learn_alg)
        self.ui.LMS.clicked.connect(self.learn_alg)
        self.ui.polar.clicked.connect(self.signal_changed)
        self.ui.biPolar.clicked.connect(self.signal_changed)
        self.ui.bipolar_lbl.clicked.connect(self.lbl_type_changed)
        self.ui.binary_lbl.clicked.connect(self.lbl_type_changed)
        self.ui.tabWidget.currentChanged.connect(self.tab_changed)
        self.ui.test_btn.clicked.connect(self.test_clicked)
        self.ui.setBias.clicked.connect(self.set_bias)

        self.treeSettings()
        self.ui.img_1.setScaledContents(True)
        self.ui.img_2.setScaledContents(True)
        self.ui.img_3.setScaledContents(True)
        self.current_test_id = 0

        self.img1 = None
        self.img2 = None

        self.active_class_item = None
        self.connect(self.ui.data_tree,
                     SIGNAL("itemClicked(QTreeWidgetItem*, int)"),
                     self.onClickItem)
        self.connect(self.ui.activation, SIGNAL("activated(const QString&)"),
                     self.activation_changed)

        validator = QtGui.QDoubleValidator()
        self.ui.bias.setValidator(validator)

        self.mController.modelIsChanged(
            self.ui.tabWidget.currentWidget().objectName())
        act_functions = [
            'Бинарный порог', 'Биполярный порог', 'Радиально-симметричная'
        ]
        self.ui.activation.addItems(act_functions)
        self.params = {
            'Signal': '',
            'Learn': '',
            'Label': '',
            'Neurons': '',
            'Activation': '',
            'Bias': '',
            'Function param': '',
        }

    def set_params(self):
        self.signal_changed()
        self.learn_alg()
        self.lbl_type_changed()
        self.params['Neurons'] = self.ui.number_neurons.value()
        self.params['Activation'] = self.ui.activation.currentText()
        bias = self.ui.bias.text()
        if bias == '':
            bias = 0
        self.params['Bias'] = bias
        k = self.ui.function_param.text()
        if k == '':
            k = 0.5
        self.params['Function param'] = k

    def set_bias(self):
        self.set_params()
        self.mController.set_bias(self.params)

    def add_class(self):
        count = self.ui.data_tree.topLevelItemCount()
        item = QTreeWidgetItem(['Класс ' + str(count)])
        self.ui.data_tree.addTopLevelItem(item)

    def tab_changed(self):
        self.mController.modelIsChanged(
            self.ui.tabWidget.currentWidget().objectName())

    def activation_changed(self):
        self.set_params()
        self.mController.activation_changed(self.params)

    def test_clicked(self):
        self.ui.info.clear()
        self.set_params()
        outputs = self.mController.test(self.current_test_id, self.params)
        text = self.ui.info.text()
        self.ui.info.setText(text + '\n' + 'Выходы нейронов: ' + '\n')
        for i in outputs:
            self.ui.info.setText(self.ui.info.text() + str(i) + '\n')

    def signal_changed(self):
        btn = self.sender()
        #self.mController.signal_type_changed(btn.objectName())
        if self.ui.tabWidget.currentWidget().objectName() == 'SLP':
            if self.ui.polar.isChecked():
                self.params['Signal'] = 'binary'
            elif self.ui.biPolar.isChecked():
                self.params['Signal'] = 'bi_polar'
            self.mController.signal_type_changed(self.params)

    def lbl_type_changed(self):
        btn = self.sender()
        if self.ui.tabWidget.currentWidget().objectName() == 'SLP':
            if self.ui.bipolar_lbl.isChecked():
                self.params['Label'] = 'bi_polar'
            elif self.ui.binary_lbl.isChecked():
                self.params['Label'] = 'binary'
            self.mController.label_type_changed(self.params)

    def learn_alg(self):
        if self.ui.tabWidget.currentWidget().objectName() == 'SLP':
            if self.ui.Hebb.isChecked():
                self.params['Learn'] = 'Hebb'
            elif self.ui.LMS.isChecked():
                self.params['Learn'] = 'LMS'

    def learn_clicked(self):
        self.ui.info.clear()
        self.set_params()
        iter = self.mController.learn(self.params)
        text = 'Количество итераций: ' + str(iter)
        self.ui.info.setText(text)

    def treeSettings(self):
        self.ui.data_tree.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui.data_tree.customContextMenuRequested.connect(
            self.on_context_menu)
        self.popMenu = QMenu(self)
        self.popMenu.addAction(QtGui.QAction('Загрузить данные', self))
        self.popMenu.addAction(QtGui.QAction('Очистить', self))
        self.popMenu.triggered[QAction].connect(self.processtrigger)
        item = QTreeWidgetItem(['Тест'])
        self.ui.data_tree.addTopLevelItem(item)

    def processtrigger(self, q):
        self.set_params()
        if q.text() == 'Загрузить данные':
            dlg = QFileDialog()
            dlg.setFileMode(QFileDialog.AnyFile)
            dlg.setFileMode(QFileDialog.ExistingFiles)
            filenames = QStringListModel()
            if dlg.exec_():
                filenames = dlg.selectedFiles()
            if self.active_class_item is not None:
                for f in filenames:
                    self.active_class_item.addChild(QTreeWidgetItem([str(f)]))
                    img = imread(f, mode='P')
                    lbl = self.active_class_item.text(0)[
                        -1]  #считаем, что не будет двузначных меток
                    if self.active_class_item.text(0) == 'Тест':
                        self.mController.add_test(img, self.params)
                    else:
                        self.mController.add_data(img, lbl, self.params)
        elif q.text() == 'Очистить':
            count = self.active_class_item.childCount()
            for _ in range(count):
                self.active_class_item.removeChild(
                    self.active_class_item.child(0))
            if self.active_class_item.text(0) == 'Тест':
                self.mController.delete_test()
            else:
                lbl = self.active_class_item.text(0)[-1]
                self.mController.delete_data(lbl)
        self.active_class_item = None

    def on_context_menu(self, point):
        # show context menu
        index = self.ui.data_tree.indexAt(point)
        if not index.isValid():
            return
        item = self.ui.data_tree.itemAt(point)
        self.active_class_item = item
        self.popMenu.exec_(self.ui.data_tree.mapToGlobal(point))

    def modelIsChanged(self):
        pass

    def onClickItem(self, item, column):
        try:
            parent = 'Класс '
            parent_name = item.parent().text(0)
            i = 1
            if parent_name == 'Тест':
                for j in range(item.parent().childCount()):
                    if item.parent().child(j) == item:
                        self.current_test_id = j
                        break
                path = item.text(column)
                self.ui.img_3.setPixmap(QPixmap(path))
                img = imread(path)
                self.current_test = img
                self.set_sim()
            else:
                parent_ = parent + str(i)
                while parent_name != parent_:
                    parent_ = parent + str(i)
                    i += 1
                path = item.text(column)

                if parent_ == 'Класс 1':
                    self.ui.img_1.setPixmap(QPixmap(path))
                    self.img1 = imread(path)
                    self.set_sim()
                else:
                    self.ui.img_2.setPixmap(QPixmap(path))
                    self.img2 = imread(path)
                    self.set_sim()
        except:
            pass

    def set_sim(self):
        s1 = similarity(self.current_test, self.img1)
        s2 = similarity(self.current_test, self.img2)
        self.ui.learn_info.clear()
        text = 'Класс 1: ' + str(s1) + '\n' + 'Класс 2: ' + str(s2)
        self.ui.learn_info.setText(text)
Ejemplo n.º 8
0
class MainControllerEXEC:

    def __init__(self):
        # Create Application Instance
        app = QtWidgets.QApplication(sys.argv)

        # Create new main_window Instance
        self.main_window = QtWidgets.QMainWindow()

        # Create a ui instance to reference from the View
        # and pass in the main_window as an argument to update the
        # main window remotely
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self.main_window)

        self.date_dict = {}

        # call functions to process events
        self.trigger_date_change()
        self.trigger_search_bar_used()
        self.trigger_recent_stock_selection()
        self.trigger_search_button()
        self.trigger_import_date()
        self.trigger_click_on_cell_row()

        # Show main_window and execute application
        self.main_window.show()
        sys.exit(app.exec_())

    """
        -- Signal methods --
    """

    def trigger_date_change(self):
        pass

    def trigger_search_bar_used(self):
        self.ui.stockSearchBar.textChanged.connect(self.update_recent_combobox)

    def trigger_recent_stock_selection(self):
        self.ui.recentStocksList.currentTextChanged.connect(self.update_search_bar)

    def trigger_search_button(self):
        self.ui.searchButton.clicked.connect(self.perform_search)

    def trigger_import_date(self):
        self.ui.importButton.clicked.connect(self.scrape_stock_data)

    def trigger_click_on_cell_row(self):
        self.ui.stockTable.clicked.connect(self.table_clicked)

    """
        -- Class Methods --
    """

    def table_clicked(self):
        index = self.ui.stockTable.selectedIndexes()[0]
        id_us = self.ui.stockTable.model().data(index)
        row_index = self.ui.stockTable.selectedItems()[0].row()

        menu = QtWidgets.QMenu()
        save = menu.addAction("Save To Watchlist")
        delete = menu.addAction("Delete Row")
        action = menu.exec_(QtGui.QCursor.pos())

        if action == save:
            confirmation = confirm_save_dialog(self)
            if confirmation == 1:
                self.save_to_watchlist(row_index, id_us)
        if action == delete:
            confirmation = confirm_delete_dialog(self)
            if confirmation == 1:
                self.delete_row_index(row_index)


    def update_recent_stock_list(self):
        """ This method will search the database
            during the application initialization
            to update the recent stock list with
            only unique stocks from the last 7
            days
        """
        pass


    def update_recent_combobox(self):
        if self.ui.stockSearchBar.text() != '':
            self.ui.recentStocksList.setDisabled(True)
        else:
            self.ui.recentStocksList.setDisabled(False)

    def update_search_bar(self):
        if self.ui.recentStocksList.currentText() != 'Select Recent':
            self.ui.stockSearchBar.setDisabled(True)
            self.ui.searchButton.setDisabled(True)
        else:
            self.ui.stockSearchBar.setDisabled(False)
            self.ui.searchButton.setDisabled(False)

    def perform_search(self):

        self.ui.dateSelect.clear()
        self.date_dict.clear()
        search_value = self.ui.stockSearchBar.text().upper()
        if search_value != '':
            result = search_for_stock_ticker(search_value)

            if result is not None:
                self.ui.stockSearchResult.setText(result[1])
                self.ui.stockSearchResult.repaint()
                self.load_date_picker(search_value)
            else:
                self.ui.stockSearchResult.setText('No Stock found with symbol \'{}\''.format(search_value))
                self.ui.stockSearchResult.repaint()
        else:
            self.ui.stockSearchResult.setText("Enter Valid Symbol")
            self.ui.stockSearchResult.repaint()

    def date_selected(self):
        convert_time_to_utc(self.ui.dateSelect.date().toString('yyyy MM dd'))

    def load_date_picker(self, stock_symbol):
        stock = StockData(stock_symbol)
        self.date_dict = stock.get_date_options()

        if not self.date_dict:
            self.ui.stockSearchResult.setText("No Options Data Available for \'{}\'".format(stock_symbol))
            self.ui.stockSearchResult.repaint()

        if self.date_dict is not None:
            for date in self.date_dict:
                self.ui.dateSelect.addItem(date)
                self.ui.dateSelect.repaint()

        else:
            show_connection_dialog(self)

    def scrape_stock_data(self):
        # TODO: disable import button until search button clicked or recent stock is selected
        date = self.date_dict[self.ui.dateSelect.currentText()]
        stock = StockData(self.ui.stockSearchBar.text().upper())
        stock_data = stock.get_call_data(date)
        if stock_data is not None:
            self.populate_data_table(stock_data)
        else:
            show_connection_dialog()

    def populate_data_table(self, stock_data):
        row_number = self.ui.stockTable.rowCount()
        self.ui.stockTable.insertRow(row_number)

        for i in range(len(stock_data)):
            self.ui.stockTable.setItem(row_number, i, QtWidgets.QTableWidgetItem(stock_data[i]))
            self.ui.stockTable.repaint()

        self.ui.stockTable.setItem(row_number, 4, QtWidgets.QTableWidgetItem(self.ui.dateSelect.currentText()))

        self.ui.stockTable.repaint()

    def save_to_watchlist(self, row_index, company_stock_symbol):
        self.ui.recentStocksList.addItem(company_stock_symbol)
        date = datetime.datetime.date(datetime.datetime.now())
        print(date)

    def delete_row_index(self, row_index):
        self.ui.stockTable.removeRow(row_index)
        self.ui.stockTable.repaint()