예제 #1
0
    def __init__(self, parent=None):
        super().__init__(parent)

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

        self.ui.pb_models.clicked.connect(self.models_changed)
        self.ui.pb_models_2.clicked.connect(self.models_predefined)
        self.ui.pb_plot.clicked.connect(self.plot_results)
        self.ui.pb_plot_diff.clicked.connect(self.plot_differences)

        self.ui.pb_models.clicked.connect(
            lambda: self.ui.stackedWidget.setCurrentIndex(2))
        self.ui.pb_models_2.clicked.connect(
            lambda: self.ui.stackedWidget.setCurrentIndex(2))

        self.ui.pb_select.clicked.connect(
            lambda: self.ui.stackedWidget.setCurrentIndex(0))
        self.ui.pb_select_2.clicked.connect(
            lambda: self.ui.stackedWidget.setCurrentIndex(1))

        self.ui.pb_filepath_selec.clicked.connect(
            lambda: self.ui.stackedWidget.setCurrentIndex(0))
        self.ui.pb_selection.clicked.connect(
            lambda: self.ui.stackedWidget.setCurrentIndex(1))

        self.ui.cbx_cat_c1.currentTextChanged.connect(self.cat_c1_changed)
        self.ui.cbx_cat_c2.currentTextChanged.connect(self.cat_c2_changed)
        self.ui.cbx_cat_c3.currentTextChanged.connect(self.cat_c3_changed)
        self.ui.cbx_cat_c4.currentTextChanged.connect(self.cat_c4_changed)

        self.ui.cbx_inp_depth_m1.currentTextChanged.connect(
            self.model1_input_change)
        self.ui.cbx_inp_depth_m2.currentTextChanged.connect(
            self.model2_input_change)
예제 #2
0
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)

        # Set default options
        self.createNewTableRB.setChecked(True)
예제 #3
0
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.saveForm = None
        self.testForm = None

        self.ui.kinect_radio.setIcon(
            QtGui.QIcon("resources/images/kinect2.png"))
        self.ui.imu_radio.setIcon(QtGui.QIcon("resources/images/IMU.png"))
        self.ui.kinect_imu_radio.setIcon(
            QtGui.QIcon("resources/images/kinectIMU.png"))

        self.ui.kinect_radio.setIconSize(QtCore.QSize(100, 100))
        self.ui.imu_radio.setIconSize(QtCore.QSize(100, 100))
        self.ui.kinect_imu_radio.setIconSize(QtCore.QSize(100, 100))

        self.ui.start_btn.clicked.connect(self.startAcquisition)
        self.ui.start_btn.clicked.connect(self.resetGUI)

        self.ui.imu_radio.clicked.connect(self.checkChanged)
        self.ui.kinect_imu_radio.clicked.connect(self.checkChanged)
        self.ui.kinect_radio.clicked.connect(self.checkChanged)

        self.ui.save_radio.clicked.connect(self.checkChanged)
        self.ui.test_radio.clicked.connect(self.checkChanged)

        self.ui.default_config.clicked.connect(self.configChecked)

        self.ui.actionHome.triggered.connect(self.resetHome)

        self.frame = frameSet()

        self.kinect = None
        # self.imu = None
        self.imu = []

        self.timer = QtCore.QTimer(self)
        self.t_fps = QtCore.QTimer(self)
        self.fps = 0

        self.calib = [False, False]
        self.calib_step = 0
        self.ui.calibBar.setVisible(False)
        self.ui.calibLabel.setVisible(False)

        self.ui.shoulder_device_box.setEnabled(True)
        self.ui.head_device_box.setEnabled(True)

        self.connect(self.timer, QtCore.SIGNAL('timeout()'), self.acquireFrame)
        self.connect(self.t_fps, QtCore.SIGNAL('timeout()'), self.updateFPS)

        self.connect(self, QtCore.SIGNAL('calibFrameAcquired()'),
                     self.updateCalibBar)
        self.connect(self, QtCore.SIGNAL('calibFrameEnded()'),
                     self.endUpdateCalibBar)

        self.connect(self, QtCore.SIGNAL('triggered()'), self.closeEvent)
예제 #4
0
    def __init__(self, parent=None):
        super().__init__(parent)

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

        self.ui.pb_start.clicked.connect(self.initiate_comparison_plot)

        self.ui.pb_plot.clicked.connect(self.plot_results)
        self.ui.pb_comp.clicked.connect(self.comparison_img)

        self.ui.cbx_cat_c1.currentTextChanged.connect(self.cat_c1_changed)
        self.ui.cbx_cat_c2.currentTextChanged.connect(self.cat_c2_changed)
        self.ui.cbx_cat_c3.currentTextChanged.connect(self.cat_c3_changed)
예제 #5
0
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # 创建一个捕包的类 线程
        self.data_capture = Capture(self.ui.show_info_text)

        # 因为当数据改变是我们需要data_statistics发出相应的信号,这样我们就可以实现界面中
        # 数据的变化
        self.data_statistics = self.data_capture.rec.proto_restore.statistic

        # 捕包状态
        self.cap_state = False
        self.init_widget()
예제 #6
0
    def __init__(self):
        super(MainWindow, self).__init__()

        # Set up the user interface from Designer.
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setWindowTitle("Kepler Manager")

        self.viewer = Viewer()
        self.viewer3d = Viewer3D()
        self.tableViewer = TableViewer()
        self.caldialog = CalDialog()
        self.errdialog = ErrDialog()
        self.cal_stop = False

        regexp = QRegExp("[0-9e\.\+\-\*\(\)/]*")
        validator = QRegExpValidator(regexp)

        self.ui.lineEdit_G.setValidator(validator)
        self.ui.lineEdit_TimeIncrement.setValidator(validator)
        self.ui.lineEdit_StopTime.setValidator(validator)
        #self.ui.actionAbout_Kepler.triggered.connect(self.about_Kepler)
        #self.ui.actionPreference.triggered.connect(self.preference)
        self.ui.actionSave.triggered.connect(self.save_file)
        self.ui.actionLoad_your_settings.triggered.connect(self.load_file)
        self.ui.actionLoad_SOL.triggered.connect(self.load_SOL)
        self.ui.actionViewer.triggered.connect(self.open_viewer)
        #self.ui.actionTable_Viewer.triggered.connect(self.open_tableviewer)
        #self.ui.actionHow_to_use.triggered.connect(self.show_help)
        #self.ui.actionHow_does_this_work.triggered.connect(self.show_mechanism)

        #self.ui.comboBox_Choose2Dor3D.currentIndexChanged.connect(self.choose2dor3d)
        self.ui.pushButton_AddPlanet.clicked.connect(self.add_planet)
        self.ui.pushButton_DeletePlanet.clicked.connect(self.remove_planets)

        self.ui.lineEdit_G.setText("6.674e-11")

        self.ui.pushButton_Calc.clicked.connect(self.calc)

        self.planets_attribute = TreeViewModel()
        self.planets = Planet_system()
        self.resultcontainer = ResultContainer()

        self.ui.treeView_PlanetAttribute.setModel(self.planets_attribute)
        self.ui.treeView_PlanetAttribute.setItemDelegate(Delegate())
예제 #7
0
    def __init__(self):
        self.app = QtGui.QApplication(sys.argv)
        self.app.setApplicationName("Plots! Plots! Plots!")

        self.app.setStyleSheet(qdarkstyle.load_stylesheet())
        # self.app.setStyle(QtGui.QGtkStyle())
        self.plotter = None
        self.state = {"started": False, "fullscreen": False}

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

        self.validateUi()
        self.addPlotWidget()
        self.setupGuiBindings()
예제 #8
0
class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)

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

        self.ui.pb_start.clicked.connect(self.initiate_comparison_plot)

        self.ui.pb_plot.clicked.connect(self.plot_results)
        self.ui.pb_comp.clicked.connect(self.comparison_img)

        self.ui.cbx_cat_c1.currentTextChanged.connect(self.cat_c1_changed)
        self.ui.cbx_cat_c2.currentTextChanged.connect(self.cat_c2_changed)
        self.ui.cbx_cat_c3.currentTextChanged.connect(self.cat_c3_changed)

    def initiate_comparison_plot(self):
        self.ui.cbx_comp.clear()

        model_comp = files_in_folder(comp_folder)
        inp_models = files_in_folder(db_folder)

        self.ui.cbx_comp.addItems(model_comp)

        # hier das abrufen und populieren der CBX

    def cat_c1_changed(self):
        self.ui.cbx_scat_c1.clear()

        cat1 = self.ui.cbx_cat_c1.currentText()
        res_pres = ['-']
        res_u = ['x', 'y', 'z']
        res_str = ['tot', 's1', 's2', 's3', 'sxx', 'syy', 'szz', 'sxy', 'syz', 'sxz']

        if cat1 == "pressure":
            self.ui.cbx_scat_c1.addItems(res_pres)
        elif cat1 == "u":
            self.ui.cbx_scat_c1.addItems(res_u)
        elif cat1 == "stress":
            self.ui.cbx_scat_c1.addItems(res_str)
        elif cat1 == "estress":
            self.ui.cbx_scat_c1.addItems(res_str)
        elif cat1 == "el. strain":
            self.ui.cbx_scat_c1.addItems(res_str)
        elif cat1 == "pl. strain":
            self.ui.cbx_scat_c1.addItems(res_str)
        elif cat1 == "tot. strain":
            self.ui.cbx_scat_c1.addItems(res_str)
        else:
            self.ui.cbx_scat_c1.addItems(" ")

    def cat_c2_changed(self):
        self.ui.cbx_scat_c2.clear()

        cat1 = self.ui.cbx_cat_c2.currentText()
        res_pres = ['-']
        res_u = ['x', 'y', 'z']
        res_str = ['tot', 's1', 's2', 's3', 'sxx', 'syy', 'szz', 'sxy', 'syz', 'sxz']

        if cat1 == "pressure":
            self.ui.cbx_scat_c2.addItems(res_pres)
        elif cat1 == "u":
            self.ui.cbx_scat_c2.addItems(res_u)
        elif cat1 == "stress":
            self.ui.cbx_scat_c2.addItems(res_str)
        elif cat1 == "estress":
            self.ui.cbx_scat_c2.addItems(res_str)
        elif cat1 == "el. strain":
            self.ui.cbx_scat_c2.addItems(res_str)
        elif cat1 == "pl. strain":
            self.ui.cbx_scat_c2.addItems(res_str)
        elif cat1 == "tot. strain":
            self.ui.cbx_scat_c2.addItems(res_str)
        else:
            self.ui.cbx_scat_c2.addItems(" ")

    def cat_c3_changed(self):
        self.ui.cbx_scat_c3.clear()

        cat1 = self.ui.cbx_cat_c3.currentText()
        res_pres = ['-']
        res_u = ['x', 'y', 'z']
        res_str = ['tot', 's1', 's2', 's3', 'sxx', 'syy', 'szz', 'sxy', 'syz', 'sxz']

        if cat1 == "pressure":
            self.ui.cbx_scat_c3.addItems(res_pres)
        elif cat1 == "u":
            self.ui.cbx_scat_c3.addItems(res_u)
        elif cat1 == "stress":
            self.ui.cbx_scat_c3.addItems(res_str)
        elif cat1 == "estress":
            self.ui.cbx_scat_c3.addItems(res_str)
        elif cat1 == "el. strain":
            self.ui.cbx_scat_c3.addItems(res_str)
        elif cat1 == "pl. strain":
            self.ui.cbx_scat_c3.addItems(res_str)
        elif cat1 == "tot. strain":
            self.ui.cbx_scat_c3.addItems(res_str)
        else:
            self.ui.cbx_scat_c3.addItems(" ")

    def plot_results(self):
        user_cat_c1 = self.ui.cbx_cat_c1.currentText()
        user_cat_c2 = self.ui.cbx_cat_c2.currentText()
        user_cat_c3 = self.ui.cbx_cat_c3.currentText()

        user_subcat_c1 = self.ui.cbx_scat_c1.currentText()
        user_subcat_c2 = self.ui.cbx_scat_c2.currentText()
        user_subcat_c3 = self.ui.cbx_scat_c3.currentText()

        user_cshades = int(self.ui.cshades.value())

        user_zoomx = self.ui.zoom_x.value()
        user_zoomy = self.ui.zoom_y.value()
        user_zoomext = self.ui.zoom_ext.value()
        col_map = 'Greys'
        user_resolution = int(self.ui.resolution.value())

        key_f1 = user_cat_c1 + '-' + user_subcat_c1
        key_f2 = user_cat_c2 + '-' + user_subcat_c2
        key_f3 = user_cat_c3 + '-' + user_subcat_c3

        if self.ui.cbox_zoom.isChecked():
            xi_1 = np.linspace(user_zoomx - 0.5 * user_zoomext, user_zoomx + 0.5 * user_zoomext, user_resolution)
            yi_1 = np.linspace(user_zoomy - 0.5 * user_zoomext, user_zoomy + 0.5 * user_zoomext, user_resolution)
        else:
            xi_1 = np.linspace(-500, 500, user_resolution)
            yi_1 = np.linspace(-500, 500, user_resolution)

        model_comp_current = [self.ui.cbx_comp.currentText()]
        inp_models = files_in_folder(db_folder)

        # Calculate Min-Max Values of all models
        # Get all Min-Max-Values from DB-models
        min_all_1, max_all_1 = grad_db(db_var, inp_models, input_output, key_f1)
        min_all_2, max_all_2 = grad_db(db_var, inp_models, input_output, key_f2)
        min_all_3, max_all_3 = grad_db(db_var, inp_models, input_output, key_f3)
        # Get all Min-Max-Values from Comp-model
        min_i_1, max_i_1 = grad_db(comp_var, model_comp_current, input_output, key_f1)
        min_i_2, max_i_2 = grad_db(comp_var, model_comp_current, input_output, key_f2)
        min_i_3, max_i_3 = grad_db(comp_var, model_comp_current, input_output, key_f3)
        # Select min-max-values for all models in comparison
        minm_1, maxm_1 = grad_all(min_all_1, max_all_1, min_i_1, max_i_1)
        minm_2, maxm_2 = grad_all(min_all_2, max_all_2, min_i_2, max_i_2)
        minm_3, maxm_3 = grad_all(min_all_3, max_all_3, min_i_3, max_i_3)

        def pic_creation(var, models, folder, data_format, inp_out, key, min_val, max_val, cshades, cmap, xi, yi):
            for i in models:
                model_paths = predef_paths(var, i)

                # Calculations
                results_mod = ans_csvdataimp_complete(model_paths)

                # generate df for plotting
                xval, yval, zval, chead, output_title = plot_df(results_mod, inp_out, key)

                # define graduation
                user_graduation = np.linspace(min_val, max_val, cshades, endpoint=True)

                # define Colormap
                colm = colormap(cmap)

                # Plotting - general settings
                fig = plt.figure(figsize=(10, 10))
                spec = gridspec.GridSpec(ncols=1, nrows=1)

                # figure 1

                # model1
                fig_img = fig.add_subplot(spec[0, 0])
                # Contour plot
                zi = griddata((xval, yval), zval, (xi[None, :], yi[:, None]), method='linear')
                cf_f1_1 = plt.contourf(xi, yi, zi, user_graduation, cmap=colm)

                fig_img.axes.get_xaxis().set_visible(False)
                fig_img.axes.get_yaxis().set_visible(False)  # Achsen unsichtbar machen

                # plt.ylabel(i)

                # plt.title(output_title)

                # fig.colorbar(cf_f1_1)

                plt.savefig(folder + i + data_format, bbox_inches='tight')
                plt.close()

                # plt.show()

        pic_creation(db_var, inp_models, fdb_1, data_format, input_output, key_f1, minm_1, maxm_1, user_cshades,
                     col_map, xi_1, yi_1)
        pic_creation(db_var, inp_models, fdb_2, data_format, input_output, key_f2, minm_2, maxm_2, user_cshades,
                     col_map, xi_1, yi_1)
        pic_creation(db_var, inp_models, fdb_3, data_format, input_output, key_f3, minm_3, maxm_3, user_cshades,
                     col_map, xi_1, yi_1)

        pic_creation(comp_var, model_comp_current, fcomp_1, data_format, input_output, key_f1, minm_1, maxm_1,
                     user_cshades, col_map, xi_1, yi_1)
        pic_creation(comp_var, model_comp_current, fcomp_2, data_format, input_output, key_f2, minm_2, maxm_2,
                     user_cshades, col_map, xi_1, yi_1)
        pic_creation(comp_var, model_comp_current, fcomp_3, data_format, input_output, key_f3, minm_3, maxm_3,
                     user_cshades, col_map, xi_1, yi_1)

    def comparison_img(self):

        model_comp_pic_1 = files_in_folder(fcomp_1)
        model_comp_pic_2 = files_in_folder(fcomp_2)
        model_comp_pic_3 = files_in_folder(fcomp_3)

        inp_models_pic_1 = files_in_folder(fdb_1)
        inp_models_pic_2 = files_in_folder(fdb_2)
        inp_models_pic_3 = files_in_folder(fdb_3)

        inp_models_csv = files_in_folder_png(fdb_1)

        for i in model_comp_pic_1:
            path1 = fcomp_1 + i

        for i in model_comp_pic_2:
            path2 = fcomp_2 + i

        for i in model_comp_pic_3:
            path3 = fcomp_3 + i



        def compare_ssim_all(inp_models, db_folder, path):

            list_scores = []
            imageB = cv2.imread(path, cv2.IMREAD_COLOR)

            for i in inp_models:
                # load the two input images
                imageA = cv2.imread(db_folder + i, cv2.IMREAD_COLOR)

                # convert the images to grayscale
                grayA = cv2.cvtColor(imageA, cv2.COLOR_BGR2GRAY)
                grayB = cv2.cvtColor(imageB, cv2.COLOR_BGR2GRAY)

                # compute the Structural Similarity Index (SSIM) between the two
                # images, ensuring that the difference image is returned
                (score, diff) = structural_similarity(grayA, grayB, full=True)
                diff = (diff * 255).astype("uint8")
                #print("SSIM: {}".format(score))

                list_scores.append(score)

            max_ind = list_scores.index(max(list_scores))

            return max_ind

        def plot_max_ssim(max_ind1, max_ind2, max_ind3):

            user_cat_c1 = self.ui.cbx_cat_c1.currentText()
            user_cat_c2 = self.ui.cbx_cat_c2.currentText()
            user_cat_c3 = self.ui.cbx_cat_c3.currentText()

            user_subcat_c1 = self.ui.cbx_scat_c1.currentText()
            user_subcat_c2 = self.ui.cbx_scat_c2.currentText()
            user_subcat_c3 = self.ui.cbx_scat_c3.currentText()

            user_cshades = int(self.ui.cshades.value())

            user_zoomx = self.ui.zoom_x.value()
            user_zoomy = self.ui.zoom_y.value()
            user_zoomext = self.ui.zoom_ext.value()
            user_colormap = str(self.ui.cbx_legend.currentText())

            user_min_c1 = self.ui.min_fig1.value()
            user_min_c2 = self.ui.min_fig2.value()
            user_min_c3 = self.ui.min_fig3.value()

            user_max_c1 = self.ui.max_fig1.value()
            user_max_c2 = self.ui.max_fig2.value()
            user_max_c3 = self.ui.max_fig3.value()

            user_comp_mod = self.ui.cbx_comp.currentText()

            user_resolution = int(self.ui.resolution.value())

            key_f1 = user_cat_c1 + '-' + user_subcat_c1
            key_f2 = user_cat_c2 + '-' + user_subcat_c2
            key_f3 = user_cat_c3 + '-' + user_subcat_c3

            if self.ui.cbox_zoom.isChecked():
                xi_1 = np.linspace(user_zoomx - 0.5 * user_zoomext, user_zoomx + 0.5 * user_zoomext, user_resolution)
                yi_1 = np.linspace(user_zoomy - 0.5 * user_zoomext, user_zoomy + 0.5 * user_zoomext, user_resolution)
            else:
                xi_1 = np.linspace(-500, 500, user_resolution)
                yi_1 = np.linspace(-500, 500, user_resolution)

            model_comp_csv = comp_folder + '/' + user_comp_mod + '.csv'

            model_comp_png1 = fcomp_1 + user_comp_mod + '.png'
            model_comp_png2 = fcomp_2 + user_comp_mod + '.png'
            model_comp_png3 = fcomp_3 + user_comp_mod + '.png'

            inp_csv = files_in_folder_png(fdb_1)

            model_db_csv1 = db_folder + '/' + inp_csv[max_ind1] + '.csv'
            model_db_csv2 = db_folder + '/' + inp_csv[max_ind2] + '.csv'
            model_db_csv3 = db_folder + '/' + inp_csv[max_ind3] + '.csv'

            model_db_png1 = fdb_1 + inp_csv[max_ind1] + '.png'
            model_db_png2 = fdb_2 + inp_csv[max_ind2] + '.png'
            model_db_png3 = fdb_3 + inp_csv[max_ind3] + '.png'

            # Calculations
            results_mod_comp = ans_csvdataimp_complete(model_comp_csv)
            results_mod_db1 = ans_csvdataimp_complete(model_db_csv1)
            results_mod_db2 = ans_csvdataimp_complete(model_db_csv2)
            results_mod_db3 = ans_csvdataimp_complete(model_db_csv3)

            # generate df for plotting
            xval_c1, yval_c1, zval_c1, chead_c1, output_title_c1 = plot_df(results_mod_comp, input_output, key_f1)
            xval_c2, yval_c2, zval_c2, chead_c2, output_title_c2 = plot_df(results_mod_comp, input_output, key_f2)
            xval_c3, yval_c3, zval_c3, chead_c3, output_title_c3 = plot_df(results_mod_comp, input_output, key_f3)

            xval_db1, yval_db1, zval_db1, chead_db1, output_title_db1 = plot_df(results_mod_db1, input_output, key_f1)
            xval_db2, yval_db2, zval_db2, chead_db2, output_title_db2 = plot_df(results_mod_db2, input_output, key_f2)
            xval_db3, yval_db3, zval_db3, chead_db3, output_title_db3 = plot_df(results_mod_db3, input_output, key_f3)

            if self.ui.cbox_man_1.isChecked():
                min_f1 = user_min_c1
                max_f1 = user_max_c1
            else:
                min_f1, max_f1 = graduation(results_mod_comp, results_mod_db1, input_output, key_f1)

            if self.ui.cbox_man_2.isChecked():
                min_f2 = user_min_c2
                max_f2 = user_max_c2
            else:
                min_f2, max_f2 = graduation(results_mod_comp, results_mod_db2, input_output, key_f2)

            if self.ui.cbox_man_3.isChecked():
                min_f3 = user_min_c3
                max_f3 = user_max_c3
            else:
                min_f3, max_f3 = graduation(results_mod_comp, results_mod_db3, input_output, key_f3)

            # define graduation
            user_graduation_f1 = np.linspace(min_f1, max_f1, user_cshades, endpoint=True)
            user_graduation_f2 = np.linspace(min_f2, max_f2, user_cshades, endpoint=True)
            user_graduation_f3 = np.linspace(min_f3, max_f3, user_cshades, endpoint=True)

            # define Colormap
            colm = colormap(user_colormap)

            #### Generation of diff image

            def compare_ssim(path_c, path_db):
                # load the two input images
                imageA = cv2.imread(path_c, cv2.IMREAD_COLOR)
                imageB = cv2.imread(path_db, cv2.IMREAD_COLOR)

                # convert the images to grayscale
                grayA = cv2.cvtColor(imageA, cv2.COLOR_BGR2GRAY)
                grayB = cv2.cvtColor(imageB, cv2.COLOR_BGR2GRAY)

                # compute the Structural Similarity Index (SSIM) between the two
                # images, ensuring that the difference image is returned
                (score, diff) = structural_similarity(grayA, grayB, full=True)
                diff = (diff * 255).astype("uint8")
                #print("SSIM: {}".format(score))

                return diff, score

            diff_1, score1 = compare_ssim(model_comp_png1, model_db_png1)
            diff_2, score2 = compare_ssim(model_comp_png2, model_db_png2)
            diff_3, score3 = compare_ssim(model_comp_png3, model_db_png3)

            # threshold the difference image, followed by finding contours to
            # obtain the regions of the two input images that differ
            # thresh = cv2.threshold(diff, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
            # cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
            # cnts = imutils.grab_contours(cnts)

            # loop over the contours
            # for c in cnts:
            # compute the bounding box of the contour and then draw the
            # bounding box on both input images to represent where the two
            # images differ
            # (x, y, w, h) = cv2.boundingRect(c)
            # cv2.rectangle(imageA, (x, y), (x + w, y + h), (0, 0, 255), 2)
            # cv2.rectangle(imageB, (x, y), (x + w, y + h), (0, 0, 255), 2)

            # show the output images
            # cv2.imshow('Original', imageA)
            # cv2.imshow(inp_models_pic[max_ind], imageB)
            # cv2.imshow("Diff1", diff_1)
            # cv2.imshow("Diff2", diff_2)
            # cv2.imshow("Diff3", diff_3)
            # cv2.imshow("Thresh", thresh)
            # cv2.waitKey(0)

            # Plotting - general settings

            # figure 1

            # Plotting - general settings
            fig = plt.figure(constrained_layout=True, figsize=(15, 15))

            spec = gridspec.GridSpec(ncols=3, nrows=3, figure=fig)

            # figure 1

            # figure 1

            f1_ax1 = fig.add_subplot(spec[0, 0])
            # Contour plot
            zi_1a = griddata((xval_c1, yval_c1), zval_c1, (xi_1[None, :], yi_1[:, None]), method='linear')
            cf_f1_1 = plt.contourf(xi_1, yi_1, zi_1a, user_graduation_f1, cmap=colm)

            f1_ax1.axes.get_xaxis().set_visible(False)  # Achsen unsichtbar machen

            plt.ylabel(user_comp_mod)

            plt.title(output_title_c1)

            f1_ax2 = fig.add_subplot(spec[1, 0])
            # Contour plot
            zi_1b = griddata((xval_db1, yval_db1), zval_db1, (xi_1[None, :], yi_1[:, None]), method='linear')
            cf_f1_2 = plt.contourf(xi_1, yi_1, zi_1b, user_graduation_f1, cmap=colm)

            plt.ylabel(inp_csv[max_ind1])

            fig.colorbar(cf_f1_1, location='bottom')

            # Diffplot

            f1_ax3 = fig.add_subplot(spec[2, 0])
            cf_f1_3 = plt.imshow(diff_1, cmap='Greys_r')
            plt.title("SSIM: {}".format(score1))
            f1_ax3.axes.get_xaxis().set_visible(False)
            f1_ax3.axes.get_yaxis().set_visible(False)

            fig.colorbar(cf_f1_3, location='bottom')

            # figure 2

            f2_ax1 = fig.add_subplot(spec[0, 1])
            zi_2a = griddata((xval_c2, yval_c2), zval_c2, (xi_1[None, :], yi_1[:, None]), method='linear')
            cf_f2_1 = plt.contourf(xi_1, yi_1, zi_2a, user_graduation_f2, cmap=colm)

            f2_ax1.axes.get_xaxis().set_visible(False)
            # f2_ax1.axes.get_yaxis().set_visible(False)

            plt.title(output_title_c2)

            f2_ax2 = fig.add_subplot(spec[1, 1])
            # Contour plot
            zi_2b = griddata((xval_db2, yval_db2), zval_db2, (xi_1[None, :], yi_1[:, None]), method='linear')
            cf_f2_2 = plt.contourf(xi_1, yi_1, zi_2b, user_graduation_f2, cmap=colm)

            # f2_ax2.axes.get_yaxis().set_visible(False)
            plt.ylabel(inp_csv[max_ind2])
            fig.colorbar(cf_f2_1, location='bottom')

            # Diffplot

            f2_ax3 = fig.add_subplot(spec[2, 1])
            cf_f2_3 = plt.imshow(diff_2, cmap='Greys_r')
            plt.title("SSIM: {}".format(score2))
            f2_ax3.axes.get_xaxis().set_visible(False)
            f2_ax3.axes.get_yaxis().set_visible(False)

            fig.colorbar(cf_f2_3, location='bottom')

            # figure 3

            f3_ax1 = fig.add_subplot(spec[0, 2])
            zi_3a = griddata((xval_c3, yval_c3), zval_c3, (xi_1[None, :], yi_1[:, None]), method='linear')
            cf_f3_1 = plt.contourf(xi_1, yi_1, zi_3a, user_graduation_f3, cmap=colm)

            f3_ax1.axes.get_xaxis().set_visible(False)
            # f3_ax1.axes.get_yaxis().set_visible(False)

            plt.title(output_title_c3)

            f3_ax2 = fig.add_subplot(spec[1, 2])
            zi_3b = griddata((xval_db3, yval_db3), zval_db3, (xi_1[None, :], yi_1[:, None]), method='linear')
            cf_f3_2 = plt.contourf(xi_1, yi_1, zi_3b, user_graduation_f3, cmap=colm)

            # f3_ax2.axes.get_yaxis().set_visible(False)
            plt.ylabel(inp_csv[max_ind3])
            fig.colorbar(cf_f3_1, location='bottom')

            # Diffplot

            f3_ax3 = fig.add_subplot(spec[2, 2])
            cf_f3_3 = plt.imshow(diff_3, cmap='Greys_r')
            plt.title("SSIM: {}".format(score1))
            f3_ax3.axes.get_xaxis().set_visible(False)
            f3_ax3.axes.get_yaxis().set_visible(False)

            fig.colorbar(cf_f3_3, location='bottom')

            plt.show()

        max_ind1 = compare_ssim_all(inp_models_pic_1, fdb_1, path1)
        max_ind2 = compare_ssim_all(inp_models_pic_2, fdb_2, path2)
        max_ind3 = compare_ssim_all(inp_models_pic_3, fdb_3, path3)

        plot_max_ssim(max_ind1, max_ind2, max_ind3)
예제 #9
0
class applicationForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.saveForm = None
        self.testForm = None

        self.ui.kinect_radio.setIcon(
            QtGui.QIcon("resources/images/kinect2.png"))
        self.ui.imu_radio.setIcon(QtGui.QIcon("resources/images/IMU.png"))
        self.ui.kinect_imu_radio.setIcon(
            QtGui.QIcon("resources/images/kinectIMU.png"))

        self.ui.kinect_radio.setIconSize(QtCore.QSize(100, 100))
        self.ui.imu_radio.setIconSize(QtCore.QSize(100, 100))
        self.ui.kinect_imu_radio.setIconSize(QtCore.QSize(100, 100))

        self.ui.start_btn.clicked.connect(self.startAcquisition)
        self.ui.start_btn.clicked.connect(self.resetGUI)

        self.ui.imu_radio.clicked.connect(self.checkChanged)
        self.ui.kinect_imu_radio.clicked.connect(self.checkChanged)
        self.ui.kinect_radio.clicked.connect(self.checkChanged)

        self.ui.save_radio.clicked.connect(self.checkChanged)
        self.ui.test_radio.clicked.connect(self.checkChanged)

        self.ui.default_config.clicked.connect(self.configChecked)

        self.ui.actionHome.triggered.connect(self.resetHome)

        self.frame = frameSet()

        self.kinect = None
        # self.imu = None
        self.imu = []

        self.timer = QtCore.QTimer(self)
        self.t_fps = QtCore.QTimer(self)
        self.fps = 0

        self.calib = [False, False]
        self.calib_step = 0
        self.ui.calibBar.setVisible(False)
        self.ui.calibLabel.setVisible(False)

        self.ui.shoulder_device_box.setEnabled(True)
        self.ui.head_device_box.setEnabled(True)

        self.connect(self.timer, QtCore.SIGNAL('timeout()'), self.acquireFrame)
        self.connect(self.t_fps, QtCore.SIGNAL('timeout()'), self.updateFPS)

        self.connect(self, QtCore.SIGNAL('calibFrameAcquired()'),
                     self.updateCalibBar)
        self.connect(self, QtCore.SIGNAL('calibFrameEnded()'),
                     self.endUpdateCalibBar)

        self.connect(self, QtCore.SIGNAL('triggered()'), self.closeEvent)

    def closeEvent(self, event):
        # if self.imu is not None:
        if len(self.imu) > 0:
            print "Killing IMU thread(s)"
            # self.imu.close()
            for imu in self.imu:
                imu.close()

        self.close()
        self.destroy()

    def calibration(self):
        msg = QtGui.QMessageBox()
        msg.setIcon(QtGui.QMessageBox.Information)
        msg.setText("IMU calibration is going to be performed")
        msg.setInformativeText(
            "Calibration needs a few seconds to complete. \nKeep your head as still as possible"
        )
        msg.setWindowTitle("Calibration")
        msg.setStandardButtons(QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel)
        ret = msg.exec_()
        if ret == QtGui.QMessageBox.Ok:
            self.calib = [True, True]
            self.calib_step = 0
            self.ui.calibBar.reset()
            self.ui.calibBar.setValue(0)
            self.ui.calibLabel.setText("Calibrating...")
            self.ui.calibBar.setVisible(True)
            self.ui.calibLabel.setVisible(True)

    def endUpdateCalibBar(self):
        self.calib_step = 0
        self.ui.calibLabel.setText("Calibration completed!")

    def updateCalibBar(self):
        self.calib_step += 1
        self.ui.calibBar.setValue(
            (self.calib_step / self.ui.numIMUBox.value()) * 100 /
            CALIBRATION_FRAMES)

    def startAcquisition(self):
        # if self.ui.test_radio.isChecked():
        #     if self.ui.kinect_radio.isChecked():
        #         acquisitionKinect.test()
        #     if self.ui.imu_radio.isChecked():
        #         acquisitionIMU.test()
        self.ui.sensor_label.setText("Trying to connect to given sensor(s)...")

        if self.ui.kinect_radio.isChecked(
        ) or self.ui.kinect_imu_radio.isChecked():
            self.kinect = acquisitionKinect.AcquisitionKinect()
        if self.ui.kinect_imu_radio.isChecked() or self.ui.imu_radio.isChecked(
        ):
            numIMU = self.ui.numIMUBox.value()
            for ni in xrange(numIMU):
                if self.ui.default_config.isChecked():
                    auto_calib = False
                    imu = acquisitionIMU.AcquisitionIMU(auto_calib=auto_calib)
                else:
                    # TODO: mettere possibilita load calibration e save calibration
                    auto_calib = str(self.ui.calib_box.currentText())
                    if auto_calib == "Auto":
                        auto_calib = True
                    else:
                        auto_calib = False

                    port = ""
                    if ni == 0:
                        port = str(self.ui.head_device_box.currentText())
                    elif ni == 1:
                        port = str(self.ui.shoulder_device_box.currentText())

                    imu = acquisitionIMU.AcquisitionIMU(
                        port=port,
                        save_conf=str(
                            self.ui.save_box.currentText()) == "True",
                        auto_calib=auto_calib,
                        accelerometer=str(self.ui.accel_box.currentText()),
                        gyro=str(self.ui.gyro_box.currentText()),
                        algo=str(self.ui.algo_box.currentText()),
                        sample_rate=str(self.ui.rate_box.currentText()),
                        frameType=ni)
                if auto_calib:
                    msg = QtGui.QMessageBox()
                    msg.setIcon(QtGui.QMessageBox.Information)
                    msg.setText("IMU calibration is going to be performed")
                    msg.setInformativeText(
                        "Keep your head as still as possible")
                    msg.setWindowTitle("Calibration")
                    msg.setStandardButtons(QtGui.QMessageBox.Ok)
                    msg.exec_()
                imu.run()
                self.imu.append(imu)
        self.ui.sensor_label.setText("Connection established!")

        if self.ui.save_radio.isChecked():
            self.saveForm = saveForm(IMU=not self.ui.kinect_radio.isChecked())
            self.saveForm.setParent(self.ui.widget)
            self.saveForm.show()
            self.ui.widget.setVisible(True)
            self.connect(self.saveForm, QtCore.SIGNAL('calibrationRequest()'),
                         self.calibration)
        if self.ui.test_radio.isChecked():
            self.testForm = testForm()
            self.testForm.setParent(self.ui.widget)
            self.testForm.show()
            self.ui.widget.setVisible(True)
            self.connect(self.testForm, QtCore.SIGNAL('calibrationRequest()'),
                         self.calibration)

        self.timer.start(40)
        self.t_fps.start(500)

    def updateFPS(self):
        fps = self.fps / 0.500
        self.ui.labelFPS.setText("%.2f" % fps)
        self.fps = 0

    def resetGUI(self):
        image = np.zeros((self.ui.RGB_label.size().width(),
                          self.ui.RGB_label.size().height()))
        image = QtGui.QImage(image, image.shape[1], image.shape[0],
                             image.shape[1], QtGui.QImage.Format_Indexed8)

        pix = QtGui.QPixmap(image).scaled(self.ui.Depth_label.size())
        self.ui.Depth_label.setPixmap(pix)

        pix = QtGui.QPixmap(image).scaled(self.ui.RGB_label.size())
        self.ui.RGB_label.setPixmap(pix)

        self.ui.mainframe.hide()

    def resetHome(self):
        self.frame = frameSet()
        if self.saveForm is not None:
            if self.saveForm.process is not None:
                self.saveForm.process.kill()
                self.saveForm.process = None
            self.saveForm.close()
            self.saveForm = None

        if self.testForm is not None:
            self.testForm.close()
            self.testForm = None

        if self.kinect is not None:
            self.kinect.close()
            self.kinect = None

        # if self.imu is not None:
        #     self.imu.close()
        #     self.imu = None
        if len(self.imu) > 0:
            for imu in self.imu:
                imu.close()
            self.imu = []

        self.resetGUI()
        self.ui.mainframe.show()

    def checkChanged(self):
        if self.ui.kinect_imu_radio.isChecked() or self.ui.imu_radio.isChecked(
        ):
            self.ui.imu_settings_box.setEnabled(True)
        elif not self.ui.kinect_imu_radio.isChecked(
        ) and not self.ui.imu_radio.isChecked():
            self.ui.imu_settings_box.setEnabled(False)

        if (self.ui.save_radio.isChecked() or self.ui.test_radio.isChecked()
            ) and (self.ui.kinect_imu_radio.isChecked()
                   or self.ui.imu_radio.isChecked()
                   or self.ui.kinect_radio.isChecked()):
            self.ui.start_btn.setEnabled(True)
        else:
            self.ui.start_btn.setEnabled(False)

    def configChecked(self):
        if self.ui.default_config.isChecked():
            self.ui.frame_settings.setEnabled(False)
        else:
            self.ui.frame_settings.setEnabled(True)

    def acquireFrame(self):
        self.frame = frameSet()
        if self.kinect is not None:
            self.kinect.get_frame(self.frame)

        # if self.imu is not None:
        if len(self.imu) > 0:
            for nimu, imu in enumerate(self.imu):
                imu.get_frame(self.frame)
                if self.calib[nimu]:
                    self.emit(QtCore.SIGNAL('calibFrameAcquired()'))
                    if imu.calibrate(self.frame):
                        self.emit(QtCore.SIGNAL('calibFrameEnded()'))
                        self.calib[nimu] = False

        if self.saveForm is not None:
            self.saveForm.saveFrame(self.frame)

        if self.testForm is not None:
            self.testForm.showFrame(self.frame)

        self.updateUI()

    def updateUI(self):
        if self.frame.frameRGB is not None:
            image = cv2.cvtColor(self.frame.frameRGB, cv2.COLOR_BGRA2RGB)
            # image = self.frame.frameRGB
        else:
            image = np.zeros((self.ui.RGB_label.size().width(),
                              self.ui.RGB_label.size().height(), 3))
        image = QtGui.QImage(image, image.shape[1], image.shape[0],
                             image.shape[1] * 3, QtGui.QImage.Format_RGB888)
        pix = QtGui.QPixmap(image).scaled(self.ui.RGB_label.size())
        self.ui.RGB_label.setPixmap(pix)

        if self.frame.frameDepthQuantized is not None:
            image = cv2.cvtColor(self.frame.frameDepthQuantized,
                                 cv2.COLOR_GRAY2RGB)
            self.fps += 1
            if self.ui.save_radio.isChecked():
                if self.frame.body_tracked:
                    calibMatrix = np.array([[391.096, 0, 243.892],
                                            [0, 463.098, 208.922], [0, 0, 1]])
                    headCenter = self.frame.bodyJoints[3]
                    shoulderRightJoint = self.frame.bodyJoints[4]
                    shoulderLeftJoint = self.frame.bodyJoints[8]
                    R = 250.0
                    Z = self.frame.frameDepthQuantized[int(
                        headCenter.y), int(headCenter.x)] * 8 + 500
                    w = int(calibMatrix[0, 0] * R / Z)
                    h = int(calibMatrix[1, 1] * R / Z)
                    x1 = int(headCenter.x - w / 2)
                    y1 = int(headCenter.y - h / 2)
                    x2 = int(headCenter.x + w / 2)
                    y2 = int(headCenter.y + h / 2)
                    cv2.circle(image, (int(headCenter.x), int(headCenter.y)),
                               7, (0, 255, 0), -1)
                    cv2.circle(
                        image,
                        (int(shoulderRightJoint.x), int(shoulderRightJoint.y)),
                        7, (127, 0, 127), -1)
                    cv2.circle(
                        image,
                        (int(shoulderLeftJoint.x), int(shoulderLeftJoint.y)),
                        7, (127, 0, 127), -1)
                else:
                    h, w = image.shape[0:2]
                    x1 = int(w / 2 - w / 10)
                    y1 = int(h / 2 - h / 7)
                    x2 = int(w / 2 + w / 10)
                    y2 = int(h / 2 + h / 8)
                cv2.rectangle(image, (x1, y1), (x2, y2), (255, 0, 0), 2)
        else:
            image = np.zeros((self.ui.Depth_label.size().width(),
                              self.ui.Depth_label.size().height(), 3))
        image = QtGui.QImage(image, image.shape[1], image.shape[0],
                             image.shape[1] * 3, QtGui.QImage.Format_RGB888)
        pix = QtGui.QPixmap(image).scaled(self.ui.Depth_label.size())
        self.ui.Depth_label.setPixmap(pix)
예제 #10
0
class MainWindow(QtGui.QMainWindow):
    # signals
    start = QtCore.Signal()
    stop = QtCore.Signal()
    reset = QtCore.Signal()

    def __init__(self):
        self.app = QtGui.QApplication(sys.argv)
        self.app.setApplicationName("Plots! Plots! Plots!")

        self.app.setStyleSheet(qdarkstyle.load_stylesheet())
        # self.app.setStyle(QtGui.QGtkStyle())
        self.plotter = None
        self.state = {"started": False, "fullscreen": False}

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

        self.validateUi()
        self.addPlotWidget()
        self.setupGuiBindings()

    def validateUi(self):
        """
        Since mainwindow.py is generated from a UI file we run
        a few checks to validate the basic UI components are there
        """
        assert hasattr(self.ui, "startStopButton")
        assert hasattr(self.ui, "resetButton")

    def addPlotWidget(self):
        del self.ui.placeholder
        self.plotWidget = pg.GraphicsLayoutWidget()
        self.ui.horizontalLayout.addWidget(self.plotWidget)

        self.plotter = Plotter(self.plotWidget)
        self.plotter.setup()

    def setNbColumns(self, n):
        settings.PLOTS_PER_ROw = n
        self.plotter.refresh_grid()

    def setupGuiBindings(self):
        self.ui.startStopButton.clicked.connect(self.startStop)
        self.ui.resetButton.clicked.connect(self.plotter.clear)
        self.plotter.fpsMessage.connect(self.ui.statusbar.showMessage)

        # connect checkboxes with show/hide plots + titles
        for i in range(settings.NUMBER_OF_SENSORS):
            getattr(self.ui, "show{}".format(i + 1)).setText(settings.plots[i]["title"].format(index=i))
            getattr(self.ui, "show{}".format(i + 1)).stateChanged.connect(
                lambda state, i=i: self.plotter.set_show_plot(state, i)
            )

        ## menus
        self.ui.acqMode = QtGui.QActionGroup(self)
        self.ui.acqMode.addAction(self.ui.actionSerial_Acquisition)
        self.ui.acqMode.addAction(self.ui.actionFake_Acquisition)
        # default
        self.ui.actionFake_Acquisition.setChecked(True)

        # @todo add a real settings manager
        self.ui.columnsSpinBox.valueChanged.connect(self.setNbColumns)
        self.ui.showTiming.stateChanged.connect(lambda state: self.plotter.set_show_plot(state, "time"))
        self.ui.showMaster.stateChanged.connect(lambda state: self.plotter.set_show_plot(state, "master"))
        self.ui.showTitles.stateChanged.connect(self.plotter.set_show_title)

    @QtCore.Slot()
    def startStop(self):
        if self.state["started"]:
            self.stop.emit()
            self.ui.startStopButton.setText("Start")
        else:
            self.start.emit()
            self.ui.startStopButton.setText("Stop")

        self.state["started"] = not self.state["started"]

    def show(self):
        self.plotter.clear()
        super().show()
        return self.app.exec_()

    def fullscreen(self):
        if not "fullscreen" in self.state or not self.state["fullscreen"]:
            self.state["fullscreen"] = True
            self.ui.menubar.setVisible(False)
            self.ui.statusbar.setVisible(False)
            self.showFullScreen()
        else:
            self.state["fullscreen"] = False
            self.showNormal()
            self.ui.menubar.setVisible(True)
            self.ui.statusbar.setVisible(True)

    def keyPressEvent(self, e):
        if e.key() == QtCore.Qt.Key_F11:
            self.fullscreen()

    @property
    def plots(self):
        return self.plotter
예제 #11
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # 创建一个捕包的类 线程
        self.data_capture = Capture(self.ui.show_info_text)

        # 因为当数据改变是我们需要data_statistics发出相应的信号,这样我们就可以实现界面中
        # 数据的变化
        self.data_statistics = self.data_capture.rec.proto_restore.statistic

        # 捕包状态
        self.cap_state = False
        self.init_widget()

    def init_widget(self):
        '''
        对主窗口的widget进行初始化,包括初始化widget数据,以及进行事件的绑定。
        :return:
        '''
        # 点击开始捕包按钮进行捕包
        self.ui.start_cap_b.clicked.connect(self.start_capture)

        self.ui.config_b.clicked.connect(self.show_config)

        self.ui.block_b.clicked.connect(self.show_block)

        self.ui.index_b.clicked.connect(self.show_index_pollution)

        # self.ui.block_b.clicked.connect(self.data_statistics.block)

        # 点击tracker信息显示tracker的相关信息
        self.ui.show_tracker_info_b.clicked.connect(self.show_tracker_info)

        # 点击peers信息显示peers的相关信息
        self.ui.show_peers_info_b.clicked.connect(self.show_peers_info)

        # self.data_statistic.signal.connect(event)
        # 以下代码仅是个例子
        #
        self.data_statistics.tracker_pkt_cnt_changed.connect(self.change_track_pkt_cnt)

        self.data_statistics.peer_pkt_cnt_changed.connect(self.change_peer_pkt_cnt)

        self.data_statistics.tracker_info_changed.connect(self.show_tracker_info)

        self.data_statistics.peer_info_changed.connect(self.show_peers_info)
        #self.data_statistics.peer_pkt_cnt_changed

    def show_config(self):
        self.config_window = ConfigWindow()
        self.config_window.show()

    def show_block(self):
        self.block_window = BlockWindow()
        self.block_window.show()

    def show_index_pollution(self):
        self.index_pollution_window = IndexPollutionWindow()
        self.index_pollution_window.show()

    def start_capture(self):
        '''
        当点击开始捕包按钮时进行捕包
        :return:
        '''
        if self.cap_state is False:
            self.ui.show_info_text.append('start capturing!')
            # print('start capturing!')
            self.cap_state = True
            self.data_capture.start()
            _translate = QtCore.QCoreApplication.translate
            self.ui.start_cap_b.setText(_translate("MainWindow", "停止捕包"))

        else:
            self.ui.show_info_text.append('stop capturing!')
            # print('stop capturing!')
            self.cap_state = False
            _translate = QtCore.QCoreApplication.translate
            self.ui.start_cap_b.setText(_translate("MainWindow", "开始捕包"))
            self.data_capture.stop_capture()

    def show_tracker_info(self):
        '''
        点击tracker信息按钮是展示tracker的信息
        :return:
        '''
        # print('show tracker info!')
        _translate = QtCore.QCoreApplication.translate
        # print(self.data_statistics.tracker_stat)
        for row, stat in zip(range(len(self.data_statistics.tracker_stat.values())), self.data_statistics.tracker_stat.values()):
            for column, i in zip(range(6), stat.get_info_list()):
                item = QtWidgets.QTableWidgetItem()
                self.ui.tableWidget.setItem(row, column, item)
                item = self.ui.tableWidget.item(row, column)
                item.setText(_translate("MainWindow", str(i)))

    def show_peers_info(self):
        '''
        点击peer信息按钮时展示peers的信息
        :return:
        '''
        # print('show peers info1')
        _translate = QtCore.QCoreApplication.translate
        # print(self.data_statistics.peer_stat)
        for row, stat in zip(range(len(self.data_statistics.peer_stat.values())),
                             self.data_statistics.peer_stat.values()):
            for column, i in zip(range(6), stat.get_info_list()):
                item = QtWidgets.QTableWidgetItem()
                self.ui.tableWidget_2.setItem(row, column, item)
                item = self.ui.tableWidget_2.item(row, column)
                item.setText(_translate("MainWindow", str(i)))
        pass

    def change_track_pkt_cnt(self, req_cnt, res_cnt):
        self.ui.tracker_req_line.setText(str(req_cnt))
        self.ui.tracker_res_line.setText(str(res_cnt))
    #
    def change_peer_pkt_cnt(self, hs_cnt, msg_cnt):
        self.ui.peer_hs_line.setText(str(hs_cnt))
        self.ui.peer_msg_line.setText(str(msg_cnt))
예제 #12
0
class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)

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

        self.ui.pb_models.clicked.connect(self.models_changed)
        self.ui.pb_models_2.clicked.connect(self.models_predefined)
        self.ui.pb_plot.clicked.connect(self.plot_results)
        self.ui.pb_plot_diff.clicked.connect(self.plot_differences)

        self.ui.pb_models.clicked.connect(
            lambda: self.ui.stackedWidget.setCurrentIndex(2))
        self.ui.pb_models_2.clicked.connect(
            lambda: self.ui.stackedWidget.setCurrentIndex(2))

        self.ui.pb_select.clicked.connect(
            lambda: self.ui.stackedWidget.setCurrentIndex(0))
        self.ui.pb_select_2.clicked.connect(
            lambda: self.ui.stackedWidget.setCurrentIndex(1))

        self.ui.pb_filepath_selec.clicked.connect(
            lambda: self.ui.stackedWidget.setCurrentIndex(0))
        self.ui.pb_selection.clicked.connect(
            lambda: self.ui.stackedWidget.setCurrentIndex(1))

        self.ui.cbx_cat_c1.currentTextChanged.connect(self.cat_c1_changed)
        self.ui.cbx_cat_c2.currentTextChanged.connect(self.cat_c2_changed)
        self.ui.cbx_cat_c3.currentTextChanged.connect(self.cat_c3_changed)
        self.ui.cbx_cat_c4.currentTextChanged.connect(self.cat_c4_changed)

        self.ui.cbx_inp_depth_m1.currentTextChanged.connect(
            self.model1_input_change)
        self.ui.cbx_inp_depth_m2.currentTextChanged.connect(
            self.model2_input_change)


# input Models

    def models_changed(self):
        self.ui.cbx_mod1.clear()
        self.ui.cbx_mod2.clear()

        model1 = self.ui.input_model1.text()
        model2 = self.ui.input_model2.text()

        models = [str(model1), str(model2)]

        self.ui.cbx_mod1.addItems(models)
        self.ui.cbx_mod2.addItems(models)

        self.ui.radb_freesel.setChecked(True)

    def models_predefined(self):
        self.ui.cbx_mod1.clear()
        self.ui.cbx_mod2.clear()

        model1 = self.ui.cbx_inp_model_m1.currentText()
        model1_ls = self.ui.cbx_inp_loadstep_m1.currentText()
        model2 = self.ui.cbx_inp_model_m2.currentText()
        model1_2s = self.ui.cbx_inp_loadstep_m2.currentText()

        models = [str(model1 + '_' + model1_ls), str(model2 + '_' + model1_2s)]

        self.ui.cbx_mod1.addItems(models)
        self.ui.cbx_mod2.addItems(models)

        self.ui.radb_predsel.setChecked(True)

    def cat_c1_changed(self):
        self.ui.cbx_scat_c1.clear()

        cat1 = self.ui.cbx_cat_c1.currentText()
        res_pres = ['-']
        res_u = ['x', 'y', 'z']
        res_str = [
            'tot', 's1', 's2', 's3', 'sxx', 'syy', 'szz', 'sxy', 'syz', 'sxz'
        ]

        if cat1 == "pressure":
            self.ui.cbx_scat_c1.addItems(res_pres)
        elif cat1 == "u":
            self.ui.cbx_scat_c1.addItems(res_u)
        elif cat1 == "stress":
            self.ui.cbx_scat_c1.addItems(res_str)
        elif cat1 == "estress":
            self.ui.cbx_scat_c1.addItems(res_str)
        elif cat1 == "el. strain":
            self.ui.cbx_scat_c1.addItems(res_str)
        elif cat1 == "pl. strain":
            self.ui.cbx_scat_c1.addItems(res_str)
        elif cat1 == "tot. strain":
            self.ui.cbx_scat_c1.addItems(res_str)
        else:
            self.ui.cbx_scat_c1.addItems(" ")

    def cat_c2_changed(self):
        self.ui.cbx_scat_c2.clear()

        cat1 = self.ui.cbx_cat_c2.currentText()
        res_pres = ['-']
        res_u = ['x', 'y', 'z']
        res_str = [
            'tot', 's1', 's2', 's3', 'sxx', 'syy', 'szz', 'sxy', 'syz', 'sxz'
        ]

        if cat1 == "pressure":
            self.ui.cbx_scat_c2.addItems(res_pres)
        elif cat1 == "u":
            self.ui.cbx_scat_c2.addItems(res_u)
        elif cat1 == "stress":
            self.ui.cbx_scat_c2.addItems(res_str)
        elif cat1 == "estress":
            self.ui.cbx_scat_c2.addItems(res_str)
        elif cat1 == "el. strain":
            self.ui.cbx_scat_c2.addItems(res_str)
        elif cat1 == "pl. strain":
            self.ui.cbx_scat_c2.addItems(res_str)
        elif cat1 == "tot. strain":
            self.ui.cbx_scat_c2.addItems(res_str)
        else:
            self.ui.cbx_scat_c2.addItems(" ")

    def cat_c3_changed(self):
        self.ui.cbx_scat_c3.clear()

        cat1 = self.ui.cbx_cat_c3.currentText()
        res_pres = ['-']
        res_u = ['x', 'y', 'z']
        res_str = [
            'tot', 's1', 's2', 's3', 'sxx', 'syy', 'szz', 'sxy', 'syz', 'sxz'
        ]

        if cat1 == "pressure":
            self.ui.cbx_scat_c3.addItems(res_pres)
        elif cat1 == "u":
            self.ui.cbx_scat_c3.addItems(res_u)
        elif cat1 == "stress":
            self.ui.cbx_scat_c3.addItems(res_str)
        elif cat1 == "estress":
            self.ui.cbx_scat_c3.addItems(res_str)
        elif cat1 == "el. strain":
            self.ui.cbx_scat_c3.addItems(res_str)
        elif cat1 == "pl. strain":
            self.ui.cbx_scat_c3.addItems(res_str)
        elif cat1 == "tot. strain":
            self.ui.cbx_scat_c3.addItems(res_str)
        else:
            self.ui.cbx_scat_c3.addItems(" ")

    def cat_c4_changed(self):
        self.ui.cbx_scat_c4.clear()

        cat1 = self.ui.cbx_cat_c4.currentText()
        res_pres = ['-']
        res_u = ['x', 'y', 'z']
        res_str = [
            'tot', 's1', 's2', 's3', 'sxx', 'syy', 'szz', 'sxy', 'syz', 'sxz'
        ]

        if cat1 == "pressure":
            self.ui.cbx_scat_c4.addItems(res_pres)
        elif cat1 == "u":
            self.ui.cbx_scat_c4.addItems(res_u)
        elif cat1 == "stress":
            self.ui.cbx_scat_c4.addItems(res_str)
        elif cat1 == "estress":
            self.ui.cbx_scat_c4.addItems(res_str)
        elif cat1 == "el. strain":
            self.ui.cbx_scat_c4.addItems(res_str)
        elif cat1 == "pl. strain":
            self.ui.cbx_scat_c4.addItems(res_str)
        elif cat1 == "tot. strain":
            self.ui.cbx_scat_c4.addItems(res_str)
        else:
            self.ui.cbx_scat_c4.addItems(" ")

    def model1_input_change(self):

        self.ui.cbx_inp_model_m1.clear()

        depth1 = self.ui.cbx_inp_depth_m1.currentText()

        if depth1 == "Mod1":
            self.ui.cbx_inp_model_m1.addItems(mod1key)
        elif depth1 == "Mod2":
            self.ui.cbx_inp_model_m1.addItems(mod2key)
        else:
            self.ui.cbx_inp_model_m1.addItems(" ")

    def model2_input_change(self):

        self.ui.cbx_inp_model_m2.clear()

        depth2 = self.ui.cbx_inp_depth_m2.currentText()

        if depth2 == "Mod1":
            self.ui.cbx_inp_model_m2.addItems(mod1key)
        elif depth2 == "Mod2":
            self.ui.cbx_inp_model_m2.addItems(mod2key)
        else:
            self.ui.cbx_inp_model_m2.addItems(" ")

    def plot_results(self):
        user_cat_c1 = self.ui.cbx_cat_c1.currentText()
        user_cat_c2 = self.ui.cbx_cat_c2.currentText()
        user_cat_c3 = self.ui.cbx_cat_c3.currentText()
        user_cat_c4 = self.ui.cbx_cat_c4.currentText()

        user_subcat_c1 = self.ui.cbx_scat_c1.currentText()
        user_subcat_c2 = self.ui.cbx_scat_c2.currentText()
        user_subcat_c3 = self.ui.cbx_scat_c3.currentText()
        user_subcat_c4 = self.ui.cbx_scat_c4.currentText()

        user_cshades_c1 = int(self.ui.cshades_c1.value())
        user_cshades_c2 = int(self.ui.cshades_c2.value())
        user_cshades_c3 = int(self.ui.cshades_c3.value())
        user_cshades_c4 = int(self.ui.cshades_c4.value())

        user_colormap = str(self.ui.cbx_legend.currentText())
        user_resolution = int(self.ui.resolution.value())

        key_f1 = user_cat_c1 + '-' + user_subcat_c1
        key_f2 = user_cat_c2 + '-' + user_subcat_c2
        key_f3 = user_cat_c3 + '-' + user_subcat_c3
        key_f4 = user_cat_c4 + '-' + user_subcat_c4

        xi = np.linspace(-500, 500, user_resolution)
        yi = np.linspace(-500, 500, user_resolution)

        user_mod1 = self.ui.cbx_mod1.currentText()
        user_mod2 = self.ui.cbx_mod2.currentText()

        if self.ui.radb_freesel.isChecked():

            user_folderpath_m1 = self.ui.input_folder_m1.text()
            user_folderpath_m2 = self.ui.input_folder_m2.text()

            model1 = self.ui.input_model1.text()
            model2 = self.ui.input_model2.text()

            if self.ui.checkbox_folder_m1.isChecked():
                model_path_m1 = user_folderpath_m1 + '/' + model1 + '/'
            else:
                model_path_m1 = 'input_files/' + model1 + '/'

            if self.ui.checkbox_folder_m2.isChecked():
                model_path_m2 = user_folderpath_m2 + '/' + model2 + '/'
            else:
                model_path_m2 = 'input_files/' + model2 + '/'

            if user_mod1 == model1 and user_mod2 == model2:
                model_path1 = model_path_m1
                model_path2 = model_path_m2
            elif user_mod2 == model1 and user_mod1 == model2:
                model_path1 = model_path_m2
                model_path2 = model_path_m1
            elif user_mod1 == model1 and user_mod2 == model1:
                model_path1 = model_path_m1
                model_path2 = model_path_m1
            elif user_mod1 == model2 and user_mod2 == model2:
                model_path1 = model_path_m2
                model_path2 = model_path_m2

        elif self.ui.radb_predsel.isChecked():

            depth_m1 = self.ui.cbx_inp_depth_m1.currentText()
            depth_m2 = self.ui.cbx_inp_depth_m2.currentText()

            loadstep_m1 = self.ui.cbx_inp_loadstep_m1.currentText()
            loadstep_m2 = self.ui.cbx_inp_loadstep_m2.currentText()

            model1 = self.ui.cbx_inp_model_m1.currentText()
            model2 = self.ui.cbx_inp_model_m2.currentText()

            model_path_m1 = predef_paths(depth_m1, model1, loadstep_m1)
            model_path_m2 = predef_paths(depth_m2, model2, loadstep_m2)

            comp_m1 = model1 + '_' + loadstep_m1
            comp_m2 = model2 + '_' + loadstep_m2

            if user_mod1 == comp_m1 and user_mod2 == comp_m2:
                model_path1 = model_path_m1
                model_path2 = model_path_m2
            elif user_mod2 == comp_m1 and user_mod1 == comp_m2:
                model_path1 = model_path_m2
                model_path2 = model_path_m1
            elif user_mod1 == comp_m1 and user_mod2 == comp_m1:
                model_path1 = model_path_m1
                model_path2 = model_path_m1
            elif user_mod1 == comp_m2 and user_mod2 == comp_m2:
                model_path1 = model_path_m2
                model_path2 = model_path_m2

        # Calculations
        results_mod1 = ans_csvdataimp_complete(model_path1)
        results_mod2 = ans_csvdataimp_complete(model_path2)

        xval_f1_m1, yval_f1_m1, zval_f1_m1, chead_f1_m1, output_title_f1_m1 = plot_df(
            results_mod1, input_output, key_f1)
        xval_f2_m1, yval_f2_m1, zval_f2_m1, chead_f2_m1, output_title_f2_m1 = plot_df(
            results_mod1, input_output, key_f2)
        xval_f3_m1, yval_f3_m1, zval_f3_m1, chead_f3_m1, output_title_f3_m1 = plot_df(
            results_mod1, input_output, key_f3)
        xval_f4_m1, yval_f4_m1, zval_f4_m1, chead_f4_m1, output_title_f4_m1 = plot_df(
            results_mod1, input_output, key_f4)

        xval_f1_m2, yval_f1_m2, zval_f1_m2, chead_f1_m2, output_title_f1_m2 = plot_df(
            results_mod2, input_output, key_f1)
        xval_f2_m2, yval_f2_m2, zval_f2_m2, chead_f2_m2, output_title_f2_m2 = plot_df(
            results_mod2, input_output, key_f2)
        xval_f3_m2, yval_f3_m2, zval_f3_m2, chead_f3_m2, output_title_f3_m2 = plot_df(
            results_mod2, input_output, key_f3)
        xval_f4_m2, yval_f4_m2, zval_f4_m2, chead_f4_m2, output_title_f4_m2 = plot_df(
            results_mod2, input_output, key_f4)

        min_f1, max_f1 = graduation(results_mod1, results_mod2, input_output,
                                    key_f1)
        min_f2, max_f2 = graduation(results_mod1, results_mod2, input_output,
                                    key_f2)
        min_f3, max_f3 = graduation(results_mod1, results_mod2, input_output,
                                    key_f3)
        min_f4, max_f4 = graduation(results_mod1, results_mod2, input_output,
                                    key_f4)

        user_graduation_f1 = np.linspace(min_f1,
                                         max_f1,
                                         user_cshades_c1,
                                         endpoint=True)
        user_graduation_f2 = np.linspace(min_f2,
                                         max_f2,
                                         user_cshades_c2,
                                         endpoint=True)
        user_graduation_f3 = np.linspace(min_f3,
                                         max_f3,
                                         user_cshades_c3,
                                         endpoint=True)
        user_graduation_f4 = np.linspace(min_f4,
                                         max_f4,
                                         user_cshades_c4,
                                         endpoint=True)

        colm = colormap(user_colormap)

        fig = plt.figure(constrained_layout=True, figsize=(18, 9))

        spec = gridspec.GridSpec(ncols=4, nrows=2, figure=fig)

        # figure 1

        f1_ax1 = fig.add_subplot(spec[0, 0])
        # Contour plot
        zi = griddata((xval_f1_m1, yval_f1_m1),
                      zval_f1_m1, (xi[None, :], yi[:, None]),
                      method='linear')
        cf_f1_1 = plt.contourf(xi, yi, zi, user_graduation_f1, cmap=colm)

        f1_ax1.axes.get_xaxis().set_visible(False)  # Achsen unsichtbar machen

        plt.ylabel(user_mod1)

        plt.title(output_title_f1_m1)

        f1_ax2 = fig.add_subplot(spec[1, 0])
        # Contour plot
        zi = griddata((xval_f1_m2, yval_f1_m2),
                      zval_f1_m2, (xi[None, :], yi[:, None]),
                      method='linear')
        cf_f1_2 = plt.contourf(xi, yi, zi, user_graduation_f1, cmap=colm)

        plt.ylabel(user_mod2)

        fig.colorbar(cf_f1_1, location='bottom')

        # figure 2

        f2_ax1 = fig.add_subplot(spec[0, 1])
        zi = griddata((xval_f2_m1, yval_f2_m1),
                      zval_f2_m1, (xi[None, :], yi[:, None]),
                      method='linear')
        cf_f2_1 = plt.contourf(xi, yi, zi, user_graduation_f2, cmap=colm)

        f2_ax1.axes.get_xaxis().set_visible(False)
        f2_ax1.axes.get_yaxis().set_visible(False)

        plt.title(output_title_f2_m1)

        f2_ax2 = fig.add_subplot(spec[1, 1])
        # Contour plot
        zi = griddata((xval_f2_m2, yval_f2_m2),
                      zval_f2_m2, (xi[None, :], yi[:, None]),
                      method='linear')
        cf_f2_2 = plt.contourf(xi, yi, zi, user_graduation_f2, cmap=colm)

        f2_ax2.axes.get_yaxis().set_visible(False)

        fig.colorbar(cf_f2_1, location='bottom')

        # figure 3

        f3_ax1 = fig.add_subplot(spec[0, 2])
        zi = griddata((xval_f3_m1, yval_f3_m1),
                      zval_f3_m1, (xi[None, :], yi[:, None]),
                      method='linear')
        cf_f3_1 = plt.contourf(xi, yi, zi, user_graduation_f3, cmap=colm)

        f3_ax1.axes.get_xaxis().set_visible(False)
        f3_ax1.axes.get_yaxis().set_visible(False)

        plt.title(output_title_f3_m1)

        f3_ax2 = fig.add_subplot(spec[1, 2])
        zi = griddata((xval_f3_m2, yval_f3_m2),
                      zval_f3_m2, (xi[None, :], yi[:, None]),
                      method='linear')
        cf_f3_2 = plt.contourf(xi, yi, zi, user_graduation_f3, cmap=colm)

        f3_ax2.axes.get_yaxis().set_visible(False)

        fig.colorbar(cf_f3_1, location='bottom')

        # figure 4

        f4_ax1 = fig.add_subplot(spec[0, 3])
        # Contour plot
        zi = griddata((xval_f4_m1, yval_f4_m1),
                      zval_f4_m1, (xi[None, :], yi[:, None]),
                      method='linear')
        cf_f4_1 = plt.contourf(xi, yi, zi, user_graduation_f4, cmap=colm)

        f4_ax1.axes.get_xaxis().set_visible(False)
        f4_ax1.axes.get_yaxis().set_visible(False)

        plt.title(output_title_f4_m1)

        f4_ax2 = fig.add_subplot(spec[1, 3])
        zi = griddata((xval_f4_m2, yval_f4_m2),
                      zval_f4_m2, (xi[None, :], yi[:, None]),
                      method='linear')
        cf_f4_2 = plt.contourf(xi, yi, zi, user_graduation_f4, cmap=colm)

        f4_ax2.axes.get_yaxis().set_visible(False)

        fig.colorbar(cf_f4_1, location='bottom')

        plt.show()

    def plot_differences(self):
        user_cat_c1 = self.ui.cbx_cat_c1.currentText()
        user_cat_c2 = self.ui.cbx_cat_c2.currentText()
        user_cat_c3 = self.ui.cbx_cat_c3.currentText()
        user_cat_c4 = self.ui.cbx_cat_c4.currentText()

        user_subcat_c1 = self.ui.cbx_scat_c1.currentText()
        user_subcat_c2 = self.ui.cbx_scat_c2.currentText()
        user_subcat_c3 = self.ui.cbx_scat_c3.currentText()
        user_subcat_c4 = self.ui.cbx_scat_c4.currentText()

        user_cshades_c1 = int(self.ui.cshades_c1.value())
        user_cshades_c2 = int(self.ui.cshades_c2.value())
        user_cshades_c3 = int(self.ui.cshades_c3.value())
        user_cshades_c4 = int(self.ui.cshades_c4.value())

        user_colormap = str(self.ui.cbx_legend.currentText())
        user_resolution = int(self.ui.resolution.value())

        key_f1 = user_cat_c1 + '-' + user_subcat_c1
        key_f2 = user_cat_c2 + '-' + user_subcat_c2
        key_f3 = user_cat_c3 + '-' + user_subcat_c3
        key_f4 = user_cat_c4 + '-' + user_subcat_c4

        xi = np.linspace(-500, 500, user_resolution)
        yi = np.linspace(-500, 500, user_resolution)

        user_mod1 = self.ui.cbx_mod1.currentText()
        user_mod2 = self.ui.cbx_mod2.currentText()

        label_diff = 'Difference: ' + str(user_mod2) + ' - ' + str(user_mod1)

        if self.ui.radb_freesel.isChecked():

            user_folderpath_m1 = self.ui.input_folder_m1.text()
            user_folderpath_m2 = self.ui.input_folder_m2.text()

            model1 = self.ui.input_model1.text()
            model2 = self.ui.input_model2.text()

            if self.ui.checkbox_folder_m1.isChecked():
                model_path_m1 = user_folderpath_m1 + '/' + model1 + '/'
            else:
                model_path_m1 = 'input_files/' + model1 + '/'

            if self.ui.checkbox_folder_m2.isChecked():
                model_path_m2 = user_folderpath_m2 + '/' + model2 + '/'
            else:
                model_path_m2 = 'input_files/' + model2 + '/'

            if user_mod1 == model1 and user_mod2 == model2:
                model_path1 = model_path_m1
                model_path2 = model_path_m2
            elif user_mod2 == model1 and user_mod1 == model2:
                model_path1 = model_path_m2
                model_path2 = model_path_m1
            elif user_mod1 == model1 and user_mod2 == model1:
                model_path1 = model_path_m1
                model_path2 = model_path_m1
            elif user_mod1 == model2 and user_mod2 == model2:
                model_path1 = model_path_m2
                model_path2 = model_path_m2

        elif self.ui.radb_predsel.isChecked():

            depth_m1 = self.ui.cbx_inp_depth_m1.currentText()
            depth_m2 = self.ui.cbx_inp_depth_m2.currentText()

            loadstep_m1 = self.ui.cbx_inp_loadstep_m1.currentText()
            loadstep_m2 = self.ui.cbx_inp_loadstep_m2.currentText()

            model1 = self.ui.cbx_inp_model_m1.currentText()
            model2 = self.ui.cbx_inp_model_m2.currentText()

            model_path_m1 = predef_paths(depth_m1, model1, loadstep_m1)
            model_path_m2 = predef_paths(depth_m2, model2, loadstep_m2)

            comp_m1 = model1 + '_' + loadstep_m1
            comp_m2 = model2 + '_' + loadstep_m2

            if user_mod1 == comp_m1 and user_mod2 == comp_m2:
                model_path1 = model_path_m1
                model_path2 = model_path_m2
            elif user_mod2 == comp_m1 and user_mod1 == comp_m2:
                model_path1 = model_path_m2
                model_path2 = model_path_m1
            elif user_mod1 == comp_m1 and user_mod2 == comp_m1:
                model_path1 = model_path_m1
                model_path2 = model_path_m1
            elif user_mod1 == comp_m2 and user_mod2 == comp_m2:
                model_path1 = model_path_m2
                model_path2 = model_path_m2

        # Calculations
        results_mod1 = ans_csvdataimp_complete(model_path1)
        results_mod2 = ans_csvdataimp_complete(model_path2)

        xval_f1_diff1, yval_f1_diff1, zval_f1_diff1, chead_f1_diff1, output_title_f1_diff1, min_diff_f1, max_diff_f1 = plot_diff_df(
            results_mod1, results_mod2, input_output, key_f1)
        xval_f2_diff1, yval_f2_diff1, zval_f2_diff1, chead_f2_diff1, output_title_f2_diff1, min_diff_f2, max_diff_f2 = plot_diff_df(
            results_mod1, results_mod2, input_output, key_f2)
        xval_f3_diff1, yval_f3_diff1, zval_f3_diff1, chead_f3_diff1, output_title_f3_diff1, min_diff_f3, max_diff_f3 = plot_diff_df(
            results_mod1, results_mod2, input_output, key_f3)
        xval_f4_diff1, yval_f4_diff1, zval_f4_diff1, chead_f4_diff1, output_title_f4_diff1, min_diff_f4, max_diff_f4 = plot_diff_df(
            results_mod1, results_mod2, input_output, key_f4)

        user_graduation_diff_f1 = np.linspace(min_diff_f1,
                                              max_diff_f1,
                                              user_cshades_c1,
                                              endpoint=True)
        user_graduation_diff_f2 = np.linspace(min_diff_f2,
                                              max_diff_f2,
                                              user_cshades_c2,
                                              endpoint=True)
        user_graduation_diff_f3 = np.linspace(min_diff_f3,
                                              max_diff_f3,
                                              user_cshades_c3,
                                              endpoint=True)
        user_graduation_diff_f4 = np.linspace(min_diff_f4,
                                              max_diff_f4,
                                              user_cshades_c4,
                                              endpoint=True)

        colm = colormap(user_colormap)

        fig_diff = plt.figure(constrained_layout=True, figsize=(18, 4.5))

        spec_diff = gridspec.GridSpec(ncols=4, nrows=1, figure=fig_diff)
        fig_diff.suptitle(label_diff, fontsize=10)

        # figure 1

        f1_diff_ax1 = fig_diff.add_subplot(spec_diff[0, 0])
        # Contour plot
        zi = griddata((xval_f1_diff1, yval_f1_diff1),
                      zval_f1_diff1, (xi[None, :], yi[:, None]),
                      method='linear')
        cf_f1_1 = plt.contourf(xi, yi, zi, user_graduation_diff_f1, cmap=colm)

        plt.ylabel('differences')

        plt.title(output_title_f1_diff1)
        fig_diff.colorbar(cf_f1_1, location='bottom')

        # figure 2

        f2_diff_ax1 = fig_diff.add_subplot(spec_diff[0, 1])
        zi = griddata((xval_f2_diff1, yval_f2_diff1),
                      zval_f2_diff1, (xi[None, :], yi[:, None]),
                      method='linear')
        cf_f2_1 = plt.contourf(xi, yi, zi, user_graduation_diff_f2, cmap=colm)

        f2_diff_ax1.axes.get_yaxis().set_visible(False)

        plt.title(output_title_f2_diff1)

        fig_diff.colorbar(cf_f2_1, location='bottom')

        # figure 3

        f3_diff_ax1 = fig_diff.add_subplot(spec_diff[0, 2])
        zi = griddata((xval_f3_diff1, yval_f3_diff1),
                      zval_f3_diff1, (xi[None, :], yi[:, None]),
                      method='linear')
        cf_f3_1 = plt.contourf(xi, yi, zi, user_graduation_diff_f3, cmap=colm)

        f3_diff_ax1.axes.get_yaxis().set_visible(False)

        plt.title(output_title_f3_diff1)

        fig_diff.colorbar(cf_f3_1, location='bottom')

        # figure 4

        f4_diff_ax1 = fig_diff.add_subplot(spec_diff[0, 3])
        # Contour plot
        zi = griddata((xval_f4_diff1, yval_f4_diff1),
                      zval_f4_diff1, (xi[None, :], yi[:, None]),
                      method='linear')
        cf_f4_1 = plt.contourf(xi, yi, zi, user_graduation_diff_f4, cmap=colm)

        f4_diff_ax1.axes.get_yaxis().set_visible(False)

        plt.title(output_title_f4_diff1)

        fig_diff.colorbar(cf_f4_1, location='bottom')

        plt.show()
예제 #13
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        # Set up the user interface from Designer.
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setWindowTitle("Kepler Manager")

        self.viewer = Viewer()
        self.viewer3d = Viewer3D()
        self.tableViewer = TableViewer()
        self.caldialog = CalDialog()
        self.errdialog = ErrDialog()
        self.cal_stop = False

        regexp = QRegExp("[0-9e\.\+\-\*\(\)/]*")
        validator = QRegExpValidator(regexp)

        self.ui.lineEdit_G.setValidator(validator)
        self.ui.lineEdit_TimeIncrement.setValidator(validator)
        self.ui.lineEdit_StopTime.setValidator(validator)
        #self.ui.actionAbout_Kepler.triggered.connect(self.about_Kepler)
        #self.ui.actionPreference.triggered.connect(self.preference)
        self.ui.actionSave.triggered.connect(self.save_file)
        self.ui.actionLoad_your_settings.triggered.connect(self.load_file)
        self.ui.actionLoad_SOL.triggered.connect(self.load_SOL)
        self.ui.actionViewer.triggered.connect(self.open_viewer)
        #self.ui.actionTable_Viewer.triggered.connect(self.open_tableviewer)
        #self.ui.actionHow_to_use.triggered.connect(self.show_help)
        #self.ui.actionHow_does_this_work.triggered.connect(self.show_mechanism)

        #self.ui.comboBox_Choose2Dor3D.currentIndexChanged.connect(self.choose2dor3d)
        self.ui.pushButton_AddPlanet.clicked.connect(self.add_planet)
        self.ui.pushButton_DeletePlanet.clicked.connect(self.remove_planets)

        self.ui.lineEdit_G.setText("6.674e-11")

        self.ui.pushButton_Calc.clicked.connect(self.calc)

        self.planets_attribute = TreeViewModel()
        self.planets = Planet_system()
        self.resultcontainer = ResultContainer()

        self.ui.treeView_PlanetAttribute.setModel(self.planets_attribute)
        self.ui.treeView_PlanetAttribute.setItemDelegate(Delegate())

    def add_planet(self):
        self.planets_attribute.addRow("","0","0","0","0","0","0","0")

    def add_planet_from_f(self, name, mass, x0, y0, z0, vx0, vy0, vz0):
        self.planets_attribute.addRow(name, mass, x0, y0, z0, vx0, vy0, vz0)

    def selected_rows(self):
        rows = []
        for index in self.ui.treeView_PlanetAttribute.selectedIndexes():
            if index.column() == 0:
                rows.append(index.row())
        return rows

    def remove_planets(self):
        self.planets_attribute.removeRows(self.selected_rows())

    def calc(self):
        if self.ui.lineEdit_G.text() == ""\
           or self.ui.lineEdit_TimeIncrement.text() == ""\
           or self.ui.lineEdit_StopTime.text() == "":
            pass
        elif self.planets_attribute.chk_duplicate():
            self.errdialog.setWindowTitle("Error Message")
            self.errdialog.ui.label_ErrMSG.setText("Initial position is a duplicate")
            self.errdialog.show()
            self.errdialog.ui.pushButton_ErrOK.clicked.connect(self.errdialog.close)
            pass
        elif self.planets_attribute.chk_filled():
            pass
        else:
            for i in range(len(self.planets)):
                self.planets.del_planet(-1)
            dt = float(eval(self.ui.lineEdit_TimeIncrement.text()))
            end = float(eval(self.ui.lineEdit_StopTime.text()))
            sum_step = int(end // dt + 1)
            G = float(eval(self.ui.lineEdit_G.text()))
            if len(self.planets_attribute.items) >= 2:
                self.caldialog.ui.progressBar_Cal.setRange(0, sum_step)
                self.caldialog.ui.pushButton_CalStop.clicked.connect(self.cal_rupt)
                self.caldialog.show()
                if self.ui.comboBox_Choose2Dor3D.currentText() == "2D":
                    for i in range(len(self.planets_attribute.items)):
                        name, mass, x0, y0, z0, vx0, vy0, vz0 = self.planets_attribute.values(i)
                        self.planets.add_planet(name, mass, x0, y0, z0, vx0, vy0, vz0)
                    for i in range(sum_step):
                        if self.cal_stop:
                            for k in range(len(self.planets)):
                                del self.planets[k]
                            self.caldialog.close()
                            self.cal_stop = False
                            break
                        self.caldialog.ui.progressBar_Cal.setValue(i)
                        RK4(self.planets, dt, i, G)
                        #print(i)
                    self.resultcontainer.load_from_ps(dt, end, True, self.planets)
                    self.caldialog.close()
                    self.open_viewer()
                    self.viewer.set_result(self.resultcontainer.results)

                else:
                    for i in range(len(self.planets_attribute.items)):
                        name, mass, x0, y0, z0, vz0, vy0, vz0 = self.planets_attribute.values(i)
                        self.planets.add_planet(name, mass, x0, y0, z0, vz0, vy0, vz0)
                    for i in range(sum_step):
                        if self.cal_stop:
                            for k in range(len(self.planets)):
                                del self.planets[k]
                            self.caldialog.close()
                            self.cal_stop = False
                            break
                        self.caldialog.ui.progressBar_Cal.setValue(i)
                        RK4z(self.planets, dt, i, G)
                    self.resultcontainer.load_from_ps(dt, end, False, self.planets)
                    self.caldialog.close()
                    self.open_viewer()
                    self.viewer.set_result(self.resultcontainer.results)
            else:
                pass

    def load_file(self):
        filedialog = QFileDialog()
        filedialog.setDirectory("./settings")
        filepath = filedialog.getOpenFileName(filter="Kepler Planet Settings (*.kps)")
        if filepath == "":
            pass
        else:
            with open(filepath, "r") as f:
                file = json.load(f)
            self.planets_attribute.items = []
            for i in range(len(file)):
                self.add_planet_from_f(file[i][0],\
                                       file[i][1],\
                                       file[i][2],\
                                       file[i][3],\
                                       file[i][4],\
                                       file[i][5],\
                                       file[i][6],\
                                       file[i][7])

    def load_SOL(self):
        with open("./settings/SOL.kps", "r") as f:
            file = json.load(f)
        self.planets_attribute.items = []
        for i in range(len(file)):
            self.add_planet_from_f(file[i][0],\
                                   file[i][1],\
                                   file[i][2],\
                                   file[i][3],\
                                   file[i][4],\
                                   file[i][5],\
                                   file[i][6],\
                                   file[i][7])

    def save_file(self):
        filedialog = QFileDialog()
        filedialog.setDirectory("./settings")
        filepath = filedialog.getSaveFileName(filter="Kepler Planet Settings (*.kps)")
        if filepath == "":
            pass
        else:
            with open(filepath, "w") as f:
                json.dump(self.planets_attribute.items, f, sort_keys=True, indent=4)

    def cal_rupt(self):
        self.cal_stop = True

    def open_viewer(self):
        self.viewer.show()

    def open_viewer3d(self):
        self.viewer3d.show()