Beispiel #1
0
class Slider():
    def update_offset(self, pos):
        offset = round(pos, 2)
        return offset

    def __init__(self, tool, text, tooltip, precision, minimal, maximal,
                 interval):
        self.tool = tool

        self.scale = precision

        self.name_label = QLabel(text)
        self.name_label.setAlignment(Qt.AlignLeft)

        if not tooltip == None:
            self.name_label.setToolTip(tooltip)

        self.offset_edit = QDoubleSpinBox()
        self.offset_edit.setRange(minimal, maximal)
        self.offset_edit.setSingleStep(precision)
        self.offset_edit.setDecimals(2)
        self.offset_edit.setAlignment(Qt.AlignRight)
        self.offset_edit.valueChanged.connect(
            lambda pos: self.slider.setSliderPosition(
                self.update_offset(pos) / self.scale))

        self.slider = QSlider(Qt.Horizontal)
        self.slider.setRange(minimal / self.scale, maximal)
        self.slider.setTickInterval(interval / self.scale)
        self.slider.setTickPosition(QSlider.TicksAbove)
        self.slider.valueChanged.connect(lambda pos: self.offset_edit.setValue(
            self.update_offset(pos * self.scale)))

        self.update_offset(0)
Beispiel #2
0
class GaussianFuzzierSetting(QFrame):
    def __init__(self):
        super().__init__()
        layout = QHBoxLayout()

        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)
        self.mean = QDoubleSpinBox()
        self.mean.setRange(-100, 100)
        self.mean.setStatusTip("The mean (mu) value for Gaussian function.")

        self.sd = QDoubleSpinBox()
        self.sd.setDecimals(3)
        self.sd.setValue(5)
        self.sd.setMinimum(0.1)
        self.sd.setStatusTip("The standard deviation (sigma) value for "
                             "Gaussian function.")

        self.ascending = QCheckBox()
        self.ascending.setIcon(QIcon(':/icons/ascending_icon.png'))
        self.ascending.setStatusTip("Make the fuzzier strictly ascending.")
        self.descending = QCheckBox()
        self.descending.setIcon(QIcon(':/icons/descending_icon.png'))
        self.descending.setStatusTip("Make the fuzzier strictly descending.")

        layout.addWidget(QLabel("Mean"))
        layout.addWidget(self.mean, 1)
        layout.addWidget(QLabel("Standard Deviation"))
        layout.addWidget(self.sd, 1)
        layout.addWidget(self.ascending)
        layout.addWidget(self.descending)

    def get_values(self):
        return (self.mean.value(), self.sd.value(), self.ascending.isChecked(),
                self.descending.isChecked())
 def createEditor(self, parent: QWidget, option: QStyleOptionViewItem,
                  index: QModelIndex) -> QWidget:
     editor = QDoubleSpinBox(parent)
     editor.setFrame(False)
     editor.setRange(self.__min, self.__max)
     editor.setDecimals(self.__decimals)
     return editor
Beispiel #4
0
 def createEditor(self, parent, option, index):
     doubleSpinBox = QDoubleSpinBox(parent)
     doubleSpinBox.setDecimals(5)
     doubleSpinBox.setMinimum(-100000)
     doubleSpinBox.setMaximum(100000)
     self.connect(doubleSpinBox, SIGNAL("valueChanged(float)"), self,
                  SLOT("valueChanged()"))
     return doubleSpinBox
Beispiel #5
0
    def change_n_components(self, n_components: int):
        for widget in self.control_widgets:
            self.control_layout.removeWidget(widget)
            widget.hide()
        self.control_widgets.clear()
        self.input_widgets.clear()

        widgets = []
        slider_range = (0, 1000)
        input_widgets = []
        mean_range = (-5, 15)
        std_range = (0.0, 10)
        weight_range = (0, 10)
        names = [self.tr("Mean"), self.tr("STD"), self.tr("Weight")]
        ranges = [mean_range, std_range, weight_range]
        slider_values = [500, 100, 100]
        input_values = [0.0, 1.0, 1.0]

        for i in range(n_components):
            group = QGroupBox(f"C{i+1}")
            group.setMinimumWidth(200)
            group_layout = QGridLayout(group)
            inputs = []
            for j, (name, range_, slider_value, input_value) in enumerate(
                    zip(names, ranges, slider_values, input_values)):
                label = QLabel(name)
                slider = QSlider()
                slider.setRange(*slider_range)
                slider.setValue(slider_value)
                slider.setOrientation(Qt.Horizontal)
                input_ = QDoubleSpinBox()
                input_.setRange(*range_)
                input_.setDecimals(3)
                input_.setSingleStep(0.01)
                input_.setValue(input_value)
                slider.valueChanged.connect(self.on_value_changed)
                input_.valueChanged.connect(self.on_value_changed)
                slider.valueChanged.connect(
                    lambda x, input_=input_, range_=range_: input_.setValue(
                        x / 1000 * (range_[-1] - range_[0]) + range_[0]))
                input_.valueChanged.connect(
                    lambda x, slider=slider, range_=range_: slider.setValue(
                        (x - range_[0]) / (range_[-1] - range_[0]) * 1000))

                group_layout.addWidget(label, j, 0)
                group_layout.addWidget(slider, j, 1)
                group_layout.addWidget(input_, j, 2)
                inputs.append(input_)

            self.control_layout.addWidget(group, i + 5, 0, 1, 4)
            widgets.append(group)
            input_widgets.append(inputs)

        self.control_widgets = widgets
        self.input_widgets = input_widgets
def init_font_size_layout(text_item):
    font_size_input = QDoubleSpinBox()
    font_size_input.setDecimals(2)
    font_size_input.setRange(0.5, 900.)
    font_size_input.setValue(text_item.font().pointSizeF())
    font_size_input.valueChanged.connect(lambda:
                                          set_font_size(
                                              font_size_input.value(),
                                              text_item))
    font_size_layout = QHBoxLayout()
    font_size_layout.addWidget(font_size_input)
    font_size_layout.addWidget(QLabel("pt"))
    return font_size_layout
Beispiel #7
0
 def get_settings_window(self, parent=None):
     gcodesender_settings = QGroupBox("GCodeSender Settings:", parent)
     buildplate_label = QLabel("Buildplate Motor:", gcodesender_settings)
     nodes = [str(item) for item in self.__g_code_sender.get_motor_nodes_id_list()]
     self.buildplate_combo_box = MyQComboBox(gcodesender_settings)
     self.buildplate_combo_box.addItems(nodes)
     self.buildplate_combo_box.setCurrentIndex(self.__g_code_sender.get_buildplate_node())
     self.buildplate_combo_box.combo_box_clicked.connect(self.__update_nodes_list)
     self.buildplate_combo_box.currentIndexChanged.connect(self.__set_buildplate_node)
     wiper_label = QLabel("Wiper Motor:", gcodesender_settings)
     self.wiper_combo_box = MyQComboBox(gcodesender_settings)
     self.wiper_combo_box.addItems(nodes)
     self.wiper_combo_box.setCurrentIndex(self.__g_code_sender.get_wiper_node())
     self.wiper_combo_box.combo_box_clicked.connect(self.__update_nodes_list)
     self.wiper_combo_box.currentIndexChanged.connect(self.__set_wiper_node)
     buildplate_recoat_offset_label = QLabel("Buildplate recoating offset (mm):", gcodesender_settings)
     buildplate_recoat_offset_spin = QDoubleSpinBox(gcodesender_settings)
     buildplate_recoat_offset_spin.setRange(0, 99999)
     buildplate_recoat_offset_spin.setDecimals(3)
     buildplate_recoat_offset_spin.setSingleStep(0.001)
     buildplate_recoat_offset_spin.setValue(self.__g_code_sender.get_building_plate_recoating_offset())
     buildplate_recoat_offset_spin.valueChanged.connect(self.__g_code_sender.set_building_plate_recoat_offset)
     buildplate_recoat_feedrate_label = QLabel("Buildplate recoating feedrate (mm/min):", gcodesender_settings)
     buildplate_recoat_feedrate_spin = QDoubleSpinBox(gcodesender_settings)
     buildplate_recoat_feedrate_spin.setRange(0, 99999)
     buildplate_recoat_feedrate_spin.setDecimals(3)
     buildplate_recoat_feedrate_spin.setSingleStep(0.001)
     buildplate_recoat_feedrate_spin.setValue(self.__g_code_sender.get_building_plate_recoating_feedrate())
     buildplate_recoat_feedrate_spin.valueChanged.connect(self.__g_code_sender.set_building_plate_recoat_feedrate)
     wiper_recoat_offset_label = QLabel("Wiper recoating offset: (mm)", gcodesender_settings)
     wiper_recoat_offset_spin = QDoubleSpinBox(gcodesender_settings)
     wiper_recoat_offset_spin.setRange(0, 99999)
     wiper_recoat_offset_spin.setDecimals(3)
     wiper_recoat_offset_spin.setSingleStep(0.001)
     wiper_recoat_offset_spin.setValue(self.__g_code_sender.get_wiper_recoating_offset())
     wiper_recoat_offset_spin.valueChanged.connect(self.__g_code_sender.set_wiper_recoat_offset)
     wiper_recoat_feedrate_label = QLabel("Wiper recoating feedrate (mm/min):", gcodesender_settings)
     wiper_recoat_feedrate_spin = QDoubleSpinBox(gcodesender_settings)
     wiper_recoat_feedrate_spin.setRange(0, 99999)
     wiper_recoat_feedrate_spin.setDecimals(3)
     wiper_recoat_feedrate_spin.setSingleStep(0.001)
     wiper_recoat_feedrate_spin.setValue(self.__g_code_sender.get_wiper_recoating_feedrate())
     wiper_recoat_feedrate_spin.valueChanged.connect(self.__g_code_sender.set_wiper_recoat_feedrate)
     motor_layout = QGridLayout(gcodesender_settings)
     motor_layout.addWidget(buildplate_label, 0, 0)
     motor_layout.addWidget(self.buildplate_combo_box, 0, 1)
     motor_layout.addWidget(buildplate_recoat_offset_label, 1, 0)
     motor_layout.addWidget(buildplate_recoat_offset_spin, 1, 1)
     motor_layout.addWidget(buildplate_recoat_feedrate_label, 2, 0)
     motor_layout.addWidget(buildplate_recoat_feedrate_spin, 2, 1)
     motor_layout.addWidget(wiper_label, 3, 0)
     motor_layout.addWidget(self.wiper_combo_box, 3, 1)
     motor_layout.addWidget(wiper_recoat_offset_label, 4, 0)
     motor_layout.addWidget(wiper_recoat_offset_spin, 4, 1)
     motor_layout.addWidget(wiper_recoat_feedrate_label, 5, 0)
     motor_layout.addWidget(wiper_recoat_feedrate_spin, 5, 1)
     return gcodesender_settings
Beispiel #8
0
 def createPointWidget(self, x, y, z):
     layout = QHBoxLayout()
     x_label = QLabel("x:")
     x_label.setFixedWidth(10)
     x_val = QDoubleSpinBox()
     x_val.setSingleStep(0.01)
     x_val.setMinimum(-100)
     x_val.setMaximum(100)
     x_val.setDecimals(5)
     x_val.setValue(x)
     x_val.valueChanged.connect(self.onCoordsChanged)
     y_label = QLabel("y:")
     y_label.setFixedWidth(10)
     y_val = QDoubleSpinBox()
     y_val.setMinimum(-100)
     y_val.setMaximum(100)
     y_val.setDecimals(5)
     y_val.setSingleStep(0.01)
     y_val.setValue(y)
     y_val.valueChanged.connect(self.onCoordsChanged)
     z_label = QLabel("z:")
     z_label.setFixedWidth(10)
     z_val = QDoubleSpinBox()
     z_val.setMinimum(-100)
     z_val.setMaximum(100)
     z_val.setDecimals(5)
     z_val.setSingleStep(0.01)
     z_val.setValue(z)
     z_val.valueChanged.connect(self.onCoordsChanged)
     layout.addWidget(x_label)
     layout.addWidget(x_val)
     layout.addWidget(y_label)
     layout.addWidget(y_val)
     layout.addWidget(z_label)
     layout.addWidget(z_val)
     self.widgets.append([x_val, y_val, z_val])
     return layout
class InputsLayout(QFormLayout):
    # this signal is connected to print_output from output_layout class. Connection is done in center_layout
    ga_result = Signal(
        str
    )  # a signal that is emitted so it can transfer resulting string to the output_layout class

    def __init__(self):
        super(InputsLayout, self).__init__()
        self.big_font = QFont()
        self.medium_font = QFont()
        self.header = QLabel()
        self.header_general = QLabel()
        self.header_fitness_remapping = QLabel()
        self.header_stop = QLabel()
        self.header_selection = QLabel()
        self.header_pairing = QLabel()
        self.header_crossover = QLabel()
        self.header_mutation = QLabel()

        self.inp_functions_combo = QComboBox()
        self.inp_num_variables = QSpinBox()
        self.inp_extrema_min = QRadioButton("Minimum")
        self.inp_extrema_max = QRadioButton("Maximum")
        self.inp_pop_size = QSpinBox()
        self.inp_lower_bound = QDoubleSpinBox()
        self.inp_upper_bound = QDoubleSpinBox()
        # Stopping
        self.inp_max_iter = QSpinBox()
        self.inp_similarity_cb = QCheckBox()
        self.inp_similarity = QSpinBox()
        self.inp_best_result_cb = QCheckBox()
        self.inp_best_result = QDoubleSpinBox()
        self.inp_average_result_cb = QCheckBox()
        self.inp_average_result = QDoubleSpinBox()
        # Fitness remapping
        self.inp_fitness_remapping = QComboBox()
        # Selection
        self.inp_selection_method = QComboBox()
        self.inp_elitism = QDoubleSpinBox()
        # Pairing
        self.inp_pairing_method = QComboBox()
        # Crossover
        self.inp_crossover_method = QComboBox()
        self.inp_crossover_fraction = QDoubleSpinBox()
        self.intermediate_offset = QDoubleSpinBox()
        # Mutation
        self.inp_mutation_method = QComboBox()
        self.inp_mutation_intensity = QDoubleSpinBox()
        self.inp_mutation_intensity_final = QDoubleSpinBox()

        self.init_fonts()
        self.init_header()
        self.init_row_functions()
        self.init_row_general()
        self.init_row_fitness_remapping()
        self.init_row_stop()
        self.init_row_selection()
        self.init_row_pairing()
        self.init_row_crossover()
        self.init_row_mutation()

    def init_fonts(self):
        self.big_font.setPointSizeF(14)
        self.medium_font.setPointSizeF(12)

    def init_header(self):
        self.header.setFont(self.big_font)
        self.header.setAlignment(Qt.AlignCenter)
        self.header.setText("Genetic Algorithm Continuous Optimization")
        self.addRow(self.header)
        self.addRow(QHLine())

    def init_row_functions(self):
        self.inp_functions_combo.addItem("Ackley", ackley)
        self.inp_functions_combo.addItem("Griewank", griewank)
        self.inp_functions_combo.addItem("Michalewicz", michalewicz)

        self.inp_extrema_min.setChecked(True)

        radio_box = QHBoxLayout()
        radio_box.addWidget(self.inp_extrema_min)
        radio_box.addWidget(self.inp_extrema_max)
        self.addRow("Function:", self.inp_functions_combo)
        self.inp_num_variables.setMaximum(10000)
        self.inp_num_variables.setValue(10)
        self.addRow("Number of variables:", self.inp_num_variables)
        self.addRow("Find:", radio_box)
        self.addRow(QHLine())

    def init_row_general(self):
        self.header_general.setFont(self.medium_font)
        self.header_general.setText("General")

        self.inp_pop_size.setMaximum(10000)
        self.inp_pop_size.setValue(300)
        self.inp_lower_bound.setMaximum(1000000)
        self.inp_lower_bound.setMinimum(-1000000.0)
        self.inp_lower_bound.setValue(-10)
        self.inp_upper_bound.setMaximum(1000000)
        self.inp_upper_bound.setMinimum(-1000000.0)
        self.inp_upper_bound.setValue(10)

        self.addRow(self.header_general)
        self.addRow("Population size", self.inp_pop_size)
        self.addRow("Lower Bound", self.inp_lower_bound)
        self.addRow("Upper Bound", self.inp_upper_bound)
        self.addRow(QHLine())

    def init_row_fitness_remapping(self):
        self.header_fitness_remapping.setFont(self.medium_font)
        self.header_fitness_remapping.setText("Fitness Remapping")

        self.inp_fitness_remapping.addItem("Rank Scaling", "Rank Scaling")
        self.inp_fitness_remapping.addItem("Fitness Scaling",
                                           "Fitness Scaling")

        self.addRow(self.header_fitness_remapping)
        self.addRow("Fitness remapping", self.inp_fitness_remapping)
        self.addRow(QHLine())

    def init_row_stop(self):
        self.header_stop.setFont(self.medium_font)
        self.header_stop.setText("Stopping Criteria")

        self.inp_max_iter.setMaximum(100000)
        self.inp_similarity.setMaximum(100000)
        self.inp_best_result.setMinimum(-100000)
        self.inp_best_result.setMaximum(100000)
        self.inp_average_result.setMinimum(-100000)
        self.inp_average_result.setMaximum(100000)

        self.inp_max_iter.setValue(500)
        self.inp_similarity.setValue(80)
        self.inp_best_result.setValue(-10)
        self.inp_average_result.setValue(-10000)

        self.inp_similarity_cb.setText("Similar Results")
        self.inp_best_result_cb.setText("Best Result")
        self.inp_average_result_cb.setText("Average Result")
        self.inp_similarity_cb.stateChanged.connect(self.cb_similarity_signal)
        self.inp_best_result_cb.stateChanged.connect(
            self.cb_best_result_signal)
        self.inp_average_result_cb.stateChanged.connect(
            self.cb_average_result_signal)

        self.inp_similarity_cb.setChecked(False)
        self.inp_best_result_cb.setChecked(False)
        self.inp_average_result_cb.setChecked(False)

        self.inp_similarity.setEnabled(True)
        self.inp_best_result.setEnabled(False)
        self.inp_best_result.setStyleSheet("background:#555")
        self.inp_average_result.setEnabled(False)
        self.inp_average_result.setStyleSheet("background:#555")

        self.addRow(self.header_stop)
        self.addRow("Max iter", self.inp_max_iter)
        self.addRow(self.inp_similarity_cb, self.inp_similarity)
        self.addRow(self.inp_best_result_cb, self.inp_best_result)
        self.addRow(self.inp_average_result_cb, self.inp_average_result)
        self.addRow(QHLine())

    def init_row_selection(self):
        self.header_selection.setFont(self.medium_font)
        self.header_selection.setText("Selection")

        self.inp_selection_method.addItem("Fittest Half", "Fittest Half")
        self.inp_selection_method.addItem("Roulette Wheel", "Roulette Wheel")
        self.inp_selection_method.addItem("Random", "Random")
        self.inp_selection_method.addItem("Whole Population",
                                          "Whole Population")
        self.inp_elitism.setMaximum(1)
        self.inp_elitism.setValue(0.01)
        self.inp_elitism.setSingleStep(0.01)

        self.addRow(self.header_selection)
        self.addRow("Selection Method", self.inp_selection_method)
        self.addRow("Elitism Percentage", self.inp_elitism)
        self.addRow(QHLine())

    def init_row_pairing(self):
        self.header_pairing.setFont(self.medium_font)
        self.header_pairing.setText("Pairing")

        self.inp_pairing_method.addItem("Random", "Random")
        self.inp_pairing_method.addItem("Roulette Wheel", "Roulette Wheel")
        self.inp_pairing_method.addItem("Fittest", "Fittest")

        self.addRow(self.header_pairing)
        self.addRow("Pairing Method", self.inp_pairing_method)
        self.addRow(QHLine())

    def init_row_crossover(self):
        self.header_crossover.setFont(self.medium_font)
        self.header_crossover.setText("Crossover")

        self.inp_crossover_method.addItem("Intermediate", "Intermediate")
        self.inp_crossover_method.addItem("Line Intermediate",
                                          "Line Intermediate")
        self.inp_crossover_method.addItem("Heuristic", "Heuristic")
        self.inp_crossover_method.addItem("One point", "One point")
        self.inp_crossover_method.addItem("Two point", "Two point")
        self.inp_crossover_method.addItem("Random", "Random")
        self.inp_mutation_method.setCurrentIndex(2)
        self.inp_crossover_fraction.setMaximum(1)
        self.inp_crossover_fraction.setValue(0.7)
        self.inp_crossover_fraction.setSingleStep(0.05)
        self.intermediate_offset.setMaximum(20)
        self.intermediate_offset.setValue(1.55)
        self.intermediate_offset.setSingleStep(0.05)

        self.addRow(self.header_crossover)
        self.addRow("Crossover Method", self.inp_crossover_method)
        self.addRow("Crossover Fraction", self.inp_crossover_fraction)
        self.addRow("Intermediate Offset", self.intermediate_offset)
        self.addRow(QHLine())

    def init_row_mutation(self):
        self.header_mutation.setFont(self.medium_font)
        self.header_mutation.setText("Mutation")

        self.inp_mutation_method.addItem("Gauss", "Gauss")
        self.inp_mutation_method.addItem("Random", "Random")
        self.inp_mutation_intensity.setMaximum(200)
        self.inp_mutation_intensity.setValue(2)
        self.inp_mutation_intensity.setDecimals(4)

        self.inp_mutation_intensity.setSingleStep(0.01)
        self.inp_mutation_intensity_final.setMaximum(200)
        self.inp_mutation_intensity_final.setDecimals(4)
        self.inp_mutation_intensity_final.setValue(0.001)
        self.inp_mutation_intensity_final.setSingleStep(0.5)

        self.addRow(self.header_mutation)
        self.addRow("Mutation Method", self.inp_mutation_method)
        self.addRow("Mutation Intensity", self.inp_mutation_intensity)
        self.addRow("Final Mutation Intensity",
                    self.inp_mutation_intensity_final)
        self.addRow(QHLine())

    def get_options(self):
        function = self.inp_functions_combo.currentData()
        num_var = self.inp_num_variables.text()
        if self.inp_extrema_min.isChecked():
            extrem = 0
        else:
            extrem = 1
        pop_size = self.inp_pop_size.text()
        low_bound = self.inp_lower_bound.text()
        upp_bound = self.inp_upper_bound.text()
        max_iter = self.inp_max_iter.text()
        sim_results = self.inp_similarity.text()
        best_res = self.inp_best_result.text()
        average_res = self.inp_average_result.text()
        select_method = self.inp_selection_method.currentText()
        elite_percent = self.inp_elitism.text()
        pairing = self.inp_pairing_method.currentText()
        crossover_method = self.inp_crossover_method.currentText()
        crossover_fraction = self.inp_crossover_fraction.text()
        intermediate_offset = self.intermediate_offset.text()
        mutation_method = self.inp_mutation_method.currentText()
        mutation_intensity = self.inp_mutation_intensity.text()
        mutation_intensity_final = self.inp_mutation_intensity_final.text()
        fitness_remapping = self.inp_fitness_remapping.currentText()

        options = {
            "function":
            function,
            "num_var":
            num_var,
            "pop_size":
            int(pop_size),
            "max_iter":
            int(max_iter),
            "lower_bound":
            float(low_bound.replace(",", ".")),
            "upper_bound":
            float(upp_bound.replace(",", ".")),
            "find_max":
            extrem,
            "prints":
            0,
            "average_result":
            float(average_res.replace(",", ".")),
            "best_result":
            float(best_res.replace(",", ".")),
            "similarity":
            float(sim_results.replace(",", ".")),
            "selection":
            select_method,
            "pairing":
            pairing,
            "crossover":
            crossover_method,
            "crossover_fraction":
            float(crossover_fraction.replace(",", ".")),
            "intermediate_offset":
            float(intermediate_offset.replace(",", ".")),
            # 0 mean child will be between parents, 1 mean offset is same as two parent distance
            "mutation":
            mutation_method,
            "mutation_intensity":
            float(mutation_intensity.replace(",", ".")),
            "mutation_intensity_final":
            float(mutation_intensity_final.replace(",", ".")),
            "elitism":
            float(elite_percent.replace(",", ".")),
            "fitness_remapping":
            fitness_remapping
        }

        if not self.inp_similarity_cb.isChecked():
            options["similarity"] = None
        if not self.inp_best_result_cb.isChecked():
            options["best_result"] = None
        if not self.inp_average_result_cb.isChecked():
            options["average_result"] = None
        return options

    def cb_similarity_signal(self):
        if self.inp_similarity_cb.isChecked():
            self.inp_similarity.setEnabled(True)
            self.inp_similarity.setStyleSheet("")
        else:
            self.inp_similarity.setEnabled(False)
            self.inp_similarity.setStyleSheet("background:#555")

    def cb_best_result_signal(self):
        if self.inp_best_result_cb.isChecked():
            self.inp_best_result.setEnabled(True)
            self.inp_best_result.setStyleSheet("")
        else:
            self.inp_best_result.setEnabled(False)
            self.inp_best_result.setStyleSheet("background:#555")

    def cb_average_result_signal(self):
        if self.inp_average_result_cb.isChecked():
            self.inp_average_result.setEnabled(True)
            self.inp_average_result.setStyleSheet("")
        else:
            self.inp_average_result.setEnabled(False)
            self.inp_average_result.setStyleSheet("background:#555")
Beispiel #10
0
 def __init_features_widget__(self, parent=None):
     self.__features_widget = QGroupBox("Features Layers Parameters",
                                        parent)
     # self.__features_widget.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
     thickness_label = QLabel("Layer Thickness", self.__features_widget)
     self.features_thickness_edit = MyDiscreteStepsSpinBox(
         self.dlp_controller.get_step_length_microns(),
         self.__features_widget)
     self.features_thickness_edit.setSuffix(str('\u03BCm'))
     self.features_thickness_edit.setMaximum(1000000)
     self.features_thickness_edit.setMinimum(0)
     self.features_thickness_edit.setDecimals(3)
     self.features_thickness_edit.my_value_changed_signal.connect(
         self.dlp_controller.set_features_thickness)
     self.features_thickness_edit.setValue(
         self.dlp_controller.features_thickness * 1000)
     exposure_label = QLabel("Exposure Time", self.__features_widget)
     exposure_edit = QDoubleSpinBox(self.__features_widget)
     exposure_edit.setSuffix(str('ms'))
     exposure_edit.setMaximum(10000000)
     exposure_edit.setMinimum(0)
     exposure_edit.setDecimals(1)
     exposure_edit.setSingleStep(0.1)
     exposure_edit.setValue(self.dlp_controller.features_exposure)
     exposure_edit.valueChanged.connect(
         self.dlp_controller.set_features_exposure_time)
     amplitude_label = QLabel("Light Amplitude", self.__features_widget)
     amplitude_edit = QSpinBox(self.__features_widget)
     amplitude_edit.setMaximum(1600)
     amplitude_edit.setMinimum(0)
     amplitude_edit.setSingleStep(1)
     amplitude_edit.setValue(self.dlp_controller.features_amplitude)
     amplitude_edit.valueChanged.connect(
         self.dlp_controller.set_features_amplitude)
     burn_layers_label = QLabel("Burn Layers", self.__features_widget)
     burn_layers_edit = QSpinBox(self.__features_widget)
     burn_layers_edit.setMaximum(1000)
     burn_layers_edit.setMinimum(0)
     burn_layers_edit.setSingleStep(1)
     burn_layers_edit.setValue(self.dlp_controller.features_burn_layers)
     burn_layers_edit.valueChanged.connect(
         self.dlp_controller.set_features_burning_layers)
     burn_exposure_label = QLabel("Burn Exposure", self.__features_widget)
     burn_exposure_edit = QDoubleSpinBox(self.__features_widget)
     burn_exposure_edit.setSuffix(str('ms'))
     burn_exposure_edit.setMaximum(100000)
     burn_exposure_edit.setMinimum(0)
     burn_exposure_edit.setDecimals(1)
     burn_exposure_edit.setSingleStep(0.1)
     burn_exposure_edit.setValue(self.dlp_controller.features_burn_exposure)
     burn_exposure_edit.valueChanged.connect(
         self.dlp_controller.set_features_burning_exposure_time)
     burn_amplitude_label = QLabel("Burn Amplitude", self.__features_widget)
     burn_amplitude_edit = QSpinBox(self.__features_widget)
     burn_amplitude_edit.setMaximum(1600)
     burn_amplitude_edit.setMinimum(0)
     burn_amplitude_edit.setSingleStep(1)
     burn_amplitude_edit.setValue(
         self.dlp_controller.features_burn_amplitude)
     burn_amplitude_edit.valueChanged.connect(
         self.dlp_controller.set_features_burning_amplitude)
     select_layers_button = QPushButton("Select Features Images")
     select_layers_button.clicked.connect(self.load_features_images)
     features_layout = QGridLayout(self.__features_widget)
     features_layout.addWidget(thickness_label, 1, 0)
     features_layout.addWidget(self.features_thickness_edit, 1, 1)
     features_layout.addWidget(exposure_label, 2, 0)
     features_layout.addWidget(exposure_edit, 2, 1)
     features_layout.addWidget(amplitude_label, 3, 0)
     features_layout.addWidget(amplitude_edit, 3, 1)
     features_layout.addWidget(burn_layers_label, 4, 0)
     features_layout.addWidget(burn_layers_edit, 4, 1)
     features_layout.addWidget(burn_exposure_label, 5, 0)
     features_layout.addWidget(burn_exposure_edit, 5, 1)
     features_layout.addWidget(burn_amplitude_label, 6, 0)
     features_layout.addWidget(burn_amplitude_edit, 6, 1)
     features_layout.addWidget(select_layers_button, 7, 0, 1, 2)
     self.__features_widget.setLayout(features_layout)
Beispiel #11
0
 def __init_advanced_features_widget__(self, parent=None):
     self.__advanced_widget = QGroupBox("Advanced Features Options", parent)
     fixed_layer_check = QCheckBox("Fixed Layer", self.__advanced_widget)
     fixed_layer_check.setChecked(self.dlp_controller.fixed_layer)
     fixed_layer_check.toggled.connect(self.dlp_controller.set_fixed_layer)
     incremental_amplitude_check = QCheckBox("Incremental Amplitude",
                                             self.__advanced_widget)
     incremental_amplitude_check.setChecked(
         self.dlp_controller.incremental_amplitude)
     incremental_amplitude_check.toggled.connect(
         self.dlp_controller.set_incremental_amplitude)
     starting_amplitude_label = QLabel("Starting Amplitude",
                                       self.__advanced_widget)
     starting_amplitude_edit = QSpinBox(self.__advanced_widget)
     starting_amplitude_edit.setMaximum(1000)
     starting_amplitude_edit.setMinimum(0)
     starting_amplitude_edit.setSingleStep(1)
     starting_amplitude_edit.setValue(
         self.dlp_controller.starting_incremental_amplitude)
     starting_amplitude_edit.valueChanged.connect(
         self.dlp_controller.set_starting_incremental_amplitude)
     amplitude_step_label = QLabel("Step Size", self.__advanced_widget)
     amplitude_step_edit = QSpinBox(self.__advanced_widget)
     amplitude_step_edit.setMaximum(1000)
     amplitude_step_edit.setMinimum(0)
     amplitude_step_edit.setSingleStep(1)
     amplitude_step_edit.setValue(
         self.dlp_controller.incremental_step_amplitude)
     amplitude_step_edit.valueChanged.connect(
         self.dlp_controller.set_incremental_step_amplitude)
     incremental_exposure_check = QCheckBox("Incremental Exposure",
                                            self.__advanced_widget)
     incremental_exposure_check.setChecked(
         self.dlp_controller.incremental_exposure)
     incremental_exposure_check.toggled.connect(
         self.dlp_controller.set_incremental_exposure)
     starting_exposure_label = QLabel("Starting Exposure",
                                      self.__advanced_widget)
     starting_exposure_edit = QDoubleSpinBox(self.__advanced_widget)
     starting_exposure_edit.setSuffix(str('ms'))
     starting_exposure_edit.setMaximum(100000)
     starting_exposure_edit.setMinimum(0)
     starting_exposure_edit.setDecimals(1)
     starting_exposure_edit.setSingleStep(0.1)
     starting_exposure_edit.valueChanged.connect(
         self.dlp_controller.set_starting_incremental_exposure)
     starting_exposure_edit.setValue(
         self.dlp_controller.starting_incremental_exposure)
     exposure_step_label = QLabel("Step Size", self.__advanced_widget)
     exposure_step_edit = QDoubleSpinBox(self.__advanced_widget)
     exposure_step_edit.setSuffix(str('ms'))
     exposure_step_edit.setMaximum(100000)
     exposure_step_edit.setMinimum(0)
     exposure_step_edit.setDecimals(1)
     exposure_step_edit.setSingleStep(0.1)
     exposure_step_edit.valueChanged.connect(
         self.dlp_controller.set_incremental_step_exposure)
     exposure_step_edit.setValue(
         self.dlp_controller.incremental_step_exposure)
     incremental_thickness_check = QCheckBox("Incremental Thickness",
                                             self.__advanced_widget)
     incremental_thickness_check.setChecked(
         self.dlp_controller.incremental_thickness)
     incremental_thickness_check.toggled.connect(
         self.dlp_controller.set_incremental_thickness)
     thickness_label = QLabel("Starting Thickness", self.__features_widget)
     self.starting_thickness_edit = MyDiscreteStepsSpinBox(
         self.dlp_controller.get_step_length_microns(),
         self.__features_widget)
     self.starting_thickness_edit.setSuffix(str('\u03BCm'))
     self.starting_thickness_edit.setMaximum(1000000)
     self.starting_thickness_edit.setMinimum(0)
     self.starting_thickness_edit.setDecimals(3)
     self.starting_thickness_edit.my_value_changed_signal.connect(
         self.dlp_controller.set_starting_incremental_thickness)
     self.starting_thickness_edit.setValue(
         self.dlp_controller.starting_incremental_thickness * 1000)
     thickness_step_label = QLabel("Step Size", self.__features_widget)
     self.thickness_step_edit = MyDiscreteStepsSpinBox(
         self.dlp_controller.get_step_length_microns(),
         self.__features_widget)
     self.thickness_step_edit.setSuffix(str('\u03BCm'))
     self.thickness_step_edit.setMaximum(1000000)
     self.thickness_step_edit.setMinimum(0)
     self.thickness_step_edit.setDecimals(3)
     self.thickness_step_edit.my_value_changed_signal.connect(
         self.dlp_controller.set_incremental_step_thickness)
     self.thickness_step_edit.setValue(
         self.dlp_controller.incremental_step_thickness * 1000)
     apply_grayscale_correction_check = QCheckBox("Grayscale Correction",
                                                  self.__advanced_widget)
     apply_grayscale_correction_check.setChecked(
         self.dlp_controller.grayscale_correction)
     apply_grayscale_correction_check.toggled.connect(
         self.dlp_controller.set_grayscale_correction)
     grayscale_parameters_widget = QWidget(self.__features_widget)
     a_parameter_label = QLabel("\u03B1", grayscale_parameters_widget)
     alpha_parameter_edit = QDoubleSpinBox(grayscale_parameters_widget)
     alpha_parameter_edit.setMaximum(1000)
     alpha_parameter_edit.setMinimum(0)
     alpha_parameter_edit.setDecimals(3)
     alpha_parameter_edit.setSingleStep(0.001)
     alpha_parameter_edit.valueChanged.connect(
         self.dlp_controller.set_grayscale_alpha)
     alpha_parameter_edit.setValue(self.dlp_controller.grayscale_alpha)
     beta_parameter_label = QLabel("\u03B2", grayscale_parameters_widget)
     beta_parameter_edit = QDoubleSpinBox(grayscale_parameters_widget)
     beta_parameter_edit.setMaximum(1000)
     beta_parameter_edit.setMinimum(0)
     beta_parameter_edit.setDecimals(3)
     beta_parameter_edit.setSingleStep(0.001)
     beta_parameter_edit.valueChanged.connect(
         self.dlp_controller.set_grayscale_beta)
     beta_parameter_edit.setValue(self.dlp_controller.grayscale_beta)
     gamma_parameter_label = QLabel("\u03B3", grayscale_parameters_widget)
     gamma_parameter_edit = QDoubleSpinBox(grayscale_parameters_widget)
     gamma_parameter_edit.setMaximum(1000)
     gamma_parameter_edit.setMinimum(0)
     gamma_parameter_edit.setDecimals(3)
     gamma_parameter_edit.setSingleStep(0.001)
     gamma_parameter_edit.valueChanged.connect(
         self.dlp_controller.set_grayscale_gamma)
     gamma_parameter_edit.setValue(self.dlp_controller.grayscale_gamma)
     grayscale_parameters_layout = QHBoxLayout(grayscale_parameters_widget)
     grayscale_parameters_layout.addWidget(a_parameter_label)
     grayscale_parameters_layout.addWidget(alpha_parameter_edit)
     grayscale_parameters_layout.addWidget(beta_parameter_label)
     grayscale_parameters_layout.addWidget(beta_parameter_edit)
     grayscale_parameters_layout.addWidget(gamma_parameter_label)
     grayscale_parameters_layout.addWidget(gamma_parameter_edit)
     grayscale_parameters_widget.setLayout(grayscale_parameters_layout)
     advanced_features_layout = QGridLayout(self.__advanced_widget)
     advanced_features_layout.addWidget(incremental_amplitude_check, 1, 0,
                                        1, 2)
     advanced_features_layout.addWidget(fixed_layer_check, 1, 3)
     advanced_features_layout.addWidget(starting_amplitude_label, 2, 0)
     advanced_features_layout.addWidget(starting_amplitude_edit, 2, 1)
     advanced_features_layout.addWidget(amplitude_step_label, 2, 2)
     advanced_features_layout.addWidget(amplitude_step_edit, 2, 3)
     advanced_features_layout.addWidget(incremental_exposure_check, 3, 0, 1,
                                        2)
     advanced_features_layout.addWidget(starting_exposure_label, 4, 0)
     advanced_features_layout.addWidget(starting_exposure_edit, 4, 1)
     advanced_features_layout.addWidget(exposure_step_label, 4, 2)
     advanced_features_layout.addWidget(exposure_step_edit, 4, 3)
     advanced_features_layout.addWidget(incremental_thickness_check, 5, 0,
                                        1, 2)
     advanced_features_layout.addWidget(thickness_label, 6, 0)
     advanced_features_layout.addWidget(self.starting_thickness_edit, 6, 1)
     advanced_features_layout.addWidget(thickness_step_label, 6, 2)
     advanced_features_layout.addWidget(self.thickness_step_edit, 6, 3)
     advanced_features_layout.addWidget(apply_grayscale_correction_check, 7,
                                        0, 1, 2)
     advanced_features_layout.addWidget(grayscale_parameters_widget, 8, 0,
                                        1, 4)
     self.__advanced_widget.setLayout(advanced_features_layout)
Beispiel #12
0
class DLPSlicerGUI(QWidget):
    def __init__(self, dlp_controller=None, parent=None):
        QWidget.__init__(self, parent)
        if dlp_controller:
            self.dlp_controller = dlp_controller
        self.main_layout = QVBoxLayout()
        self.__init_slicer_widget__()
        self.__init_options_widget__()
        self.__options_widget.setSizePolicy(QSizePolicy.MinimumExpanding,
                                            QSizePolicy.Maximum)
        self.main_layout.addWidget(self.__slicer_widget)
        self.main_layout.addWidget(self.__options_widget)
        self.setLayout(self.main_layout)

    def __init_slicer_widget__(self):
        self.__slicer_widget = DLPSlicer(parent=self,
                                         dlp_controller=self.dlp_controller)
        self.__slicer_widget.update_physical_size.connect(
            self.update_size_label)
        self.__slicer_widget.update_fps.connect(self.update_fps_label)
        self.__slicer_widget.update_slice_counts.connect(
            self.update_slices_label)

    def __init_options_widget__(self):
        self.__options_widget = QWidget(self)
        self.__init_info_widget__()
        self.__init_geometry_widget__()
        self.__init_slicer_options_widget__()
        self.__options_layout = QGridLayout()
        self.__options_layout.addWidget(self.__info_widget, 0, 0, 1, 3)
        self.__options_layout.addWidget(self.__geometry_widget, 1, 0, 1, 2)
        self.__options_layout.addWidget(self.__slicer_options_widget, 1, 2)
        self.__options_widget.setLayout(self.__options_layout)

    def __init_info_widget__(self):
        self.__info_widget = QWidget(self)
        current_geometry_label = QLabel("Selected Geometry:",
                                        self.__info_widget)
        self.current_geometry_index = -1
        self.geometry_list = MyQComboBox(self.__info_widget)
        self.geometry_list.currentIndexChanged.connect(
            self.update_geometry_transformations)
        self.fps_label = QLabel(f'fps: {0:.2f}', self.__info_widget)
        self.physical_size_label = QLabel(
            f'Width: {0:.2f} \u03BCm, Depth: {0:.2f} \u03BCm, Height: {0:.2f} \u03BCm',
            self.__info_widget)
        info_layout = QHBoxLayout()
        info_layout.addWidget(current_geometry_label)
        info_layout.addWidget(self.geometry_list)
        info_layout.addWidget(self.physical_size_label)
        info_layout.addWidget(self.fps_label)
        self.__info_widget.setLayout(info_layout)
        self.__info_widget.setSizePolicy(QSizePolicy.Preferred,
                                         QSizePolicy.Maximum)

    def __init_geometry_widget__(self):
        self.__geometry_widget = QGroupBox("Geometry", self)

        load_geometry_button = QPushButton("Load Geometry")
        load_geometry_button.clicked.connect(self.load_geometry)
        remove_geometry_button = QPushButton("Remove Geometry")
        remove_geometry_button.clicked.connect(self.remove_geometry)
        rotate_x_label = QLabel("Rotate X:", self.__geometry_widget)
        self.rotate_x_slider = QSlider(orientation=Qt.Horizontal,
                                       parent=self.__geometry_widget)
        self.rotate_x_slider.setTickPosition(QSlider.TicksBothSides)
        self.rotate_x_slider.setTickInterval(45)
        self.rotate_x_slider.setRange(-180, 180)
        self.rotate_x_slider.setValue(0)
        self.rotate_x_spin = QSpinBox(self.__geometry_widget)
        self.rotate_x_spin.setMinimum(-180)
        self.rotate_x_spin.setMaximum(180)
        self.rotate_x_spin.setValue(0)
        self.rotate_x_slider.valueChanged.connect(self.rotate_x_spin.setValue)
        self.rotate_x_slider.valueChanged.connect(
            self.__slicer_widget.set_x_rotation)
        self.rotate_x_spin.valueChanged.connect(self.rotate_x_slider.setValue)
        self.rotate_x_spin.valueChanged.connect(
            self.__slicer_widget.set_x_rotation)

        rotate_y_label = QLabel("Rotate Y:", self.__geometry_widget)
        self.rotate_y_slider = QSlider(orientation=Qt.Horizontal,
                                       parent=self.__geometry_widget)
        self.rotate_y_slider.setTickPosition(QSlider.TicksBothSides)
        self.rotate_y_slider.setTickInterval(45)
        self.rotate_y_slider.setRange(-180, 180)
        self.rotate_y_slider.setValue(0)
        self.rotate_y_spin = QSpinBox(self.__geometry_widget)
        self.rotate_y_spin.setMinimum(-180)
        self.rotate_y_spin.setMaximum(180)
        self.rotate_y_spin.setValue(0)
        self.rotate_y_slider.valueChanged.connect(self.rotate_y_spin.setValue)
        self.rotate_y_slider.valueChanged.connect(
            self.__slicer_widget.set_y_rotation)
        self.rotate_y_spin.valueChanged.connect(self.rotate_y_slider.setValue)
        self.rotate_y_spin.valueChanged.connect(
            self.__slicer_widget.set_y_rotation)

        rotate_z_label = QLabel("Rotate Z:", self.__geometry_widget)
        self.rotate_z_slider = QSlider(orientation=Qt.Horizontal,
                                       parent=self.__geometry_widget)
        self.rotate_z_slider.setTickPosition(QSlider.TicksBothSides)
        self.rotate_z_slider.setTickInterval(45)
        self.rotate_z_slider.setRange(-180, 180)
        self.rotate_z_slider.setValue(0)
        self.rotate_z_spin = QSpinBox(self.__geometry_widget)
        self.rotate_z_spin.setMinimum(-180)
        self.rotate_z_spin.setMaximum(180)
        self.rotate_z_spin.setValue(0)
        self.rotate_z_slider.valueChanged.connect(self.rotate_z_spin.setValue)
        self.rotate_z_slider.valueChanged.connect(
            self.__slicer_widget.set_z_rotation)
        self.rotate_z_spin.valueChanged.connect(self.rotate_z_slider.setValue)
        self.rotate_z_spin.valueChanged.connect(
            self.__slicer_widget.set_z_rotation)

        translate_x_label = QLabel("Translate X:", self.__geometry_widget)
        self.translate_x_slider = QSlider(orientation=Qt.Horizontal,
                                          parent=self.__geometry_widget)
        self.translate_x_slider.setTickPosition(QSlider.TicksBothSides)
        self.translate_x_slider.setTickInterval(
            self.dlp_controller.projector_pixel_size)
        self.translate_x_slider.setRange(
            -self.dlp_controller.projector_width *
            self.dlp_controller.projector_pixel_size * 0.5,
            self.dlp_controller.projector_width *
            self.dlp_controller.projector_pixel_size * 0.5)
        self.translate_x_slider.setValue(0)
        self.translate_x_spin = QDoubleSpinBox(self.__geometry_widget)
        self.translate_x_spin.setMinimum(
            -self.dlp_controller.projector_width *
            self.dlp_controller.projector_pixel_size * 0.5)
        self.translate_x_spin.setMaximum(
            self.dlp_controller.projector_width *
            self.dlp_controller.projector_pixel_size * 0.5)
        self.translate_x_spin.setSingleStep(
            self.dlp_controller.projector_pixel_size)
        self.translate_x_spin.setValue(0)
        self.translate_x_slider.valueChanged.connect(
            self.translate_x_spin.setValue)
        self.translate_x_slider.valueChanged.connect(
            self.__slicer_widget.set_x_pos)
        self.translate_x_spin.valueChanged.connect(
            self.translate_x_slider.setValue)
        self.translate_x_spin.valueChanged.connect(
            self.__slicer_widget.set_x_pos)

        translate_z_label = QLabel("Translate Z:", self.__geometry_widget)
        self.translate_z_slider = QSlider(orientation=Qt.Horizontal,
                                          parent=self.__geometry_widget)
        self.translate_z_slider.setTickPosition(QSlider.TicksBothSides)
        self.translate_z_slider.setTickInterval(
            self.dlp_controller.projector_pixel_size)
        self.translate_z_slider.setRange(
            -self.dlp_controller.projector_height *
            self.dlp_controller.projector_pixel_size * 0.5,
            self.dlp_controller.projector_height *
            self.dlp_controller.projector_pixel_size * 0.5)
        self.translate_z_slider.setValue(0)
        self.translate_z_spin = QDoubleSpinBox(self.__geometry_widget)
        self.translate_z_spin.setMinimum(
            -self.dlp_controller.projector_height *
            self.dlp_controller.projector_pixel_size * 0.5)
        self.translate_z_spin.setMaximum(
            self.dlp_controller.projector_height *
            self.dlp_controller.projector_pixel_size * 0.5)
        self.translate_z_spin.setSingleStep(
            self.dlp_controller.projector_pixel_size)
        self.translate_z_spin.setValue(0)
        self.translate_z_slider.valueChanged.connect(
            self.translate_z_spin.setValue)
        self.translate_z_slider.valueChanged.connect(
            self.__slicer_widget.set_z_pos)
        self.translate_z_spin.valueChanged.connect(
            self.translate_z_slider.setValue)
        self.translate_z_spin.valueChanged.connect(
            self.__slicer_widget.set_z_pos)

        scale_x_label = QLabel("Scale X:", self.__geometry_widget)
        self.scale_x_spin = QDoubleSpinBox(self.__geometry_widget)
        self.scale_x_spin.setMinimum(-1000)
        self.scale_x_spin.setMaximum(1000)
        self.scale_x_spin.setDecimals(2)
        self.scale_x_spin.setValue(1)
        self.scale_x_spin.setSingleStep(0.01)
        self.scale_x_spin.setObjectName("scale_x_spin")
        self.scale_x_spin.valueChanged.connect(self.set_scaling)

        scale_y_label = QLabel("Scale Y:", self.__geometry_widget)
        self.scale_y_spin = QDoubleSpinBox(self.__geometry_widget)
        self.scale_y_spin.setMinimum(-1000)
        self.scale_y_spin.setMaximum(1000)
        self.scale_y_spin.setDecimals(2)
        self.scale_y_spin.setValue(1)
        self.scale_y_spin.setSingleStep(0.01)
        self.scale_y_spin.setObjectName("scale_y_spin")
        self.scale_y_spin.valueChanged.connect(self.set_scaling)

        scale_z_label = QLabel("Scale Z:", self.__geometry_widget)
        self.scale_z_spin = QDoubleSpinBox(self.__geometry_widget)
        self.scale_z_spin.setMinimum(-1000)
        self.scale_z_spin.setMaximum(1000)
        self.scale_z_spin.setDecimals(2)
        self.scale_z_spin.setValue(1)
        self.scale_z_spin.setSingleStep(0.01)
        self.scale_z_spin.setObjectName("scale_z_spin")
        self.scale_z_spin.valueChanged.connect(self.set_scaling)

        self.uniform_scaling = QCheckBox("Uniform Scaling",
                                         self.__geometry_widget)
        self.uniform_scaling.setChecked(True)
        # self.uniform_scaling.setLayoutDirection(Qt.RightToLeft)

        list_of_measures = ('\u03BCm', 'mm', 'cm', 'dm', 'm')
        self.list_of_measures_coefficients = [0.001, 1, 10, 100, 1000]
        unit_of_measure_label = QLabel("Unit of Measure",
                                       self.__geometry_widget)
        self.unit_of_measure_combo = QComboBox(self.__geometry_widget)
        for measure in list_of_measures:
            self.unit_of_measure_combo.addItem(measure)
        self.unit_of_measure_combo.setCurrentIndex(1)
        self.unit_of_measure_combo.currentIndexChanged.connect(
            self.update_unit_of_measure)

        rotate_x_row = 0
        rotate_y_row = rotate_x_row + 1
        rotate_z_row = rotate_y_row + 1
        translate_x_row = rotate_z_row + 1
        translate_z_row = translate_x_row + 1
        scale_x_row = translate_z_row + 1
        scale_y_row = scale_x_row + 1
        scale_z_row = scale_y_row + 1
        uniform_scaling_row = scale_x_row
        unit_of_measure_row = scale_y_row
        load_geometry_row = scale_z_row + 1
        remove_geometry_row = load_geometry_row

        geometry_layout = QGridLayout(self.__geometry_widget)
        geometry_layout.addWidget(load_geometry_button, load_geometry_row, 1,
                                  1, 2)
        geometry_layout.addWidget(remove_geometry_button, remove_geometry_row,
                                  3, 1, 2)
        geometry_layout.addWidget(rotate_x_label, rotate_x_row, 0)
        geometry_layout.addWidget(self.rotate_x_slider, rotate_x_row, 1, 1, 4)
        geometry_layout.addWidget(self.rotate_x_spin, rotate_x_row, 5)
        geometry_layout.addWidget(rotate_y_label, rotate_y_row, 0)
        geometry_layout.addWidget(self.rotate_y_slider, rotate_y_row, 1, 1, 4)
        geometry_layout.addWidget(self.rotate_y_spin, rotate_y_row, 5)
        geometry_layout.addWidget(rotate_z_label, rotate_z_row, 0)
        geometry_layout.addWidget(self.rotate_z_slider, rotate_z_row, 1, 1, 4)
        geometry_layout.addWidget(self.rotate_z_spin, rotate_z_row, 5)
        geometry_layout.addWidget(translate_x_label, translate_x_row, 0)
        geometry_layout.addWidget(self.translate_x_slider, translate_x_row, 1,
                                  1, 4)
        geometry_layout.addWidget(self.translate_x_spin, translate_x_row, 5)
        geometry_layout.addWidget(translate_z_label, translate_z_row, 0)
        geometry_layout.addWidget(self.translate_z_slider, translate_z_row, 1,
                                  1, 4)
        geometry_layout.addWidget(self.translate_z_spin, translate_z_row, 5)
        geometry_layout.addWidget(scale_x_label, scale_x_row, 0)
        geometry_layout.addWidget(self.scale_x_spin, scale_x_row, 1)
        geometry_layout.addWidget(scale_y_label, scale_y_row, 0)
        geometry_layout.addWidget(self.scale_y_spin, scale_y_row, 1)
        geometry_layout.addWidget(scale_z_label, scale_z_row, 0)
        geometry_layout.addWidget(self.scale_z_spin, scale_z_row, 1)
        geometry_layout.addWidget(self.uniform_scaling, uniform_scaling_row, 3,
                                  1, 2)
        geometry_layout.addWidget(unit_of_measure_label, unit_of_measure_row,
                                  4)
        geometry_layout.addWidget(self.unit_of_measure_combo,
                                  unit_of_measure_row, 3)
        self.__geometry_widget.setLayout(geometry_layout)

    def __init_slicer_options_widget__(self):
        self.__slicer_options_widget = QGroupBox("Slicer Options", self)

        thickness_label = QLabel("Layer Thickness",
                                 self.__slicer_options_widget)
        thickness_edit = QDoubleSpinBox(self.__slicer_options_widget)
        thickness_edit.setSuffix(str('\u03BCm'))
        thickness_edit.setMaximum(1000000)
        thickness_edit.setMinimum(0)
        thickness_edit.setDecimals(3)
        thickness_edit.setSingleStep(0.001)
        thickness_edit.setValue(self.dlp_controller.support_thickness * 1000)
        # self.__opengl_widget.set_slice_thickness(self.dlp_controller.support_thickness)
        thickness_edit.valueChanged.connect(
            self.__slicer_widget.set_slice_thickness)

        pixel_size_label = QLabel("Projector Pixel Size",
                                  self.__slicer_options_widget)
        pixel_size_edit = QDoubleSpinBox(self.__slicer_options_widget)
        pixel_size_edit.setSuffix(str('\u03BCm'))
        pixel_size_edit.setMaximum(1000000)
        pixel_size_edit.setMinimum(0)
        pixel_size_edit.setDecimals(2)
        pixel_size_edit.setSingleStep(0.01)
        pixel_size_edit.setValue(self.dlp_controller.projector_pixel_size *
                                 1000)
        pixel_size_edit.valueChanged.connect(
            self.__slicer_widget.set_pixel_size)

        projector_resolution_label = QLabel("Projector Resolution",
                                            self.__slicer_options_widget)
        projector_resolution_edit_x = QSpinBox(self.__slicer_options_widget)
        projector_resolution_edit_x.setSuffix(str('W'))
        projector_resolution_edit_x.setMaximum(1000000)
        projector_resolution_edit_x.setMinimum(0)
        projector_resolution_edit_x.setValue(
            self.dlp_controller.projector_width)
        projector_resolution_edit_x.valueChanged.connect(
            self.__slicer_widget.set_projector_width)
        projector_resolution_edit_y = QSpinBox(self.__slicer_options_widget)
        projector_resolution_edit_y.setSuffix(str('H'))
        projector_resolution_edit_y.setMaximum(1000000)
        projector_resolution_edit_y.setMinimum(0)
        projector_resolution_edit_y.setValue(
            self.dlp_controller.projector_height)
        projector_resolution_edit_y.valueChanged.connect(
            self.__slicer_widget.set_projector_height)

        samples_per_pixel_label = QLabel("Samples per Pixel",
                                         self.__slicer_options_widget)
        samples_per_pixel_edit = QSpinBox(self.__slicer_options_widget)
        samples_per_pixel_edit.setMaximum(1000000)
        samples_per_pixel_edit.setMinimum(1)
        samples_per_pixel_edit.setValue(self.dlp_controller.samples_per_pixel)
        samples_per_pixel_edit.valueChanged.connect(
            self.__slicer_widget.set_samples_per_pixel)

        slice_geometry_button = QPushButton("Slice Geometry")
        slice_geometry_button.clicked.connect(self.start_slicing_process)

        slice_interrupt_button = QPushButton("Stop Slicing")
        slice_interrupt_button.clicked.connect(
            self.__slicer_widget.interrupt_slicing)

        self.slices_label = QLabel(f'Slicing progress: {0:.0f}/{0:.0f}',
                                   self.__info_widget)

        thickness_label_row = 0
        pixel_size_row = 1
        projector_resolution_row = 2
        samples_per_pixel_row = 3
        slice_button_row = 4
        slices_label_row = 5
        # slice_interrupt_row = slice_button_row

        slice_layout = QGridLayout(self.__slicer_options_widget)
        slice_layout.addWidget(thickness_label, thickness_label_row, 0)
        slice_layout.addWidget(thickness_edit, thickness_label_row, 1)
        slice_layout.addWidget(pixel_size_label, pixel_size_row, 0)
        slice_layout.addWidget(pixel_size_edit, pixel_size_row, 1)
        slice_layout.addWidget(projector_resolution_label,
                               projector_resolution_row, 0)
        slice_layout.addWidget(projector_resolution_edit_x,
                               projector_resolution_row, 1)
        slice_layout.addWidget(projector_resolution_edit_y,
                               projector_resolution_row, 2)
        slice_layout.addWidget(self.slices_label, slice_button_row, 0)
        slice_layout.addWidget(slice_geometry_button, slice_button_row, 1)
        slice_layout.addWidget(slice_interrupt_button, slice_button_row, 2)
        slice_layout.addWidget(samples_per_pixel_label, samples_per_pixel_row,
                               0)
        slice_layout.addWidget(samples_per_pixel_edit, samples_per_pixel_row,
                               1)
        self.__slicer_options_widget.setLayout(slice_layout)

    @Slot(float)
    def set_scaling(self, value):
        if self.uniform_scaling.isChecked():
            self.__slicer_widget.set_x_scale(value)
            self.__slicer_widget.set_y_scale(value)
            self.__slicer_widget.set_z_scale(value)
            self.scale_x_spin.setValue(value)
            self.scale_y_spin.setValue(value)
            self.scale_z_spin.setValue(value)
        else:
            self.__slicer_widget.set_x_scale(self.scale_x_spin.value())
            self.__slicer_widget.set_y_scale(self.scale_y_spin.value())
            self.__slicer_widget.set_z_scale(self.scale_z_spin.value())

    @Slot()
    def load_geometry(self):
        file_names = QFileDialog.getOpenFileNames(caption='Select Geometry',
                                                  dir='../',
                                                  filter="Files (*.obj *.stl)",
                                                  parent=self)
        loading_dialog = QMessageBox()
        loading_dialog.setText("Loading Geometry...")
        loading_dialog.setWindowTitle("AMLab Software")
        loading_dialog.setStandardButtons(QMessageBox.NoButton)
        loading_dialog.open()
        QGuiApplication.processEvents()
        swapyz = True
        for file_name in file_names[0]:
            if self.__slicer_widget.load_geometry(file_name, swapyz):
                self.geometry_list.addItem(
                    self.__slicer_widget.geometry_name_list[
                        self.__slicer_widget.geometries_loaded - 1])
                self.geometry_list.setCurrentIndex(self.geometry_list.count() -
                                                   1)
        QGuiApplication.processEvents()

    @Slot()
    def remove_geometry(self):
        self.__slicer_widget.remove_geometry()
        self.geometry_list.removeItem(self.geometry_list.currentIndex())

    @Slot()
    def start_slicing_process(self):
        directory_name = QFileDialog.getExistingDirectory(
            caption='Select Directory', dir='../', parent=self)
        if len(directory_name) > 0:
            self.__slicer_widget.prepare_for_slicing(directory=directory_name)

    @Slot(float, float, float)
    def update_size_label(self, width, depth, height):
        self.physical_size_label.setText(
            f'Width: {width:.3f} mm, Depth: {depth:.3f} mm, Height: {height:.3f} mm'
        )

    @Slot(float)
    def update_fps_label(self, fps):
        self.fps_label.setText(f'fps: {fps:.2f}')

    @Slot(float, float)
    def update_slices_label(self, slice, total_slices):
        self.slices_label.setText(
            f'Slicing progress: {slice:.0f}/{total_slices:.0f}')

    @Slot(int)
    def update_unit_of_measure(self, index):
        self.__slicer_widget.set_unit_of_measurement(
            self.list_of_measures_coefficients[index])

    @Slot(int)
    def update_geometry_transformations(self, index):
        if index >= 0:
            self.__slicer_widget.current_geometry_idx = index
            x_rot = self.__slicer_widget.get_x_rot()
            y_rot = self.__slicer_widget.get_y_rot()
            z_rot = self.__slicer_widget.get_z_rot()
            x_scale = self.__slicer_widget.get_x_scale()
            y_scale = self.__slicer_widget.get_y_scale()
            z_scale = self.__slicer_widget.get_z_scale()
            x_pos = self.__slicer_widget.get_x_pos()
            z_pos = self.__slicer_widget.get_z_pos()
            unit_measurement = self.__slicer_widget.get_unit_of_measurement()
            self.__geometry_widget.blockSignals(True)
            self.rotate_x_slider.setValue(x_rot)
            self.rotate_x_spin.setValue(x_rot)
            self.rotate_y_slider.setValue(y_rot)
            self.rotate_y_spin.setValue(y_rot)
            self.rotate_z_slider.setValue(z_rot)
            self.rotate_z_spin.setValue(z_rot)
            self.translate_x_slider.setValue(x_pos)
            self.translate_x_spin.setValue(x_pos)
            self.translate_z_slider.setValue(z_pos)
            self.translate_z_spin.setValue(z_pos)
            self.scale_x_spin.setValue(x_scale)
            self.scale_y_spin.setValue(y_scale)
            self.scale_z_spin.setValue(z_scale)
            self.unit_of_measure_combo.setCurrentIndex(
                self.list_of_measures_coefficients.index(unit_measurement))
            self.__geometry_widget.blockSignals(False)
Beispiel #13
0
 def __init_projector_widget__(self, parent=None):
     self.__projector_widget = QGroupBox("Projector Options", parent)
     # self.__projector_widget.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
     mirror_x = QCheckBox("Mirror X")
     mirror_x.setChecked(self.dlp_controller.is_horizontal_mirrored())
     mirror_x.toggled.connect(self.dlp_controller.set_horizontal_mirroring)
     mirror_y = QCheckBox("Mirror Y")
     mirror_y.setChecked(self.dlp_controller.is_vertical_mirrored())
     mirror_y.toggled.connect(self.dlp_controller.set_vertical_mirroring)
     start_projector_button = QPushButton("Start Projector",
                                          self.__projector_widget)
     start_projector_button.clicked.connect(
         self.dlp_controller.start_projector)
     project_pattern_button = QPushButton("Project Pattern",
                                          self.__projector_widget)
     project_pattern_button.clicked.connect(
         self.dlp_controller.project_calibration_pattern)
     print_position_button = QPushButton("Print Position",
                                         self.__projector_widget)
     print_position_button.clicked.connect(
         self.dlp_controller.print_motor_position)
     home_projector_button = QPushButton("Home Projector",
                                         self.__projector_widget)
     home_projector_button.clicked.connect(
         self.dlp_controller.home_projector)
     move_projector_button = QPushButton("Move Projector",
                                         self.__projector_widget)
     move_projector_button.clicked.connect(
         self.dlp_controller.move_projector)
     move_projector_edit = QDoubleSpinBox(self.__projector_widget)
     move_projector_edit.setSuffix("mm")
     move_projector_edit.setMaximum(10000)
     move_projector_edit.setMinimum(-10000)
     move_projector_edit.setDecimals(3)
     move_projector_edit.setSingleStep(0.001)
     move_projector_edit.valueChanged.connect(
         self.dlp_controller.update_projector_distance)
     set_amplitude_button = QPushButton("Set Projector Amplitude",
                                        self.__projector_widget)
     set_amplitude_button.clicked.connect(
         self.dlp_controller.set_projector_amplitude)
     set_amplitude_edit = QSpinBox(self.__projector_widget)
     set_amplitude_edit.setMaximum(1000)
     set_amplitude_edit.setMinimum(0)
     set_amplitude_edit.setValue(self.dlp_controller.projector_amplitude)
     set_amplitude_edit.valueChanged.connect(
         self.dlp_controller.update_projector_amplitude)
     lock_unlock_projector_button = QPushButton("Lock/Unlock Projector",
                                                self.__projector_widget)
     lock_unlock_projector_button.clicked.connect(
         self.dlp_controller.lock_unlock_projector)
     projector_layout = QGridLayout(self.__projector_widget)
     # projector_layout.addWidget(projector_label, 0, 0)
     projector_layout.addWidget(mirror_x, 0, 1)
     projector_layout.addWidget(mirror_y, 0, 2)
     projector_layout.addWidget(start_projector_button, 1, 0, 1, 1)
     projector_layout.addWidget(project_pattern_button, 1, 1, 1, 1)
     projector_layout.addWidget(print_position_button, 1, 2, 1, 1)
     projector_layout.addWidget(home_projector_button, 2, 0, 1, 1)
     projector_layout.addWidget(move_projector_button, 2, 1, 1, 1)
     projector_layout.addWidget(move_projector_edit, 2, 2)
     projector_layout.addWidget(set_amplitude_button, 3, 0, 1, 1)
     projector_layout.addWidget(set_amplitude_edit, 3, 1)
     projector_layout.addWidget(lock_unlock_projector_button, 3, 2, 1, 1)
     self.__projector_widget.setLayout(projector_layout)
Beispiel #14
0
class WidgetConfig(QGroupBox):
    def __init__(self):
        super(WidgetConfig, self).__init__()

        HEIGHT = 40

        grid = QGridLayout()

        # 使用默认摄像头复选框
        self.check_camera = QCheckBox('Use default camera')
        self.check_camera.setChecked(False)
        self.check_camera.stateChanged.connect(self.slot_check_camera)

        grid.addWidget(self.check_camera, 0, 0, 1, 3)  # 一行三列

        # 选择视频文件
        label_video = QLabel('Detect File')
        self.line_video = QLineEdit()
        if 'video' in GLOBAL.config:
            self.line_video.setText(GLOBAL.config['video'])
        self.line_video.setFixedHeight(HEIGHT)
        self.line_video.setEnabled(False)
        self.line_video.editingFinished.connect(
            lambda: GLOBAL.record_config({'video': self.line_video.text()}))

        self.btn_video = QPushButton('Choose')
        self.btn_video.setFixedHeight(HEIGHT)
        self.btn_video.setEnabled(False)
        self.btn_video.clicked.connect(self.choose_video_file)

        self.slot_check_camera()

        grid.addWidget(label_video, 1, 0)
        grid.addWidget(self.line_video, 1, 1)
        grid.addWidget(self.btn_video, 1, 2)

        # 选择权重文件
        label_weights = QLabel('Weights File')
        self.line_weights = QLineEdit()
        if 'weights' in GLOBAL.config:
            self.line_weights.setText(GLOBAL.config['weights'])
        self.line_weights.setFixedHeight(HEIGHT)
        self.line_weights.editingFinished.connect(lambda: GLOBAL.record_config(
            {'weights': self.line_weights.text()}))

        self.btn_weights = QPushButton('Choose')
        self.btn_weights.setFixedHeight(HEIGHT)
        self.btn_weights.clicked.connect(self.choose_weights_file)

        grid.addWidget(label_weights, 2, 0)
        grid.addWidget(self.line_weights, 2, 1)
        grid.addWidget(self.btn_weights, 2, 2)

        # 是否使用GPU
        label_device = QLabel('CUDA device')
        self.line_device = QLineEdit('gpu')
        if 'device' in GLOBAL.config:
            self.line_device.setText(GLOBAL.config['device'])
        else:
            self.line_device.setText('cpu')
        self.line_device.setPlaceholderText('cpu or 0 or 0,1,2,3')
        self.line_device.setFixedHeight(HEIGHT)
        self.line_device.editingFinished.connect(
            lambda: GLOBAL.record_config({'device': self.line_device.text()}))

        grid.addWidget(label_device, 3, 0)
        grid.addWidget(self.line_device, 3, 1, 1, 2)

        # 设置图像大小
        label_size = QLabel('Img Size')
        self.combo_size = QComboBox()
        self.combo_size.setFixedHeight(HEIGHT)
        self.combo_size.setStyleSheet(
            'QAbstractItemView::item {height: 40px;}')
        self.combo_size.setView(QListView())
        self.combo_size.addItem('320', 320)
        self.combo_size.addItem('416', 416)
        self.combo_size.addItem('480', 480)
        self.combo_size.addItem('544', 544)
        self.combo_size.addItem('640', 640)
        self.combo_size.setCurrentIndex(2)
        self.combo_size.currentIndexChanged.connect(
            lambda: GLOBAL.record_config(
                {'img_size': self.combo_size.currentData()}))

        grid.addWidget(label_size, 4, 0)
        grid.addWidget(self.combo_size, 4, 1, 1, 2)

        #choose net camera
        label_stream = QLabel('NetVedioStream')
        self.combo_stream = QComboBox()
        self.combo_stream.setFixedHeight(HEIGHT)
        self.combo_stream.setStyleSheet(
            'QAbstractItemView::item {height: 40px;}')
        self.combo_stream.setView(QListView())
        self.combo_stream.addItem('rtsp://*****:*****@192.168.0.65/',
                                  'rtsp://*****:*****@192.168.0.65/')
        self.combo_stream.addItem('rtsp://*****:*****@192.168.0.66/',
                                  'rtsp://*****:*****@192.168.0.66/')
        self.combo_stream.addItem('rtsp://*****:*****@192.168.0.67/',
                                  'rtsp://*****:*****@192.168.0.67/')
        self.combo_stream.addItem('rtsp://*****:*****@192.168.0.68/',
                                  'rtsp://*****:*****@192.168.0.68/')
        self.combo_stream.addItem('rtsp://*****:*****@192.168.0.65/',
                                  'rtsp://*****:*****@192.168.0.65/')
        self.combo_stream.setCurrentIndex(0)
        self.combo_stream.currentIndexChanged.connect(
            lambda: GLOBAL.record_config(
                {'netstreamvedio': self.combo_stream.currentData()}))

        grid.addWidget(label_stream, 5, 0)
        grid.addWidget(self.combo_stream, 5, 1, 1, 2)

        # 设置置信度阈值
        label_conf = QLabel('Confidence')
        self.spin_conf = QDoubleSpinBox()
        self.spin_conf.setFixedHeight(HEIGHT)
        self.spin_conf.setDecimals(1)
        self.spin_conf.setRange(0.1, 0.9)
        self.spin_conf.setSingleStep(0.1)
        if 'conf_thresh' in GLOBAL.config:
            self.spin_conf.setValue(GLOBAL.config['conf_thresh'])
        else:
            self.spin_conf.setValue(0.4)  # 默认值
            GLOBAL.record_config({'conf_thresh': 0.4})
        self.spin_conf.valueChanged.connect(lambda: GLOBAL.record_config(
            {'conf_thresh': round(self.spin_conf.value(), 1)}))

        grid.addWidget(label_conf, 6, 0)
        grid.addWidget(self.spin_conf, 6, 1, 1, 2)

        # 设置IOU阈值
        label_iou = QLabel('IOU')
        self.spin_iou = QDoubleSpinBox()
        self.spin_iou.setFixedHeight(HEIGHT)
        self.spin_iou.setDecimals(1)
        self.spin_iou.setRange(0.1, 0.9)
        self.spin_iou.setSingleStep(0.1)
        if 'iou_thresh' in GLOBAL.config:
            self.spin_iou.setValue(GLOBAL.config['iou_thresh'])
        else:
            self.spin_iou.setValue(0.5)  # 默认值
            GLOBAL.record_config({'iou_thresh': 0.5})
        self.spin_iou.valueChanged.connect(lambda: GLOBAL.record_config(
            {'iou_thresh': round(self.spin_iou.value(), 1)}))

        grid.addWidget(label_iou, 7, 0)
        grid.addWidget(self.spin_iou, 7, 1, 1, 2)

        # class-agnostic NMS
        self.check_agnostic = QCheckBox('Agnostic')
        if 'agnostic' in GLOBAL.config:
            self.check_agnostic.setChecked(GLOBAL.config['agnostic'])
        else:
            self.check_agnostic.setChecked(True)
        self.check_agnostic.stateChanged.connect(lambda: GLOBAL.record_config(
            {'agnostic': self.check_agnostic.isChecked()}))

        grid.addWidget(self.check_agnostic, 8, 0, 1, 3)  # 一行三列

        # augmented inference
        self.check_augment = QCheckBox('Augment')
        if 'augment' in GLOBAL.config:
            self.check_augment.setChecked(GLOBAL.config['augment'])
        else:
            self.check_augment.setChecked(True)
        self.check_augment.stateChanged.connect(lambda: GLOBAL.record_config(
            {'augment': self.check_augment.isChecked()}))

        grid.addWidget(self.check_augment, 9, 0, 1, 3)  # 一行三列

        self.setLayout(grid)  # 设置布局

    def slot_check_camera(self):
        check = self.check_camera.isChecked()
        GLOBAL.record_config({'use_camera': check})  # 保存配置
        if check:
            self.line_video.setEnabled(False)
            self.btn_video.setEnabled(False)
        else:
            self.line_video.setEnabled(True)
            self.btn_video.setEnabled(True)

    def choose_weights_file(self):
        """从系统中选择权重文件"""
        file = QFileDialog.getOpenFileName(
            self, "Pre-trained YOLOv5 Weights", "./",
            "Weights Files (*.pt);;All Files (*)")
        if file[0] != '':
            self.line_weights.setText(file[0])
            GLOBAL.record_config({'weights': file[0]})

    def choose_video_file(self):
        """从系统中选择视频文件"""
        file = QFileDialog.getOpenFileName(self, "Video Files", "./",
                                           "Video Files (*)")
        if file[0] != '':
            self.line_video.setText(file[0])
            GLOBAL.record_config({'video': file[0]})

    def save_config(self):
        """保存当前的配置到配置文件"""
        config = {
            'use_camera': self.check_camera.isChecked(),
            'video': self.line_video.text(),
            'weights': self.line_weights.text(),
            'device': self.line_device.text(),
            'img_size': self.combo_size.currentData(),
            'conf_thresh': round(self.spin_conf.value(), 1),
            'iou_thresh': round(self.spin_iou.value(), 1),
            'agnostic': self.check_agnostic.isChecked(),
            'augment': self.check_augment.isChecked(),
            'netstreamvedio': self.combo_stream.currentData()
        }
        GLOBAL.record_config(config)
Beispiel #15
0
class DomainDock(PlotterDock):
    """
    Domain options dock
    """
    def __init__(self, model, font_metric, parent=None):
        super().__init__(model, font_metric, parent)

        self.setAllowedAreas(QtCore.Qt.LeftDockWidgetArea)

        # Create Controls
        self._createOriginBox()
        self._createOptionsBox()
        self._createResolutionBox()

        # Create submit button
        self.applyButton = QPushButton("Apply Changes")
        # Mac bug fix
        self.applyButton.setMinimumHeight(self.font_metric.height() * 1.6)
        self.applyButton.clicked.connect(self.main_window.applyChanges)

        # Create Zoom box
        self.zoomBox = QSpinBox()
        self.zoomBox.setSuffix(' %')
        self.zoomBox.setRange(25, 2000)
        self.zoomBox.setValue(100)
        self.zoomBox.setSingleStep(25)
        self.zoomBox.valueChanged.connect(self.main_window.editZoom)
        self.zoomLayout = QHBoxLayout()
        self.zoomLayout.addWidget(QLabel('Zoom:'))
        self.zoomLayout.addWidget(self.zoomBox)
        self.zoomLayout.setContentsMargins(0, 0, 0, 0)
        self.zoomWidget = QWidget()
        self.zoomWidget.setLayout(self.zoomLayout)

        # Create Layout
        self.dockLayout = QVBoxLayout()
        self.dockLayout.addWidget(QLabel("Geometry/Properties"))
        self.dockLayout.addWidget(HorizontalLine())
        self.dockLayout.addWidget(self.originGroupBox)
        self.dockLayout.addWidget(self.optionsGroupBox)
        self.dockLayout.addWidget(self.resGroupBox)
        self.dockLayout.addWidget(HorizontalLine())
        self.dockLayout.addWidget(self.zoomWidget)
        self.dockLayout.addWidget(HorizontalLine())
        self.dockLayout.addStretch()
        self.dockLayout.addWidget(self.applyButton)
        self.dockLayout.addWidget(HorizontalLine())

        self.optionsWidget = QWidget()
        self.optionsWidget.setLayout(self.dockLayout)
        self.setWidget(self.optionsWidget)

    def _createOriginBox(self):

        # X Origin
        self.xOrBox = QDoubleSpinBox()
        self.xOrBox.setDecimals(9)
        self.xOrBox.setRange(-99999, 99999)
        xbox_connector = partial(self.main_window.editSingleOrigin,
                                 dimension=0)
        self.xOrBox.valueChanged.connect(xbox_connector)

        # Y Origin
        self.yOrBox = QDoubleSpinBox()
        self.yOrBox.setDecimals(9)
        self.yOrBox.setRange(-99999, 99999)
        ybox_connector = partial(self.main_window.editSingleOrigin,
                                 dimension=1)
        self.yOrBox.valueChanged.connect(ybox_connector)

        # Z Origin
        self.zOrBox = QDoubleSpinBox()
        self.zOrBox.setDecimals(9)
        self.zOrBox.setRange(-99999, 99999)
        zbox_connector = partial(self.main_window.editSingleOrigin,
                                 dimension=2)
        self.zOrBox.valueChanged.connect(zbox_connector)

        # Origin Form Layout
        self.orLayout = QFormLayout()
        self.orLayout.addRow('X:', self.xOrBox)
        self.orLayout.addRow('Y:', self.yOrBox)
        self.orLayout.addRow('Z:', self.zOrBox)
        self.orLayout.setLabelAlignment(QtCore.Qt.AlignLeft)
        self.orLayout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)

        # Origin Group Box
        self.originGroupBox = QGroupBox('Origin')
        self.originGroupBox.setLayout(self.orLayout)

    def _createOptionsBox(self):

        # Width
        self.widthBox = QDoubleSpinBox(self)
        self.widthBox.setRange(.1, 99999)
        self.widthBox.setDecimals(9)
        self.widthBox.valueChanged.connect(self.main_window.editWidth)

        # Height
        self.heightBox = QDoubleSpinBox(self)
        self.heightBox.setRange(.1, 99999)
        self.heightBox.setDecimals(9)
        self.heightBox.valueChanged.connect(self.main_window.editHeight)

        # ColorBy
        self.colorbyBox = QComboBox(self)
        self.colorbyBox.addItem("material")
        self.colorbyBox.addItem("cell")
        self.colorbyBox.addItem("temperature")
        self.colorbyBox.addItem("density")
        self.colorbyBox.currentTextChanged[str].connect(
            self.main_window.editColorBy)

        # Universe level (applies to cell coloring only)
        self.universeLevelBox = QComboBox(self)
        self.universeLevelBox.addItem('all')
        for i in range(self.model.max_universe_levels):
            self.universeLevelBox.addItem(str(i))
        self.universeLevelBox.currentTextChanged[str].connect(
            self.main_window.editUniverseLevel)

        # Alpha
        self.domainAlphaBox = QDoubleSpinBox(self)
        self.domainAlphaBox.setValue(self.model.activeView.domainAlpha)
        self.domainAlphaBox.setSingleStep(0.05)
        self.domainAlphaBox.setDecimals(2)
        self.domainAlphaBox.setRange(0.0, 1.0)
        self.domainAlphaBox.valueChanged.connect(self.main_window.editPlotAlpha)

        # Visibility
        self.visibilityBox = QCheckBox(self)
        self.visibilityBox.stateChanged.connect(
            self.main_window.editPlotVisibility)

        # Outlines
        self.outlinesBox = QCheckBox(self)
        self.outlinesBox.stateChanged.connect(self.main_window.toggleOutlines)

        # Basis
        self.basisBox = QComboBox(self)
        self.basisBox.addItem("xy")
        self.basisBox.addItem("xz")
        self.basisBox.addItem("yz")
        self.basisBox.currentTextChanged.connect(self.main_window.editBasis)

        # Advanced Color Options
        self.colorOptionsButton = QPushButton('Color Options...')
        self.colorOptionsButton.setMinimumHeight(self.font_metric.height() * 1.6)
        self.colorOptionsButton.clicked.connect(self.main_window.showColorDialog)

        # Options Form Layout
        self.opLayout = QFormLayout()
        self.opLayout.addRow('Width:', self.widthBox)
        self.opLayout.addRow('Height:', self.heightBox)
        self.opLayout.addRow('Basis:', self.basisBox)
        self.opLayout.addRow('Color By:', self.colorbyBox)
        self.opLayout.addRow('Universe Level:', self.universeLevelBox)
        self.opLayout.addRow('Plot alpha:', self.domainAlphaBox)
        self.opLayout.addRow('Visible:', self.visibilityBox)
        self.opLayout.addRow('Outlines:', self.outlinesBox)
        self.opLayout.addRow(self.colorOptionsButton)
        self.opLayout.setLabelAlignment(QtCore.Qt.AlignLeft)
        self.opLayout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)

        # Options Group Box
        self.optionsGroupBox = QGroupBox('Options')
        self.optionsGroupBox.setLayout(self.opLayout)

    def _createResolutionBox(self):

        # Horizontal Resolution
        self.hResBox = QSpinBox(self)
        self.hResBox.setRange(1, 99999)
        self.hResBox.setSingleStep(25)
        self.hResBox.setSuffix(' px')
        self.hResBox.valueChanged.connect(self.main_window.editHRes)

        # Vertical Resolution
        self.vResLabel = QLabel('Pixel Height:')
        self.vResBox = QSpinBox(self)
        self.vResBox.setRange(1, 99999)
        self.vResBox.setSingleStep(25)
        self.vResBox.setSuffix(' px')
        self.vResBox.valueChanged.connect(self.main_window.editVRes)

        # Ratio checkbox
        self.ratioCheck = QCheckBox("Fixed Aspect Ratio", self)
        self.ratioCheck.stateChanged.connect(self.main_window.toggleAspectLock)

        # Resolution Form Layout
        self.resLayout = QFormLayout()
        self.resLayout.addRow(self.ratioCheck)
        self.resLayout.addRow('Pixel Width:', self.hResBox)
        self.resLayout.addRow(self.vResLabel, self.vResBox)
        self.resLayout.setLabelAlignment(QtCore.Qt.AlignLeft)
        self.resLayout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)

        # Resolution Group Box
        self.resGroupBox = QGroupBox("Resolution")
        self.resGroupBox.setLayout(self.resLayout)

    def updateDock(self):
        self.updateOrigin()
        self.updateWidth()
        self.updateHeight()
        self.updateColorBy()
        self.updateUniverseLevel()
        self.updatePlotAlpha()
        self.updatePlotVisibility()
        self.updateOutlines()
        self.updateBasis()
        self.updateAspectLock()
        self.updateHRes()
        self.updateVRes()

    def updateOrigin(self):
        self.xOrBox.setValue(self.model.activeView.origin[0])
        self.yOrBox.setValue(self.model.activeView.origin[1])
        self.zOrBox.setValue(self.model.activeView.origin[2])

    def updateWidth(self):
        self.widthBox.setValue(self.model.activeView.width)

    def updateHeight(self):
        self.heightBox.setValue(self.model.activeView.height)

    def updateColorBy(self):
        self.colorbyBox.setCurrentText(self.model.activeView.colorby)
        if self.model.activeView.colorby != 'cell':
            self.universeLevelBox.setEnabled(False)
        else:
            self.universeLevelBox.setEnabled(True)

    def updateUniverseLevel(self):
        self.universeLevelBox.setCurrentIndex(self.model.activeView.level + 1)

    def updatePlotAlpha(self):
        self.domainAlphaBox.setValue(self.model.activeView.domainAlpha)

    def updatePlotVisibility(self):
        self.visibilityBox.setChecked(self.model.activeView.domainVisible)

    def updateOutlines(self):
        self.outlinesBox.setChecked(self.model.activeView.outlines)

    def updateBasis(self):
        self.basisBox.setCurrentText(self.model.activeView.basis)

    def updateAspectLock(self):
        aspect_lock = bool(self.model.activeView.aspectLock)
        self.ratioCheck.setChecked(aspect_lock)
        self.vResBox.setDisabled(aspect_lock)
        self.vResLabel.setDisabled(aspect_lock)

    def updateHRes(self):
        self.hResBox.setValue(self.model.activeView.h_res)

    def updateVRes(self):
        self.vResBox.setValue(self.model.activeView.v_res)

    def revertToCurrent(self):
        cv = self.model.currentView

        self.xOrBox.setValue(cv.origin[0])
        self.yOrBox.setValue(cv.origin[1])
        self.zOrBox.setValue(cv.origin[2])

        self.widthBox.setValue(cv.width)
        self.heightBox.setValue(cv.height)

    def resizeEvent(self, event):
        self.main_window.resizeEvent(event)

    hideEvent = showEvent = moveEvent = resizeEvent
Beispiel #16
0
class ConfigDialog(QDialog):
    config_changed = Signal()

    def __init__(self, requester, config, parent=None):
        super().__init__(parent)
        self.requester = requester
        self.requester.pin_needed.connect(self.input_pin)
        self.requester.umi_made.connect(self.write_umi)
        self.requester.msg_passed.connect(self.error_msg)
        self.config = config
        self.lbl_id = QLabel('계정명')
        self.lbl_id.setAlignment(Qt.AlignCenter)
        self.lbl_pw = QLabel('비밀번호')
        self.lbl_pw.setAlignment(Qt.AlignCenter)
        self.lbl_umi = QLabel('umi 쿠키')
        self.lbl_umi.setAlignment(Qt.AlignCenter)
        self.lbl_ua = QLabel('유저 에이전트')
        self.lbl_ua.setAlignment(Qt.AlignCenter)
        self.lbl_delay = QLabel('저속 간격')
        self.lbl_delay.setAlignment(Qt.AlignCenter)
        self.lbl_msg = QLabel('')
        self.line_id = QLineEdit()
        self.line_pw = QLineEdit()
        self.line_pw.setEchoMode(QLineEdit.PasswordEchoOnEdit)
        self.line_umi = QLineEdit()
        self.line_umi.setPlaceholderText('로그인 시 자동 입력')
        self.line_ua = QLineEdit()
        self.line_delay = QDoubleSpinBox()
        self.line_delay.setMinimum(3)
        self.line_delay.setDecimals(1)
        self.line_delay.setSuffix('초')
        self.line_delay.setSingleStep(0.1)
        self.btn_save = NPButton('저장', 10, self)
        self.btn_save.clicked.connect(self.save)
        self.btn_cancel = NPButton('취소', 10, self)
        self.btn_cancel.clicked.connect(self.reject)
        self.btn_get_umi = NPButton('로그인', 10, self)
        self.btn_get_umi.setSizePolicy(QSizePolicy.Preferred,
                                       QSizePolicy.MinimumExpanding)
        self.btn_get_umi.clicked.connect(self.get_umi)
        grid = QGridLayout()
        grid.addWidget(self.lbl_id, 0, 0, 1, 1)
        grid.addWidget(self.line_id, 0, 1, 1, 6)
        grid.addWidget(self.lbl_pw, 1, 0, 1, 1)
        grid.addWidget(self.line_pw, 1, 1, 1, 6)
        grid.addWidget(self.btn_get_umi, 0, 7, 2, 2)
        grid.addWidget(self.lbl_umi, 2, 0, 1, 1)
        grid.addWidget(self.line_umi, 2, 1, 1, 8)
        grid.addWidget(self.lbl_ua, 3, 0, 1, 1)
        grid.addWidget(self.line_ua, 3, 1, 1, 8)
        grid.addWidget(self.lbl_delay, 4, 0, 1, 1)
        grid.addWidget(self.line_delay, 4, 1, 1, 8)
        grid.addWidget(self.lbl_msg, 5, 0, 1, 4)
        grid.addWidget(self.btn_save, 5, 5, 1, 2)
        grid.addWidget(self.btn_cancel, 5, 7, 1, 2)
        self.setLayout(grid)
        self.input_dialog = InputDialog(self)
        self.input_dialog.input.setInputMask('999999')
        self.setWindowTitle('개인정보')
        self.setWindowIcon(QIcon('icon.png'))
        self.setStyleSheet('font: 10pt \'맑은 고딕\'')
        self.setWindowFlag(Qt.WindowContextHelpButtonHint, False)
        self.c_login, self.c_work = {}, {}

    @Slot(str)
    def error_msg(self, t):
        self.lbl_msg.setText(t)

    def load(self):
        self.line_id.setText(self.config.c['login']['ID'])
        self.line_pw.setText(self.config.c['login']['PW'])
        self.line_umi.setText(self.config.c['login']['UMI'])
        self.line_ua.setText(self.config.c['login']['UA'])
        self.line_ua.setCursorPosition(0)
        self.line_delay.setValue(float(self.config.c['work']['DELAY']))
        self.lbl_msg.clear()
        ok = self.exec_()
        if ok == QDialog.Accepted:
            self.config_changed.emit()

    def save(self):
        self.config.save(login={
            'ID': self.line_id.text().strip(),
            'PW': self.line_pw.text().strip(),
            'UMI': self.line_umi.text().strip(),
            'UA': self.line_ua.text().strip()
        },
                         delay=self.line_delay.value())
        self.accept()

    def get_umi(self):
        self.lbl_msg.setText('로그인 시도...')
        self.line_umi.clear()
        self.input_dialog.input.clear()
        self.requester.init_login(self.line_id.text().strip(),
                                  self.line_pw.text().strip())

    @Slot(str)
    def write_umi(self, umi):
        self.line_umi.setText(umi)

    @Slot(str)
    def input_pin(self, mail):
        pin, ok = self.input_dialog.get_text('로그인 PIN 입력',
                                             f'이메일({mail})로 전송된 PIN을 입력해주세요.')
        if ok:
            if pin:
                self.requester.typed_pin = pin
            else:
                self.requester.typed_pin = 'nothing'
        else:
            self.requester.typed_pin = 'deny'
class AddRecipeWidget(QWidget):
    def __init__(self, database, parent):
        QWidget.__init__(self)
        self.recipe_ingredients = 0
        self.add_recipe_win = QWidget()
        self.add_recipe_win.setFixedWidth(400)
        self.add_recipe_win.setWindowTitle("Add Recipe")
        add_rec_main_layout = QVBoxLayout()

        self.meal_planner_db = database
        self.setParent(parent)

        self.rec_name_input = QLineEdit()
        self.rec_desc_input = QLineEdit()
        self.rec_source_input = QLineEdit()
        rec_form_layout = QFormLayout()
        rec_form_layout.addRow(QLabel("Recipe Name"), self.rec_name_input)
        rec_form_layout.addRow(QLabel("Recipe Desc"), self.rec_desc_input)
        rec_form_layout.addRow(QLabel("Recipe Source"), self.rec_source_input)
        add_rec_main_layout.addLayout(rec_form_layout)

        rec_info_layout = QHBoxLayout()
        difficulty_layout = QVBoxLayout()
        self.difficulty_spinbox = QSpinBox()
        self.difficulty_spinbox.setRange(1, 5)
        self.difficulty_spinbox.setValue(3)
        difficulty_layout.addWidget(QLabel("Difficulty"))
        difficulty_layout.addWidget(self.difficulty_spinbox)

        prep_time_layout = QVBoxLayout()
        self.prep_time_spinbox = QSpinBox()
        self.prep_time_spinbox.setRange(0, 600)
        self.prep_time_spinbox.setValue(30)
        prep_time_layout.addWidget(QLabel("Prep. Time (min.)"))
        prep_time_layout.addWidget(self.prep_time_spinbox)

        rating_layout = QVBoxLayout()
        self.rating_spinbox = QSpinBox()
        self.rating_spinbox.setRange(1, 5)
        self.rating_spinbox.setValue(3)
        rating_layout.addWidget(QLabel("Rating"))
        rating_layout.addWidget(self.rating_spinbox)

        rec_info_layout.addLayout(difficulty_layout)
        rec_info_layout.addLayout(prep_time_layout)
        rec_info_layout.addLayout(rating_layout)

        add_rec_main_layout.addLayout(rec_info_layout)

        rec_tags_layout = QHBoxLayout()
        rec_cuisine_layout = QVBoxLayout()
        cuisines = [
            "Mexican", "Swedish", "Austrian", "Italian", "Spanish", "American",
            "British", "Thai", "Greek", "Vietnamese", "Caribbean", "Japanese",
            "Chinese", "Indian", "French", "Swiss", "Portuguese", "Korean",
            "Turkish", "Moroccan", "Russian", "Malaysian", "Philippines",
            "Ethiopian", "Lebanese", "Arab", "Peruvian", "Brazilian", "Asian",
            "Middle Eastern", "South American", "African", "-"
        ]
        cuisines.sort()
        self.tag_cuisine = QComboBox()
        self.tag_cuisine.addItems(cuisines)
        rec_cuisine_layout.addWidget(QLabel("Cuisine"))
        rec_cuisine_layout.addWidget(self.tag_cuisine)
        rec_tags_layout.addLayout(rec_cuisine_layout)

        rec_category_layout = QVBoxLayout()
        categories = [
            "Beef & Calf", "Chicken & Poultry", "Lamb", "Pork", "Preservation",
            "Salad", "Sandwich", "Soup", "Stew", "Pasta", "Rice",
            "Grain & Beans", "Fish & Seafood", "Vegetables", "Eggs & Cheese",
            "BBQ", "Fruits", "Cake & Pie (Sweet)", "Pie", "Bread", "Beverage",
            "Cookies & Sweets", "Sauce", "-"
        ]
        categories.sort()
        self.tag_category = QComboBox()
        self.tag_category.addItems(categories)
        rec_category_layout.addWidget(QLabel("Category"))
        rec_category_layout.addWidget(self.tag_category)
        rec_tags_layout.addLayout(rec_category_layout)

        rec_meal_type_layout = QVBoxLayout()
        meal_types = [
            "Breakfast", "Brunch", "Lunch", "Dinner", "Dessert", "Starter",
            "Side", "Buffet", "Snack", "-"
        ]
        meal_types.sort()
        self.tag_meal_types = QComboBox()
        self.tag_meal_types.addItems(meal_types)
        rec_meal_type_layout.addWidget(QLabel("Meal Type"))
        rec_meal_type_layout.addWidget(self.tag_meal_types)
        rec_tags_layout.addLayout(rec_meal_type_layout)

        add_rec_main_layout.addLayout(rec_tags_layout)

        self.ingredient_name_input = QLineEdit()
        self.ingredient_qty_input = QDoubleSpinBox()
        self.ingredient_qty_input.setValue(1.0)
        self.ingredient_qty_input.setMaximum(1000)
        self.ingredient_qty_input.setDecimals(2)
        self.ingredient_unit_input = QComboBox()
        self.ingredient_unit_input.addItems(
            ["g", "ml", "dl", "l", "msk", "tsk", "st", "-"])
        add_ingredient_btn = QPushButton("Create ingredient")
        add_ingredient_btn.clicked.connect(self.create_ingredient)
        add_ingredient_layout = QHBoxLayout()
        add_rec_main_layout.addWidget(QLabel("Ingredient"))
        add_ingredient_layout.addWidget(self.ingredient_name_input)
        add_ingredient_layout.addWidget(self.ingredient_qty_input)
        add_ingredient_layout.addWidget(self.ingredient_unit_input)
        add_ingredient_layout.addWidget(add_ingredient_btn)
        add_rec_main_layout.addLayout(add_ingredient_layout)

        btn_layout = QHBoxLayout()
        add_ingredient_to_recipe_btn = QPushButton("Add ingredient")
        add_ingredient_to_recipe_btn.clicked.connect(
            self.add_ingredient_to_recipe)

        del_ingredient_from_recipe_btn = QPushButton("Remove ingredient")
        del_ingredient_from_recipe_btn.clicked.connect(
            self.del_ingredient_from_recipe)
        btn_layout.addWidget(add_ingredient_to_recipe_btn)
        btn_layout.addWidget(del_ingredient_from_recipe_btn)
        add_rec_main_layout.addLayout(btn_layout)

        self.rec_ingredient_table = QTableWidget()
        self.rec_ingredient_table.setColumnCount(3)
        self.rec_ingredient_table.setHorizontalHeaderLabels(
            ["Amount", "Unit", "Ingredient"])
        header = self.rec_ingredient_table.horizontalHeader()
        header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
        header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
        header.setSectionResizeMode(2, QtWidgets.QHeaderView.Stretch)
        add_rec_main_layout.addWidget(self.rec_ingredient_table)

        self.step_count = 0
        self.add_recipe_step_btn = QPushButton("Add recipe instruction")
        add_rec_main_layout.addWidget(self.add_recipe_step_btn)
        self.add_recipe_step_btn.clicked.connect(self.add_recipe_step_win)
        self.rec_step_table = QTableWidget()
        self.rec_step_table.setColumnCount(1)
        self.rec_step_table.setHorizontalHeaderLabels(["Instructions"])
        self.rec_step_table.setWordWrap(True)
        header = self.rec_step_table.horizontalHeader()
        header.setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch)
        add_rec_main_layout.addWidget(self.rec_step_table)

        bottom_btn_layout = QHBoxLayout()
        self.add_rec_btn = QPushButton("Add recipe")
        self.add_rec_btn.clicked.connect(self.add_recipe_to_db)

        self.back_btn = QPushButton("Cancel")
        self.back_btn.clicked.connect(self.add_recipe_win.close)

        bottom_btn_layout.addWidget(self.add_rec_btn)
        bottom_btn_layout.addWidget(self.back_btn)
        add_rec_main_layout.addLayout(bottom_btn_layout)

        self.add_recipe_win.setLayout(add_rec_main_layout)
        self.add_recipe_win.show()

    @Slot()
    def add_recipe_step_win(self):
        self.rec_step_table.insertRow(self.step_count)
        self.step_count += 1

    @Slot()
    def create_ingredient(self):
        self.add_ingredient_widget = AddIngredientWidget(
            self.meal_planner_db, self, self.ingredient_name_input.text())

    @Slot()
    def add_ingredient_to_recipe(self):
        if self.meal_planner_db.ingredient_exists(
                self.ingredient_name_input.text()):
            self.rec_ingredient_table.insertRow(self.recipe_ingredients)
            self.rec_ingredient_table.setItem(
                self.recipe_ingredients, 0,
                QTableWidgetItem(str(self.ingredient_qty_input.value())))
            self.rec_ingredient_table.setItem(
                self.recipe_ingredients, 1,
                QTableWidgetItem(self.ingredient_unit_input.currentText()))
            self.rec_ingredient_table.setItem(
                self.recipe_ingredients, 2,
                QTableWidgetItem(self.ingredient_name_input.text()))
            self.recipe_ingredients += 1

            self.ingredient_name_input.clear()
            self.ingredient_qty_input.setValue(1.0)
            self.ingredient_unit_input.setCurrentIndex(0)
        else:
            print("Ingredient does not exist in database, please add it first")

    @Slot()
    def del_ingredient_from_recipe(self):
        recipe = self.rec_name_input.text()
        ingredient = self.rec_ingredient_table.currentItem().text()
        self.rec_ingredient_table.removeRow(
            self.rec_ingredient_table.currentRow())
        self.meal_planner_db.del_recipe_ingredient(recipe, ingredient)

    @Slot()
    def add_recipe_to_db(self):
        rec_id = self.meal_planner_db.get_table_len("recipes")
        self.meal_planner_db.add_recipe(rec_id, self.rec_name_input.text(),
                                        self.rec_desc_input.text(),
                                        self.rec_source_input.text(),
                                        self.difficulty_spinbox.value(),
                                        self.prep_time_spinbox.value(),
                                        self.rating_spinbox.value(),
                                        "2000-01-01", 0)

        for row in range(self.rec_ingredient_table.rowCount()):
            qty_id = self.meal_planner_db.get_table_len("measurement_qty")
            qty_id = self.meal_planner_db.add_qty(
                qty_id,
                self.rec_ingredient_table.item(row, 0).text())
            unit_id = self.meal_planner_db.get_table_len("measurement_units")
            unit_id = self.meal_planner_db.add_measurement(
                unit_id,
                self.rec_ingredient_table.item(row, 1).text())
            ing_id = self.meal_planner_db.get_ingredient_id(
                self.rec_ingredient_table.item(row, 2).text())
            if ing_id == -1:
                print("INGREDIENT DOES NOT EXIST! WE F****D UP!")
                break
            self.meal_planner_db.add_recipe_ingredient(rec_id, ing_id, unit_id,
                                                       qty_id)

        for row in range(self.step_count):
            print(row, self.rec_step_table.item(row, 0).text())
            self.meal_planner_db.add_step(
                rec_id, row,
                self.rec_step_table.item(row, 0).text())

        # Cuisine tag
        tag_id = self.meal_planner_db.get_table_len("tags")
        tag_id = self.meal_planner_db.add_tag(tag_id,
                                              self.tag_cuisine.currentText())
        self.meal_planner_db.add_recipe_tag(tag_id, rec_id)
        # Category tag
        tag_id = self.meal_planner_db.get_table_len("tags")
        tag_id = self.meal_planner_db.add_tag(tag_id,
                                              self.tag_category.currentText())
        self.meal_planner_db.add_recipe_tag(tag_id, rec_id)
        # Meal type tag
        tag_id = self.meal_planner_db.get_table_len("tags")
        tag_id = self.meal_planner_db.add_tag(
            tag_id, self.tag_meal_types.currentText())
        self.meal_planner_db.add_recipe_tag(tag_id, rec_id)

        self.rec_name_input.clear()
        self.rec_desc_input.clear()
        self.rec_ingredient_table.setRowCount(0)
        self.rec_step_table.setRowCount(0)
        self.step_count = 0

        self.parent().update_recipe_table()
Beispiel #18
0
    def __init__(self, prefs, icon=None):
        super().__init__()
        self.prefs = prefs
        self.hotkey_format_regex = r'^\<ctrl\>\+\<alt\>(\+\<shift\>)?\+[a-zA-Z0-9]$'
        if icon:
            self.setWindowIcon(icon)

        # checkbox: Include Minimized
        include_minimized = QCheckBox()
        include_minimized.setFixedWidth(35)
        include_minimized.setChecked(self.prefs["include_minimized"]["value"])
        include_minimized.stateChanged.connect(
            lambda: self.include_minimized(include_minimized.isChecked()))
        include_minimized_descr = QLabel(
            self.prefs["include_minimized"]["description"])
        include_minimized_descr.setWordWrap(True)

        include_minimized_layout = QHBoxLayout()
        include_minimized_layout.addWidget(include_minimized)
        include_minimized_layout.addWidget(include_minimized_descr)

        include_minimized_groupbox = QGroupBox("Include Minimized")
        include_minimized_groupbox.setLayout(include_minimized_layout)

        # checkbox: snap to grid
        snap_to_grid = QCheckBox()
        snap_to_grid.setFixedWidth(35)
        snap_to_grid.setChecked(self.prefs["snap_to_grid"]["value"])
        snap_to_grid.stateChanged.connect(
            lambda: self.snap_to_grid(snap_to_grid.isChecked()))
        snap_to_grid_descr = QLabel(self.prefs["snap_to_grid"]["description"])
        snap_to_grid_descr.setWordWrap(True)

        snap_to_grid_layout = QHBoxLayout()
        snap_to_grid_layout.addWidget(snap_to_grid)
        snap_to_grid_layout.addWidget(snap_to_grid_descr)

        snap_to_grid_groupbox = QGroupBox("Snap To Grid")
        snap_to_grid_groupbox.setLayout(snap_to_grid_layout)

        # checkbox: fit into screen
        fit_into_screen = QCheckBox()
        fit_into_screen.setFixedWidth(35)
        fit_into_screen.setChecked(self.prefs["fit_into_screen"]["value"])
        fit_into_screen.stateChanged.connect(
            lambda: self.fit_into_screen(fit_into_screen.isChecked()))
        fit_into_screen_descr = QLabel(
            self.prefs["fit_into_screen"]["description"])
        fit_into_screen_descr.setWordWrap(True)

        fit_into_screen_layout = QHBoxLayout()
        fit_into_screen_layout.addWidget(fit_into_screen)
        fit_into_screen_layout.addWidget(fit_into_screen_descr)

        fit_into_screen_groupbox = QGroupBox("Fit Into Screen")
        fit_into_screen_groupbox.setLayout(fit_into_screen_layout)

        # doublespinBox: match cutoff
        match_cutoff = QDoubleSpinBox()
        match_cutoff.setFixedWidth(35)
        match_cutoff.setValue(self.prefs["match_cutoff"]["value"])
        match_cutoff.setRange(0.1, 1.0)
        match_cutoff.setSingleStep(0.1)
        match_cutoff.setDecimals(1)
        match_cutoff.valueChanged.connect(
            lambda: self.match_cutoff(match_cutoff.value()))
        match_cutoff_descr = QLabel(self.prefs["match_cutoff"]["description"])
        match_cutoff_descr.setWordWrap(True)

        match_cutoff_layout = QHBoxLayout()
        match_cutoff_layout.addWidget(match_cutoff)
        match_cutoff_layout.addWidget(match_cutoff_descr)

        match_cutoff_groupbox = QGroupBox("Match Cutoff")
        match_cutoff_groupbox.setLayout(match_cutoff_layout)

        # checkbox: enable hotkeys
        enable_hotkeys = QCheckBox()
        enable_hotkeys.setFixedWidth(35)
        enable_hotkeys.setChecked(self.prefs["enable_hotkeys"]["value"])
        enable_hotkeys.stateChanged.connect(
            lambda: self.enable_hotkeys(enable_hotkeys.isChecked()))
        enable_hotkeys_descr = QLabel(
            self.prefs["enable_hotkeys"]["description"])
        enable_hotkeys_descr.setWordWrap(True)

        enable_hotkeys_layout = QHBoxLayout()
        enable_hotkeys_layout.addWidget(enable_hotkeys)
        enable_hotkeys_layout.addWidget(enable_hotkeys_descr)

        # lineedit: hotkeys shortcuts
        hotkey_freeze_new_name = QLabel("Freeze New:")
        hotkey_freeze_new_name.setFixedWidth(75)
        self.hotkey_freeze_new_status = QLabel()
        self.hotkey_freeze_new = QLineEdit(
            self.prefs["hotkeys"]["value"]["freeze_new"])
        self.hotkey_freeze_new.setFixedWidth(140)
        self.hotkey_freeze_new.editingFinished.connect(
            lambda: self.hotkey_freeze_new_update(self.hotkey_freeze_new.text(
            )))
        self.hotkey_freeze_new.cursorPositionChanged.connect(
            self.hotkey_freeze_new_status.clear)

        hotkey_freeze_new_layout = QHBoxLayout()
        hotkey_freeze_new_layout.addWidget(hotkey_freeze_new_name)
        hotkey_freeze_new_layout.addWidget(self.hotkey_freeze_new)
        hotkey_freeze_new_layout.addWidget(self.hotkey_freeze_new_status)

        hotkey_freeze_all_name = QLabel("Freeze All:")
        hotkey_freeze_all_name.setFixedWidth(75)
        self.hotkey_freeze_all_status = QLabel()
        self.hotkey_freeze_all = QLineEdit(
            self.prefs["hotkeys"]["value"]["freeze_all"])
        self.hotkey_freeze_all.setFixedWidth(140)
        self.hotkey_freeze_all.editingFinished.connect(
            lambda: self.hotkey_freeze_all_update(self.hotkey_freeze_all.text(
            )))
        self.hotkey_freeze_all.cursorPositionChanged.connect(
            self.hotkey_freeze_all_status.clear)

        hotkey_freeze_all_layout = QHBoxLayout()
        hotkey_freeze_all_layout.addWidget(hotkey_freeze_all_name)
        hotkey_freeze_all_layout.addWidget(self.hotkey_freeze_all)
        hotkey_freeze_all_layout.addWidget(self.hotkey_freeze_all_status)

        hotkey_restore_name = QLabel("Restore:")
        hotkey_restore_name.setFixedWidth(75)
        self.hotkey_restore_status = QLabel()
        self.hotkey_restore = QLineEdit(
            self.prefs["hotkeys"]["value"]["restore"])
        self.hotkey_restore.setFixedWidth(140)
        self.hotkey_restore.editingFinished.connect(
            lambda: self.hotkey_restore_update(self.hotkey_restore.text()))
        self.hotkey_restore.cursorPositionChanged.connect(
            self.hotkey_restore_status.clear)

        hotkey_restore_layout = QHBoxLayout()
        hotkey_restore_layout.addWidget(hotkey_restore_name)
        hotkey_restore_layout.addWidget(self.hotkey_restore)
        hotkey_restore_layout.addWidget(self.hotkey_restore_status)

        self.hotkeys_statusbar = QLabel()
        self.hotkeys_statusbar.setWordWrap(True)
        self.hotkeys_statusbar.setText(hotkeys_statusbar_map[
            self.prefs['enable_hotkeys']['value']]['text'])
        self.hotkeys_statusbar.setStyleSheet(hotkeys_statusbar_map[
            self.prefs['enable_hotkeys']['value']]['style'])

        close_button = QPushButton("Close")
        close_button.setMaximumWidth(75)
        close_button.clicked.connect(self.close)

        hotkeys_statusbar_layout = QHBoxLayout()
        hotkeys_statusbar_layout.addWidget(self.hotkeys_statusbar)
        hotkeys_statusbar_layout.addWidget(close_button)

        hotkeys_layout = QVBoxLayout()
        hotkeys_layout.addLayout(hotkey_freeze_new_layout)
        hotkeys_layout.addLayout(hotkey_freeze_all_layout)
        hotkeys_layout.addLayout(hotkey_restore_layout)

        self.hotkeys_groupbox = QGroupBox()
        self.hotkeys_groupbox.setFlat(True)
        self.hotkeys_groupbox.setDisabled(
            not self.prefs["enable_hotkeys"]["value"])
        self.hotkeys_groupbox.setLayout(hotkeys_layout)

        enable_hotkeys_outer_layout = QVBoxLayout()
        enable_hotkeys_outer_layout.addLayout(enable_hotkeys_layout)
        enable_hotkeys_outer_layout.addWidget(self.hotkeys_groupbox)

        enable_hotkeys_groupbox = QGroupBox("Enable Hotkeys")
        enable_hotkeys_groupbox.setLayout(enable_hotkeys_outer_layout)

        # Create main layout and add widgets
        main_layout = QVBoxLayout()
        main_layout.addWidget(include_minimized_groupbox)
        main_layout.addWidget(snap_to_grid_groupbox)
        main_layout.addWidget(fit_into_screen_groupbox)
        main_layout.addWidget(match_cutoff_groupbox)
        main_layout.addWidget(enable_hotkeys_groupbox)
        main_layout.addWidget(self.hotkeys_groupbox)
        #main_layout.addWidget(hotkeys_statusbar_groupbox)
        main_layout.addLayout(hotkeys_statusbar_layout)
        self.setLayout(main_layout)
Beispiel #19
0
        def addArrowsBox(title, indexOffset, scale):
            layout = QGridLayout()

            deltaSB = QDoubleSpinBox()
            deltaSB.setSizePolicy(QSizePolicy.Maximum,
                                  QSizePolicy.MinimumExpanding)

            if title == "Translation":
                deltaSB.setRange(-7, 7)
                deltaSB.setDecimals(3)
                deltaSB.setValue(1.0)
            else:
                deltaSB.setRange(-60, 60)
                deltaSB.setDecimals(2)
                deltaSB.setValue(10.0)

            setattr(self, "delta_" + title, deltaSB)

            deltaF = QFormLayout()
            deltaF.addRow("Delta", deltaSB)

            layout.addLayout(deltaF, 0, 0, 1, 3)

            layout.addWidget(
                positionButton(
                    style.standardIcon(QStyle.SP_ArrowUp),
                    "X+",
                    0 + indexOffset,
                    deltaSB,
                    scale,
                ),
                1,
                1,
            )
            layout.addWidget(
                positionButton(
                    style.standardIcon(QStyle.SP_ArrowDown),
                    "X-",
                    0 + indexOffset,
                    deltaSB,
                    -scale,
                ),
                3,
                1,
            )
            layout.addWidget(
                positionButton(
                    style.standardIcon(QStyle.SP_ArrowLeft),
                    "Y-",
                    1 + indexOffset,
                    deltaSB,
                    -scale,
                ),
                2,
                0,
            )
            layout.addWidget(
                positionButton(
                    style.standardIcon(QStyle.SP_ArrowRight),
                    "Y+",
                    1 + indexOffset,
                    deltaSB,
                    scale,
                ),
                2,
                2,
            )
            layout.addWidget(
                positionButton(
                    style.standardIcon(QStyle.SP_ArrowUp),
                    "Z+",
                    2 + indexOffset,
                    deltaSB,
                    scale,
                ),
                1,
                4,
            )
            layout.addWidget(
                positionButton(
                    style.standardIcon(QStyle.SP_ArrowDown),
                    "Z-",
                    2 + indexOffset,
                    deltaSB,
                    -scale,
                ),
                3,
                4,
            )

            ret = QGroupBox(title)
            ret.setLayout(layout)
            return ret
Beispiel #20
0
class SSUTypicalComponentChart(QDialog):
    def __init__(self, parent=None, toolbar=False):
        flags = Qt.Window | Qt.WindowTitleHint | Qt.CustomizeWindowHint | Qt.WindowCloseButtonHint
        super().__init__(parent=parent, f=flags)
        self.setWindowTitle(self.tr("SSU Typical Component Chart"))
        self.figure = plt.figure(figsize=(6, 3))
        self.clustering_axes = self.figure.add_subplot(1, 2, 1)
        self.component_axes = self.figure.add_subplot(1, 2, 2)
        self.canvas = FigureCanvas(self.figure)
        self.toolbar = NavigationToolbar(self.canvas, self)
        self.main_layout = QGridLayout(self)
        self.main_layout.addWidget(self.toolbar, 0, 0, 1, 4)
        self.main_layout.addWidget(self.canvas, 1, 0, 1, 4)
        if not toolbar:
            self.toolbar.hide()
        self.supported_scales = [("log-linear", self.tr("Log-linear")),
                                 ("log", self.tr("Log")),
                                 ("phi", self.tr("φ")),
                                 ("linear", self.tr("Linear"))]
        self.AXIS_LIST = [
            self.tr("Mean [φ]"),
            self.tr("Standard deviation [φ]"),
            self.tr("Skewness"),
            self.tr("Kurtosis")
        ]
        self.x_axis_label = QLabel(self.tr("X Axis"))
        self.x_axis_combo_box = QComboBox()
        self.x_axis_combo_box.addItems(self.AXIS_LIST)
        self.y_axis_label = QLabel(self.tr("Y Axis"))
        self.y_axis_combo_box = QComboBox()
        self.y_axis_combo_box.addItems(self.AXIS_LIST)
        self.y_axis_combo_box.setCurrentIndex(1)
        self.main_layout.addWidget(self.x_axis_label, 2, 0)
        self.main_layout.addWidget(self.x_axis_combo_box, 2, 1)
        self.main_layout.addWidget(self.y_axis_label, 3, 0)
        self.main_layout.addWidget(self.y_axis_combo_box, 3, 1)
        self.scale_label = QLabel(self.tr("Scale"))
        self.scale_combo_box = QComboBox()
        self.scale_combo_box.addItems(
            [name for key, name in self.supported_scales])
        self.main_layout.addWidget(self.scale_label, 2, 2)
        self.main_layout.addWidget(self.scale_combo_box, 2, 3)
        self.min_samples_label = QLabel(self.tr("Minimum Samples"))
        self.min_samples_input = QDoubleSpinBox()
        self.min_samples_input.setRange(0.0001, 0.9999)
        self.min_samples_input.setDecimals(4)
        self.min_samples_input.setSingleStep(0.001)
        self.min_samples_input.setValue(0.03)
        self.min_cluster_size_label = QLabel(self.tr("Minimum Cluster Size"))
        self.min_cluster_size_input = QDoubleSpinBox()
        self.min_cluster_size_input.setRange(0.0001, 0.9999)
        self.min_cluster_size_input.setDecimals(4)
        self.min_cluster_size_input.setSingleStep(0.001)
        self.min_cluster_size_input.setValue(0.1)
        self.xi_label = QLabel(self.tr("xi"))
        self.xi_input = QDoubleSpinBox()
        self.xi_input.setRange(0.0001, 0.9999)
        self.xi_input.setDecimals(4)
        self.xi_input.setSingleStep(0.001)
        self.xi_input.setValue(0.05)
        self.main_layout.addWidget(self.min_samples_label, 3, 2)
        self.main_layout.addWidget(self.min_samples_input, 3, 3)
        self.main_layout.addWidget(self.min_cluster_size_label, 4, 0)
        self.main_layout.addWidget(self.min_cluster_size_input, 4, 1)
        self.main_layout.addWidget(self.xi_label, 4, 2)
        self.main_layout.addWidget(self.xi_input, 4, 3)
        self.update_chart_button = QPushButton(self.tr("Update Chart"))
        self.update_chart_button.clicked.connect(self.update_chart)
        self.save_typical_button = QPushButton(self.tr("Save Typical"))
        self.save_typical_button.setEnabled(False)
        self.save_typical_button.clicked.connect(self.on_save_clicked)
        self.main_layout.addWidget(self.update_chart_button, 5, 0, 1, 2)
        self.main_layout.addWidget(self.save_typical_button, 5, 2, 1, 2)

        self.last_results = None  # type: list[SSUResult]
        self.data_to_clustering = None
        self.stacked_components = None
        self.normal_msg = QMessageBox(self)
        self.file_dialog = QFileDialog(parent=self)

    @property
    def scale(self) -> str:
        index = self.scale_combo_box.currentIndex()
        key, name = self.supported_scales[index]
        return key

    @property
    def transfer(self) -> typing.Callable:
        if self.scale == "log-linear":
            return lambda classes_φ: convert_φ_to_μm(classes_φ)
        elif self.scale == "log":
            return lambda classes_φ: np.log(convert_φ_to_μm(classes_φ))
        elif self.scale == "phi":
            return lambda classes_φ: classes_φ
        elif self.scale == "linear":
            return lambda classes_φ: convert_φ_to_μm(classes_φ)

    @property
    def xlabel(self) -> str:
        if self.scale == "log-linear":
            return self.tr("Grain-size [μm]")
        elif self.scale == "log":
            return self.tr("Ln(grain-size in μm)")
        elif self.scale == "phi":
            return self.tr("Grain-size [φ]")
        elif self.scale == "linear":
            return self.tr("Grain-size [μm]")

    @property
    def ylabel(self) -> str:
        return self.tr("Frequency")

    @property
    def xlog(self) -> bool:
        if self.scale == "log-linear":
            return True
        else:
            return False

    def show_message(self, title: str, message: str):
        self.normal_msg.setWindowTitle(title)
        self.normal_msg.setText(message)
        self.normal_msg.exec_()

    def show_info(self, message: str):
        self.show_message(self.tr("Info"), message)

    def show_warning(self, message: str):
        self.show_message(self.tr("Warning"), message)

    def show_error(self, message: str):
        self.show_message(self.tr("Error"), message)

    def update_chart(self):
        if self.last_results is None:
            return
        x = self.transfer(self.last_results[0].classes_φ)
        self.save_typical_button.setEnabled(True)
        cluster = OPTICS(min_samples=self.min_samples_input.value(),
                         min_cluster_size=self.min_cluster_size_input.value(),
                         xi=self.xi_input.value())
        flags = cluster.fit_predict(self.data_to_clustering)
        cmap = plt.get_cmap()

        self.clustering_axes.clear()
        flag_set = set(flags)
        for flag in flag_set:
            key = np.equal(flags, flag)
            if flag == -1:
                c = "#7a7374"
                label = self.tr("Not clustered")
            else:
                c = cmap(flag)
                label = self.tr("EM{0}").format(flag + 1)
            self.clustering_axes.plot(self.data_to_clustering[key]
                                      [:,
                                       self.x_axis_combo_box.currentIndex()],
                                      self.data_to_clustering[key]
                                      [:,
                                       self.y_axis_combo_box.currentIndex()],
                                      c="#ffffff00",
                                      marker=".",
                                      ms=8,
                                      mfc=c,
                                      mew=0.0,
                                      zorder=flag,
                                      label=label)
        if len(flag_set) < 6:
            self.clustering_axes.legend(loc="upper left")
        self.clustering_axes.set_xlabel(self.x_axis_combo_box.currentText())
        self.clustering_axes.set_ylabel(self.y_axis_combo_box.currentText())
        self.clustering_axes.set_title(self.tr("Clustering of end-members"))

        self.component_axes.clear()
        if self.xlog:
            self.component_axes.set_xscale("log")

        for flag in flag_set:
            if flag == -1:
                c = "#7a7374"
            else:
                c = cmap(flag)
            key = np.equal(flags, flag)
            for distribution in self.stacked_components[key]:
                self.component_axes.plot(x, distribution, c=c, zorder=flag)

            if flag != -1:
                typical = np.mean(self.stacked_components[key], axis=0)
                self.component_axes.plot(x,
                                         typical,
                                         c="black",
                                         zorder=1e10,
                                         ls="--",
                                         linewidth=1)
        self.component_axes.set_title(self.tr("Typical end-members"))
        self.component_axes.set_xlabel(self.xlabel)
        self.component_axes.set_ylabel(self.ylabel)
        self.component_axes.set_xlim(x[0], x[-1])
        self.component_axes.set_ylim(0, None)

        self.figure.tight_layout()
        self.canvas.draw()

    def show_typical(self, results: typing.Iterable[GrainSizeSample]):
        if len(results) == 0:
            return
        keys_to_clustering = ["mean", "std", "skewness", "kurtosis"]
        data_to_clustering = []
        stacked_components = []
        for result in results:
            for component in result.components:
                has_nan = False
                for key in keys_to_clustering:
                    if np.isnan(
                            component.logarithmic_moments[key]) or np.isinf(
                                component.logarithmic_moments[key]):
                        has_nan = True
                        break
                if has_nan:
                    continue
                data_to_clustering.append([
                    component.logarithmic_moments[key]
                    for key in keys_to_clustering
                ])
                stacked_components.append(component.distribution)
        # convert to numpy array
        data_to_clustering = np.array(data_to_clustering)
        stacked_components = np.array(stacked_components)
        self.last_results = results
        self.data_to_clustering = data_to_clustering
        self.stacked_components = stacked_components
        self.update_chart()

    def save_typical(self, filename):
        assert self.last_results is not None
        if len(self.last_results) == 0:
            return
        cluster = OPTICS(min_samples=self.min_samples_input.value(),
                         min_cluster_size=self.min_cluster_size_input.value(),
                         xi=self.xi_input.value())
        classes_μm = self.last_results[0].classes_μm
        flags = cluster.fit_predict(self.data_to_clustering)
        flag_set = set(flags)
        typicals = []
        for flag in flag_set:
            if flag != -1:
                key = np.equal(flags, flag)
                typical = np.mean(self.stacked_components[key], axis=0)
                typicals.append(typical)

        wb = openpyxl.Workbook()
        prepare_styles(wb)
        ws = wb.active
        ws.title = self.tr("README")
        description = \
            """
            This Excel file was generated by QGrain ({0}).

            Please cite:
            Liu, Y., Liu, X., Sun, Y., 2021. QGrain: An open-source and easy-to-use software for the comprehensive analysis of grain size distributions. Sedimentary Geology 423, 105980. https://doi.org/10.1016/j.sedgeo.2021.105980

            It contanins 2 + N_clusters sheets:
            1. The first sheet is the sum distributions of all component clusters.
            2. The second sheet is used to put the component distributions that not in any cluster.
            3. The left sheet is the component distributions of each cluster, separately.

            The clustering algorithm is OPTICS, implemented by scikit-learn.
            https://scikit-learn.org/stable/modules/generated/sklearn.cluster.OPTICS.html

            Clustering algorithm details
                min_samples={1}
                min_cluster_size={2}
                xi={3}
                others=default

            """.format(QGRAIN_VERSION,
                       self.min_samples_input.value(),
                       self.min_cluster_size_input.value(),
                       self.xi_input.value())

        def write(row, col, value, style="normal_light"):
            cell = ws.cell(row + 1, col + 1, value=value)
            cell.style = style

        lines_of_desc = description.split("\n")
        for row, line in enumerate(lines_of_desc):
            write(row, 0, line, style="description")
        ws.column_dimensions[column_to_char(0)].width = 200

        ws = wb.create_sheet(self.tr("Typical Components"))
        write(0, 0, self.tr("Typical Component"), style="header")
        ws.column_dimensions[column_to_char(0)].width = 16
        for col, value in enumerate(classes_μm, 1):
            write(0, col, value, style="header")
            ws.column_dimensions[column_to_char(col)].width = 10
        for row, distribution in enumerate(typicals, 1):
            if row % 2 == 0:
                style = "normal_dark"
            else:
                style = "normal_light"
            write(row, 0, self.tr("Component{0}").format(row), style=style)
            for col, value in enumerate(distribution, 1):
                write(row, col, value, style=style)
            QCoreApplication.processEvents()

        for flag in flag_set:
            if flag == -1:
                ws = wb.create_sheet(self.tr("Not Clustered"), 2)
            else:
                ws = wb.create_sheet(self.tr("Cluster{0}").format(flag + 1))

            write(0, 0, self.tr("Index"), style="header")
            ws.column_dimensions[column_to_char(0)].width = 16
            for col, value in enumerate(classes_μm, 1):
                write(0, col, value, style="header")
                ws.column_dimensions[column_to_char(col)].width = 10
            key = np.equal(flags, flag)
            for row, component in enumerate(self.stacked_components[key], 1):
                if row % 2 == 0:
                    style = "normal_dark"
                else:
                    style = "normal_light"
                write(row, 0, str(row), style=style)
                for col, value in enumerate(component, 1):
                    write(row, col, value, style=style)
                QCoreApplication.processEvents()

        wb.save(filename)
        wb.close()

    def on_save_clicked(self):
        if len(self.last_results) == 0:
            self.show_warning(self.tr("There is not an SSU result."))
            return

        filename, _ = self.file_dialog.getSaveFileName(
            self,
            self.
            tr("Choose a filename to save the typical components of SSU results"
               ), None, f"{self.tr('Microsoft Excel')} (*.xlsx)")
        if filename is None or filename == "":
            return
        try:
            self.save_typical(filename)
            self.show_info(self.tr("The typical components have been saved."))
        except Exception as e:
            self.show_error(
                self.tr("Error raised while saving it to Excel file.\n    {0}"
                        ).format(e.__str__()))
            return
Beispiel #21
0
class OptionsDock(QDockWidget):
    def __init__(self, model, FM, parent=None):
        super(OptionsDock, self).__init__(parent)

        self.model = model
        self.FM = FM
        self.mw = parent

        self.setSizePolicy(QSizePolicy.Fixed,
                           QSizePolicy.Expanding)  # Doesn't work?
        self.setAllowedAreas(QtCore.Qt.LeftDockWidgetArea
                             | QtCore.Qt.RightDockWidgetArea)

        # Create Controls
        self.createOriginBox()
        self.createOptionsBox()
        self.createResolutionBox()

        # Create submit button
        self.applyButton = QPushButton("Apply Changes")
        self.applyButton.setMinimumHeight(self.FM.height() *
                                          1.6)  # Mac bug fix
        self.applyButton.clicked.connect(self.mw.applyChanges)

        # Create Zoom box
        self.zoomBox = QSpinBox()
        self.zoomBox.setSuffix(' %')
        self.zoomBox.setRange(25, 2000)
        self.zoomBox.setValue(100)
        self.zoomBox.setSingleStep(25)
        self.zoomBox.valueChanged.connect(self.mw.editZoom)
        self.zoomLayout = QHBoxLayout()
        self.zoomLayout.addWidget(QLabel('Zoom:'))
        self.zoomLayout.addWidget(self.zoomBox)
        self.zoomLayout.setContentsMargins(0, 0, 0, 0)
        self.zoomWidget = QWidget()
        self.zoomWidget.setLayout(self.zoomLayout)

        # Create Layout
        self.dockLayout = QVBoxLayout()
        self.dockLayout.addWidget(self.originGroupBox)
        self.dockLayout.addWidget(self.optionsGroupBox)
        self.dockLayout.addWidget(self.resGroupBox)
        self.dockLayout.addWidget(self.applyButton)
        self.dockLayout.addStretch()
        self.dockLayout.addWidget(HorizontalLine())
        self.dockLayout.addWidget(self.zoomWidget)

        self.optionsWidget = QWidget()
        self.optionsWidget.setLayout(self.dockLayout)
        self.setWidget(self.optionsWidget)

    def createOriginBox(self):

        # X Origin
        self.xOrBox = QDoubleSpinBox()
        self.xOrBox.setDecimals(9)
        self.xOrBox.setRange(-99999, 99999)
        self.xOrBox.valueChanged.connect(
            lambda value: self.mw.editSingleOrigin(value, 0))

        # Y Origin
        self.yOrBox = QDoubleSpinBox()
        self.yOrBox.setDecimals(9)
        self.yOrBox.setRange(-99999, 99999)
        self.yOrBox.valueChanged.connect(
            lambda value: self.mw.editSingleOrigin(value, 1))

        # Z Origin
        self.zOrBox = QDoubleSpinBox()
        self.zOrBox.setDecimals(9)
        self.zOrBox.setRange(-99999, 99999)
        self.zOrBox.valueChanged.connect(
            lambda value: self.mw.editSingleOrigin(value, 2))

        # Origin Form Layout
        self.orLayout = QFormLayout()
        self.orLayout.addRow('X:', self.xOrBox)
        self.orLayout.addRow('Y:', self.yOrBox)
        self.orLayout.addRow('Z:', self.zOrBox)
        #self.orLayout.setVerticalSpacing(4)
        self.orLayout.setLabelAlignment(QtCore.Qt.AlignLeft)
        self.orLayout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)

        # Origin Group Box
        self.originGroupBox = QGroupBox('Origin')
        self.originGroupBox.setLayout(self.orLayout)

    def createOptionsBox(self):

        # Width
        self.widthBox = QDoubleSpinBox(self)
        self.widthBox.setRange(.1, 99999)
        self.widthBox.valueChanged.connect(self.mw.editWidth)

        # Height
        self.heightBox = QDoubleSpinBox(self)
        self.heightBox.setRange(.1, 99999)
        self.heightBox.valueChanged.connect(self.mw.editHeight)

        # ColorBy
        self.colorbyBox = QComboBox(self)
        self.colorbyBox.addItem("material")
        self.colorbyBox.addItem("cell")
        self.colorbyBox.currentTextChanged[str].connect(self.mw.editColorBy)

        # Alpha
        self.plotAlphaBox = QDoubleSpinBox(self)
        self.plotAlphaBox.setValue(self.model.activeView.plotAlpha)
        self.plotAlphaBox.setSingleStep(0.05)
        self.plotAlphaBox.setDecimals(2)
        self.plotAlphaBox.setRange(0.0, 1.0)
        self.plotAlphaBox.valueChanged.connect(self.mw.editPlotAlpha)

        # Basis
        self.basisBox = QComboBox(self)
        self.basisBox.addItem("xy")
        self.basisBox.addItem("xz")
        self.basisBox.addItem("yz")
        self.basisBox.currentTextChanged.connect(self.mw.editBasis)

        # Advanced Color Options
        self.colorOptionsButton = QPushButton('Color Options...')
        self.colorOptionsButton.setMinimumHeight(self.FM.height() * 1.6)
        self.colorOptionsButton.clicked.connect(self.mw.showColorDialog)

        # Options Form Layout
        self.opLayout = QFormLayout()
        self.opLayout.addRow('Width:', self.widthBox)
        self.opLayout.addRow('Height:', self.heightBox)
        self.opLayout.addRow('Basis:', self.basisBox)
        self.opLayout.addRow('Color By:', self.colorbyBox)
        self.opLayout.addRow('Plot alpha:', self.plotAlphaBox)
        self.opLayout.addRow(self.colorOptionsButton)
        self.opLayout.setLabelAlignment(QtCore.Qt.AlignLeft)
        self.opLayout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)

        # Options Group Box
        self.optionsGroupBox = QGroupBox('Options')
        self.optionsGroupBox.setLayout(self.opLayout)

    def createResolutionBox(self):

        # Horizontal Resolution
        self.hResBox = QSpinBox(self)
        self.hResBox.setRange(1, 99999)
        self.hResBox.setSingleStep(25)
        self.hResBox.setSuffix(' px')
        self.hResBox.valueChanged.connect(self.mw.editHRes)

        # Vertical Resolution
        self.vResLabel = QLabel('Pixel Height:')
        self.vResBox = QSpinBox(self)
        self.vResBox.setRange(1, 99999)
        self.vResBox.setSingleStep(25)
        self.vResBox.setSuffix(' px')
        self.vResBox.valueChanged.connect(self.mw.editVRes)

        # Ratio checkbox
        self.ratioCheck = QCheckBox("Fixed Aspect Ratio", self)
        self.ratioCheck.stateChanged.connect(self.mw.toggleAspectLock)

        # Resolution Form Layout
        self.resLayout = QFormLayout()
        self.resLayout.addRow(self.ratioCheck)
        self.resLayout.addRow('Pixel Width:', self.hResBox)
        self.resLayout.addRow(self.vResLabel, self.vResBox)
        self.resLayout.setLabelAlignment(QtCore.Qt.AlignLeft)
        self.resLayout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)

        # Resolution Group Box
        self.resGroupBox = QGroupBox("Resolution")
        self.resGroupBox.setLayout(self.resLayout)

    def updateDock(self):
        self.updateOrigin()
        self.updateWidth()
        self.updateHeight()
        self.updateColorBy()
        self.updatePlotAlpha()
        self.updateBasis()
        self.updateAspectLock()
        self.updateHRes()
        self.updateVRes()

    def updateOrigin(self):
        self.xOrBox.setValue(self.model.activeView.origin[0])
        self.yOrBox.setValue(self.model.activeView.origin[1])
        self.zOrBox.setValue(self.model.activeView.origin[2])

    def updateWidth(self):
        self.widthBox.setValue(self.model.activeView.width)

    def updateHeight(self):
        self.heightBox.setValue(self.model.activeView.height)

    def updateColorBy(self):
        self.colorbyBox.setCurrentText(self.model.activeView.colorby)

    def updatePlotAlpha(self):
        self.plotAlphaBox.setValue(self.model.activeView.plotAlpha)

    def updateBasis(self):
        self.basisBox.setCurrentText(self.model.activeView.basis)

    def updateAspectLock(self):
        if self.model.activeView.aspectLock:
            self.ratioCheck.setChecked(True)
            self.vResBox.setDisabled(True)
            self.vResLabel.setDisabled(True)
        else:
            self.ratioCheck.setChecked(False)
            self.vResBox.setDisabled(False)
            self.vResLabel.setDisabled(False)

    def updateHRes(self):
        self.hResBox.setValue(self.model.activeView.h_res)

    def updateVRes(self):
        self.vResBox.setValue(self.model.activeView.v_res)

    def revertToCurrent(self):
        cv = self.model.currentView

        self.xOrBox.setValue(cv.origin[0])
        self.yOrBox.setValue(cv.origin[1])
        self.zOrBox.setValue(cv.origin[2])

        self.widthBox.setValue(cv.width)
        self.heightBox.setValue(cv.height)

    def resizeEvent(self, event):
        self.mw.resizeEvent(event)

    def hideEvent(self, event):
        self.mw.resizeEvent(event)

    def showEvent(self, event):
        self.mw.resizeEvent(event)

    def moveEvent(self, event):
        self.mw.resizeEvent(event)
Beispiel #22
0
class AudioInfoDialog(QDialog):
    def __init__(self,
                 audios_name,
                 audios_delay,
                 audios_language,
                 audios_track_name,
                 audios_set_default,
                 audios_set_forced,
                 audios_default_value_delay,
                 audios_default_value_language,
                 audios_default_value_track_name,
                 audios_default_value_set_default,
                 audios_default_value_set_forced,
                 audio_set_default_disabled=False,
                 audio_set_forced_disabled=False,
                 disable_edit=False,
                 parent=None):
        super().__init__(parent)
        self.window_title = "Audio Info"
        self.state = "no"
        self.audios_count = len(audios_delay)

        self.messageIcon = QLabel()
        self.audio_tab_comboBox = InfoCellDialogTabComboBox(
            hint="Audios Groups")
        for i in range(self.audios_count):
            self.audio_tab_comboBox.addItem("Audio #" + str(i + 1))
        self.audio_tab_comboBox.setCurrentIndex(0)
        self.audio_tab_comboBox.currentIndexChanged.connect(
            self.update_current_audio_index)
        self.current_audio_index = 0

        self.disable_edit = disable_edit
        self.current_audio_name = audios_name
        self.current_audio_language = audios_language
        self.current_audio_delay = audios_delay
        self.current_audio_track_name = audios_track_name
        self.current_audio_set_default = audios_set_default
        self.current_audio_set_forced = audios_set_forced

        self.default_audio_language = audios_default_value_language
        self.default_audio_delay = audios_default_value_delay
        self.default_audio_track_name = audios_default_value_track_name
        self.default_audio_set_default = audios_default_value_set_default
        self.default_audio_set_forced = audios_default_value_set_forced

        self.audio_set_default_disabled = audio_set_default_disabled
        self.audio_set_forced_disabled = audio_set_forced_disabled

        self.audio_name_label = QLabel("Audio Name:")
        self.audio_name_value = QLabel(
            str(self.current_audio_name[self.current_audio_index]))
        width_to_be_fixed = 0
        for i in range(len(self.current_audio_name)):
            width_to_be_fixed = max(
                width_to_be_fixed,
                self.audio_name_value.fontMetrics().boundingRect(
                    self.current_audio_name[i]).width())
        self.audio_name_value.setFixedWidth(width_to_be_fixed + 10)
        self.audio_delay_label = QLabel("Audio Delay:")
        self.audio_delay_spin = QDoubleSpinBox()
        self.setup_audio_delay_spin()

        self.audio_language_label = QLabel("Audio Language:")
        self.audio_language_comboBox = QComboBox()
        self.setup_audio_language_comboBox()

        self.audio_track_name_label = QLabel("Audio Track Name:")
        self.audio_track_name_lineEdit = QLineEdit()
        self.setup_audio_track_name_lineEdit()

        self.audio_set_forced_label = QLabel("Audio Forced State:")
        self.audio_set_forced_checkBox = QCheckBox()
        self.setup_audio_set_forced_checkBox()

        self.audio_set_default_label = QLabel("Audio Default State:")
        self.audio_set_default_checkBox = QCheckBox()
        self.setup_audio_set_default_checkBox()

        self.yes_button = QPushButton("OK")
        self.no_button = QPushButton("Cancel")
        self.reset_button = QPushButton("Reset To Default")

        self.buttons_layout = QHBoxLayout()
        self.audio_delay_layout = QHBoxLayout()
        self.audio_language_layout = QHBoxLayout()
        self.audio_track_name_layout = QHBoxLayout()
        self.audio_set_default_layout = QHBoxLayout()
        self.audio_set_forced_layout = QHBoxLayout()
        self.buttons_layout.addWidget(QLabel(""), stretch=3)
        self.buttons_layout.addWidget(self.reset_button, stretch=2)
        self.buttons_layout.addWidget(self.yes_button, stretch=2)
        self.buttons_layout.addWidget(self.no_button, stretch=2)
        self.buttons_layout.addWidget(QLabel(""), stretch=3)
        self.audio_setting_layout = QGridLayout()
        self.audio_editable_setting_layout = QFormLayout()
        self.audio_editable_setting_layout.addRow(self.audio_name_label,
                                                  self.audio_name_value)
        self.audio_editable_setting_layout.addRow(
            self.audio_track_name_label, self.audio_track_name_lineEdit)
        self.audio_editable_setting_layout.addRow(self.audio_language_label,
                                                  self.audio_language_comboBox)
        self.audio_editable_setting_layout.addRow(self.audio_delay_label,
                                                  self.audio_delay_spin)
        self.audio_editable_setting_layout.addRow(
            self.audio_set_default_label, self.audio_set_default_checkBox)
        self.audio_editable_setting_layout.addRow(
            self.audio_set_forced_label, self.audio_set_forced_checkBox)
        self.audio_setting_layout.addWidget(self.audio_tab_comboBox, 0, 0)
        self.audio_setting_layout.addLayout(self.audio_editable_setting_layout,
                                            1, 0, 5, 2)
        self.audio_setting_layout.addWidget(self.messageIcon, 1, 3, 5, -1)

        self.main_layout = QGridLayout()
        self.main_layout.addLayout(self.audio_setting_layout, 0, 0, 2, 3)
        self.main_layout.addLayout(self.buttons_layout, 2, 0, 1, -1)
        self.main_layout.setContentsMargins(20, 20, 20, 20)
        self.setLayout(self.main_layout)

        self.setup_ui()
        self.signal_connect()

    def setup_ui(self):
        self.disable_question_mark_window()
        self.messageIcon.setPixmap(
            QtGui.QPixmap(GlobalFiles.AudioIconPath).scaledToHeight(100))
        self.set_dialog_values()
        self.set_default_buttons()
        if self.audio_set_default_disabled:
            self.audio_set_default_disable()
        if self.audio_set_forced_disabled:
            self.audio_set_forced_disable()
        if self.disable_edit:
            self.audio_track_name_lineEdit.setEnabled(False)
            self.audio_language_comboBox.setEnabled(False)
            self.audio_delay_spin.setEnabled(False)
            self.audio_set_default_checkBox.setEnabled(False)
            self.audio_set_forced_checkBox.setEnabled(False)
            self.reset_button.setEnabled(False)

        self.setup_tool_tip_hint_audio_set_default()
        self.setup_tool_tip_hint_audio_set_forced()

    def signal_connect(self):
        self.audio_track_name_lineEdit.textEdited.connect(
            self.update_current_audio_track_name)
        self.audio_delay_spin.editingFinished.connect(
            self.update_current_audio_delay)
        self.audio_language_comboBox.currentTextChanged.connect(
            self.update_current_audio_language)
        self.audio_set_default_checkBox.stateChanged.connect(
            self.update_current_audio_set_default)
        self.audio_set_forced_checkBox.stateChanged.connect(
            self.update_current_audio_set_forced)
        self.yes_button.clicked.connect(self.click_yes)
        self.no_button.clicked.connect(self.click_no)
        self.reset_button.clicked.connect(self.reset_audio_setting)

    def click_yes(self):
        self.state = "yes"
        self.close()

    def click_no(self):
        self.state = "no"
        self.close()

    def set_dialog_values(self):
        self.setWindowTitle(self.window_title)
        self.setWindowIcon(GlobalFiles.InfoSettingIcon)

    def disable_question_mark_window(self):
        self.setWindowFlag(Qt.WindowContextHelpButtonHint, on=False)

    def increase_message_font_size(self, value):
        message_font = self.message.font()
        message_font.setPointSize(self.message.fontInfo().pointSize() + value)
        self.message.setFont(message_font)

    def set_default_buttons(self):
        self.yes_button.setDefault(True)
        self.yes_button.setFocus()

    def showEvent(self, a0: QtGui.QShowEvent) -> None:
        super().showEvent(a0)
        self.setFixedSize(self.size())

    def setup_audio_track_name_lineEdit(self):
        self.audio_track_name_lineEdit.setClearButtonEnabled(True)
        self.audio_track_name_lineEdit.setText(
            self.current_audio_track_name[self.current_audio_index])

    def setup_audio_language_comboBox(self):
        self.audio_language_comboBox.addItems(AllAudiosLanguages)
        self.audio_language_comboBox.setCurrentIndex(
            AllAudiosLanguages.index(
                self.current_audio_language[self.current_audio_index]))
        self.audio_language_comboBox.setMaxVisibleItems(8)
        self.audio_language_comboBox.setStyleSheet(
            "QComboBox { combobox-popup: 0; }")

    def setup_audio_delay_spin(self):
        # self.audio_delay_spin.setMaximumWidth(screen_size.width() // 16)
        self.audio_delay_spin.setDecimals(3)
        self.audio_delay_spin.setMinimum(-9999.0)
        self.audio_delay_spin.setMaximum(9999.0)
        self.audio_delay_spin.setSingleStep(0.5)
        self.audio_delay_spin.setValue(
            float(self.current_audio_delay[self.current_audio_index]))

    def setup_audio_set_default_checkBox(self):
        self.audio_set_default_checkBox.setText("Set Default")
        self.audio_set_default_checkBox.setChecked(
            bool(self.current_audio_set_default[self.current_audio_index]))

    def setup_audio_set_forced_checkBox(self):
        self.audio_set_forced_checkBox.setText("Set Forced")
        self.audio_set_forced_checkBox.setChecked(
            bool(self.current_audio_set_forced[self.current_audio_index]))

    def update_current_audio_track_name(self):
        self.current_audio_track_name[self.current_audio_index] = str(
            self.audio_track_name_lineEdit.text())

    def update_current_audio_delay(self):
        self.current_audio_delay[self.current_audio_index] = round(
            self.audio_delay_spin.value(), 5)

    def update_current_audio_language(self):
        self.current_audio_language[self.current_audio_index] = str(
            self.audio_language_comboBox.currentText())

    def update_current_audio_set_default(self):
        new_state = self.audio_set_default_checkBox.checkState() == Qt.Checked
        self.current_audio_set_default[self.current_audio_index] = new_state
        if new_state:
            for i in range(len(self.current_audio_set_default)):
                if i != self.current_audio_index:
                    self.current_audio_set_default[i] = False

    def update_current_audio_set_forced(self):
        new_state = self.audio_set_forced_checkBox.checkState() == Qt.Checked
        self.current_audio_set_forced[self.current_audio_index] = new_state
        if new_state:
            for i in range(len(self.current_audio_set_forced)):
                if i != self.current_audio_index:
                    self.current_audio_set_forced[i] = False

    def reset_audio_setting(self):
        self.current_audio_language[
            self.current_audio_index] = self.default_audio_language[
                self.current_audio_index]
        self.current_audio_delay[
            self.current_audio_index] = self.default_audio_delay[
                self.current_audio_index]
        self.current_audio_track_name[
            self.current_audio_index] = self.default_audio_track_name[
                self.current_audio_index]
        self.current_audio_set_default[
            self.current_audio_index] = self.default_audio_set_default[
                self.current_audio_index]
        self.current_audio_set_forced[
            self.current_audio_index] = self.default_audio_set_forced[
                self.current_audio_index]

        self.audio_language_comboBox.setCurrentIndex(
            AllAudiosLanguages.index(
                self.current_audio_language[self.current_audio_index]))
        self.audio_delay_spin.setValue(
            float(self.current_audio_delay[self.current_audio_index]))
        self.audio_track_name_lineEdit.setText(
            self.current_audio_track_name[self.current_audio_index])
        self.audio_set_default_checkBox.setChecked(
            bool(self.current_audio_set_default[self.current_audio_index]))
        self.audio_set_forced_checkBox.setChecked(
            bool(self.current_audio_set_forced[self.current_audio_index]))

    def audio_set_default_disable(self):
        self.audio_set_default_checkBox.setDisabled(True)

    def audio_set_forced_disable(self):
        self.audio_set_forced_checkBox.setDisabled(True)

    def setup_tool_tip_hint_audio_set_default(self):
        if self.audio_set_default_checkBox.isEnabled():
            self.audio_set_default_checkBox.setToolTip(
                "<nobr>set this audio to be the default audio track "
                "when play")
            self.audio_set_default_checkBox.setToolTipDuration(12000)
        else:
            self.audio_set_default_checkBox.setToolTip(
                "<nobr>set this audio to be the default audio track when play<br><b>Disabled</b> because "
                "option "
                "<b>make this audio default</b> is enabled on mux setting tab "
            )
            self.audio_set_default_checkBox.setToolTipDuration(12000)

    def setup_tool_tip_hint_audio_set_forced(self):
        if self.audio_set_forced_checkBox.isEnabled():
            self.audio_set_forced_checkBox.setToolTip(
                "<nobr>set this audio to be the forced audio track when "
                "play")
            self.audio_set_forced_checkBox.setToolTipDuration(12000)
        else:
            self.audio_set_forced_checkBox.setToolTip(
                "<nobr>set this audio to be the forced audio track when play<br><b>Disabled</b> because "
                "option "
                "<b>make this audio default and forced</b> is enabled on mux setting tab "
            )
            self.audio_set_forced_checkBox.setToolTipDuration(12000)

    def update_current_audio_index(self, new_index):
        self.current_audio_index = new_index
        self.audio_delay_spin.setValue(
            float(self.current_audio_delay[self.current_audio_index]))
        self.audio_set_default_checkBox.setChecked(
            bool(self.current_audio_set_default[self.current_audio_index]))
        self.audio_set_forced_checkBox.setChecked(
            bool(self.current_audio_set_forced[self.current_audio_index]))
        self.audio_language_comboBox.setCurrentIndex(
            AllAudiosLanguages.index(
                self.current_audio_language[self.current_audio_index]))
        self.audio_track_name_lineEdit.setText(
            self.current_audio_track_name[self.current_audio_index])
        self.audio_name_value.setText(
            str(self.current_audio_name[self.current_audio_index]))

    def execute(self):
        self.exec_()
def createDoubleSpinBox():
    spinbox = QDoubleSpinBox()
    spinbox.setDecimals(3)
    spinbox.setValue(0.000)
    spinbox.setAlignment(Qt.AlignCenter)
    return spinbox
Beispiel #24
0
class PlotsWidget(ToolWidget):
    def __init__(self, image, parent=None):
        super(PlotsWidget, self).__init__(parent)

        choices = ['Red', 'Green', 'Blue', 'Hue', 'Saturation', 'Value']
        self.xaxis_combo = QComboBox()
        self.xaxis_combo.addItems(choices)
        self.xaxis_combo.setCurrentIndex(3)
        self.yaxis_combo = QComboBox()
        self.yaxis_combo.addItems(choices)
        self.yaxis_combo.setCurrentIndex(4)
        self.sampling_spin = QSpinBox()
        levels = int(np.log2(min(image.shape[:-1])))
        self.sampling_spin.setRange(0, levels)
        self.sampling_spin.setSpecialValueText(self.tr('Off'))
        self.sampling_spin.setValue(1)
        self.sampling_spin.setSuffix(self.tr(' level(s)'))
        self.size_spin = QSpinBox()
        self.size_spin.setRange(1, 10)
        self.size_spin.setValue(2)
        self.size_spin.setSuffix(self.tr(' pt'))
        self.style_combo = QComboBox()
        self.markers = [
            ',', '.', 'o', '8', 's', 'p', 'P', '*', 'h', 'H', 'X', 'D'
        ]
        self.style_combo.addItems([
            'pixel', 'point', 'circle', 'octa', 'square', 'penta', 'plus',
            'star', 'hexa1', 'hexa2', 'cross', 'diamond'
        ])
        self.alpha_spin = QDoubleSpinBox()
        self.alpha_spin.setRange(0, 1)
        self.alpha_spin.setDecimals(2)
        self.alpha_spin.setSingleStep(0.05)
        self.alpha_spin.setValue(1)
        self.colors_check = QCheckBox(self.tr('Show colors'))
        self.grid_check = QCheckBox(self.tr('Show grid'))
        self.norm_check = QCheckBox(self.tr('Normalized'))
        self.total_label = QLabel()

        img = np.copy(image)
        self.colors = [None] * (levels + 1)
        for scale in range(levels + 1):
            rgb = cv.cvtColor(img.astype(np.float32) / 255, cv.COLOR_BGR2RGB)
            hsv = cv.cvtColor(rgb, cv.COLOR_RGB2HSV)
            hsv[:, :, 0] /= 360
            shape = (img.shape[0] * img.shape[1], img.shape[2])
            self.colors[scale] = np.concatenate(
                (np.reshape(rgb, shape), np.reshape(hsv, shape)), axis=1)
            img = cv.pyrDown(img)
        figure = Figure()
        plot_canvas = FigureCanvas(figure)
        self.axes = plot_canvas.figure.subplots()
        self.redraw()
        figure.set_tight_layout(True)

        self.xaxis_combo.currentIndexChanged.connect(self.redraw)
        self.yaxis_combo.currentIndexChanged.connect(self.redraw)
        self.sampling_spin.valueChanged.connect(self.redraw)
        self.size_spin.valueChanged.connect(self.redraw)
        self.style_combo.currentIndexChanged.connect(self.redraw)
        self.alpha_spin.valueChanged.connect(self.redraw)
        self.colors_check.stateChanged.connect(self.redraw)
        self.grid_check.stateChanged.connect(self.redraw)
        self.norm_check.stateChanged.connect(self.redraw)

        bottom_layout = QGridLayout()
        bottom_layout.addWidget(NavigationToolbar(plot_canvas, self), 0, 0, 1,
                                5)
        bottom_layout.addWidget(QLabel(self.tr('X axis:')), 1, 0)
        bottom_layout.addWidget(self.xaxis_combo, 1, 1)
        bottom_layout.addWidget(QLabel(self.tr('Y Axis:')), 2, 0)
        bottom_layout.addWidget(self.yaxis_combo, 2, 1)
        bottom_layout.addWidget(QLabel(self.tr('Subsampling:')), 3, 0)
        bottom_layout.addWidget(self.sampling_spin, 3, 1)
        bottom_layout.addWidget(QLabel(self.tr('Point size:')), 1, 2)
        bottom_layout.addWidget(self.size_spin, 1, 3)
        bottom_layout.addWidget(QLabel(self.tr('Point style:')), 2, 2)
        bottom_layout.addWidget(self.style_combo, 2, 3)
        bottom_layout.addWidget(QLabel(self.tr('Point alpha:')), 3, 2)
        bottom_layout.addWidget(self.alpha_spin, 3, 3)
        bottom_layout.addWidget(self.colors_check, 1, 4)
        bottom_layout.addWidget(self.grid_check, 2, 4)
        bottom_layout.addWidget(self.total_label, 3, 4)

        main_layout = QVBoxLayout()
        main_layout.addWidget(plot_canvas)
        main_layout.addLayout(bottom_layout)
        self.setLayout(main_layout)

    def redraw(self):
        start = time()
        v = self.sampling_spin.value()
        x = self.colors[v][:, self.xaxis_combo.currentIndex()]
        y = self.colors[v][:, self.yaxis_combo.currentIndex()]
        xlim = self.axes.get_xlim()
        ylim = self.axes.get_ylim()
        s = self.size_spin.value()**2
        c = None if not self.colors_check.isChecked(
        ) else self.colors[v][:, :3]
        a = self.alpha_spin.value()
        m = self.markers[self.style_combo.currentIndex()]
        self.axes.clear()
        self.axes.set_facecolor([0.5] * 3 if c is not None else [1.0] * 3)
        self.axes.scatter(x, y, s, c, m, alpha=a)
        self.axes.set_xlabel(self.xaxis_combo.currentText())
        self.axes.set_ylabel(self.yaxis_combo.currentText())
        self.axes.grid(self.grid_check.isChecked(), which='both')
        self.axes.set_xlim(xlim)
        self.axes.set_ylim(ylim)
        self.axes.figure.canvas.draw()
        self.total_label.setText(self.tr('[{} points]'.format(len(x))))
        self.info_message.emit('Plot redraw = {}'.format(elapsed_time(start)))
Beispiel #25
0
class NGL_HKLViewer(QWidget):
    def __init__(self, parent=None):
        super(NGL_HKLViewer, self).__init__(parent)

        self.verbose = 0
        self.UseOSbrowser = False
        self.jscriptfname = ""
        self.devmode = False
        for e in sys.argv:
            if "verbose" in e:
                self.verbose = e.split("verbose=")[1]
            if "UseOSbrowser" in e:
                self.UseOSbrowser = e.split("UseOSbrowser=")[1]
            if "jscriptfname" in e:
                self.jscriptfname = e.split("jscriptfname=")[1]
            if "devmode" in e:
                self.devmode = True

        self.zmq_context = None
        self.bufsize = 20000

        self.originalPalette = QApplication.palette()

        self.openFileNameButton = QPushButton("Load reflection file")
        self.openFileNameButton.setDefault(True)
        self.openFileNameButton.clicked.connect(self.OpenReflectionsFile)

        self.debugbutton = QPushButton("Debug")
        self.debugbutton.clicked.connect(self.DebugInteractively)

        self.settingsbtn = QPushButton("Settings")
        self.settingsbtn.clicked.connect(self.SettingsDialog)

        self.mousemoveslider = QSlider(Qt.Horizontal)
        self.mousemoveslider.setMinimum(0)
        self.mousemoveslider.setMaximum(300)
        self.mousemoveslider.setValue(0)
        self.mousemoveslider.sliderReleased.connect(
            self.onFinalMouseSensitivity)
        self.mousemoveslider.valueChanged.connect(self.onMouseSensitivity)
        self.mousesensitxtbox = QLineEdit('')
        self.mousesensitxtbox.setReadOnly(True)
        self.fontspinBox = QDoubleSpinBox()
        self.fontspinBox.setSingleStep(1)
        self.fontspinBox.setRange(4, 50)
        self.font = QFont()
        self.font.setFamily(self.font.defaultFamily())
        self.fontspinBox.setValue(self.font.pointSize())
        #self.fontspinBox.setValue(self.font.pixelSize())
        self.fontspinBox.valueChanged.connect(self.onFontsizeChanged)
        self.Fontsize_labeltxt = QLabel()
        self.Fontsize_labeltxt.setText("Font size:")

        self.cameraPerspectCheckBox = QCheckBox()
        self.cameraPerspectCheckBox.setText("Perspective camera")
        self.cameraPerspectCheckBox.clicked.connect(self.onCameraPerspect)
        self.cameraPerspectCheckBox.setCheckState(Qt.Unchecked)

        self.settingsform = SettingsForm(self)

        self.MillerComboBox = QComboBox()
        self.MillerComboBox.activated.connect(self.onMillerComboSelchange)
        #self.MillerComboBox.setSizeAdjustPolicy(QComboBox.AdjustToContents)

        self.MillerLabel = QLabel()
        self.MillerLabel.setText("Selected HKL Scene")

        self.HKLnameedit = QLineEdit('')
        self.HKLnameedit.setReadOnly(True)
        self.textInfo = QTextEdit()
        self.textInfo.setLineWrapMode(QTextEdit.NoWrap)
        self.textInfo.setReadOnly(True)

        labels = [
            "Label", "Type", "no. of HKLs", "Span of HKLs", "Min Max data",
            "Min Max sigmas", "d_min, d_max", "Symmetry unique", "Anomalous"
        ]
        self.millertable = QTableWidget(0, len(labels))
        self.millertable.setHorizontalHeaderLabels(labels)
        self.millertable.horizontalHeader().setDefaultAlignment(Qt.AlignLeft)
        # don't allow editing this table
        self.millertable.setEditTriggers(QTableWidget.NoEditTriggers)

        self.createExpansionBox()
        self.createFileInfoBox()
        self.CreateSliceTabs()
        self.createRadiiScaleGroupBox()
        self.createBinsBox()
        self.CreateFunctionTabs()

        mainLayout = QGridLayout()
        mainLayout.addWidget(self.FileInfoBox, 0, 0)
        mainLayout.addWidget(self.MillerLabel, 1, 0)
        mainLayout.addWidget(self.MillerComboBox, 2, 0)
        mainLayout.addWidget(self.functionTabWidget, 3, 0)
        mainLayout.addWidget(self.settingsbtn, 4, 0, 1, 1)

        #import code, traceback; code.interact(local=locals(), banner="".join( traceback.format_stack(limit=10) ) )
        if self.UseOSbrowser == False:
            self.BrowserBox = QWebEngineView()
            mainLayout.addWidget(self.BrowserBox, 0, 1, 5, 3)
            self.BrowserBox.setUrl("https://cctbx.github.io/")
            #self.BrowserBox.setUrl("https://webglreport.com/")
            #self.BrowserBox.loadFinished.connect(self.onLoadFinished)
            mainLayout.setColumnStretch(2, 1)

        mainLayout.setRowStretch(0, 1)
        mainLayout.setRowStretch(1, 0)
        mainLayout.setRowStretch(2, 1)
        mainLayout.setRowStretch(3, 1)
        mainLayout.setColumnStretch(4, 0)
        self.setLayout(mainLayout)

        self.setWindowTitle("HKL-Viewer")
        self.cctbxproc = None
        self.LaunchCCTBXPython()
        self.out = None
        self.err = None
        self.comboviewwidth = 0
        self.hklscenes_arrays = []
        self.array_infotpls = []
        self.matching_arrays = []
        self.bin_infotpls = None
        self.bin_opacities = None
        self.html_url = ""
        self.spacegroups = []
        self.info = []
        self.infostr = ""
        self.fileisvalid = False
        self.NewFileLoaded = False
        self.NewHKLscenes = False
        self.updatingNbins = False
        self.binstableitemchanges = False

        self.show()

    def SettingsDialog(self):
        self.settingsform.show()

    def update(self):
        if self.cctbxproc:
            if self.cctbxproc.stdout:
                print(self.cctbxproc.stdout.read().decode("utf-8"))
            if self.cctbxproc.stderr:
                print(self.cctbxproc.stderr.read().decode("utf-8"))
        if self.out:
            print(self.out.decode("utf-8"))
        if self.err:
            print(self.err.decode("utf-8"))
        if self.zmq_context:
            try:
                msg = self.socket.recv(
                    flags=zmq.NOBLOCK
                )  #To empty the socket from previous messages
                msgstr = msg.decode()
                self.infodict = eval(msgstr)
                #print("received from cctbx: " + str(self.infodict))
                if self.infodict:

                    if self.infodict.get("hklscenes_arrays"):
                        self.hklscenes_arrays = self.infodict.get(
                            "hklscenes_arrays", [])

                    if self.infodict.get("array_infotpls"):
                        self.array_infotpls = self.infodict.get(
                            "array_infotpls", [])

                    if self.infodict.get("bin_data_label"):
                        self.BinDataComboBox.setCurrentText(
                            self.infodict["bin_data_label"])

                    if self.infodict.get("bin_infotpls"):
                        self.bin_infotpls = self.infodict["bin_infotpls"]

                        self.nbins = len(self.bin_infotpls)
                        self.updatingNbins = True
                        self.Nbins_spinBox.setValue(self.nbins)
                        self.updatingNbins = False
                        self.binstable.clearContents()
                        self.binstable.setRowCount(self.nbins)
                        for row, bin_infotpl in enumerate(self.bin_infotpls):
                            for col, elm in enumerate(bin_infotpl):
                                # only allow changing the last column with opacity values
                                if col != 3:
                                    item = QTableWidgetItem(str(elm))
                                else:
                                    item = QTableWidgetItem()
                                    item.setFlags(Qt.ItemIsUserCheckable
                                                  | Qt.ItemIsEnabled)
                                    item.setCheckState(Qt.Checked)
                                item.setFlags(item.flags() ^ Qt.ItemIsEditable)
                                self.binstable.setItem(row, col, item)
                        if self.bin_opacities:
                            self.update_table_opacities()

                    if self.infodict.get("bin_opacities"):
                        self.bin_opacities = self.infodict["bin_opacities"]
                        if self.binstable.rowCount() > 0:
                            self.update_table_opacities()

                    if self.infodict.get("html_url"):
                        self.html_url = self.infodict["html_url"]
                        if self.UseOSbrowser == False:
                            self.BrowserBox.setUrl(self.html_url)
                            # workaround for background colour bug in chromium
                            # https://bugreports.qt.io/browse/QTBUG-41960
                            self.BrowserBox.page().setBackgroundColor(
                                QColor(100, 100, 100, 1.0))

                    if self.infodict.get("spacegroups"):
                        self.spacegroups = self.infodict.get("spacegroups", [])
                        self.SpaceGroupComboBox.clear()
                        self.SpaceGroupComboBox.addItems(self.spacegroups)

                    if self.infodict.get("merge_data"):
                        self.mergedata = self.infodict["merge_data"]

                    currentinfostr = ""
                    if self.infodict.get("info"):
                        currentinfostr = self.infodict.get("info", [])

                    if self.infodict.get("NewFileLoaded"):
                        self.NewFileLoaded = self.infodict.get(
                            "NewFileLoaded", False)

                    if self.infodict.get("NewHKLscenes"):
                        self.NewHKLscenes = self.infodict.get(
                            "NewHKLscenes", False)

                    self.fileisvalid = True
                    #print("ngl_hkl_infodict: " + str(ngl_hkl_infodict))

                    if currentinfostr:
                        #print(currentinfostr)
                        self.infostr += currentinfostr + "\n"
                        # display no more than self.bufsize bytes of text
                        self.infostr = self.infostr[-self.bufsize:]
                        self.textInfo.setPlainText(self.infostr)
                        self.textInfo.verticalScrollBar().setValue(
                            self.textInfo.verticalScrollBar().maximum())

                    if self.NewFileLoaded and self.NewHKLscenes:
                        #if self.mergedata == True : val = Qt.CheckState.Checked
                        #if self.mergedata == None : val = Qt.CheckState.PartiallyChecked
                        #if self.mergedata == False : val = Qt.CheckState.Unchecked
                        #self.mergecheckbox.setCheckState(val )
                        #print("got hklscenes: " + str(self.hklscenes_arrays))

                        self.MillerComboBox.clear()
                        self.MillerComboBox.addItems(
                            [e[3] for e in self.hklscenes_arrays])
                        self.MillerComboBox.setCurrentIndex(
                            -1)  # unselect the first item in the list
                        self.comboviewwidth = 0
                        for e in self.hklscenes_arrays:
                            self.comboviewwidth = max(
                                self.comboviewwidth,
                                self.MillerComboBox.fontMetrics().width(e[3]))
                        self.MillerComboBox.view().setMinimumWidth(
                            self.comboviewwidth)

                        self.millertable.clearContents()
                        self.millertable.setRowCount(len(
                            self.hklscenes_arrays))
                        for n, millarr in enumerate(self.array_infotpls):
                            for m, elm in enumerate(millarr):
                                self.millertable.setItem(
                                    n, m, QTableWidgetItem(str(elm)))
                        self.functionTabWidget.setDisabled(True)
                        self.NewFileLoaded = False

                    if self.NewHKLscenes:
                        self.BinDataComboBox.clear()
                        self.BinDataComboBox.addItems(
                            ["Resolution"] +
                            [e[3] for e in self.hklscenes_arrays])
                        self.BinDataComboBox.view().setMinimumWidth(
                            self.comboviewwidth)
                        #self.BinDataComboBox.setCurrentIndex(-1) # unselect the first item in the list
                        self.NewHKLscenes = False

            except Exception as e:
                errmsg = str(e)
                if "Resource temporarily unavailable" not in errmsg:
                    print(errmsg + traceback.format_exc(limit=10))
                pass

    def onFinalMouseSensitivity(self):
        val = self.mousemoveslider.value() / 100.0
        self.NGL_HKL_command(
            'NGL_HKLviewer.viewer.NGL.mouse_sensitivity = %f' % val)

    def onMouseSensitivity(self):
        val = self.mousemoveslider.value() / 100.0
        self.mousesensitxtbox.setText("%2.2f" % val)

    def onFontsizeChanged(self, val):
        font = app.font()
        font.setPointSize(val)
        app.setFont(font)
        self.settingsform.setFixedSize(self.settingsform.sizeHint())

    def onCameraPerspect(self, val):
        if self.cameraPerspectCheckBox.isChecked():
            self.NGL_HKL_command("NGL_HKLviewer.camera_type = perspective")
        else:
            self.NGL_HKL_command("NGL_HKLviewer.camera_type = orthographic")

    def MergeData(self):
        if self.mergecheckbox.checkState() == Qt.CheckState.Checked:
            self.NGL_HKL_command('NGL_HKLviewer.mergedata = True')
        if self.mergecheckbox.checkState() == Qt.CheckState.PartiallyChecked:
            self.NGL_HKL_command('NGL_HKLviewer.mergedata = None')
        if self.mergecheckbox.checkState() == Qt.CheckState.Unchecked:
            self.NGL_HKL_command('NGL_HKLviewer.mergedata = False')

    def ExpandToP1(self):
        if self.expandP1checkbox.isChecked():
            self.NGL_HKL_command('NGL_HKLviewer.viewer.expand_to_p1 = True')
        else:
            self.NGL_HKL_command('NGL_HKLviewer.viewer.expand_to_p1 = False')

    def ExpandAnomalous(self):
        if self.expandAnomalouscheckbox.isChecked():
            self.NGL_HKL_command(
                'NGL_HKLviewer.viewer.expand_anomalous = True')
        else:
            self.NGL_HKL_command(
                'NGL_HKLviewer.viewer.expand_anomalous = False')

    def showSysAbsent(self):
        if self.sysabsentcheckbox.isChecked():
            self.NGL_HKL_command(
                'NGL_HKLviewer.viewer.show_systematic_absences = True')
        else:
            self.NGL_HKL_command(
                'NGL_HKLviewer.viewer.show_systematic_absences = False')

    def showMissing(self):
        if self.missingcheckbox.isChecked():
            self.NGL_HKL_command('NGL_HKLviewer.viewer.show_missing = True')
        else:
            self.NGL_HKL_command('NGL_HKLviewer.viewer.show_missing = False')

    def showOnlyMissing(self):
        if self.onlymissingcheckbox.isChecked():
            self.NGL_HKL_command(
                'NGL_HKLviewer.viewer.show_only_missing = True')
        else:
            self.NGL_HKL_command(
                'NGL_HKLviewer.viewer.show_only_missing = False')

    def showSlice(self):
        if self.showslicecheckbox.isChecked():
            self.NGL_HKL_command('NGL_HKLviewer.viewer.slice_mode = True')
            if self.expandP1checkbox.isChecked():
                self.NGL_HKL_command("""NGL_HKLviewer.viewer {
                                                       expand_to_p1 = True
                                                       inbrowser = False
                                                    }
                             """)
            if self.expandAnomalouscheckbox.isChecked():
                self.NGL_HKL_command("""NGL_HKLviewer.viewer {
                                                       expand_anomalous = True
                                                       inbrowser = False
                                                     }
                             """)
        else:
            self.NGL_HKL_command("""NGL_HKLviewer.viewer {
                                                      slice_mode = False
                                                      inbrowser = True
                                                    }
                            """)

    def onSliceComboSelchange(self, i):
        rmin = self.array_infotpls[self.MillerComboBox.currentIndex()][3][0][i]
        rmax = self.array_infotpls[self.MillerComboBox.currentIndex()][3][1][i]
        self.sliceindexspinBox.setRange(rmin, rmax)
        self.NGL_HKL_command("NGL_HKLviewer.viewer.slice_axis = %s" %
                             self.sliceaxis[i])

    def onSliceIndexChanged(self, val):
        self.sliceindex = val
        self.NGL_HKL_command("NGL_HKLviewer.viewer.slice_index = %d" %
                             self.sliceindex)

    def onBindataComboSelchange(self, i):
        if self.BinDataComboBox.currentText():
            if self.BinDataComboBox.currentIndex() > 0:
                bin_scene_label = str(self.BinDataComboBox.currentIndex() - 1)
            else:
                bin_scene_label = "Resolution"
            self.NGL_HKL_command("NGL_HKLviewer.bin_scene_label = %s" %
                                 bin_scene_label)

    def update_table_opacities(self, allalpha=None):
        bin_opacitieslst = eval(self.bin_opacities)
        self.binstable_isready = False
        for binopacity in bin_opacitieslst:
            if not allalpha:
                alpha = float(binopacity.split(",")[0])
            else:
                alpha = allalpha
            bin = int(binopacity.split(",")[1])
            item = QTableWidgetItem()
            item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
            if alpha < 0.5:
                item.setCheckState(Qt.Unchecked)
            else:
                item.setCheckState(Qt.Checked)
            item.setFlags(item.flags() ^ Qt.ItemIsEditable)
            self.binstable.setItem(bin, 3, item)
        self.binstable_isready = True

    def SetOpaqueAll(self):
        if self.binstableitemchanges:
            return
        bin_opacitieslst = eval(self.bin_opacities)
        nbins = len(bin_opacitieslst)
        sum = 0
        for binopacity in bin_opacitieslst:
            sum += float(binopacity.split(",")[0])
        if sum >= nbins:
            self.OpaqueAllCheckbox.setCheckState(Qt.Checked)
        if sum == 0:
            self.OpaqueAllCheckbox.setCheckState(Qt.Unchecked)
        if sum > 0.0 and sum < nbins:
            self.OpaqueAllCheckbox.setCheckState(Qt.PartiallyChecked)

    def onBinsTableItemChanged(self, item):
        row = item.row()
        column = item.column()
        try:
            if item.checkState() == Qt.Unchecked:
                newval = 0
            else:
                newval = 1.0
            if column == 3 and self.binstable_isready:  # changing opacity
                assert (newval <= 1.0 and newval >= 0.0)
                bin_opacitieslst = eval(self.bin_opacities)
                bin_opacitieslst[row] = str(newval) + ', ' + str(row)
                self.bin_opacities = str(bin_opacitieslst)
                self.SetOpaqueAll()
                self.NGL_HKL_command(
                    'NGL_HKLviewer.viewer.NGL.bin_opacities = "%s"' %
                    self.bin_opacities)
        except Exception as e:
            print(str(e))
            #self.binstable.currentItem().setText( self.currentSelectedBinsTableVal)

    def onBinsTableItemSelectionChanged(self):
        row = self.binstable.currentItem().row()
        column = self.binstable.currentItem().column()
        self.currentSelectedBinsTableVal = self.binstable.currentItem().text()
        #print( "in itemSelectionChanged " + self.currentSelectedBinsTableVal)

    def onOpaqueAll(self):
        self.binstableitemchanges = True
        bin_opacitieslst = eval(self.bin_opacities)
        nbins = len(bin_opacitieslst)
        bin_opacitieslst = []
        self.binstable_isready = False
        if self.OpaqueAllCheckbox.isChecked():
            for i in range(nbins):
                bin_opacitieslst.append("1.0, %d" % i)
        else:
            for i in range(nbins):
                bin_opacitieslst.append("0.0, %d" % i)
        self.bin_opacities = str(bin_opacitieslst)
        self.NGL_HKL_command('NGL_HKLviewer.viewer.NGL.bin_opacities = "%s"' %
                             self.bin_opacities)
        self.binstableitemchanges = False
        self.binstable_isready = True

    """
  def onLoadFinished(self, val):
    pass
    #print("web page finished loading now")


  def onBinsTableitemActivated(self, item):
    row = item.row()
    column = item.column()
    currentval = item.text()
    #print( "in itemActivated " + currentval)


  def onBinsTableCellentered(self, row, col):
    pass
    #print( "in Cellentered " + self.binstable.currentItem().text() )


  def onBinsTableCellPressed(self, row, col):
    pass
    #print( "in CellPressed " + self.binstable.currentItem().text() )
  """

    def onNbinsChanged(self, val):
        self.nbins = val
        if not self.updatingNbins:  # avoid possible endless loop to cctbx
            self.NGL_HKL_command("NGL_HKLviewer.nbins = %d" % self.nbins)

    def onRadiiScaleChanged(self, val):
        self.radii_scale = val
        self.NGL_HKL_command("""
      NGL_HKLviewer.viewer {
        nth_power_scale_radii = %f
        scale = %f
      }
      """ % (self.nth_power_scale, self.radii_scale))

    def onPowerScaleChanged(self, val):
        self.nth_power_scale = val
        self.NGL_HKL_command("""
      NGL_HKLviewer.viewer {
        nth_power_scale_radii = %f
        scale = %f
      }
      """ % (self.nth_power_scale, self.radii_scale))

    def onManualPowerScale(self):
        if self.ManualPowerScalecheckbox.isChecked():
            self.NGL_HKL_command(
                'NGL_HKLviewer.viewer.nth_power_scale_radii = %f' %
                self.nth_power_scale)
            self.power_scale_spinBox.setEnabled(True)
        else:
            self.NGL_HKL_command(
                'NGL_HKLviewer.viewer.nth_power_scale_radii = -1.0')
            self.power_scale_spinBox.setEnabled(False)
            self.nth_power_scale = -1.0

    def OpenReflectionsFile(self):
        options = QFileDialog.Options()
        fileName, filtr = QFileDialog.getOpenFileName(
            self, "Load reflections file", "",
            "All Files (*);;MTZ Files (*.mtz);;CIF (*.cif)", "", options)
        if fileName:
            self.HKLnameedit.setText(fileName)
            #self.infostr = ""
            self.textInfo.setPlainText("")
            self.fileisvalid = False
            self.NGL_HKL_command('NGL_HKLviewer.filename = "%s"' % fileName)
            self.MillerComboBox.clear()
            self.BinDataComboBox.clear()

    def createExpansionBox(self):
        self.SpaceGroupComboBox = QComboBox()
        self.SpaceGroupComboBox.activated.connect(self.SpacegroupSelchange)

        self.SpacegroupLabel = QLabel()
        self.SpacegroupLabel.setText("Space Subgroups")

        self.mergecheckbox = QCheckBox()
        self.mergecheckbox.setText("Merge data")
        #self.mergecheckbox.setTristate (True)
        self.mergecheckbox.clicked.connect(self.MergeData)

        self.expandP1checkbox = QCheckBox()
        self.expandP1checkbox.setText("Expand to P1")
        self.expandP1checkbox.clicked.connect(self.ExpandToP1)

        self.expandAnomalouscheckbox = QCheckBox()
        self.expandAnomalouscheckbox.setText("Show Friedel pairs")
        self.expandAnomalouscheckbox.clicked.connect(self.ExpandAnomalous)

        self.sysabsentcheckbox = QCheckBox()
        self.sysabsentcheckbox.setText("Show Systematic Absences")
        self.sysabsentcheckbox.clicked.connect(self.showSysAbsent)

        self.missingcheckbox = QCheckBox()
        self.missingcheckbox.setText("Show Missing")
        self.missingcheckbox.clicked.connect(self.showMissing)

        self.onlymissingcheckbox = QCheckBox()
        self.onlymissingcheckbox.setText("Only Show Missing")
        self.onlymissingcheckbox.clicked.connect(self.showOnlyMissing)

        self.ExpansionBox = QGroupBox("Expansions")
        layout = QGridLayout()
        layout.addWidget(self.SpacegroupLabel, 0, 0)
        layout.addWidget(self.SpaceGroupComboBox, 0, 1)
        #layout.addWidget(self.mergecheckbox,             1, 0)
        layout.addWidget(self.expandP1checkbox, 1, 0)
        layout.addWidget(self.expandAnomalouscheckbox, 1, 1)
        layout.addWidget(self.sysabsentcheckbox, 2, 0)
        layout.addWidget(self.missingcheckbox, 3, 0)
        layout.addWidget(self.onlymissingcheckbox, 3, 1)
        layout.setRowStretch(0, 0)
        layout.setRowStretch(1, 0)
        layout.setRowStretch(2, 0)
        layout.setRowStretch(3, 1)
        self.ExpansionBox.setLayout(layout)

    def CreateSliceTabs(self):
        self.showslicecheckbox = QCheckBox()
        self.showslicecheckbox.setText("Show Slice")
        self.showslicecheckbox.clicked.connect(self.showSlice)

        self.sliceindexspinBox = QDoubleSpinBox()
        self.sliceindex = 0
        self.sliceindexspinBox.setValue(self.sliceindex)
        self.sliceindexspinBox.setDecimals(0)
        self.sliceindexspinBox.setSingleStep(1)
        self.sliceindexspinBox.setRange(0, 20)
        self.sliceindexspinBox.valueChanged.connect(self.onSliceIndexChanged)

        self.SliceLabelComboBox = QComboBox()
        self.SliceLabelComboBox.activated.connect(self.onSliceComboSelchange)
        self.sliceaxis = ["h", "k", "l"]
        self.SliceLabelComboBox.addItems(self.sliceaxis)

        self.sliceTabWidget = QTabWidget()
        tab1 = QWidget()
        layout1 = QGridLayout()
        layout1.addWidget(self.showslicecheckbox, 0, 0, 1, 1)
        layout1.addWidget(self.SliceLabelComboBox, 0, 1, 1, 1)
        layout1.addWidget(self.sliceindexspinBox, 0, 2, 1, 1)
        tab1.setLayout(layout1)

        tab2 = QWidget()
        layout2 = QGridLayout()

        self.hvec_spinBox = QDoubleSpinBox(self.sliceTabWidget)
        self.hvecval = 2.0
        self.hvec_spinBox.setValue(self.hvecval)
        self.hvec_spinBox.setDecimals(2)
        self.hvec_spinBox.setSingleStep(0.5)
        self.hvec_spinBox.setRange(-100.0, 10.0)
        self.hvec_spinBox.valueChanged.connect(self.onHvecChanged)
        self.hvec_Label = QLabel()
        self.hvec_Label.setText("H")
        layout2.addWidget(self.hvec_Label, 0, 0, 1, 1)
        layout2.addWidget(self.hvec_spinBox, 0, 1, 1, 1)

        self.kvec_spinBox = QDoubleSpinBox(self.sliceTabWidget)
        self.kvecval = 0.0
        self.kvec_spinBox.setValue(self.kvecval)
        self.kvec_spinBox.setDecimals(2)
        self.kvec_spinBox.setSingleStep(0.5)
        self.kvec_spinBox.setRange(-100.0, 100.0)
        self.kvec_spinBox.valueChanged.connect(self.onKvecChanged)
        self.kvec_Label = QLabel()
        self.kvec_Label.setText("K")
        layout2.addWidget(self.kvec_Label, 1, 0, 1, 1)
        layout2.addWidget(self.kvec_spinBox, 1, 1, 1, 1)

        self.lvec_spinBox = QDoubleSpinBox(self.sliceTabWidget)
        self.lvecval = 0.0
        self.lvec_spinBox.setValue(self.lvecval)
        self.lvec_spinBox.setDecimals(2)
        self.lvec_spinBox.setSingleStep(0.5)
        self.lvec_spinBox.setRange(-100.0, 100.0)
        self.lvec_spinBox.valueChanged.connect(self.onLvecChanged)
        self.lvec_Label = QLabel()
        self.lvec_Label.setText("L")
        layout2.addWidget(self.lvec_Label, 2, 0, 1, 1)
        layout2.addWidget(self.lvec_spinBox, 2, 1, 1, 1)

        self.hkldist_spinBox = QDoubleSpinBox(self.sliceTabWidget)
        self.hkldistval = 0.0
        self.hkldist_spinBox.setValue(self.hkldistval)
        self.hkldist_spinBox.setDecimals(2)
        self.hkldist_spinBox.setSingleStep(0.5)
        self.hkldist_spinBox.setRange(-100.0, 100.0)
        self.hkldist_spinBox.valueChanged.connect(self.onHKLdistChanged)
        self.hkldist_Label = QLabel()
        self.hkldist_Label.setText("Distance from Origin")
        layout2.addWidget(self.hkldist_Label, 3, 0, 1, 1)
        layout2.addWidget(self.hkldist_spinBox, 3, 1, 1, 1)

        self.clipwidth_spinBox = QDoubleSpinBox(self.sliceTabWidget)
        self.clipwidthval = 0.5
        self.clipwidth_spinBox.setValue(self.clipwidthval)
        self.clipwidth_spinBox.setDecimals(2)
        self.clipwidth_spinBox.setSingleStep(0.05)
        self.clipwidth_spinBox.setRange(0.0, 100.0)
        self.clipwidth_spinBox.valueChanged.connect(self.onClipwidthChanged)
        self.clipwidth_Label = QLabel()
        self.clipwidth_Label.setText("Clip Plane Width")
        layout2.addWidget(self.clipwidth_Label, 4, 0, 1, 1)
        layout2.addWidget(self.clipwidth_spinBox, 4, 1, 1, 1)

        self.ClipBox = QGroupBox("Normal Vector to Clip Plane")
        self.ClipBox.setLayout(layout2)

        layout3 = QGridLayout()
        self.ClipPlaneChkBox = QCheckBox(self.sliceTabWidget)
        self.ClipPlaneChkBox.setText(
            "Use clip plane normal to HKL vector pointing out")
        self.ClipPlaneChkBox.clicked.connect(self.onClipPlaneChkBox)

        layout3.addWidget(self.ClipPlaneChkBox, 0, 0)
        layout3.addWidget(self.ClipBox, 1, 0)
        tab2.setLayout(layout3)
        self.sliceTabWidget.addTab(tab1, "Explicit Slicing")
        self.sliceTabWidget.addTab(tab2, "Clip Plane Slicing")
        self.ClipBox.setDisabled(True)

    def onClipPlaneChkBox(self):
        if self.ClipPlaneChkBox.isChecked():
            self.ClipBox.setDisabled(False)
            philstr = """NGL_HKLviewer.normal_clip_plane {
  h = %s
  k = %s
  l = %s
  hkldist = %s
  clipwidth = %s
}
  NGL_HKLviewer.viewer.NGL.fixorientation = %s

      """ %(self.hvecval, self.kvecval, self.lvecval, self.hkldistval, self.clipwidthval, \
                                    str(self.fixedorientcheckbox.isChecked()) )
            self.NGL_HKL_command(philstr)
        else:
            self.ClipBox.setDisabled(True)
            self.NGL_HKL_command(
                "NGL_HKLviewer.normal_clip_plane.clipwidth = None")

    def onClipwidthChanged(self, val):
        self.clipwidthval = val
        self.NGL_HKL_command("NGL_HKLviewer.normal_clip_plane.clipwidth = %f" %
                             self.clipwidthval)

    def onHKLdistChanged(self, val):
        self.hkldistval = val
        self.NGL_HKL_command("NGL_HKLviewer.normal_clip_plane.hkldist = %f" %
                             self.hkldistval)

    def onHvecChanged(self, val):
        self.hvecval = val
        self.NGL_HKL_command("NGL_HKLviewer.normal_clip_plane.h = %f" %
                             self.hvecval)

    def onKvecChanged(self, val):
        self.kvecval = val
        self.NGL_HKL_command("NGL_HKLviewer.normal_clip_plane.k = %f" %
                             self.kvecval)

    def onLvecChanged(self, val):
        self.lvecval = val
        self.NGL_HKL_command("NGL_HKLviewer.normal_clip_plane.l = %f" %
                             self.lvecval)

    def onFixedorient(self):
        self.NGL_HKL_command('NGL_HKLviewer.viewer.NGL.fixorientation = %s' \
                                        %str(self.fixedorientcheckbox.isChecked()))

    def onMillerComboSelchange(self, i):
        self.NGL_HKL_command("NGL_HKLviewer.scene_id = %d" % i)
        #self.MillerComboBox.setCurrentIndex(i)
        if self.MillerComboBox.currentText():
            self.functionTabWidget.setEnabled(True)
            self.expandAnomalouscheckbox.setEnabled(True)
            # don' allow anomalous expansion for data that's already anomalous
            for arrayinfo in self.array_infotpls:
                isanomalous = arrayinfo[-1]
                label = arrayinfo[0]
                if isanomalous and label == self.MillerComboBox.currentText(
                )[:len(label)]:
                    self.expandAnomalouscheckbox.setDisabled(True)
        else:
            self.functionTabWidget.setDisabled(True)

        self.SpaceGroupComboBox.clear()
        self.SpaceGroupComboBox.addItems(self.spacegroups)
        # need to supply issymunique flag in infotuple
        #if self.hklscenes_arrays[ i ][6] == 0:
        #  self.mergecheckbox.setEnabled(True)
        #else:
        #  self.mergecheckbox.setEnabled(False)

    def createFileInfoBox(self):
        self.FileInfoBox = QGroupBox("Reflection File Information")
        layout = QGridLayout()
        layout.addWidget(self.openFileNameButton, 0, 0, 1, 2)
        if self.devmode:
            layout.addWidget(self.debugbutton, 0, 2, 1, 1)
        layout.addWidget(self.HKLnameedit, 1, 0, 1, 3)
        layout.addWidget(self.millertable, 2, 0, 1, 3)
        layout.addWidget(self.textInfo, 3, 0, 1, 3)
        #layout.setColumnStretch(1, 2)
        self.FileInfoBox.setLayout(layout)

    def createRadiiScaleGroupBox(self):
        self.RadiiScaleGroupBox = QGroupBox("Radii Size of HKL Spheres")

        self.ManualPowerScalecheckbox = QCheckBox()
        self.ManualPowerScalecheckbox.setText(
            "Manual Power Scaling of Sphere Radii")
        self.ManualPowerScalecheckbox.clicked.connect(self.onManualPowerScale)

        self.power_scale_spinBox = QDoubleSpinBox(self.RadiiScaleGroupBox)
        self.nth_power_scale = 0.5
        self.power_scale_spinBox.setValue(self.nth_power_scale)
        self.power_scale_spinBox.setDecimals(2)
        self.power_scale_spinBox.setSingleStep(0.05)
        self.power_scale_spinBox.setRange(0.0, 1.0)
        self.power_scale_spinBox.valueChanged.connect(self.onPowerScaleChanged)
        self.power_scale_spinBox.setEnabled(False)
        self.powerscaleLabel = QLabel()
        self.powerscaleLabel.setText("Power scale Factor")

        self.radii_scale_spinBox = QDoubleSpinBox(self.RadiiScaleGroupBox)
        self.radii_scale = 1.0
        self.radii_scale_spinBox.setValue(self.radii_scale)
        self.radii_scale_spinBox.setDecimals(1)
        self.radii_scale_spinBox.setSingleStep(0.1)
        self.radii_scale_spinBox.setRange(0.2, 2.0)
        self.radii_scale_spinBox.valueChanged.connect(self.onRadiiScaleChanged)
        self.radiiscaleLabel = QLabel()
        self.radiiscaleLabel.setText("Linear Scale Factor")

        layout = QGridLayout()
        layout.addWidget(self.ManualPowerScalecheckbox, 1, 0, 1, 2)
        layout.addWidget(self.powerscaleLabel, 2, 0, 1, 2)
        layout.addWidget(self.power_scale_spinBox, 2, 1, 1, 2)
        layout.addWidget(self.radiiscaleLabel, 3, 0, 1, 2)
        layout.addWidget(self.radii_scale_spinBox, 3, 1, 1, 2)
        layout.setColumnStretch(0, 1)
        layout.setColumnStretch(1, 0)
        self.RadiiScaleGroupBox.setLayout(layout)

    def createBinsBox(self):
        self.binstable = QTableWidget(0, 4)
        self.binstable_isready = False
        labels = [
            "no. of HKLs", "lower bin value", "upper bin value", "opacity"
        ]
        self.binstable.setHorizontalHeaderLabels(labels)
        self.binstable.horizontalHeader().setDefaultAlignment(Qt.AlignLeft)
        self.bindata_labeltxt = QLabel()
        self.bindata_labeltxt.setText("Data binned:")
        self.Nbins_spinBox = QSpinBox()
        self.Nbins_spinBox.setSingleStep(1)
        self.Nbins_spinBox.setRange(1, 40)
        self.Nbins_spinBox.valueChanged.connect(self.onNbinsChanged)
        self.Nbins_labeltxt = QLabel()
        self.Nbins_labeltxt.setText("Number of bins:")

        self.OpaqueAllCheckbox = QCheckBox()
        #self.OpaqueAllCheckbox.setTristate()
        self.OpaqueAllCheckbox.setText("Show all data in bins")
        self.OpaqueAllCheckbox.clicked.connect(self.onOpaqueAll)

        self.binstable.itemChanged.connect(self.onBinsTableItemChanged)
        self.binstable.itemSelectionChanged.connect(
            self.onBinsTableItemSelectionChanged)
        self.BinDataComboBox = QComboBox()
        self.BinDataComboBox.activated.connect(self.onBindataComboSelchange)
        self.BinsGroupBox = QGroupBox("Bins")
        layout = QGridLayout()
        layout.addWidget(self.bindata_labeltxt, 0, 0)
        layout.addWidget(self.BinDataComboBox, 0, 1)
        layout.addWidget(self.Nbins_labeltxt, 0, 2)
        layout.addWidget(self.Nbins_spinBox, 0, 3)
        layout.addWidget(self.OpaqueAllCheckbox, 1, 2)
        layout.addWidget(self.binstable, 2, 0, 1, 4)
        layout.setColumnStretch(0, 0)
        layout.setColumnStretch(1, 2)
        layout.setColumnStretch(3, 1)
        self.BinsGroupBox.setLayout(layout)

    def DebugInteractively(self):
        import code, traceback
        code.interact(local=locals(),
                      banner="".join(traceback.format_stack(limit=10)))

    def CreateFunctionTabs(self):
        self.functionTabWidget = QTabWidget()
        tab1 = QWidget()
        layout1 = QGridLayout()
        layout1.addWidget(self.ExpansionBox, 0, 0)
        layout1.setRowStretch(0, 0)
        tab1.setLayout(layout1)

        tab2 = QWidget()
        layout2 = QGridLayout()

        self.fixedorientcheckbox = QCheckBox(self.sliceTabWidget)
        self.fixedorientcheckbox.setText(
            "Fix orientation but allow zoom and translation")
        self.fixedorientcheckbox.clicked.connect(self.onFixedorient)
        layout2.addWidget(self.fixedorientcheckbox, 0, 0)

        layout2.addWidget(self.sliceTabWidget, 1, 0)
        tab2.setLayout(layout2)

        tab3 = QWidget()
        layout3 = QGridLayout()
        layout3.addWidget(self.RadiiScaleGroupBox, 0, 0)
        tab3.setLayout(layout3)

        tab4 = QWidget()
        layout4 = QGridLayout()
        layout4.addWidget(self.BinsGroupBox, 0, 0)
        tab4.setLayout(layout4)

        self.functionTabWidget.addTab(tab1, "Expand")
        self.functionTabWidget.addTab(tab2, "Slice")
        self.functionTabWidget.addTab(tab3, "Size")
        self.functionTabWidget.addTab(tab4, "Bins")
        self.functionTabWidget.setDisabled(True)

    def SpacegroupSelchange(self, i):
        self.NGL_HKL_command("NGL_HKLviewer.spacegroup_choice = %d" % i)

    def find_free_port(self):
        import socket
        s = socket.socket()
        s.bind(('', 0))  # Bind to a free port provided by the host.
        port = s.getsockname()[1]
        s.close()
        return port

    def LaunchCCTBXPython(self):
        self.sockport = self.find_free_port()
        self.zmq_context = zmq.Context()
        self.socket = self.zmq_context.socket(zmq.PAIR)
        self.socket.bind("tcp://127.0.0.1:%s" % self.sockport)
        try:
            msg = self.socket.recv(
                flags=zmq.NOBLOCK)  #To empty the socket from previous messages
        except Exception as e:
            pass
        cmdargs = 'cctbx.python.bat -i -c "from crys3d.hklview import cmdlineframes;' \
         + ' myHKLview = cmdlineframes.HKLViewFrame(useGuiSocket=%s, high_quality=True,' %self.sockport \
         + ' jscriptfname = \'%s\', ' %self.jscriptfname \
         + ' verbose=%s, UseOSBrowser= %s )"\n' %(self.verbose, str(self.UseOSbrowser))
        self.cctbxproc = subprocess.Popen(cmdargs,
                                          shell=True,
                                          stdin=subprocess.PIPE,
                                          stdout=sys.stdout,
                                          stderr=sys.stderr)
        #time.sleep(1)

    def NGL_HKL_command(self, cmdstr):
        #print("sending:\n" + cmdstr)
        self.socket.send(bytes(cmdstr, "utf-8"))
Beispiel #26
0
    def __init_slicer_options_widget__(self):
        self.__slicer_options_widget = QGroupBox("Slicer Options", self)

        thickness_label = QLabel("Layer Thickness",
                                 self.__slicer_options_widget)
        thickness_edit = QDoubleSpinBox(self.__slicer_options_widget)
        thickness_edit.setSuffix(str('\u03BCm'))
        thickness_edit.setMaximum(1000000)
        thickness_edit.setMinimum(0)
        thickness_edit.setDecimals(3)
        thickness_edit.setSingleStep(0.001)
        thickness_edit.setValue(self.dlp_controller.support_thickness * 1000)
        # self.__opengl_widget.set_slice_thickness(self.dlp_controller.support_thickness)
        thickness_edit.valueChanged.connect(
            self.__slicer_widget.set_slice_thickness)

        pixel_size_label = QLabel("Projector Pixel Size",
                                  self.__slicer_options_widget)
        pixel_size_edit = QDoubleSpinBox(self.__slicer_options_widget)
        pixel_size_edit.setSuffix(str('\u03BCm'))
        pixel_size_edit.setMaximum(1000000)
        pixel_size_edit.setMinimum(0)
        pixel_size_edit.setDecimals(2)
        pixel_size_edit.setSingleStep(0.01)
        pixel_size_edit.setValue(self.dlp_controller.projector_pixel_size *
                                 1000)
        pixel_size_edit.valueChanged.connect(
            self.__slicer_widget.set_pixel_size)

        projector_resolution_label = QLabel("Projector Resolution",
                                            self.__slicer_options_widget)
        projector_resolution_edit_x = QSpinBox(self.__slicer_options_widget)
        projector_resolution_edit_x.setSuffix(str('W'))
        projector_resolution_edit_x.setMaximum(1000000)
        projector_resolution_edit_x.setMinimum(0)
        projector_resolution_edit_x.setValue(
            self.dlp_controller.projector_width)
        projector_resolution_edit_x.valueChanged.connect(
            self.__slicer_widget.set_projector_width)
        projector_resolution_edit_y = QSpinBox(self.__slicer_options_widget)
        projector_resolution_edit_y.setSuffix(str('H'))
        projector_resolution_edit_y.setMaximum(1000000)
        projector_resolution_edit_y.setMinimum(0)
        projector_resolution_edit_y.setValue(
            self.dlp_controller.projector_height)
        projector_resolution_edit_y.valueChanged.connect(
            self.__slicer_widget.set_projector_height)

        samples_per_pixel_label = QLabel("Samples per Pixel",
                                         self.__slicer_options_widget)
        samples_per_pixel_edit = QSpinBox(self.__slicer_options_widget)
        samples_per_pixel_edit.setMaximum(1000000)
        samples_per_pixel_edit.setMinimum(1)
        samples_per_pixel_edit.setValue(self.dlp_controller.samples_per_pixel)
        samples_per_pixel_edit.valueChanged.connect(
            self.__slicer_widget.set_samples_per_pixel)

        slice_geometry_button = QPushButton("Slice Geometry")
        slice_geometry_button.clicked.connect(self.start_slicing_process)

        slice_interrupt_button = QPushButton("Stop Slicing")
        slice_interrupt_button.clicked.connect(
            self.__slicer_widget.interrupt_slicing)

        self.slices_label = QLabel(f'Slicing progress: {0:.0f}/{0:.0f}',
                                   self.__info_widget)

        thickness_label_row = 0
        pixel_size_row = 1
        projector_resolution_row = 2
        samples_per_pixel_row = 3
        slice_button_row = 4
        slices_label_row = 5
        # slice_interrupt_row = slice_button_row

        slice_layout = QGridLayout(self.__slicer_options_widget)
        slice_layout.addWidget(thickness_label, thickness_label_row, 0)
        slice_layout.addWidget(thickness_edit, thickness_label_row, 1)
        slice_layout.addWidget(pixel_size_label, pixel_size_row, 0)
        slice_layout.addWidget(pixel_size_edit, pixel_size_row, 1)
        slice_layout.addWidget(projector_resolution_label,
                               projector_resolution_row, 0)
        slice_layout.addWidget(projector_resolution_edit_x,
                               projector_resolution_row, 1)
        slice_layout.addWidget(projector_resolution_edit_y,
                               projector_resolution_row, 2)
        slice_layout.addWidget(self.slices_label, slice_button_row, 0)
        slice_layout.addWidget(slice_geometry_button, slice_button_row, 1)
        slice_layout.addWidget(slice_interrupt_button, slice_button_row, 2)
        slice_layout.addWidget(samples_per_pixel_label, samples_per_pixel_row,
                               0)
        slice_layout.addWidget(samples_per_pixel_edit, samples_per_pixel_row,
                               1)
        self.__slicer_options_widget.setLayout(slice_layout)
Beispiel #27
0
class Ui_Transformation(object):
    def setupUi(self, Transformation, instrument):
        Transformation.setObjectName("Transformation")
        Transformation.resize(361, 171)
        self.frame_layout = QVBoxLayout(Transformation)
        self.frame_layout.setContentsMargins(4, 4, 4, 4)
        self.main_layout = QVBoxLayout()
        self.main_layout.setSpacing(4)

        self.name_layout = QHBoxLayout()
        self.name_layout.setSpacing(-1)
        self.name_label = QLabel("Name", Transformation)
        self._make_text_bold(self.name_label)

        self.name_layout.addWidget(self.name_label)
        self.name_line_edit = QLineEdit(Transformation)

        self.name_layout.addWidget(self.name_line_edit)
        self.main_layout.addLayout(self.name_layout)

        self._add_line()

        self.vector_label = QLabel("", Transformation)
        self._make_text_bold(self.vector_label)
        self.main_layout.addWidget(self.vector_label)

        self._set_up_vector_box(Transformation)

        self._add_line()

        self.value_label = QLabel("")
        self._make_text_bold(self.value_label)
        self.main_layout.addWidget(self.value_label)

        self.magnitude_widget = FieldWidget(hide_name_field=True,
                                            instrument=instrument)
        self.magnitude_widget.setFrameShape(QFrame.NoFrame)
        self.magnitude_widget.setMinimumHeight(40)
        self.main_layout.addWidget(self.magnitude_widget)

        self.ui_placeholder_layout = QFormLayout()
        self.value_spinbox = QDoubleSpinBox(Transformation)
        self.value_spinbox.setToolTip("Placeholder value for 3D view to use")
        self.value_spinbox.setDecimals(8)
        self.value_spinbox.setMaximumSize(QSize(100, 16777215))
        self.ui_placeholder_layout.addRow("Value to use in 3D view:",
                                          self.value_spinbox)

        self.main_layout.addLayout(self.ui_placeholder_layout)

        self.set_spinbox_ranges()

        self.frame_layout.addLayout(self.main_layout)

        self.retranslateUi(Transformation)
        QMetaObject.connectSlotsByName(Transformation)

    def _add_line(self):
        line = QFrame()
        line.setFrameShape((QFrame.HLine))
        line.setFrameShadow(QFrame.Sunken)
        self.main_layout.addWidget(line)

    @staticmethod
    def _make_text_bold(label: QLabel):
        font = label.font()
        font.setBold(True)
        label.setFont(font)

    def _set_up_vector_box(self, Transformation):
        self.xyz_layout = QHBoxLayout()

        self.x_layout = QFormLayout()
        self.x_spinbox = QDoubleSpinBox(Transformation)
        self.x_layout.addRow("x:", self.x_spinbox)
        self.xyz_layout.addLayout(self.x_layout)

        self.y_layout = QFormLayout()
        self.y_spinbox = QDoubleSpinBox(Transformation)
        self.y_layout.addRow("y:", self.y_spinbox)
        self.xyz_layout.addLayout(self.y_layout)

        self.z_layout = QFormLayout()
        self.z_spinbox = QDoubleSpinBox(Transformation)
        self.z_layout.addRow("z:", self.z_spinbox)
        self.xyz_layout.addLayout(self.z_layout)

        self.main_layout.addLayout(self.xyz_layout)

    def set_spinbox_ranges(self):
        self.spinboxes = [
            self.x_spinbox,
            self.y_spinbox,
            self.z_spinbox,
            self.value_spinbox,
        ]
        for spinbox in self.spinboxes:
            spinbox.setRange(-10000000, 10000000)
            spinbox.setDecimals(5)

    def retranslateUi(self, Transformation):
        Transformation.setWindowTitle(
            QApplication.translate("Transformation", "GroupBox", None, -1))
        Transformation.setTitle(
            QApplication.translate("Transformation", "Translation", None, -1))
Beispiel #28
0
class ColorForm(QWidget):
    """
    Class for handling a field with a colormap, alpha, and visibility

    Attributes
    ----------

    model : PlotModel
        The model instance used when updating information on the form.
    colormapBox : QComboBox
        Holds the string of the matplotlib colorbar being used
    visibilityBox : QCheckBox
        Indicator for whether or not the field should be visible
    alphaBox : QDoubleSpinBox
        Holds the alpha value for the displayed field data
    colormapBox : QComboBox
        Selector for colormap
    dataIndicatorCheckBox : QCheckBox
        Inidcates whether or not the data indicator will appear on the colorbar
    userMinMaxBox : QCheckBox
        Indicates whether or not the user defined values in the min and max
        will be used to set the bounds of the colorbar.
    maxBox : ScientificDoubleSpinBox
        Max value of the colorbar. If the userMinMaxBox is checked, this will be
        the user's input. If the userMinMaxBox is not checked, this box will
        hold the max value of the visible data.
    minBox : ScientificDoubleSpinBox
        Min value of the colorbar. If the userMinMaxBox is checked, this will be
        the user's input. If the userMinMaxBox is not checked, this box will
        hold the max value of the visible data.
    scaleBox : QCheckBox
        Indicates whether or not the data is displayed on a log or linear
        scale
    maskZeroBox : QCheckBox
        Indicates whether or not values equal to zero are displayed
    clipDataBox : QCheckBox
        Indicates whether or not values outside the min/max are displayed
    contoursBox :  QCheckBox
        Inidicates whether or not data is displayed as contours
    contourLevelsLine : QLineEdit
        Controls the contours of the data. If this line contains a single
        integer, that number of levels is used to display the data. If a
        comma-separated set of values is entered, those values will be used as
        levels in the contour plot.
    """
    def __init__(self, model, main_window, field, colormaps=None):
        super().__init__()

        self.model = model
        self.main_window = main_window
        self.field = field

        self.layout = QFormLayout()

        # Visibility check box
        self.visibilityBox = QCheckBox()
        visible_connector = partial(main_window.toggleTallyVisibility)
        self.visibilityBox.stateChanged.connect(visible_connector)

        # Alpha value
        self.alphaBox = QDoubleSpinBox()
        self.alphaBox.setDecimals(2)
        self.alphaBox.setRange(0, 1)
        self.alphaBox.setSingleStep(0.05)
        alpha_connector = partial(main_window.editTallyAlpha)
        self.alphaBox.valueChanged.connect(alpha_connector)

        # Color map selector
        self.colormapBox = QComboBox()
        if colormaps is None:
            colormaps = sorted(m for m in mcolormaps.datad if not m.endswith("_r"))
        for colormap in colormaps:
            self.colormapBox.addItem(colormap)
        cmap_connector = partial(main_window.editTallyDataColormap)
        self.colormapBox.currentTextChanged[str].connect(cmap_connector)

        # Data indicator line check box
        self.dataIndicatorCheckBox = QCheckBox()
        data_indicator_connector = partial(main_window.toggleTallyDataIndicator)
        self.dataIndicatorCheckBox.stateChanged.connect(data_indicator_connector)

        # User specified min/max check box
        self.userMinMaxBox = QCheckBox()
        minmax_connector = partial(main_window.toggleTallyDataUserMinMax)
        self.userMinMaxBox.stateChanged.connect(minmax_connector)

        # Data min spin box
        self.minBox = ScientificDoubleSpinBox()
        self.minBox.setMinimum(0.0)
        min_connector = partial(main_window.editTallyDataMin)
        self.minBox.valueChanged.connect(min_connector)

        # Data max spin box
        self.maxBox = ScientificDoubleSpinBox()
        self.maxBox.setMinimum(0.0)
        max_connector = partial(main_window.editTallyDataMax)
        self.maxBox.valueChanged.connect(max_connector)

        # Linear/Log scaling check box
        self.scaleBox = QCheckBox()
        scale_connector = partial(main_window.toggleTallyLogScale)
        self.scaleBox.stateChanged.connect(scale_connector)

        # Masking of zero values check box
        self.maskZeroBox = QCheckBox()
        zero_connector = partial(main_window.toggleTallyMaskZero)
        self.maskZeroBox.stateChanged.connect(zero_connector)

        # Clip data to min/max check box
        self.clipDataBox = QCheckBox()
        clip_connector = partial(main_window.toggleTallyDataClip)
        self.clipDataBox.stateChanged.connect(clip_connector)

        # Display data as contour plot check box
        self.contoursBox = QCheckBox()
        self.contoursBox.stateChanged.connect(main_window.toggleTallyContours)
        self.contourLevelsLine = QLineEdit()
        self.contourLevelsLine.textChanged.connect(
            main_window.editTallyContourLevels)

        # Organize widgets on layout
        self.layout.addRow("Visible:", self.visibilityBox)
        self.layout.addRow("Alpha: ", self.alphaBox)
        self.layout.addRow("Colormap: ", self.colormapBox)
        self.layout.addRow("Data Indicator: ", self.dataIndicatorCheckBox)
        self.layout.addRow("Custom Min/Max: ", self.userMinMaxBox)
        self.layout.addRow("Min: ", self.minBox)
        self.layout.addRow("Max: ", self.maxBox)
        self.layout.addRow("Log Scale: ", self.scaleBox)
        self.layout.addRow("Clip Data: ", self.clipDataBox)
        self.layout.addRow("Mask Zeros: ", self.maskZeroBox)
        self.layout.addRow("Contours: ", self.contoursBox)
        self.layout.addRow("Contour Levels:", self.contourLevelsLine)
        self.setLayout(self.layout)

    def updateTallyContours(self):
        cv = self.model.currentView
        self.contoursBox.setChecked(cv.tallyContours)
        self.contourLevelsLine.setText(cv.tallyContourLevels)

    def updateDataIndicator(self):
        cv = self.model.currentView
        self.dataIndicatorCheckBox.setChecked(cv.tallyDataIndicator)

    def setMinMaxEnabled(self, enable):
        enable = bool(enable)
        self.minBox.setEnabled(enable)
        self.maxBox.setEnabled(enable)

    def updateMinMax(self):
        cv = self.model.currentView
        self.minBox.setValue(cv.tallyDataMin)
        self.maxBox.setValue(cv.tallyDataMax)
        self.setMinMaxEnabled(cv.tallyDataUserMinMax)

    def updateTallyVisibility(self):
        cv = self.model.currentView
        self.visibilityBox.setChecked(cv.tallyDataVisible)

    def updateMaskZeros(self):
        cv = self.model.currentView
        self.maskZeroBox.setChecked(cv.tallyMaskZeroValues)

    def updateDataClip(self):
        cv = self.model.currentView
        self.clipDataBox.setChecked(cv.clipTallyData)

    def update(self):
        cv = self.model.currentView

        # set colormap value in selector
        cmap = cv.tallyDataColormap
        idx = self.colormapBox.findText(cmap, QtCore.Qt.MatchFixedString)
        self.colormapBox.setCurrentIndex(idx)

        self.alphaBox.setValue(cv.tallyDataAlpha)
        self.visibilityBox.setChecked(cv.tallyDataVisible)
        self.userMinMaxBox.setChecked(cv.tallyDataUserMinMax)
        self.scaleBox.setChecked(cv.tallyDataLogScale)

        self.updateMinMax()
        self.updateMaskZeros()
        self.updateDataClip()
        self.updateDataIndicator()
        self.updateTallyContours()
Beispiel #29
0
class SubtitleInfoDialog(QDialog):
    def __init__(self,
                 subtitle_name="Test",
                 subtitle_delay=0.0,
                 subtitle_language=Default_Subtitle_Language,
                 subtitle_track_name="Test",
                 subtitle_set_default=False,
                 subtitle_set_forced=False,
                 subtitle_default_value_delay=0.0,
                 subtitle_default_value_language=Default_Subtitle_Language,
                 subtitle_default_value_track_name="Test",
                 subtitle_default_value_set_default=False,
                 subtitle_default_value_set_forced=False,
                 subtitle_set_default_disabled=False,
                 subtitle_set_forced_disabled=False,
                 disable_edit=False,
                 parent=None):
        super().__init__(parent)
        self.window_title = "Subtitle Info"
        self.state = "no"
        self.messageIcon = QLabel()

        self.disable_edit = disable_edit

        self.current_subtitle_language = str(subtitle_language)
        self.current_subtitle_delay = str(subtitle_delay)
        self.current_subtitle_track_name = str(subtitle_track_name)
        self.current_subtitle_set_default = subtitle_set_default
        self.current_subtitle_set_forced = subtitle_set_forced

        self.default_subtitle_language = str(subtitle_default_value_language)
        self.default_subtitle_delay = str(subtitle_default_value_delay)
        self.default_subtitle_track_name = str(
            subtitle_default_value_track_name)
        self.default_subtitle_set_default = subtitle_default_value_set_default
        self.default_subtitle_set_forced = subtitle_default_value_set_forced

        self.subtitle_set_default_disabled = subtitle_set_default_disabled
        self.subtitle_set_forced_disabled = subtitle_set_forced_disabled

        self.subtitle_name_label = QLabel("Subtitle Name:")
        self.subtitle_name_value = QLabel(str(subtitle_name))

        self.subtitle_delay_label = QLabel("Subtitle Delay:")
        self.subtitle_delay_spin = QDoubleSpinBox()
        self.setup_subtitle_delay_spin()

        self.subtitle_language_label = QLabel("Subtitle Language:")
        self.subtitle_language_comboBox = QComboBox()
        self.setup_subtitle_language_comboBox()

        self.subtitle_track_name_label = QLabel("Subtitle Track Name:")
        self.subtitle_track_name_lineEdit = QLineEdit()
        self.setup_subtitle_track_name_lineEdit()

        self.subtitle_set_forced_label = QLabel("Subtitle Forced State:")
        self.subtitle_set_forced_checkBox = QCheckBox()
        self.setup_subtitle_set_forced_checkBox()

        self.subtitle_set_default_label = QLabel("Subtitle Default State:")
        self.subtitle_set_default_checkBox = QCheckBox()
        self.setup_subtitle_set_default_checkBox()

        self.yes_button = QPushButton("OK")
        self.no_button = QPushButton("Cancel")
        self.reset_button = QPushButton("Reset To Default")

        self.buttons_layout = QHBoxLayout()
        self.subtitle_delay_layout = QHBoxLayout()
        self.subtitle_language_layout = QHBoxLayout()
        self.subtitle_track_name_layout = QHBoxLayout()
        self.subtitle_set_default_layout = QHBoxLayout()
        self.subtitle_set_forced_layout = QHBoxLayout()
        self.buttons_layout.addWidget(QLabel(""), stretch=3)
        self.buttons_layout.addWidget(self.reset_button, stretch=2)
        self.buttons_layout.addWidget(self.yes_button, stretch=2)
        self.buttons_layout.addWidget(self.no_button, stretch=2)
        self.buttons_layout.addWidget(QLabel(""), stretch=3)
        self.subtitle_setting_layout = QGridLayout()
        self.subtitle_changeble_setting_layout = QFormLayout()
        self.subtitle_changeble_setting_layout.addRow(self.subtitle_name_label,
                                                      self.subtitle_name_value)
        self.subtitle_changeble_setting_layout.addRow(
            self.subtitle_track_name_label, self.subtitle_track_name_lineEdit)
        self.subtitle_changeble_setting_layout.addRow(
            self.subtitle_language_label, self.subtitle_language_comboBox)
        self.subtitle_changeble_setting_layout.addRow(
            self.subtitle_delay_label, self.subtitle_delay_spin)
        self.subtitle_changeble_setting_layout.addRow(
            self.subtitle_set_default_label,
            self.subtitle_set_default_checkBox)
        self.subtitle_changeble_setting_layout.addRow(
            self.subtitle_set_forced_label, self.subtitle_set_forced_checkBox)

        self.subtitle_setting_layout.addLayout(
            self.subtitle_changeble_setting_layout, 0, 0, 5, 2)
        self.subtitle_setting_layout.addWidget(self.messageIcon, 0, 3, 5, -1)

        self.main_layout = QGridLayout()
        self.main_layout.addLayout(self.subtitle_setting_layout, 0, 0, 2, 3)
        self.main_layout.addLayout(self.buttons_layout, 2, 0, 1, -1)
        self.main_layout.setContentsMargins(20, 20, 20, 20)
        self.setLayout(self.main_layout)

        self.setup_ui()
        self.signal_connect()

    def setup_ui(self):
        self.disable_question_mark_window()
        self.messageIcon.setPixmap(
            QtGui.QPixmap(GlobalFiles.SubtitleIconPath).scaledToHeight(100))
        self.set_dialog_values()
        self.set_default_buttons()
        if self.subtitle_set_default_disabled:
            self.subtitle_set_default_disable()
        if self.subtitle_set_forced_disabled:
            self.subtitle_set_forced_disable()
        if self.disable_edit:
            self.subtitle_track_name_lineEdit.setEnabled(False)
            self.subtitle_language_comboBox.setEnabled(False)
            self.subtitle_delay_spin.setEnabled(False)
            self.subtitle_set_default_checkBox.setEnabled(False)
            self.subtitle_set_forced_checkBox.setEnabled(False)
            self.reset_button.setEnabled(False)

        self.setup_tool_tip_hint_subtitle_set_default()
        self.setup_tool_tip_hint_subtitle_set_forced()

    def signal_connect(self):
        self.subtitle_track_name_lineEdit.textEdited.connect(
            self.update_current_subtitle_track_name)
        self.subtitle_delay_spin.editingFinished.connect(
            self.update_current_subtitle_delay)
        self.subtitle_language_comboBox.currentTextChanged.connect(
            self.update_current_subtitle_language)
        self.subtitle_set_default_checkBox.stateChanged.connect(
            self.update_current_subtitle_set_default)
        self.subtitle_set_forced_checkBox.stateChanged.connect(
            self.update_current_subtitle_set_forced)
        self.yes_button.clicked.connect(self.click_yes)
        self.no_button.clicked.connect(self.click_no)
        self.reset_button.clicked.connect(self.reset_subtitle_setting)

    def click_yes(self):
        self.state = "yes"
        self.close()

    def click_no(self):
        self.close()

    def set_dialog_values(self):
        self.setWindowTitle(self.window_title)
        self.setWindowIcon(GlobalFiles.InfoSettingIcon)

    def disable_question_mark_window(self):
        self.setWindowFlag(Qt.WindowContextHelpButtonHint, on=False)

    def increase_message_font_size(self, value):
        message_font = self.message.font()
        message_font.setPointSize(self.message.fontInfo().pointSize() + value)
        self.message.setFont(message_font)

    def set_default_buttons(self):
        self.yes_button.setDefault(True)
        self.yes_button.setFocus()

    def showEvent(self, a0: QtGui.QShowEvent) -> None:
        super().showEvent(a0)
        self.setFixedSize(self.size())

    def setup_subtitle_track_name_lineEdit(self):
        self.subtitle_track_name_lineEdit.setClearButtonEnabled(True)
        self.subtitle_track_name_lineEdit.setText(
            self.current_subtitle_track_name)

    def setup_subtitle_language_comboBox(self):
        self.subtitle_language_comboBox.addItems(AllSubtitlesLanguages)
        self.subtitle_language_comboBox.setCurrentIndex(
            AllSubtitlesLanguages.index(self.current_subtitle_language))
        self.subtitle_language_comboBox.setMaxVisibleItems(8)
        self.subtitle_language_comboBox.setStyleSheet(
            "QComboBox { combobox-popup: 0; }")

    def setup_subtitle_delay_spin(self):
        # self.subtitle_delay_spin.setMaximumWidth(screen_size.width() // 16)
        self.subtitle_delay_spin.setDecimals(3)
        self.subtitle_delay_spin.setMinimum(-9999.0)
        self.subtitle_delay_spin.setMaximum(9999.0)
        self.subtitle_delay_spin.setSingleStep(0.5)
        self.subtitle_delay_spin.setValue(float(self.current_subtitle_delay))

    def setup_subtitle_set_default_checkBox(self):
        self.subtitle_set_default_checkBox.setText("Set Default")
        self.subtitle_set_default_checkBox.setChecked(
            bool(self.current_subtitle_set_default))

    def setup_subtitle_set_forced_checkBox(self):
        self.subtitle_set_forced_checkBox.setText("Set Forced")
        self.subtitle_set_forced_checkBox.setChecked(
            bool(self.current_subtitle_set_forced))

    def update_current_subtitle_track_name(self):
        self.current_subtitle_track_name = str(
            self.subtitle_track_name_lineEdit.text())

    def update_current_subtitle_delay(self):
        self.current_subtitle_delay = round(self.subtitle_delay_spin.value(),
                                            5)

    def update_current_subtitle_language(self):
        self.current_subtitle_language = str(
            self.subtitle_language_comboBox.currentText())

    def update_current_subtitle_set_default(self):
        self.current_subtitle_set_default = (
            self.subtitle_set_default_checkBox.checkState() == Qt.Checked)

    def update_current_subtitle_set_forced(self):
        self.current_subtitle_set_forced = (
            self.subtitle_set_forced_checkBox.checkState() == Qt.Checked)

    def reset_subtitle_setting(self):
        self.current_subtitle_language = self.default_subtitle_language
        self.current_subtitle_delay = self.default_subtitle_delay
        self.current_subtitle_track_name = self.default_subtitle_track_name
        self.current_subtitle_set_default = self.default_subtitle_set_default
        self.current_subtitle_set_forced = self.default_subtitle_set_forced

        self.subtitle_language_comboBox.setCurrentIndex(
            AllSubtitlesLanguages.index(self.current_subtitle_language))
        self.subtitle_delay_spin.setValue(float(self.current_subtitle_delay))
        self.subtitle_track_name_lineEdit.setText(
            self.current_subtitle_track_name)
        self.subtitle_set_default_checkBox.setChecked(
            bool(self.current_subtitle_set_default))
        self.subtitle_set_forced_checkBox.setChecked(
            bool(self.current_subtitle_set_forced))

    def subtitle_set_default_disable(self):
        self.subtitle_set_default_checkBox.setDisabled(True)

    def subtitle_set_forced_disable(self):
        self.subtitle_set_forced_checkBox.setDisabled(True)

    def setup_tool_tip_hint_subtitle_set_default(self):
        if self.subtitle_set_default_checkBox.isEnabled():
            self.subtitle_set_default_checkBox.setToolTip(
                "<nobr>set this subtitle to be the default subtitle track "
                "when play")
            self.subtitle_set_default_checkBox.setToolTipDuration(12000)
        else:
            self.subtitle_set_default_checkBox.setToolTip(
                "<nobr>set this subtitle to be the default subtitle track when play<br><b>Disabled</b> because "
                "option "
                "<b>make this subtitle default</b> is enabled on mux setting tab "
            )
            self.subtitle_set_default_checkBox.setToolTipDuration(12000)

    def setup_tool_tip_hint_subtitle_set_forced(self):
        if self.subtitle_set_forced_checkBox.isEnabled():
            self.subtitle_set_forced_checkBox.setToolTip(
                "<nobr>set this subtitle to be the forced subtitle track when "
                "play")
            self.subtitle_set_forced_checkBox.setToolTipDuration(12000)
        else:
            self.subtitle_set_forced_checkBox.setToolTip(
                "<nobr>set this subtitle to be the forced subtitle track when play<br><b>Disabled</b> because "
                "option "
                "<b>make this subtitle default and forced</b> is enabled on mux setting tab "
            )
            self.subtitle_set_forced_checkBox.setToolTipDuration(12000)

    def execute(self):
        self.exec_()
Beispiel #30
0
class CleanSkinUI(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.setParent(uiUtils.getTopLevelWidget(), 1)

        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setWindowTitle("Clean Skin")
        self.setWindowIcon(QIcon(uiUtils.getIconFolder()+"arikara_CleanSkin.png"))

        lLayout = QFormLayout()

        # Max Weight
        self.dsb_maxWeight = QDoubleSpinBox()
        self.dsb_maxWeight.setRange(0.0, 1.0)
        self.dsb_maxWeight.setDecimals(4)
        self.dsb_maxWeight.setSingleStep(0.001)
        weight = 0.001
        if cmds.optionVar(exists="ariCleanSkin_MW"):
            weight = cmds.optionVar(q="ariCleanSkin_MW")
        else:
            cmds.optionVar(fv=("ariCleanSkin_MW", weight))
        self.dsb_maxWeight.setValue(weight)
        self.dsb_maxWeight.editingFinished.connect(self.dsb_maxWeightEdited)

        # Max Influence
        self.sb_maxInfluence = QSpinBox()
        self.sb_maxInfluence.setRange(1, 12)
        infl = 4
        if cmds.optionVar(exists="ariCleanSkin_MI"):
            infl = cmds.optionVar(q="ariCleanSkin_MI")
        else:
            cmds.optionVar(iv=("ariCleanSkin_MI", infl))
        self.sb_maxInfluence.setValue(infl)
        self.sb_maxInfluence.editingFinished.connect(self.sb_maxInfluenceEdited)

        self.pb_cleanSkin = QPushButton("Clean Skin")
        self.pb_cleanSkin.clicked.connect(self.cleanSkinCallback)

        lLayout.addRow("Max Weight:", self.dsb_maxWeight)
        lLayout.addRow("Max Influence:", self.sb_maxInfluence)
        lLayout.addRow(self.pb_cleanSkin)

        self.setLayout(lLayout)

        if cmds.optionVar(exists="ariCleanSkin_Geo"):
            geo = cmds.optionVar(q="ariCleanSkin_Geo")
            self.setGeometry(*geo)

    def cleanSkinCallback(self):
        cmds.undoInfo(openChunk=True, chunkName="Arikara Clean Skin")
        selection = cmds.ls(selection=True)
        maxWeight = self.dsb_maxWeight.value()
        maxInfluence = self.sb_maxInfluence.value()
        for obj in selection:
            try:
                cmds.arikaraInfluence(obj, maxInfluence=maxInfluence)
            except Exception as e:
                print e
            try:
                cmds.arikaraInfluence(obj, ru=maxWeight)
            except Exception as e:
                print e
        cmds.undoInfo(closeChunk=True)

    def updateGeometry(self):
        geo = self.geometry()
        cmds.optionVar(iv=("ariCleanSkin_Geo", geo.x()))
        cmds.optionVar(iva=("ariCleanSkin_Geo", geo.y()))
        cmds.optionVar(iva=("ariCleanSkin_Geo", geo.width()))
        cmds.optionVar(iva=("ariCleanSkin_Geo", geo.height()))

    def moveEvent(self, event):
        self.updateGeometry()

    def resizeEvent(self, event):
        self.updateGeometry()
    
    def dsb_maxWeightEdited(self):
        val = self.dsb_maxWeight.value()
        cmds.optionVar(fv=("ariCleanSkin_MW", val))

    def sb_maxInfluenceEdited(self):
        val = self.sb_maxInfluence.value()
        cmds.optionVar(iv=("ariCleanSkin_MI", val))