def createExtendedContinuousPalette(self, paletteName, boxCaption, passThroughColors=0, initialColor1=Qt.white, initialColor2=Qt.black, extendedPassThroughColors=((Qt.red, 1), (Qt.black, 1), (Qt.green, 1))): buttBox = gui.vBox(self.mainArea, boxCaption) box = gui.hBox(buttBox) self.__dict__["exCont" + paletteName + "Left"] = ColorButton(self, box, color=QColor(initialColor1)) self.__dict__["exCont" + paletteName + "View"] = PaletteView(box) self.__dict__["exCont" + paletteName + "Right"] = ColorButton(self, box, color=QColor(initialColor2)) self.__dict__["exCont" + paletteName + "passThroughColors"] = passThroughColors self.__dict__["exCont" + paletteName + "passThroughColorsCheckbox"] = gui.checkBox(buttBox, self, "exCont" + paletteName + "passThroughColors", "Use pass-through colors", callback=self.colorSchemaChange) box = gui.hBox(buttBox, "Pass-through colors") for i, (color, check) in enumerate(extendedPassThroughColors): self.__dict__["exCont" + paletteName + "passThroughColor" + str(i)] = check self.__dict__["exCont" + paletteName + "passThroughColor" + str(i) + "Checkbox"] = cb = gui.checkBox(box, self, "exCont" + paletteName + "passThroughColor" + str( i), "", tooltip="Use color", callback=self.colorSchemaChange) self.__dict__["exCont" + paletteName + "color" + str(i)] = ColorButton(self, box, color=QColor(color)) if i < len(extendedPassThroughColors) - 1: gui.rubber(box) self.__dict__["exCont" + paletteName + "colorCount"] = len(extendedPassThroughColors) self.exContPaletteNames.append(paletteName)
def _add_kernel_box(self): # Initialize with the widest label to measure max width self.kernel_eq = self.kernels[-1][1] box = gui.hBox(self.controlArea, "Kernel") self.kernel_box = buttonbox = gui.radioButtonsInBox( box, self, "kernel_type", btnLabels=[k[0] for k in self.kernels], callback=self._on_kernel_changed, addSpace=20) buttonbox.layout().setSpacing(10) gui.rubber(buttonbox) parambox = gui.vBox(box) gui.label(parambox, self, "Kernel: %(kernel_eq)s") common = dict(orientation=Qt.Horizontal, callback=self.settings_changed, alignment=Qt.AlignRight, controlWidth=80) spbox = gui.hBox(parambox) gui.rubber(spbox) inbox = gui.vBox(spbox) gamma = gui.doubleSpin( inbox, self, "gamma", 0.0, 10.0, 0.01, label=" g: ", **common) gamma.setSpecialValueText(self._default_gamma) coef0 = gui.doubleSpin( inbox, self, "coef0", 0.0, 10.0, 0.01, label=" c: ", **common) degree = gui.doubleSpin( inbox, self, "degree", 0.0, 10.0, 0.5, label=" d: ", **common) self._kernel_params = [gamma, coef0, degree] gui.rubber(parambox) # This is the maximal height (all double spins are visible) # and the maximal width (the label is initialized to the widest one) box.layout().activate() box.setFixedHeight(box.sizeHint().height()) box.setMinimumWidth(box.sizeHint().width())
def createExtendedContinuousPalette( self, paletteName, boxCaption, passThroughColors=0, initialColor1=Qt.white, initialColor2=Qt.black, extendedPassThroughColors=((Qt.red, 1), (Qt.black, 1), (Qt.green, 1))): buttBox = gui.vBox(self.mainArea, boxCaption) box = gui.hBox(buttBox) def _set(keypart, val): self.__dict__["exCont{}{}".format(paletteName, keypart)] = val _set("Left", ColorButton(self, box, color=QColor(initialColor1))) _set("View", PaletteView(box)) _set("Right", ColorButton(self, box, color=QColor(initialColor2))) _set("passThroughColors", passThroughColors) _set("passThroughColorsCheckbox", gui.checkBox(buttBox, self, "exCont" + paletteName + "passThroughColors", "Use pass-through colors", callback=self.colorSchemaChange)) box = gui.hBox(buttBox, "Pass-through colors") for i, (color, check) in enumerate(extendedPassThroughColors): _set("passThroughColor" + str(i), check) _set("passThroughColor" + str(i) + "Checkbox", gui.checkBox( box, self, "exCont" + paletteName + "passThroughColor" + str(i), "", tooltip="Use color", callback=self.colorSchemaChange)) _set("color" + str(i), ColorButton(self, box, color=QColor(color))) if i < len(extendedPassThroughColors) - 1: gui.rubber(box) _set("colorCount", len(extendedPassThroughColors)) self.exContPaletteNames.append(paletteName)
def __init__(self): super().__init__() self.data = None self.input_features = None self.attrs = [] self.attr_box = gui.hBox(self.mainArea) model = VariableListModel() model.wrap(self.attrs) self.attrXCombo = gui.comboBox( self.attr_box, self, value="attrX", contentsLength=12, callback=self.change_attr, sendSelectedValue=True, valueType=str) self.attrXCombo.setModel(model) gui.widgetLabel(self.attr_box, "\u2715").\ setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.attrYCombo = gui.comboBox( self.attr_box, self, value="attrY", contentsLength=12, callback=self.change_attr, sendSelectedValue=True, valueType=str) self.attrYCombo.setModel(model) self.canvas = QGraphicsScene() self.canvasView = ViewWithPress(self.canvas, self.mainArea, handler=self.reset_selection) self.mainArea.layout().addWidget(self.canvasView) self.canvasView.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.canvasView.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) box = gui.hBox(self.mainArea) box.layout().addWidget(self.graphButton) box.layout().addWidget(self.report_button)
def add_main_layout(self): box = gui.hBox(self.controlArea, "Regularization") gui.radioButtons(box, self, "reg_type", btnLabels=self.REGULARIZATION_TYPES, callback=self._reg_type_changed) gui.separator(box, 20, 20) self.alpha_box = box2 = gui.vBox(box, margin=10) gui.widgetLabel(box2, "Regularization strength:") self.alpha_slider = gui.hSlider( box2, self, "alpha_index", minValue=0, maxValue=len(self.alphas) - 1, callback=self._alpha_changed, createLabel=False) box3 = gui.hBox(box2) box3.layout().setAlignment(Qt.AlignCenter) self.alpha_label = gui.widgetLabel(box3, "") self._set_alpha_label() gui.separator(box2, 10, 10) box4 = gui.vBox(box2, margin=0) gui.widgetLabel(box4, "Elastic net mixing:") box5 = gui.hBox(box4) gui.widgetLabel(box5, "L1") self.l1_ratio_slider = gui.hSlider( box5, self, "l1_ratio", minValue=0.01, maxValue=0.99, intOnly=False, ticks=0.1, createLabel=False, width=120, step=0.01, callback=self._l1_ratio_changed) gui.widgetLabel(box5, "L2") self.l1_ratio_label = gui.widgetLabel( box4, "", sizePolicy=(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed)) self.l1_ratio_label.setAlignment(Qt.AlignCenter)
def add_main_layout(self): box = gui.widgetBox(self.controlArea, box=True) self.penalty_combo = gui.comboBox( box, self, "penalty_type", label="Regularization type: ", items=self.penalty_types, orientation=Qt.Horizontal, addSpace=4, callback=self.settings_changed, ) gui.widgetLabel(box, "Strength:") box2 = gui.hBox(gui.indentedBox(box)) gui.widgetLabel(box2, "Weak").setStyleSheet("margin-top:6px") self.c_slider = gui.hSlider( box2, self, "C_index", minValue=0, maxValue=len(self.C_s) - 1, callback=lambda: (self.set_c(), self.settings_changed()), createLabel=False, ) gui.widgetLabel(box2, "Strong").setStyleSheet("margin-top:6px") box2 = gui.hBox(box) box2.layout().setAlignment(Qt.AlignCenter) self.c_label = gui.widgetLabel(box2) self.set_c()
def __init__(self): # pylint: disable=missing-docstring super().__init__() self.data = self.discrete_data = None self.attrs = [] self.input_features = None self.areas = [] self.selection = set() self.attr_box = gui.hBox(self.mainArea) self.domain_model = DomainModel(valid_types=DomainModel.PRIMITIVE) combo_args = dict( widget=self.attr_box, master=self, contentsLength=12, callback=self.update_attr, sendSelectedValue=True, valueType=str, model=self.domain_model) fixed_size = (QSizePolicy.Fixed, QSizePolicy.Fixed) gui.comboBox(value="attr_x", **combo_args) gui.widgetLabel(self.attr_box, "\u2715", sizePolicy=fixed_size) gui.comboBox(value="attr_y", **combo_args) self.vizrank, self.vizrank_button = SieveRank.add_vizrank( self.attr_box, self, "Score Combinations", self.set_attr) self.vizrank_button.setSizePolicy(*fixed_size) self.canvas = QGraphicsScene() self.canvasView = ViewWithPress( self.canvas, self.mainArea, handler=self.reset_selection) self.mainArea.layout().addWidget(self.canvasView) self.canvasView.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.canvasView.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) box = gui.hBox(self.mainArea) box.layout().addWidget(self.graphButton) box.layout().addWidget(self.report_button)
def _add_algorithm_to_layout(self): box = gui.widgetBox(self.controlArea, 'Algorithm') # Classfication loss function self.cls_loss_function_combo = gui.comboBox( box, self, 'cls_loss_function_index', orientation=Qt.Horizontal, label='Classificaton loss function: ', items=list(zip(*self.cls_losses))[0], callback=self._on_cls_loss_change) param_box = gui.hBox(box) gui.rubber(param_box) self.cls_epsilon_spin = gui.spin( param_box, self, 'cls_epsilon', 0, 1., 1e-2, spinType=float, label='ε: ', controlWidth=80, alignment=Qt.AlignRight, callback=self.settings_changed) # Regression loss function self.reg_loss_function_combo = gui.comboBox( box, self, 'reg_loss_function_index', orientation=Qt.Horizontal, label='Regression loss function: ', items=list(zip(*self.reg_losses))[0], callback=self._on_reg_loss_change) param_box = gui.hBox(box) gui.rubber(param_box) self.reg_epsilon_spin = gui.spin( param_box, self, 'reg_epsilon', 0, 1., 1e-2, spinType=float, label='ε: ', controlWidth=80, alignment=Qt.AlignRight, callback=self.settings_changed) # Enable/disable appropriate controls self._on_cls_loss_change() self._on_reg_loss_change()
def __init__(self): super().__init__() self.data = None self.orig_domain = self.domain = None self.disc_colors = [] self.cont_colors = [] box = gui.hBox(self.controlArea, "Discrete Variables") self.disc_model = DiscColorTableModel() disc_view = self.disc_view = DiscreteTable(self.disc_model) disc_view.horizontalHeader().setSectionResizeMode( QHeaderView.ResizeToContents) self.disc_model.dataChanged.connect(self._on_data_changed) box.layout().addWidget(disc_view) box = gui.hBox(self.controlArea, "Numeric Variables") self.cont_model = ContColorTableModel() cont_view = self.cont_view = ContinuousTable(self, self.cont_model) cont_view.setColumnWidth(1, 256) self.cont_model.dataChanged.connect(self._on_data_changed) box.layout().addWidget(cont_view) box = gui.auto_commit( self.controlArea, self, "auto_apply", "Apply", orientation=Qt.Horizontal, checkbox_label="Apply automatically") box.button.setFixedWidth(180) box.layout().insertStretch(0)
def __init__(self): super().__init__() self.data = None self.reference = None box = gui.vBox(self.controlArea, "Info") self.data_info_label = gui.widgetLabel(box, self._data_info_default) self.ref_info_label = gui.widgetLabel(box, self._ref_info_default) box = gui.vBox(self.controlArea, "Settings") self.distance_combo = gui.comboBox( box, self, "distance_index", orientation=Qt.Horizontal, label="Distance: ", items=[d[0] for d in METRICS], callback=self.settings_changed) check_box = gui.hBox(box) self.exclude_ref_label = gui.label( check_box, self, "Exclude references:") self.exclude_ref_check = gui.checkBox( check_box, self, "exclude_reference", label="", callback=self.settings_changed) box = gui.vBox(self.controlArea, "Output") self.nn_spin = gui.spin( box, self, "n_neighbors", label="Neighbors:", step=1, spinType=int, minv=0, maxv=100, callback=self.settings_changed) box = gui.hBox(self.controlArea, True) self.apply_button = gui.auto_commit(box, self, "auto_apply", "&Apply", box=False, commit=self.apply)
def __init__(self): super().__init__() self.old_purge_classes = True self.conditions = [] self.last_output_conditions = None self.data = None self.data_desc = self.match_desc = self.nonmatch_desc = None box = gui.vBox(self.controlArea, 'Conditions', stretch=100) self.cond_list = QtGui.QTableWidget(box) box.layout().addWidget(self.cond_list) self.cond_list.setShowGrid(False) self.cond_list.setSelectionMode(QtGui.QTableWidget.NoSelection) self.cond_list.setColumnCount(3) self.cond_list.setRowCount(0) self.cond_list.verticalHeader().hide() self.cond_list.horizontalHeader().hide() self.cond_list.resizeColumnToContents(0) self.cond_list.horizontalHeader().setResizeMode( QtGui.QHeaderView.Stretch) self.cond_list.viewport().setBackgroundRole(QtGui.QPalette.Window) box2 = gui.hBox(box) self.add_button = gui.button(box2, self, "Add Condition", callback=self.add_row) self.add_all_button = gui.button(box2, self, "Add All Variables", callback=self.add_all) self.remove_all_button = gui.button(box2, self, "Remove All", callback=self.remove_all) gui.rubber(box2) info = gui.hBox(self.controlArea) box_data_in = gui.vBox(info, 'Data In') # self.data_in_rows = gui.widgetLabel(box_data_in, " ") self.data_in_variables = gui.widgetLabel(box_data_in, " ") gui.rubber(box_data_in) box_data_out = gui.vBox(info, 'Data Out') self.data_out_rows = gui.widgetLabel(box_data_out, " ") # self.dataOutAttributesLabel = gui.widgetLabel(box_data_out, " ") gui.rubber(box_data_out) box = gui.hBox(self.controlArea) box_setting = gui.vBox(box, 'Purging') self.cb_pa = gui.checkBox( box_setting, self, "purge_attributes", "Remove unused features", callback=self.conditions_changed) gui.separator(box_setting, height=1) self.cb_pc = gui.checkBox( box_setting, self, "purge_classes", "Remove unused classes", callback=self.conditions_changed) gui.auto_commit(box, self, "auto_commit", label="Send", checkbox_label="Send automatically") self.set_data(None) self.resize(600, 400)
def __init__(self): super().__init__() self.data = None self.results = None self.learners = [] self.headers = [] self.learners_box = gui.listBox( self.controlArea, self, "selected_learner", "learners", box=True, callback=self._learner_changed ) self.outputbox = gui.vBox(self.controlArea, "Output") box = gui.hBox(self.outputbox) gui.checkBox(box, self, "append_predictions", "Predictions", callback=self._invalidate) gui.checkBox(box, self, "append_probabilities", "Probabilities", callback=self._invalidate) gui.auto_commit(self.outputbox, self, "autocommit", "Send Selected", "Send Automatically", box=False) self.mainArea.layout().setContentsMargins(0, 0, 0, 0) box = gui.vBox(self.mainArea, box=True) sbox = gui.hBox(box) gui.rubber(sbox) gui.comboBox(sbox, self, "selected_quantity", items=self.quantities, label="Show: ", orientation=Qt.Horizontal, callback=self._update) self.tablemodel = QStandardItemModel(self) view = self.tableview = QTableView( editTriggers=QTableView.NoEditTriggers) view.setModel(self.tablemodel) view.horizontalHeader().hide() view.verticalHeader().hide() view.horizontalHeader().setMinimumSectionSize(60) view.selectionModel().selectionChanged.connect(self._invalidate) view.setShowGrid(False) view.setItemDelegate(BorderedItemDelegate(Qt.white)) view.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) view.clicked.connect(self.cell_clicked) box.layout().addWidget(view) selbox = gui.hBox(box) gui.button(selbox, self, "Select Correct", callback=self.select_correct, autoDefault=False) gui.button(selbox, self, "Select Misclassified", callback=self.select_wrong, autoDefault=False) gui.button(selbox, self, "Clear Selection", callback=self.select_none, autoDefault=False)
def add_group_settings(self, parent): box = gui.vBox(parent, "Groups") box2 = gui.hBox(box) gui.checkBox(box2, self, "graph.group_lines", "Group lines into", tooltip="Show clusters instead of lines", callback=self.update_graph) gui.spin(box2, self, "graph.number_of_groups", 0, 30, callback=self.update_graph) gui.label(box2, self, "groups") box2 = gui.hBox(box) gui.spin(box2, self, "graph.number_of_steps", 0, 100, label="In no more than", callback=self.update_graph) gui.label(box2, self, "steps")
def _create_check_parameter(self, name, label): self.__check_parameter_update(name) box = gui.hBox(self.main_area) return gui.checkBox( box, self, name, label, callback=lambda f=self.__check_parameter_update, p=name: self.__parameter_changed(f, p))
def __init__(self): super().__init__() self.selectedIndex = -1 #: input model/classifier self.model = None box = gui.hBox(self.controlArea, self.tr("File")) self.filesCB = gui.comboBox(box, self, "selectedIndex", callback=self._on_recent) self.filesCB.setMinimumContentsLength(20) self.filesCB.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLength) button = gui.button(box, self, "...", callback=self.browse, default=True) button.setIcon(self.style().standardIcon(QStyle.SP_DirOpenIcon)) button.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed) self.savebutton = gui.button(self.controlArea, self, "Save", callback=self.savecurrent, default=True) self.savebutton.setEnabled(False) # filter valid existing filenames self.history = list(filter(os.path.isfile, self.history))[:20] for filename in self.history: self.filesCB.addItem(os.path.basename(filename), userData=filename) # restore the current selection if the filename is # in the history list if self.filename in self.history: self.selectedIndex = self.history.index(self.filename) else: self.selectedIndex = -1 self.filename = None
def __init__(self): super().__init__() self.cap = None self.snapshot_flash = 0 self.IMAGE_DIR = tempfile.mkdtemp(prefix='Orange-WebcamCapture-') self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) box = self.controlArea image = self.imageLabel = QLabel( margin=0, alignment=Qt.AlignCenter, sizePolicy=QSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)) box.layout().addWidget(image, 100) self.name_edit = line_edit = gui.lineEdit( box, self, 'image_title', 'Title:', orientation=Qt.Horizontal) line_edit.setPlaceholderText(self.DEFAULT_TITLE) hbox = gui.hBox(box) gui.checkBox(hbox, self, 'avatar_filter', 'Avatar filter') button = self.capture_button = QPushButton('Capture', self, clicked=self.capture_image) hbox.layout().addWidget(button, 1000) box.layout().addWidget(hbox) timer = QTimer(self, interval=40) timer.timeout.connect(self.update_webcam_image) timer.start()
def __init__(self): hbox = gui.hBox(self.controlArea) _properties = dict(alternatingRowColors=True, defaultDropAction=Qt.MoveAction, dragDropMode=QListView.DragDrop, dragEnabled=True, selectionMode=QListView.ExtendedSelection, selectionBehavior=QListView.SelectRows, showDropIndicator=True, acceptDrops=True) listview_avail = DnDListView(lambda: self.commit(), self, **_properties) self.model_avail = model = VariableListModel(parent=self, enable_dnd=True) listview_avail.setModel(model) listview_key = DnDListView(lambda: self.commit(), self, **_properties) self.model_key = model = VariableListModel(parent=self, enable_dnd=True) listview_key.setModel(model) box = gui.vBox(hbox, 'Available Variables') box.layout().addWidget(listview_avail) box = gui.vBox(hbox, 'Group-By Key') box.layout().addWidget(listview_key) gui.comboBox(self.controlArea, self, 'tiebreaker', label='Which instance to select in each group:', items=tuple(self.TIEBREAKERS.keys()), callback=lambda: self.commit(), sendSelectedValue=True) gui.auto_commit(self.controlArea, self, 'autocommit', 'Commit', orientation=Qt.Horizontal)
def __init__(self): super().__init__() self.data = None self.cont_data = None # GUI box = gui.vBox(self.mainArea) self.correlation_combo = gui.comboBox( box, self, "correlation_type", items=CorrelationType.items(), orientation=Qt.Horizontal, callback=self._correlation_combo_changed ) self.feature_model = DomainModel( order=DomainModel.ATTRIBUTES, separators=False, placeholder="(All combinations)", valid_types=ContinuousVariable) gui.comboBox( box, self, "feature", callback=self._feature_combo_changed, model=self.feature_model ) self.vizrank, _ = CorrelationRank.add_vizrank( None, self, None, self._vizrank_selection_changed) self.vizrank.progressBar = self.progressBar self.vizrank.button.setEnabled(False) self.vizrank.threadStopped.connect(self._vizrank_stopped) gui.separator(box) box.layout().addWidget(self.vizrank.filter) box.layout().addWidget(self.vizrank.rank_table) button_box = gui.hBox(self.mainArea) button_box.layout().addWidget(self.vizrank.button)
def __init__(self): super().__init__() RecentPathsWComboMixin.__init__(self) self.loaded_file = "" vbox = gui.vBox(self.controlArea, "Distance File", addSpace=True) box = gui.hBox(vbox) self.file_combo.setMinimumWidth(300) box.layout().addWidget(self.file_combo) self.file_combo.activated[int].connect(self.select_file) button = gui.button(box, self, '...', callback=self.browse_file) button.setIcon(self.style().standardIcon(QtGui.QStyle.SP_DirOpenIcon)) button.setSizePolicy( QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Fixed) button = gui.button( box, self, "Reload", callback=self.reload, default=True) button.setIcon(self.style().standardIcon(QtGui.QStyle.SP_BrowserReload)) button.setSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) box = gui.vBox(self.controlArea, "Info", addSpace=True) self.infoa = gui.widgetLabel(box, 'No data loaded.') self.warnings = gui.widgetLabel(box, ' ') #Set word wrap, so long warnings won't expand the widget self.warnings.setWordWrap(True) self.warnings.setSizePolicy( QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.MinimumExpanding) self.set_file_list() QtCore.QTimer.singleShot(0, self.open_file)
def __init__(self, parent, windowTitle="Color Palette"): super().__init__(parent, windowTitle=windowTitle) if PYQT_VERSION < 0x50000: gui.OWComponent.__init__(self, None) self.setLayout(QVBoxLayout()) self.layout().setContentsMargins(4, 4, 4, 4) self.contPaletteNames = [] self.exContPaletteNames = [] self.discPaletteNames = [] self.colorButtonNames = [] self.colorSchemas = [] self.selectedSchemaIndex = 0 self.mainArea = gui.vBox(self, spacing=4) self.layout().addWidget(self.mainArea) self.schemaCombo = gui.comboBox( self.mainArea, self, "selectedSchemaIndex", box="Saved Profiles", callback=self.paletteSelected) self.hbox = gui.hBox(self) self.okButton = gui.button(self.hbox, self, "OK", self.acceptChanges) self.cancelButton = gui.button(self.hbox, self, "Cancel", self.reject) self.setMinimumWidth(230) self.resize(350, 200)
def __init__(self): super().__init__() self.data = None self.input_vars = () self._invalidated = False box = gui.vBox(self.controlArea, "Domain Features") self.domain_model = itemmodels.VariableListModel() self.domain_view = QListView( selectionMode=QListView.SingleSelection ) self.domain_view.setModel(self.domain_model) self.domain_view.selectionModel().selectionChanged.connect( self._on_selection_changed) box.layout().addWidget(self.domain_view) box = gui.hBox(self.controlArea) gui.button(box, self, "Reset Selected", callback=self.reset_selected) gui.button(box, self, "Reset All", callback=self.reset_all) gui.auto_commit(self.controlArea, self, "autocommit", "Apply") box = gui.vBox(self.mainArea, "Edit") self.editor_stack = QStackedWidget() self.editor_stack.addWidget(DiscreteVariableEditor()) self.editor_stack.addWidget(ContinuousVariableEditor()) self.editor_stack.addWidget(VariableEditor()) box.layout().addWidget(self.editor_stack)
def __init__(self): super().__init__() self.data = None self.extra_data = None self.extra_data = None self.model = itemmodels.VariableListModel() self.model_unique_with_id = itemmodels.VariableListModel() self.extra_model_unique = itemmodels.VariableListModel() self.extra_model_unique_with_id = itemmodels.VariableListModel() box = gui.hBox(self.controlArea, box=None) self.infoBoxData = gui.label( box, self, self.dataInfoText(None), box="Data") self.infoBoxExtraData = gui.label( box, self, self.dataInfoText(None), box="Extra Data") grp = gui.radioButtonsInBox( self.controlArea, self, "merging", box="Merging", callback=self.change_merging) self.attr_boxes = [] radio_width = \ QApplication.style().pixelMetric(QStyle.PM_ExclusiveIndicatorWidth) def add_option(label, pre_label, between_label, merge_type, model, extra_model): gui.appendRadioButton(grp, label) vbox = gui.vBox(grp) box = gui.hBox(vbox) box.layout().addSpacing(radio_width) self.attr_boxes.append(box) gui.widgetLabel(box, pre_label) model[:] = [getattr(self, 'attr_{}_data'.format(merge_type))] extra_model[:] = [getattr(self, 'attr_{}_extra'.format(merge_type))] cb = gui.comboBox(box, self, 'attr_{}_data'.format(merge_type), contentsLength=12, callback=self._invalidate, model=model) cb.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) cb.setFixedWidth(190) gui.widgetLabel(box, between_label) cb = gui.comboBox(box, self, 'attr_{}_extra'.format(merge_type), contentsLength=12, callback=self._invalidate, model=extra_model) cb.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) cb.setFixedWidth(190) vbox.layout().addSpacing(6) add_option("Append columns from Extra Data", "by matching", "with", "augment", self.model, self.extra_model_unique) add_option("Find matching rows", "where", "equals", "merge", self.model_unique_with_id, self.extra_model_unique_with_id) add_option("Concatenate tables, merge rows", "where", "equals", "combine", self.model_unique_with_id, self.extra_model_unique_with_id) self.set_merging()
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.api = WikipediaAPI(on_error=self.Error.api_error) self.result = None query_box = gui.hBox(self.controlArea, 'Query') # Queries configuration layout = QGridLayout() layout.setSpacing(7) row = 0 self.query_edit = ListEdit(self, 'query_list', "Each line represents a " "separate query.", 100, self) layout.addWidget(QLabel('Query word list:'), row, 0, 1, self.label_width) layout.addWidget(self.query_edit, row, self.label_width, 1, self.widgets_width) # Language row += 1 language_edit = ComboBox(self, 'language', tuple(sorted(lang2code.items()))) layout.addWidget(QLabel('Language:'), row, 0, 1, self.label_width) layout.addWidget(language_edit, row, self.label_width, 1, self.widgets_width) # Articles per query row += 1 layout.addWidget(QLabel('Articles per query:'), row, 0, 1, self.label_width) slider = gui.valueSlider(query_box, self, 'articles_per_query', box='', values=[1, 3, 5, 10, 25]) layout.addWidget(slider.box, row, 1, 1, self.widgets_width) query_box.layout().addLayout(layout) self.controlArea.layout().addWidget(query_box) self.controlArea.layout().addWidget( CheckListLayout('Text includes', self, 'text_includes', self.attributes, cols=2, callback=self.set_text_features)) self.info_box = gui.hBox(self.controlArea, 'Info') self.result_label = gui.label(self.info_box, self, self.info_label.format(0)) self.button_box = gui.hBox(self.controlArea) self.search_button = gui.button(self.button_box, self, 'Search', self.start_stop) self.search_button.setFocusPolicy(Qt.NoFocus)
def _insert_warning_bar(self): self.warning_bar = gui.hBox(self, spacing=0) self.warning_icon = gui.widgetLabel(self.warning_bar, "") self.warning_label = gui.widgetLabel(self.warning_bar, "") self.warning_label.setStyleSheet("padding-top: 5px") self.warning_bar.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Maximum) gui.rubber(self.warning_bar) self.warning_bar.setVisible(False)
def __init__(self): # pylint: disable=missing-docstring super().__init__() self.data = self.discrete_data = None self.attrs = [] self.input_features = None self.areas = [] self.selection = set() self.attr_box = gui.hBox(self.mainArea) model = VariableListModel() model.wrap(self.attrs) combo_args = dict( widget=self.attr_box, master=self, contentsLength=12, callback=self.update_attr, sendSelectedValue=True, valueType=str, model=model, ) fixed_size = (QSizePolicy.Fixed, QSizePolicy.Fixed) self.attrXCombo = gui.comboBox(value="attrX", **combo_args) gui.widgetLabel(self.attr_box, "\u2715", sizePolicy=fixed_size) self.attrYCombo = gui.comboBox(value="attrY", **combo_args) self.vizrank = SieveRank(self) self.vizrank_button = gui.button( self.attr_box, self, "Score Combinations", sizePolicy=fixed_size, callback=self.vizrank.reshow, enabled=False, ) self.vizrank.pairSelected.connect(self.set_attr) self.canvas = QGraphicsScene() self.canvasView = ViewWithPress(self.canvas, self.mainArea, handler=self.reset_selection) self.mainArea.layout().addWidget(self.canvasView) self.canvasView.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.canvasView.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) box = gui.hBox(self.mainArea) box.layout().addWidget(self.graphButton) box.layout().addWidget(self.report_button)
def add_form(box): gui.separator(box) box2 = gui.hBox(box) gui.rubber(box2) form = QtGui.QFormLayout() form.setContentsMargins(0, 0, 0, 0) box2.layout().addLayout(form) return form
def __init__(self): box = gui.widgetBox(self.controlArea, 'Yahoo Finance Stock Data', orientation='horizontal') lbox = gui.widgetBox(box, orientation='vertical') hbox = gui.widgetBox(lbox, orientation='horizontal') gui.label(hbox, self, 'Ticker:') self.combo = combo = QComboBox(editable=True, insertPolicy=QComboBox.InsertAtTop) combo.addItems(self.symbols) hbox.layout().addWidget(combo) # combo = gui.comboBox( # lbox, self, 'symbol',#, items=self.symbols, # label='Ticker:', orientation='horizontal', # editable=True, maximumContentsLength=-1) gui.rubber(combo.parentWidget()) minDate = QDate.fromString(self.MIN_DATE.strftime(self.PY_DATE_FORMAT), self.QT_DATE_FORMAT) date_from = QDateEdit( QDate.fromString(self.date_from, self.QT_DATE_FORMAT), displayFormat=self.QT_DATE_FORMAT, minimumDate=minDate, calendarPopup=True) date_to = QDateEdit( QDate.fromString(self.date_to, self.QT_DATE_FORMAT), displayFormat=self.QT_DATE_FORMAT, minimumDate=minDate, calendarPopup=True) date_from.dateChanged.connect( lambda date: setattr(self, 'date_from', date.toString(self.QT_DATE_FORMAT))) date_to.dateChanged.connect( lambda date: setattr(self, 'date_to', date.toString(self.QT_DATE_FORMAT))) hbox = gui.hBox(lbox) gui.label(hbox, self, "From:") hbox.layout().addWidget(date_from) hbox = gui.hBox(lbox) gui.label(hbox, self, "To:") hbox.layout().addWidget(date_to) gui.radioButtons(box, self, 'data_granularity', btnLabels=[i.name.capitalize().replace('_', ' ') for i in DataGranularity], box='Resolution') self.button = gui.button(self.controlArea, self, 'Download', callback=self.download)
def _add_controls_start_box(self): box = gui.vBox(self.controlArea, True) form = QFormLayout( labelAlignment=Qt.AlignLeft, formAlignment=Qt.AlignLeft, fieldGrowthPolicy=QFormLayout.AllNonFixedFieldsGrow, verticalSpacing=10, ) self.perplexity_spin = gui.spin( box, self, "perplexity", 1, 500, step=1, alignment=Qt.AlignRight, callback=self._params_changed ) form.addRow("Perplexity:", self.perplexity_spin) self.perplexity_spin.setEnabled(not self.multiscale) form.addRow(gui.checkBox( box, self, "multiscale", label="Preserve global structure", callback=self._multiscale_changed )) sbe = gui.hBox(self.controlArea, False, addToLayout=False) gui.hSlider( sbe, self, "exaggeration", minValue=1, maxValue=4, step=1, callback=self._params_changed ) form.addRow("Exaggeration:", sbe) sbp = gui.hBox(self.controlArea, False, addToLayout=False) gui.hSlider( sbp, self, "pca_components", minValue=2, maxValue=50, step=1, callback=self._invalidate_pca_projection ) form.addRow("PCA components:", sbp) self.normalize_cbx = gui.checkBox( box, self, "normalize", "Normalize data", callback=self._invalidate_pca_projection, ) form.addRow(self.normalize_cbx) box.layout().addLayout(form) gui.separator(box, 10) self.runbutton = gui.button(box, self, "Run", callback=self._toggle_run)
def _setup_layout(self): self.controlArea.setMinimumWidth(self.controlArea.sizeHint().width()) self.layout().setSizeConstraint(QLayout.SetFixedSize) widget_box = widgetBox(self.controlArea, 'Info') self.input_data_info = widgetLabel(widget_box, self._NO_DATA_INFO_TEXT) self.connection_info = widgetLabel(widget_box, "") widget_box = widgetBox(self.controlArea, 'Settings') self.cb_image_attr = comboBox( widget=widget_box, master=self, value='cb_image_attr_current_id', label='Image attribute:', orientation=Qt.Horizontal, callback=self._cb_image_attr_changed ) self.cb_embedder = comboBox( widget=widget_box, master=self, value='cb_embedder_current_id', label='Embedder:', orientation=Qt.Horizontal, callback=self._cb_embedder_changed ) names = [EMBEDDERS_INFO[e]['name'] + (" (local)" if EMBEDDERS_INFO[e].get("is_local") else "") for e in self.embedders] self.cb_embedder.setModel(VariableListModel(names)) if not self.cb_embedder_current_id < len(self.embedders): self.cb_embedder_current_id = 0 self.cb_embedder.setCurrentIndex(self.cb_embedder_current_id) current_embedder = self.embedders[self.cb_embedder_current_id] self.embedder_info = widgetLabel( widget_box, EMBEDDERS_INFO[current_embedder]['description'] ) self.auto_commit_widget = auto_commit( widget=self.controlArea, master=self, value='_auto_apply', label='Apply', commit=self.commit ) self.cancel_button = QPushButton( 'Cancel', icon=self.style().standardIcon(QStyle.SP_DialogCancelButton), ) self.cancel_button.clicked.connect(self.cancel) hbox = hBox(self.controlArea) hbox.layout().addWidget(self.cancel_button) self.cancel_button.setDisabled(True)
def __init__(self): super().__init__() self.data = None self.results = None self.learners = [] self.learners_box = gui.listBox( self.controlArea, self, "selected_learner", "learners", box=True, callback=self._learner_changed ) self.outputbox = gui.vBox(self.controlArea, "Output") box = gui.hBox(self.outputbox) gui.checkBox(box, self, "append_predictions", "Predictions", callback=self._invalidate) gui.checkBox(box, self, "append_probabilities", "Probabilities", callback=self._invalidate) gui.auto_commit(self.outputbox, self, "autocommit", "Send Selected", "Send Automatically", box=False) self.mainArea.layout().setContentsMargins(0, 0, 0, 0) box = gui.vBox(self.mainArea, box=True) sbox = gui.hBox(box) gui.rubber(sbox) gui.comboBox(sbox, self, "selected_quantity", items=self.quantities, label="Show: ", orientation=Qt.Horizontal, callback=self._update) self.tableview = ContingencyTable(self) box.layout().addWidget(self.tableview) selbox = gui.hBox(box) gui.button(selbox, self, "Select Correct", callback=self.select_correct, autoDefault=False) gui.button(selbox, self, "Select Misclassified", callback=self.select_wrong, autoDefault=False) gui.button(selbox, self, "Clear Selection", callback=self.select_none, autoDefault=False)
def __init__(self): super().__init__() self.output_corpus = None self.pubmed_api = None self.progress = None self.email_is_valid = False self.record_count = 0 self.download_running = False # To hold all the controls. Makes access easier. self.pubmed_controls = [] h_box = gui.hBox(self.controlArea) label = gui.label(h_box, self, 'Email:') label.setMaximumSize(label.sizeHint()) # Drop-down for recent emails. self.email_combo = QComboBox(h_box) self.email_combo.setMinimumWidth(150) self.email_combo.setEditable(True) self.email_combo.lineEdit().textChanged.connect(self.sync_email) h_box.layout().addWidget(self.email_combo) self.email_combo.activated[int].connect(self.select_email) # RECORD SEARCH self.search_tabs = gui.tabWidget(self.controlArea) # --- Regular search --- regular_search_box = gui.widgetBox(self.controlArea, addSpace=True) # Author self.author_input = gui.lineEdit(regular_search_box, self, 'author', 'Author:', orientation=Qt.Horizontal) self.pubmed_controls.append(self.author_input) h_box = gui.hBox(regular_search_box) year_box = gui.widgetBox(h_box, orientation=Qt.Horizontal) min_date = QDate.fromString( self.MIN_DATE.strftime(self.PY_DATE_FORMAT), self.QT_DATE_FORMAT) if not self.pub_date_from: self.pub_date_from = self.MIN_DATE.strftime(self.PY_DATE_FORMAT) if not self.pub_date_to: self.pub_date_to = date.today().strftime(self.PY_DATE_FORMAT) self.date_from = QDateEdit(QDate.fromString(self.pub_date_from, self.QT_DATE_FORMAT), displayFormat=self.QT_DATE_FORMAT, minimumDate=min_date, calendarPopup=True) self.date_to = QDateEdit(QDate.fromString(self.pub_date_to, self.QT_DATE_FORMAT), displayFormat=self.QT_DATE_FORMAT, minimumDate=min_date, calendarPopup=True) self.date_from.dateChanged.connect(lambda date: setattr( self, 'pub_date_from', date.toString(self.QT_DATE_FORMAT))) self.date_to.dateChanged.connect(lambda date: setattr( self, 'pub_date_to', date.toString(self.QT_DATE_FORMAT))) self.pubmed_controls.append(self.date_from) self.pubmed_controls.append(self.date_to) gui.label(year_box, self, 'From:') year_box.layout().addWidget(self.date_from) gui.label(year_box, self, 'to:') year_box.layout().addWidget(self.date_to) # Keywords. h_box = gui.hBox(regular_search_box) label = gui.label(h_box, self, 'Query:') label.setMaximumSize(label.sizeHint()) self.keyword_combo = QComboBox(h_box) self.keyword_combo.setMinimumWidth(150) self.keyword_combo.setEditable(True) h_box.layout().addWidget(self.keyword_combo) self.keyword_combo.activated[int].connect(self.select_keywords) self.pubmed_controls.append(self.keyword_combo) tab_height = regular_search_box.sizeHint() regular_search_box.setMaximumSize(tab_height) # --- Advanced search --- advanced_search_box = gui.widgetBox(self.controlArea, addSpace=True) # Advanced search query. h_box = gui.hBox(advanced_search_box) self.advanced_query_input = QTextEdit(h_box) h_box.layout().addWidget(self.advanced_query_input) self.advanced_query_input.setMaximumSize(tab_height) self.pubmed_controls.append(self.advanced_query_input) gui.createTabPage(self.search_tabs, 'Regular search', regular_search_box) gui.createTabPage(self.search_tabs, 'Advanced search', advanced_search_box) # Search info label. self.search_info_label = gui.label(self.controlArea, self, 'Number of records found: /') # Search for records button. self.run_search_button = gui.button( self.controlArea, self, 'Find records', callback=self.run_search, tooltip='Performs a search for articles that fit the ' 'specified parameters.') self.pubmed_controls.append(self.run_search_button) h_line = QFrame() h_line.setFrameShape(QFrame.HLine) h_line.setFrameShadow(QFrame.Sunken) self.controlArea.layout().addWidget(h_line) # RECORD RETRIEVAL # Text includes box. text_includes_box = gui.widgetBox(self.controlArea, 'Text includes', addSpace=True) self.authors_checkbox = gui.checkBox(text_includes_box, self, 'includes_authors', 'Authors') self.title_checkbox = gui.checkBox(text_includes_box, self, 'includes_title', 'Article title') self.mesh_checkbox = gui.checkBox(text_includes_box, self, 'includes_mesh', 'Mesh headings') self.abstract_checkbox = gui.checkBox(text_includes_box, self, 'includes_abstract', 'Abstract') self.url_checkbox = gui.checkBox(text_includes_box, self, 'includes_url', 'URL') self.pubmed_controls.append(self.authors_checkbox) self.pubmed_controls.append(self.title_checkbox) self.pubmed_controls.append(self.mesh_checkbox) self.pubmed_controls.append(self.abstract_checkbox) self.pubmed_controls.append(self.url_checkbox) # Num. records. h_box = gui.hBox(self.controlArea) label = gui.label(h_box, self, 'Retrieve') label.setMaximumSize(label.sizeHint()) self.num_records_input = gui.spin(h_box, self, 'num_records', minv=1, maxv=100000) self.max_records_label = gui.label(h_box, self, 'records from /.') self.max_records_label.setMaximumSize( self.max_records_label.sizeHint()) self.pubmed_controls.append(self.num_records_input) # Download articles. # Search for records button. self.retrieve_records_button = gui.button( self.controlArea, self, 'Retrieve records', callback=self.retrieve_records, tooltip='Retrieves the specified documents.') self.pubmed_controls.append(self.retrieve_records_button) # Num. retrieved records info label. self.retrieval_info_label = gui.label( self.controlArea, self, 'Number of records retrieved: /') # Load the most recent emails. self.set_email_list() # Load the most recent queries. self.set_keyword_list() # Check the email and enable controls accordingly. if self.recent_emails: email = self.recent_emails[0] self.email_is_valid = validate_email(email) self.enable_controls()
def __init__(self): super().__init__() self.data = None self.distributions = None self.contingencies = None self.var = self.cvar = None varbox = gui.vBox(self.controlArea, "Variable") self.varmodel = itemmodels.VariableListModel() self.groupvarmodel = [] self.varview = QtGui.QListView( selectionMode=QtGui.QListView.SingleSelection) self.varview.setSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.varview.setModel(self.varmodel) self.varview.setSelectionModel( itemmodels.ListSingleSelectionModel(self.varmodel)) self.varview.selectionModel().selectionChanged.connect( self._on_variable_idx_changed) varbox.layout().addWidget(self.varview) box = gui.vBox(self.controlArea, "Precision") gui.separator(self.controlArea, 4, 4) box2 = gui.hBox(box) self.l_smoothing_l = gui.widgetLabel(box2, "Smooth") gui.hSlider(box2, self, "smoothing_index", minValue=0, maxValue=len(self.smoothing_facs) - 1, callback=self._on_set_smoothing, createLabel=False) self.l_smoothing_r = gui.widgetLabel(box2, "Precise") self.cb_disc_cont = gui.checkBox( gui.indentedBox(box, sep=4), self, "disc_cont", "Bin continuous variables", callback=self._on_groupvar_idx_changed, tooltip="Show continuous variables as discrete.") box = gui.vBox(self.controlArea, "Group by") self.icons = gui.attributeIconDict self.groupvarview = gui.comboBox( box, self, "groupvar_idx", callback=self._on_groupvar_idx_changed, valueType=str, contentsLength=12) box2 = gui.indentedBox(box, sep=4) self.cb_rel_freq = gui.checkBox( box2, self, "relative_freq", "Show relative frequencies", callback=self._on_relative_freq_changed, tooltip= "Normalize probabilities so that probabilities for each group-by value sum to 1." ) gui.separator(box2) self.cb_prob = gui.comboBox( box2, self, "show_prob", label="Show probabilities:", orientation=Qt.Horizontal, callback=self._on_relative_freq_changed, tooltip= "Show probabilities for a chosen group-by value (at each point probabilities for all group-by values sum to 1)." ) self.plotview = pg.PlotWidget(background=None) self.plotview.setRenderHint(QtGui.QPainter.Antialiasing) self.mainArea.layout().addWidget(self.plotview) w = QtGui.QLabel() w.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed) self.mainArea.layout().addWidget(w, Qt.AlignCenter) self.ploti = pg.PlotItem() self.plot = self.ploti.vb self.ploti.hideButtons() self.plotview.setCentralItem(self.ploti) self.plot_prob = pg.ViewBox() self.ploti.hideAxis('right') self.ploti.scene().addItem(self.plot_prob) self.ploti.getAxis("right").linkToView(self.plot_prob) self.ploti.getAxis("right").setLabel("Probability") self.plot_prob.setZValue(10) self.plot_prob.setXLink(self.ploti) self.update_views() self.ploti.vb.sigResized.connect(self.update_views) self.plot_prob.setRange(yRange=[0, 1]) def disable_mouse(plot): plot.setMouseEnabled(False, False) plot.setMenuEnabled(False) disable_mouse(self.plot) disable_mouse(self.plot_prob) self.tooltip_items = [] self.plot.scene().installEventFilter( HelpEventDelegate(self.help_event, self)) pen = QtGui.QPen(self.palette().color(QtGui.QPalette.Text)) for axis in ("left", "bottom"): self.ploti.getAxis(axis).setPen(pen) self._legend = LegendItem() self._legend.setParentItem(self.plot) self._legend.hide() self._legend.anchor((1, 0), (1, 0))
def __init__(self): super().__init__() box = gui.vBox(self.mainArea, True, margin=0) self.graph = OWScatterPlotGraph(self, box) box.layout().addWidget(self.graph.plot_widget) self.subset_data = None # Orange.data.Table self.subset_indices = None self.sql_data = None # Orange.data.sql.table.SqlTable self.attribute_selection_list = None # list of Orange.data.Variable self.__timer = QTimer(self, interval=1200) self.__timer.timeout.connect(self.add_data) #: Remember the saved state to restore self.__pending_selection_restore = self.selection_group self.selection_group = None common_options = dict(labelWidth=50, orientation=Qt.Horizontal, sendSelectedValue=True, valueType=str, contentsLength=14) box = gui.vBox(self.controlArea, True) dmod = DomainModel self.xy_model = DomainModel(dmod.MIXED, valid_types=dmod.PRIMITIVE) self.cb_attr_x = gui.comboBox(box, self, "attr_x", label="Axis x:", callback=self.attr_changed, model=self.xy_model, **common_options) self.cb_attr_y = gui.comboBox(box, self, "attr_y", label="Axis y:", callback=self.attr_changed, model=self.xy_model, **common_options) vizrank_box = gui.hBox(box) #gui.separator(vizrank_box, width=common_options["labelWidth"]) self.vizrank, self.vizrank_button = ScatterPlotVizRank.add_vizrank( vizrank_box, self, "Find Informative Projections", self.set_attr) g = self.graph.gui self.sampling = gui.auto_commit(self.controlArea, self, "auto_sample", "Sample", box="Sampling", callback=self.switch_sampling, commit=lambda: self.add_data(1)) self.sampling.setVisible(False) g.point_properties_box(self.controlArea) box = g.effects_box(self.controlArea) g.add_widget(g.JitterNumericValues, box) box_plot_prop = g.plot_properties_box(self.controlArea) g.add_widgets([g.ShowGridLines, g.ToolTipShowsAll, g.RegressionLine], box_plot_prop) self.controlArea.layout().addStretch(100) self.graph.box_zoom_select(self.controlArea) gui.auto_commit(self.controlArea, self, "auto_send_selection", "Send Selection", "Send Automatically") # manually register Matplotlib file writers self.graph_writers = self.graph_writers.copy() for w in [MatplotlibFormat, MatplotlibPDFFormat]: for ext in w.EXTENSIONS: self.graph_writers[ext] = w
def __init__(self): super().__init__() RecentPathsWComboMixin.__init__(self) self.domain = None self.data = None self.loaded_file = "" self.reader = None readers = [ f for f in FileFormat.formats if getattr(f, 'read', None) and getattr(f, "EXTENSIONS", None) ] def group_readers_per_addon_key(w): # readers from Orange.data.io should go first def package(w): package = w.qualified_name().split(".")[:-1] package = package[:2] if ".".join(package) == "Orange.data": return ["0"] # force "Orange" to come first return package return package(w), w.DESCRIPTION self.available_readers = sorted(set(readers), key=group_readers_per_addon_key) layout = QGridLayout() layout.setSpacing(4) gui.widgetBox(self.controlArea, orientation=layout, box='数据源') vbox = gui.radioButtons(None, self, "source", box=True, callback=self.load_data, addToLayout=False) rb_button = gui.appendRadioButton(vbox, "文件:", addToLayout=False) layout.addWidget(rb_button, 0, 0, Qt.AlignVCenter) box = gui.hBox(None, addToLayout=False, margin=0) box.setSizePolicy(Policy.Expanding, Policy.Fixed) self.file_combo.setSizePolicy(Policy.Expanding, Policy.Fixed) self.file_combo.setMinimumSize(QSize(100, 1)) self.file_combo.activated[int].connect(self.select_file) box.layout().addWidget(self.file_combo) layout.addWidget(box, 0, 1) file_button = gui.button(None, self, '...', callback=self.browse_file, autoDefault=False) file_button.setIcon(self.style().standardIcon(QStyle.SP_DirOpenIcon)) file_button.setSizePolicy(Policy.Maximum, Policy.Fixed) layout.addWidget(file_button, 0, 2) reload_button = gui.button(None, self, "重新加载", callback=self.load_data, autoDefault=False) reload_button.setIcon(self.style().standardIcon( QStyle.SP_BrowserReload)) reload_button.setSizePolicy(Policy.Fixed, Policy.Fixed) layout.addWidget(reload_button, 0, 3) self.sheet_box = gui.hBox(None, addToLayout=False, margin=0) self.sheet_combo = QComboBox() self.sheet_combo.activated[str].connect(self.select_sheet) self.sheet_combo.setSizePolicy(Policy.Expanding, Policy.Fixed) self.sheet_combo.setMinimumSize(QSize(50, 1)) self.sheet_label = QLabel() self.sheet_label.setText('Sheet') self.sheet_label.setSizePolicy(Policy.MinimumExpanding, Policy.Fixed) self.sheet_box.layout().addWidget(self.sheet_label, Qt.AlignLeft) self.sheet_box.layout().addWidget(self.sheet_combo, Qt.AlignVCenter) layout.addWidget(self.sheet_box, 2, 1) self.sheet_box.hide() rb_button = gui.appendRadioButton(vbox, "URL:", addToLayout=False) layout.addWidget(rb_button, 3, 0, Qt.AlignVCenter) self.url_combo = url_combo = QComboBox() url_model = NamedURLModel(self.sheet_names) url_model.wrap(self.recent_urls) url_combo.setLineEdit(LineEditSelectOnFocus()) url_combo.setModel(url_model) url_combo.setSizePolicy(Policy.Ignored, Policy.Fixed) url_combo.setEditable(True) url_combo.setInsertPolicy(url_combo.InsertAtTop) url_edit = url_combo.lineEdit() l, t, r, b = url_edit.getTextMargins() url_edit.setTextMargins(l + 5, t, r, b) layout.addWidget(url_combo, 3, 1, 1, 3) url_combo.activated.connect(self._url_set) # whit completer we set that combo box is case sensitive when # matching the history completer = QCompleter() completer.setCaseSensitivity(Qt.CaseSensitive) url_combo.setCompleter(completer) layout = QGridLayout() layout.setSpacing(4) gui.widgetBox(self.controlArea, orientation=layout, box='文件类型') box = gui.hBox(None, addToLayout=False, margin=0) box.setSizePolicy(Policy.Expanding, Policy.Fixed) self.reader_combo = QComboBox(self) self.reader_combo.setSizePolicy(Policy.Expanding, Policy.Fixed) self.reader_combo.setMinimumSize(QSize(100, 1)) self.reader_combo.activated[int].connect(self.select_reader) box.layout().addWidget(self.reader_combo) layout.addWidget(box, 0, 1) box = gui.vBox(self.controlArea, "信息") self.infolabel = gui.widgetLabel(box, '未加载数据.') box = gui.widgetBox(self.controlArea, "列(双击编辑)") self.domain_editor = DomainEditor(self) self.editor_model = self.domain_editor.model() box.layout().addWidget(self.domain_editor) box = gui.hBox(box) gui.button(box, self, "重置", callback=self.reset_domain_edit, autoDefault=False) gui.rubber(box) self.apply_button = gui.button(box, self, "应用", callback=self.apply_domain_edit) self.apply_button.setEnabled(False) self.apply_button.setFixedWidth(170) self.editor_model.dataChanged.connect( lambda: self.apply_button.setEnabled(True)) hBox = gui.hBox(self.controlArea) gui.rubber(hBox) gui.button(hBox, self, "浏览文档数据集", callback=lambda: self.browse_file(True), autoDefault=False) gui.rubber(hBox) self.set_file_list() # Must not call open_file from within __init__. open_file # explicitly re-enters the event loop (by a progress bar) self.setAcceptDrops(True) if self.source == self.LOCAL_FILE: last_path = self.last_path() if last_path and os.path.exists(last_path) and \ os.path.getsize(last_path) > self.SIZE_LIMIT: self.Warning.file_too_big() return QTimer.singleShot(0, self.load_data)
def __init__(self): super().__init__() for name in self.signal_names: setattr(self, name, []) self.splitCanvas = QSplitter(Qt.Vertical, self.mainArea) self.mainArea.layout().addWidget(self.splitCanvas) # Styling self.defaultFont = defaultFont = ( 'Menlo' if sys.platform == 'darwin' else 'Courier' if sys.platform in ['win32', 'cygwin'] else 'DejaVu Sans Mono') self.defaultFontSize = defaultFontSize = 13 self.editorBox = gui.vBox(self, box="Editor", spacing=4) self.splitCanvas.addWidget(self.editorBox) darkMode = QApplication.instance().property('darkMode') scheme_name = 'Dark' if darkMode else 'Light' syntax_highlighting_scheme = SYNTAX_HIGHLIGHTING_STYLES[scheme_name] self.pygments_style_class = make_pygments_style(scheme_name) eFont = QFont(defaultFont) eFont.setPointSize(defaultFontSize) # Fake Signature self.func_sig = func_sig = FunctionSignature( self.editorBox, syntax_highlighting_scheme, eFont) # Editor editor = PythonEditor(self) editor.setFont(eFont) editor.setup_completer_appearance((300, 180), eFont) # Fake return return_stmt = ReturnStatement(self.editorBox, syntax_highlighting_scheme, eFont) self.return_stmt = return_stmt # Match indentation textEditBox = QWidget(self.editorBox) textEditBox.setLayout(QHBoxLayout()) char_4_width = QFontMetrics(eFont).horizontalAdvance('0000') @editor.viewport_margins_updated.connect def _(width): func_sig.setIndent(width) textEditMargin = max(0, round(char_4_width - width)) return_stmt.setIndent(textEditMargin + width) textEditBox.layout().setContentsMargins(textEditMargin, 0, 0, 0) self.text = editor textEditBox.layout().addWidget(editor) self.editorBox.layout().addWidget(func_sig) self.editorBox.layout().addWidget(textEditBox) self.editorBox.layout().addWidget(return_stmt) self.editorBox.setAlignment(Qt.AlignVCenter) self.text.setTabStopWidth(4) self.text.modificationChanged[bool].connect(self.onModificationChanged) # Controls self.editor_controls = gui.vBox(self.controlArea, box='Preferences') self.vim_box = gui.hBox(self.editor_controls, spacing=20) self.vim_indicator = VimIndicator(self.vim_box) vim_sp = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) vim_sp.setRetainSizeWhenHidden(True) self.vim_indicator.setSizePolicy(vim_sp) def enable_vim_mode(): editor.vimModeEnabled = self.vimModeEnabled self.vim_indicator.setVisible(self.vimModeEnabled) enable_vim_mode() gui.checkBox(self.vim_box, self, 'vimModeEnabled', 'Vim mode', tooltip="Only for the coolest.", callback=enable_vim_mode) self.vim_box.layout().addWidget(self.vim_indicator) @editor.vimModeIndicationChanged.connect def _(color, text): self.vim_indicator.indicator_color = color self.vim_indicator.indicator_text = text self.vim_indicator.update() # Library self.libraryListSource = [] self._cachedDocuments = {} self.libraryList = itemmodels.PyListModel( [], self, flags=Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsEditable) self.libraryList.wrap(self.libraryListSource) self.controlBox = gui.vBox(self.controlArea, 'Library') self.controlBox.layout().setSpacing(1) self.libraryView = QListView( editTriggers=QListView.DoubleClicked | QListView.EditKeyPressed, sizePolicy=QSizePolicy(QSizePolicy.Ignored, QSizePolicy.Preferred)) self.libraryView.setItemDelegate(ScriptItemDelegate(self)) self.libraryView.setModel(self.libraryList) self.libraryView.selectionModel().selectionChanged.connect( self.onSelectedScriptChanged) self.controlBox.layout().addWidget(self.libraryView) w = itemmodels.ModelActionsWidget() self.addNewScriptAction = action = QAction("+", self) action.setToolTip("Add a new script to the library") action.triggered.connect(self.onAddScript) w.addAction(action) action = QAction(unicodedata.lookup("MINUS SIGN"), self) action.setToolTip("Remove script from library") action.triggered.connect(self.onRemoveScript) w.addAction(action) action = QAction("Update", self) action.setToolTip("Save changes in the editor to library") action.setShortcut(QKeySequence(QKeySequence.Save)) action.triggered.connect(self.commitChangesToLibrary) w.addAction(action) action = QAction("More", self, toolTip="More actions") new_from_file = QAction("Import Script from File", self) save_to_file = QAction("Save Selected Script to File", self) restore_saved = QAction("Undo Changes to Selected Script", self) save_to_file.setShortcut(QKeySequence(QKeySequence.SaveAs)) new_from_file.triggered.connect(self.onAddScriptFromFile) save_to_file.triggered.connect(self.saveScript) restore_saved.triggered.connect(self.restoreSaved) menu = QMenu(w) menu.addAction(new_from_file) menu.addAction(save_to_file) menu.addAction(restore_saved) action.setMenu(menu) button = w.addAction(action) button.setPopupMode(QToolButton.InstantPopup) w.layout().setSpacing(1) self.controlBox.layout().addWidget(w) self.execute_button = gui.button(self.buttonsArea, self, 'Run', callback=self.commit) self.run_action = QAction("Run script", self, triggered=self.commit, shortcut=QKeySequence(Qt.ControlModifier | Qt.Key_R)) self.addAction(self.run_action) self.saveAction = action = QAction("&Save", self.text) action.setToolTip("Save script to file") action.setShortcut(QKeySequence(QKeySequence.Save)) action.setShortcutContext(Qt.WidgetWithChildrenShortcut) action.triggered.connect(self.saveScript) self.consoleBox = gui.vBox(self.splitCanvas, 'Console') self.console = PythonConsole({}, self) self.consoleBox.layout().addWidget(self.console) self.console.document().setDefaultFont(QFont(defaultFont)) self.consoleBox.setAlignment(Qt.AlignBottom) self.splitCanvas.setSizes([2, 1]) self.controlArea.layout().addStretch(10) self._restoreState() self.settingsAboutToBePacked.connect(self._saveState)
def __init__(self): OWWidget.__init__(self) ConcurrentWidgetMixin.__init__(self) self.corpus = None # Browse file box fbox = gui.widgetBox(self.controlArea, "Corpus file", orientation=0) self.file_widget = widgets.FileWidget( recent_files=self.recent_files, icon_size=(16, 16), on_open=self.open_file, dialog_format=self.dlgFormats, dialog_title='Open Orange Document Corpus', reload_label='Reload', browse_label='Browse', allow_empty=False, minimal_width=250, ) fbox.layout().addWidget(self.file_widget) # dropdown to select title variable self.title_model = DomainModel(valid_types=(StringVariable, ), placeholder="(no title)") gui.comboBox(self.controlArea, self, "title_variable", box="Title variable", model=self.title_model, callback=self.update_feature_selection) # Used Text Features fbox = gui.widgetBox(self.controlArea, orientation=0) ubox = gui.widgetBox(fbox, "Used text features", addSpace=False) self.used_attrs_model = VariableListModel(enable_dnd=True) self.used_attrs_view = VariablesListItemView() self.used_attrs_view.setModel(self.used_attrs_model) ubox.layout().addWidget(self.used_attrs_view) aa = self.used_attrs_model aa.dataChanged.connect(self.update_feature_selection) aa.rowsInserted.connect(self.update_feature_selection) aa.rowsRemoved.connect(self.update_feature_selection) # Ignored Text Features ibox = gui.widgetBox(fbox, "Ignored text features", addSpace=False) self.unused_attrs_model = VariableListModel(enable_dnd=True) self.unused_attrs_view = VariablesListItemView() self.unused_attrs_view.setModel(self.unused_attrs_model) ibox.layout().addWidget(self.unused_attrs_view) gui.checkBox(self.controlArea, self, "detect_languages", "Detect language automatically", callback=self.handle_languages) # Documentation Data Sets & Report box = gui.hBox(self.controlArea) self.browse_documentation = gui.button( box, self, "Browse documentation corpora", callback=lambda: self.file_widget.browse(get_sample_corpora_dir()), autoDefault=False, ) # load first file self.file_widget.select(0) self.update_output_info() self.update_input_info(None)
def _init_ui(self): namesBox = gui.vBox(self.controlArea, "Names") hbox = gui.hBox(namesBox, margin=0, spacing=0) gui.lineEdit(hbox, self, "attr1", "Variable X: ", controlWidth=80, orientation=Qt.Horizontal, callback=self._attr_name_changed) gui.separator(hbox, 21) hbox = gui.hBox(namesBox, margin=0, spacing=0) attr2 = gui.lineEdit(hbox, self, "attr2", "Variable Y: ", controlWidth=80, orientation=Qt.Horizontal, callback=self._attr_name_changed) gui.separator(hbox) gui.checkBox(hbox, self, "hasAttr2", '', disables=attr2, labelWidth=0, callback=self.set_dimensions) gui.separator(namesBox) gui.widgetLabel(namesBox, "Labels") self.classValuesView = listView = gui.ListViewWithSizeHint( preferred_size=(-1, 30)) listView.setModel(self.class_model) itemmodels.select_row(listView, 0) namesBox.layout().addWidget(listView) self.addClassLabel = QAction( "+", self, toolTip="Add new class label", triggered=self.add_new_class_label ) self.removeClassLabel = QAction( unicodedata.lookup("MINUS SIGN"), self, toolTip="Remove selected class label", triggered=self.remove_selected_class_label ) actionsWidget = itemmodels.ModelActionsWidget( [self.addClassLabel, self.removeClassLabel], self ) actionsWidget.layout().addStretch(10) actionsWidget.layout().setSpacing(1) namesBox.layout().addWidget(actionsWidget) tBox = gui.vBox(self.controlArea, "Tools", addSpace=True) buttonBox = gui.hBox(tBox) toolsBox = gui.widgetBox(buttonBox, orientation=QGridLayout()) self.toolActions = QActionGroup(self) self.toolActions.setExclusive(True) self.toolButtons = [] for i, (name, tooltip, tool, icon) in enumerate(self.TOOLS): action = QAction( name, self, toolTip=tooltip, checkable=tool.checkable, icon=QIcon(icon), ) action.triggered.connect(partial(self.set_current_tool, tool)) button = QToolButton( iconSize=QSize(24, 24), toolButtonStyle=Qt.ToolButtonTextUnderIcon, sizePolicy=QSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) ) button.setDefaultAction(action) self.toolButtons.append((button, tool)) toolsBox.layout().addWidget(button, i / 3, i % 3) self.toolActions.addAction(action) for column in range(3): toolsBox.layout().setColumnMinimumWidth(column, 10) toolsBox.layout().setColumnStretch(column, 1) undo = self.undo_stack.createUndoAction(self) redo = self.undo_stack.createRedoAction(self) undo.setShortcut(QKeySequence.Undo) redo.setShortcut(QKeySequence.Redo) self.addActions([undo, redo]) self.undo_stack.indexChanged.connect(lambda _: self.invalidate()) gui.separator(tBox) indBox = gui.indentedBox(tBox, sep=8) form = QFormLayout( formAlignment=Qt.AlignLeft, labelAlignment=Qt.AlignLeft, fieldGrowthPolicy=QFormLayout.AllNonFixedFieldsGrow ) indBox.layout().addLayout(form) slider = gui.hSlider( indBox, self, "brushRadius", minValue=1, maxValue=100, createLabel=False ) form.addRow("Radius:", slider) slider = gui.hSlider( indBox, self, "density", None, minValue=1, maxValue=100, createLabel=False ) form.addRow("Intensity:", slider) slider = gui.hSlider( indBox, self, "symbol_size", None, minValue=1, maxValue=100, createLabel=False, callback=self.set_symbol_size ) form.addRow("Symbol:", slider) self.btResetToInput = gui.button( tBox, self, "Reset to Input Data", self.reset_to_input) self.btResetToInput.setDisabled(True) gui.auto_commit(self.controlArea, self, "autocommit", "Send") # main area GUI viewbox = PaintViewBox(enableMouse=False) self.plotview = pg.PlotWidget(background="w", viewBox=viewbox) self.plotview.sizeHint = lambda: QSize(200, 100) # Minimum size for 1-d painting self.plot = self.plotview.getPlotItem() axis_color = self.palette().color(QPalette.Text) axis_pen = QPen(axis_color) tickfont = QFont(self.font()) tickfont.setPixelSize(max(int(tickfont.pixelSize() * 2 // 3), 11)) axis = self.plot.getAxis("bottom") axis.setLabel(self.attr1) axis.setPen(axis_pen) axis.setTickFont(tickfont) axis = self.plot.getAxis("left") axis.setLabel(self.attr2) axis.setPen(axis_pen) axis.setTickFont(tickfont) if not self.hasAttr2: self.plot.hideAxis('left') self.plot.hideButtons() self.plot.setXRange(0, 1, padding=0.01) self.mainArea.layout().addWidget(self.plotview) # enable brush tool self.toolActions.actions()[0].setChecked(True) self.set_current_tool(self.TOOLS[0][2]) self.set_dimensions()
def __init__(self): super().__init__() self.data = None self.test_data = None self.preprocessor = None self.train_data_missing_vals = False self.test_data_missing_vals = False self.scorers = [] self.__pending_comparison_criterion = self.comparison_criterion #: An Ordered dictionary with current inputs and their testing results. self.learners = OrderedDict() # type: Dict[Any, Input] self.__state = State.Waiting # Do we need to [re]test any learners, set by _invalidate and # cleared by __update self.__needupdate = False self.__task = None # type: Optional[TaskState] self.__executor = ThreadExecutor() sbox = gui.vBox(self.controlArea, "Sampling") rbox = gui.radioButtons(sbox, self, "resampling", callback=self._param_changed) gui.appendRadioButton(rbox, "Cross validation") ibox = gui.indentedBox(rbox) gui.comboBox(ibox, self, "n_folds", label="Number of folds: ", items=[str(x) for x in self.NFolds], orientation=Qt.Horizontal, callback=self.kfold_changed) gui.checkBox(ibox, self, "cv_stratified", "Stratified", callback=self.kfold_changed) gui.appendRadioButton(rbox, "Cross validation by feature") ibox = gui.indentedBox(rbox) self.feature_model = DomainModel(order=DomainModel.METAS, valid_types=DiscreteVariable) self.features_combo = gui.comboBox(ibox, self, "fold_feature", model=self.feature_model, orientation=Qt.Horizontal, callback=self.fold_feature_changed) gui.appendRadioButton(rbox, "Random sampling") ibox = gui.indentedBox(rbox) gui.comboBox(ibox, self, "n_repeats", label="Repeat train/test: ", items=[str(x) for x in self.NRepeats], orientation=Qt.Horizontal, callback=self.shuffle_split_changed) gui.comboBox(ibox, self, "sample_size", label="Training set size: ", items=["{} %".format(x) for x in self.SampleSizes], orientation=Qt.Horizontal, callback=self.shuffle_split_changed) gui.checkBox(ibox, self, "shuffle_stratified", "Stratified", callback=self.shuffle_split_changed) gui.appendRadioButton(rbox, "Leave one out") gui.appendRadioButton(rbox, "Test on train data") gui.appendRadioButton(rbox, "Test on test data") self.cbox = gui.vBox(self.controlArea, "Target Class") self.class_selection_combo = gui.comboBox( self.cbox, self, "class_selection", items=[], sendSelectedValue=True, callback=self._on_target_class_changed, contentsLength=8) self.modcompbox = box = gui.vBox(self.controlArea, "Model Comparison") gui.comboBox(box, self, "comparison_criterion", callback=self.update_comparison_table) hbox = gui.hBox(box) gui.checkBox(hbox, self, "use_rope", "Negligible difference: ", callback=self._on_use_rope_changed) gui.lineEdit(hbox, self, "rope", validator=QDoubleValidator(), controlWidth=70, callback=self.update_comparison_table, alignment=Qt.AlignRight) self.controls.rope.setEnabled(self.use_rope) gui.rubber(self.controlArea) self.score_table = ScoreTable(self) self.score_table.shownScoresChanged.connect(self.update_stats_model) view = self.score_table.view view.setSizeAdjustPolicy(view.AdjustToContents) box = gui.vBox(self.mainArea, "Evaluation Results") box.layout().addWidget(self.score_table.view) self.compbox = box = gui.vBox(self.mainArea, box="Model comparison") table = self.comparison_table = QTableWidget( wordWrap=False, editTriggers=QTableWidget.NoEditTriggers, selectionMode=QTableWidget.NoSelection) table.setSizeAdjustPolicy(table.AdjustToContents) header = table.verticalHeader() header.setSectionResizeMode(QHeaderView.Fixed) header.setSectionsClickable(False) header = table.horizontalHeader() header.setTextElideMode(Qt.ElideRight) header.setDefaultAlignment(Qt.AlignCenter) header.setSectionsClickable(False) header.setStretchLastSection(False) header.setSectionResizeMode(QHeaderView.ResizeToContents) avg_width = self.fontMetrics().averageCharWidth() header.setMinimumSectionSize(8 * avg_width) header.setMaximumSectionSize(15 * avg_width) header.setDefaultSectionSize(15 * avg_width) box.layout().addWidget(table) box.layout().addWidget( QLabel( "<small>Table shows probabilities that the score for the model in " "the row is higher than that of the model in the column. " "Small numbers show the probability that the difference is " "negligible.</small>", wordWrap=True))
def add_main_layout(self): # top-level control procedure top_box = gui.hBox(widget=self.controlArea, box=None, addSpace=2) rule_ordering_box = gui.hBox(widget=top_box, box="规则排序") rule_ordering_rbs = gui.radioButtons( widget=rule_ordering_box, master=self, value="rule_ordering", callback=self.settings_changed, btnLabels=("有序的", "无序的")) rule_ordering_rbs.layout().setSpacing(7) covering_algorithm_box = gui.hBox( widget=top_box, box="覆盖算法(Covering algorithm)") covering_algorithm_rbs = gui.radioButtons( widget=covering_algorithm_box, master=self, value="covering_algorithm", callback=self.settings_changed, btnLabels=("互斥的(Exclusive)", "加权(Weighted)")) covering_algorithm_rbs.layout().setSpacing(7) insert_gamma_box = gui.vBox(widget=covering_algorithm_box, box=None) gui.separator(insert_gamma_box, 0, 14) self.gamma_spin = gui.doubleSpin( widget=insert_gamma_box, master=self, value="gamma", minv=0.0, maxv=1.0, step=0.01, label="γ:", orientation=Qt.Horizontal, callback=self.settings_changed, alignment=Qt.AlignRight, enabled=self.storage_covers[self.covering_algorithm] == "weighted") # bottom-level search procedure (search bias) middle_box = gui.vBox(widget=self.controlArea, box="规则搜索") gui.comboBox( widget=middle_box, master=self, value="evaluation_measure", label="评价措施:", orientation=Qt.Horizontal, items=("熵值(Entropy)", "拉普拉斯精度(Laplace accuracy)", "WRAcc"), callback=self.settings_changed, contentsLength=3) gui.spin( widget=middle_box, master=self, value="beam_width", minv=1, maxv=100, step=1, label="集束宽度(Beam width):", orientation=Qt.Horizontal, callback=self.settings_changed, alignment=Qt.AlignRight, controlWidth=80) # bottom-level search procedure (over-fitting avoidance bias) bottom_box = gui.vBox(widget=self.controlArea, box="规则筛选") gui.spin( widget=bottom_box, master=self, value="min_covered_examples", minv=1, maxv=10000, step=1, label="最小规则覆盖范围:", orientation=Qt.Horizontal, callback=self.settings_changed, alignment=Qt.AlignRight, controlWidth=80) gui.spin( widget=bottom_box, master=self, value="max_rule_length", minv=1, maxv=100, step=1, label="最大规则长度:", orientation=Qt.Horizontal, callback=self.settings_changed, alignment=Qt.AlignRight, controlWidth=80) gui.doubleSpin( widget=bottom_box, master=self, value="default_alpha", minv=0.0, maxv=1.0, step=0.01, label="统计显著性\n(默认 α):", orientation=Qt.Horizontal, callback=self.settings_changed, alignment=Qt.AlignRight, controlWidth=80, checked="checked_default_alpha") gui.doubleSpin( widget=bottom_box, master=self, value="parent_alpha", minv=0.0, maxv=1.0, step=0.01, label="相对显著性\n(父 α):", orientation=Qt.Horizontal, callback=self.settings_changed, alignment=Qt.AlignRight, controlWidth=80, checked="checked_parent_alpha")
def __add_annotation_controls(self): common_options = { 'labelWidth': 100, 'orientation': Qt.Horizontal, 'sendSelectedValue': True, 'valueType': str, 'contentsLength': 14, } box = gui.vBox(self.controlArea, True) ord = (DomainModel.METAS, DomainModel.ATTRIBUTES, DomainModel.CLASSES) mod = DomainModel(ord, valid_types=ContinuousVariable) gui.comboBox(box, self, "attr_x", label="Axis x:", model=mod, callback=self.__axis_attr_changed, **common_options) gui.comboBox(box, self, "attr_y", label="Axis y:", model=mod, callback=self.__axis_attr_changed, **common_options) gui.comboBox( box, self, "scoring_method", label="Scoring method:", items=ScoringMethod.items(), orientation=Qt.Horizontal, contentsLength=13, labelWidth=100, callback=self.__scoring_combo_changed, ) gui.comboBox( box, self, "statistical_test", label="Statistical test:", items=StatisticalTest.items(), orientation=Qt.Horizontal, labelWidth=100, callback=self.__scoring_combo_changed, ) gui.doubleSpin(box, self, "p_threshold", 0, 1, 0.01, label="FDR threshold:", callback=self.__p_threshold_changed) hbox = gui.hBox(box) gui.checkBox(hbox, self, "use_user_epsilon", "ε for DBSCAN:", callback=self.__epsilon_check_changed) self.epsilon_spin = gui.doubleSpin(hbox, self, "epsilon", 0, 10, 0.1, callback=self.__epsilon_changed) self.run_button = gui.button(box, self, "Start", self._toggle_run)
def set_new_values(self, oper_combo, adding_all, selected_values=None): # def remove_children(): # for child in box.children()[1:]: # box.layout().removeWidget(child) # child.setParent(None) def add_textual(contents): le = gui.lineEdit(box, self, None, sizePolicy=QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)) if contents: le.setText(contents) le.setAlignment(Qt.AlignRight) le.editingFinished.connect(self.conditions_changed) return le def add_numeric(contents): le = add_textual(contents) le.setValidator(OWSelectRows.QDoubleValidatorEmpty()) return le def add_datetime(contents): le = add_textual(contents) le.setValidator(QRegExpValidator(QRegExp(TimeVariable.REGEX))) return le var = self.data.domain[oper_combo.attr_combo.currentText()] box = self.cond_list.cellWidget(oper_combo.row, 2) if selected_values is not None: lc = list(selected_values) + ["", ""] lc = [str(x) for x in lc[:2]] else: lc = ["", ""] if box and vartype(var) == box.var_type: lc = self._get_lineedit_contents(box) + lc oper = oper_combo.currentIndex() if oper_combo.currentText() == "is defined": label = QLabel() label.var_type = vartype(var) self.cond_list.setCellWidget(oper_combo.row, 2, label) elif var.is_discrete: if oper_combo.currentText() == "is one of": if selected_values: lc = [x for x in list(selected_values)] button = DropDownToolButton(self, var, lc) button.var_type = vartype(var) self.cond_list.setCellWidget(oper_combo.row, 2, button) else: combo = QComboBox() combo.addItems([""] + var.values) if lc[0]: combo.setCurrentIndex(int(lc[0])) else: combo.setCurrentIndex(0) combo.var_type = vartype(var) self.cond_list.setCellWidget(oper_combo.row, 2, combo) combo.currentIndexChanged.connect(self.conditions_changed) else: box = gui.hBox(self, addToLayout=False) box.var_type = vartype(var) self.cond_list.setCellWidget(oper_combo.row, 2, box) if var.is_continuous: validator = add_datetime if isinstance( var, TimeVariable) else add_numeric box.controls = [validator(lc[0])] if oper > 5: gui.widgetLabel(box, " and ") box.controls.append(validator(lc[1])) elif var.is_string: box.controls = [add_textual(lc[0])] if oper in [6, 7]: gui.widgetLabel(box, " and ") box.controls.append(add_textual(lc[1])) else: box.controls = [] if not adding_all: self.conditions_changed()
def __init__(self): super().__init__() self.old_purge_classes = True self.conditions = [] self.last_output_conditions = None self.data = None self.data_desc = self.match_desc = self.nonmatch_desc = None box = gui.vBox(self.controlArea, 'Conditions', stretch=100) self.cond_list = QTableWidget(box, showGrid=False, selectionMode=QTableWidget.NoSelection) box.layout().addWidget(self.cond_list) self.cond_list.setColumnCount(4) self.cond_list.setRowCount(0) self.cond_list.verticalHeader().hide() self.cond_list.horizontalHeader().hide() for i in range(3): self.cond_list.horizontalHeader().setSectionResizeMode( i, QHeaderView.Stretch) self.cond_list.horizontalHeader().resizeSection(3, 30) self.cond_list.viewport().setBackgroundRole(QPalette.Window) box2 = gui.hBox(box) gui.rubber(box2) self.add_button = gui.button(box2, self, "Add Condition", callback=self.add_row) self.add_all_button = gui.button(box2, self, "Add All Variables", callback=self.add_all) self.remove_all_button = gui.button(box2, self, "Remove All", callback=self.remove_all) gui.rubber(box2) boxes = gui.widgetBox(self.controlArea, orientation=QGridLayout()) layout = boxes.layout() layout.setColumnStretch(0, 1) layout.setColumnStretch(1, 1) box_data = gui.vBox(boxes, 'Data', addToLayout=False) self.data_in_variables = gui.widgetLabel(box_data, " ") self.data_out_rows = gui.widgetLabel(box_data, " ") layout.addWidget(box_data, 0, 0) box_setting = gui.vBox(boxes, 'Purging', addToLayout=False) self.cb_pa = gui.checkBox(box_setting, self, "purge_attributes", "Remove unused features", callback=self.conditions_changed) gui.separator(box_setting, height=1) self.cb_pc = gui.checkBox(box_setting, self, "purge_classes", "Remove unused classes", callback=self.conditions_changed) layout.addWidget(box_setting, 0, 1) self.report_button.setFixedWidth(120) gui.rubber(self.buttonsArea.layout()) layout.addWidget(self.buttonsArea, 1, 0) acbox = gui.auto_commit(None, self, "auto_commit", label="Send", orientation=Qt.Horizontal, checkbox_label="Send automatically") layout.addWidget(acbox, 1, 1) self.set_data(None) self.resize(600, 400)
def __init__(self): super().__init__() self.stats = [] self.dataset = None self.posthoc_lines = [] self.label_txts = self.mean_labels = self.boxes = self.labels = \ self.label_txts_all = self.attr_labels = self.order = [] self.scale_x = self.scene_min_x = self.scene_width = 0 self.label_width = 0 self.attrs = VariableListModel() view = gui.listView(self.controlArea, self, "attribute", box="Variable", model=self.attrs, callback=self.attr_changed) view.setMinimumSize(QSize(30, 30)) # Any other policy than Ignored will let the QListBox's scrollbar # set the minimal height (see the penultimate paragraph of # http://doc.qt.io/qt-4.8/qabstractscrollarea.html#addScrollBarWidget) view.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Ignored) gui.separator(view.box, 6, 6) self.cb_order = gui.checkBox( view.box, self, "order_by_importance", "Order by relevance", tooltip="Order by 𝜒² or ANOVA over the subgroups", callback=self.apply_sorting) self.group_vars = DomainModel(placeholder="None", separators=False, valid_types=Orange.data.DiscreteVariable) self.group_view = view = gui.listView(self.controlArea, self, "group_var", box="Subgroups", model=self.group_vars, callback=self.grouping_changed) view.setEnabled(False) view.setMinimumSize(QSize(30, 30)) # See the comment above view.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Ignored) # TODO: move Compare median/mean to grouping box # The vertical size policy is needed to let only the list views expand self.display_box = gui.vBox(self.controlArea, "Display", sizePolicy=(QSizePolicy.Minimum, QSizePolicy.Maximum), addSpace=False) gui.checkBox(self.display_box, self, "show_annotations", "Annotate", callback=self.display_changed) self.compare_rb = gui.radioButtonsInBox( self.display_box, self, 'compare', btnLabels=["No comparison", "Compare medians", "Compare means"], callback=self.layout_changed) # The vertical size policy is needed to let only the list views expand self.stretching_box = box = gui.vBox(self.controlArea, box="Display", sizePolicy=(QSizePolicy.Minimum, QSizePolicy.Fixed)) self.stretching_box.sizeHint = self.display_box.sizeHint gui.checkBox(box, self, 'stretched', "Stretch bars", callback=self.display_changed) gui.checkBox(box, self, 'show_labels', "Show box labels", callback=self.display_changed) self.sort_cb = gui.checkBox(box, self, 'sort_freqs', "Sort by subgroup frequencies", callback=self.display_changed) gui.rubber(box) gui.auto_commit(self.controlArea, self, "auto_commit", "Send Selection", "Send Automatically") gui.vBox(self.mainArea, addSpace=True) self.box_scene = QGraphicsScene() self.box_scene.selectionChanged.connect(self.commit) self.box_view = QGraphicsView(self.box_scene) self.box_view.setRenderHints(QPainter.Antialiasing | QPainter.TextAntialiasing | QPainter.SmoothPixmapTransform) self.box_view.viewport().installEventFilter(self) self.mainArea.layout().addWidget(self.box_view) e = gui.hBox(self.mainArea, addSpace=False) self.infot1 = gui.widgetLabel(e, "<center>No test results.</center>") self.mainArea.setMinimumWidth(600) self.stats = self.dist = self.conts = [] self.is_continuous = False self.update_display_box()
def add_main_layout(self): # top-level control procedure top_box = gui.hBox(widget=self.controlArea, box=None) rule_ordering_box = gui.hBox(widget=top_box, box="Rule ordering") rule_ordering_rbs = gui.radioButtons(widget=rule_ordering_box, master=self, value="rule_ordering", callback=self.settings_changed, btnLabels=("Ordered", "Unordered")) rule_ordering_rbs.layout().setSpacing(7) covering_algorithm_box = gui.hBox(widget=top_box, box="Covering algorithm") covering_algorithm_rbs = gui.radioButtons( widget=covering_algorithm_box, master=self, value="covering_algorithm", callback=self.settings_changed, btnLabels=("Exclusive", "Weighted")) covering_algorithm_rbs.layout().setSpacing(7) insert_gamma_box = gui.vBox(widget=covering_algorithm_box, box=None) gui.separator(insert_gamma_box, 0, 14) self.gamma_spin = gui.doubleSpin( widget=insert_gamma_box, master=self, value="gamma", minv=0.0, maxv=1.0, step=0.01, label="γ:", orientation=Qt.Horizontal, callback=self.settings_changed, alignment=Qt.AlignRight, enabled=self.storage_covers[self.covering_algorithm] == "weighted") # bottom-level search procedure (search bias) middle_box = gui.vBox(widget=self.controlArea, box="Rule search") gui.comboBox(widget=middle_box, master=self, value="evaluation_measure", label="Evaluation measure:", orientation=Qt.Horizontal, items=("Entropy", "Laplace accuracy", "WRAcc"), callback=self.settings_changed, contentsLength=3) gui.spin(widget=middle_box, master=self, value="beam_width", minv=1, maxv=100, step=1, label="Beam width:", orientation=Qt.Horizontal, callback=self.settings_changed, alignment=Qt.AlignRight, controlWidth=80) # bottom-level search procedure (over-fitting avoidance bias) bottom_box = gui.vBox(widget=self.controlArea, box="Rule filtering") gui.spin(widget=bottom_box, master=self, value="min_covered_examples", minv=1, maxv=10000, step=1, label="Minimum rule coverage:", orientation=Qt.Horizontal, callback=self.settings_changed, alignment=Qt.AlignRight, controlWidth=80) gui.spin(widget=bottom_box, master=self, value="max_rule_length", minv=1, maxv=100, step=1, label="Maximum rule length:", orientation=Qt.Horizontal, callback=self.settings_changed, alignment=Qt.AlignRight, controlWidth=80) gui.doubleSpin(widget=bottom_box, master=self, value="default_alpha", minv=0.0, maxv=1.0, step=0.01, label="Statistical significance (default α):", orientation=Qt.Horizontal, callback=self.settings_changed, alignment=Qt.AlignRight, controlWidth=80, checked="checked_default_alpha") gui.doubleSpin(widget=bottom_box, master=self, value="parent_alpha", minv=0.0, maxv=1.0, step=0.01, label="Relative significance (parent α):", orientation=Qt.Horizontal, callback=self.settings_changed, alignment=Qt.AlignRight, controlWidth=80, checked="checked_parent_alpha")
def __init__(self): super().__init__() self.data = None self.editors = {} box = gui.vBox(self.controlArea, "变量定义") toplayout = QHBoxLayout() toplayout.setContentsMargins(0, 0, 0, 0) box.layout().addLayout(toplayout) self.editorstack = QStackedWidget( sizePolicy=QSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) ) for descclass, editorclass in self.EDITORS: editor = editorclass() editor.featureChanged.connect(self._on_modified) self.editors[descclass] = editor self.editorstack.addWidget(editor) self.editorstack.setEnabled(False) buttonlayout = QVBoxLayout(spacing=10) buttonlayout.setContentsMargins(0, 0, 0, 0) self.addbutton = QPushButton( "新建", toolTip="新建变量", minimumWidth=120, shortcut=QKeySequence.New ) def unique_name(fmt, reserved): candidates = (fmt.format(i) for i in count(1)) return next(c for c in candidates if c not in reserved) def reserved_names(): varnames = [] if self.data is not None: varnames = [var.name for var in self.data.domain.variables + self.data.domain.metas] varnames += [desc.name for desc in self.featuremodel] return set(varnames) def generate_newname(fmt): return unique_name(fmt, reserved_names()) menu = QMenu(self.addbutton) cont = menu.addAction("数字") cont.triggered.connect( lambda: self.addFeature( ContinuousDescriptor(generate_newname("X{}"), "", 3)) ) disc = menu.addAction("分类") disc.triggered.connect( lambda: self.addFeature( DiscreteDescriptor(generate_newname("D{}"), "", ("A", "B"), -1, False)) ) string = menu.addAction("文本") string.triggered.connect( lambda: self.addFeature( StringDescriptor(generate_newname("S{}"), "")) ) menu.addSeparator() self.duplicateaction = menu.addAction("复制选中变量") self.duplicateaction.triggered.connect(self.duplicateFeature) self.duplicateaction.setEnabled(False) self.addbutton.setMenu(menu) self.removebutton = QPushButton( "删除", toolTip="删除选中变量", minimumWidth=120, shortcut=QKeySequence.Delete ) self.removebutton.clicked.connect(self.removeSelectedFeature) buttonlayout.addWidget(self.addbutton) buttonlayout.addWidget(self.removebutton) buttonlayout.addStretch(10) toplayout.addLayout(buttonlayout, 0) toplayout.addWidget(self.editorstack, 10) # Layout for the list view layout = QVBoxLayout(spacing=1, margin=0) self.featuremodel = DescriptorModel(parent=self) self.featureview = QListView( minimumWidth=200, sizePolicy=QSizePolicy(QSizePolicy.Minimum, QSizePolicy.MinimumExpanding) ) self.featureview.setItemDelegate(FeatureItemDelegate(self)) self.featureview.setModel(self.featuremodel) self.featureview.selectionModel().selectionChanged.connect( self._on_selectedVariableChanged ) layout.addWidget(self.featureview) box.layout().addLayout(layout, 1) box = gui.hBox(self.controlArea) gui.rubber(box) commit = gui.button(box, self, "发送", callback=self.apply, default=True) commit.setMinimumWidth(180)
def __init__(self): super().__init__() self.instances = None self.domain = None self.data = None self.classifier = None self.align = OWNomogram.ALIGN_ZERO self.log_odds_ratios = [] self.log_reg_coeffs = [] self.log_reg_coeffs_orig = [] self.log_reg_cont_data_extremes = [] self.p = None self.b0 = None self.points = [] self.feature_items = {} self.feature_marker_values = [] self.scale_marker_values = lambda x: x self.nomogram_main = None self.vertical_line = None self.hidden_vertical_line = None self.old_target_class_index = self.target_class_index self.repaint = False # GUI box = gui.vBox(self.controlArea, "Target class") self.class_combo = gui.comboBox( box, self, "target_class_index", callback=self._class_combo_changed, contentsLength=12, ) self.norm_check = gui.checkBox( box, self, "normalize_probabilities", "Normalize probabilities", hidden=True, callback=self.update_scene, tooltip="For multiclass data 1 vs. all probabilities do not" " sum to 1 and therefore could be normalized.", ) self.scale_radio = gui.radioButtons( self.controlArea, self, "scale", ["Point scale", "Log odds ratios"], box="Scale", callback=self.update_scene, ) box = gui.vBox(self.controlArea, "Display features") grid = QGridLayout() radio_group = gui.radioButtonsInBox(box, self, "display_index", [], orientation=grid, callback=self.update_scene) radio_all = gui.appendRadioButton(radio_group, "All", addToLayout=False) radio_best = gui.appendRadioButton(radio_group, "Best ranked:", addToLayout=False) spin_box = gui.hBox(None, margin=0) self.n_spin = gui.spin( spin_box, self, "n_attributes", 1, self.MAX_N_ATTRS, label=" ", controlWidth=60, callback=self._n_spin_changed, ) grid.addWidget(radio_all, 1, 1) grid.addWidget(radio_best, 2, 1) grid.addWidget(spin_box, 2, 2) self.sort_combo = gui.comboBox( box, self, "sort_index", label="Rank by:", items=SortBy.items(), orientation=Qt.Horizontal, callback=self.update_scene, ) self.cont_feature_dim_combo = gui.comboBox( box, self, "cont_feature_dim_index", label="Numeric features: ", items=["1D projection", "2D curve"], orientation=Qt.Horizontal, callback=self.update_scene, ) gui.rubber(self.controlArea) class _GraphicsView(QGraphicsView): def __init__(self, scene, parent, **kwargs): for k, v in dict( verticalScrollBarPolicy=Qt.ScrollBarAlwaysOff, horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOff, viewportUpdateMode=QGraphicsView. BoundingRectViewportUpdate, renderHints=(QPainter.Antialiasing | QPainter.TextAntialiasing | QPainter.SmoothPixmapTransform), alignment=(Qt.AlignTop | Qt.AlignLeft), sizePolicy=QSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding), ).items(): kwargs.setdefault(k, v) super().__init__(scene, parent, **kwargs) class GraphicsView(_GraphicsView): def __init__(self, scene, parent): super().__init__( scene, parent, verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn, styleSheet="QGraphicsView {background: white}", ) self.viewport().setMinimumWidth( 300) # XXX: This prevents some tests failing self._is_resizing = False w = self def resizeEvent(self, resizeEvent): # Recompute main scene on window width change if resizeEvent.size().width() != resizeEvent.oldSize().width(): self._is_resizing = True self.w.update_scene() self._is_resizing = False return super().resizeEvent(resizeEvent) def is_resizing(self): return self._is_resizing def sizeHint(self): return QSize(400, 200) class FixedSizeGraphicsView(_GraphicsView): def __init__(self, scene, parent): super().__init__( scene, parent, sizePolicy=QSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Minimum), ) def sizeHint(self): return QSize(400, 85) scene = self.scene = QGraphicsScene(self) top_view = self.top_view = FixedSizeGraphicsView(scene, self) mid_view = self.view = GraphicsView(scene, self) bottom_view = self.bottom_view = FixedSizeGraphicsView(scene, self) for view in (top_view, mid_view, bottom_view): self.mainArea.layout().addWidget(view)
def _add_controls_start_box(self): box = gui.vBox(self.controlArea, box="Optimize") form = QFormLayout( labelAlignment=Qt.AlignLeft, formAlignment=Qt.AlignLeft, fieldGrowthPolicy=QFormLayout.AllNonFixedFieldsGrow, ) self.perplexity_spin = gui.spin(box, self, "perplexity", 1, 500, step=1, alignment=Qt.AlignRight, callback=self._invalidate_affinities, addToLayout=False) self.controls.perplexity.setDisabled(self.multiscale) form.addRow("Perplexity:", self.perplexity_spin) form.addRow( gui.checkBox(box, self, "multiscale", label="Preserve global structure", callback=self._multiscale_changed, addToLayout=False)) sbe = gui.hBox(self.controlArea, False, addToLayout=False) gui.hSlider( sbe, self, "exaggeration", minValue=1, maxValue=4, step=1, callback=self._invalidate_tsne_embedding, ) form.addRow("Exaggeration:", sbe) sbp = gui.hBox(self.controlArea, False, addToLayout=False) gui.hSlider( sbp, self, "pca_components", minValue=2, maxValue=_MAX_PCA_COMPONENTS, step=1, callback=self._invalidate_pca_projection, ) form.addRow("PCA components:", sbp) self.normalize_cbx = gui.checkBox( box, self, "normalize", "Normalize data", callback=self._invalidate_pca_projection, addToLayout=False) form.addRow(self.normalize_cbx) box.layout().addLayout(form) self.run_button = gui.button(box, self, "Start", callback=self._toggle_run)
def __init__(self): super().__init__() self.csv_filename = '' self.folder_path = '' self.edtCSVFile = gui.lineEdit(None, self, "csv_filename") self.btnSelectFile = gui.button(None, self, "☰", callback=self._OnChooseCSV, autoDefault=False) self.edtFolder = gui.lineEdit(None, self, "choosePath") self.btnSelFolder = gui.button(None, self, "☰", callback=self._OnChooseFolder, autoDefault=False) self.cboFileList = QComboBox( self, sizeAdjustPolicy=QComboBox.AdjustToContents) self.cboFileList.activated[int].connect(self.load_data) #info_box = gui.widgetBox(self.controlArea, "Info") vlayoutBase = QtWidgets.QVBoxLayout() vlayoutBase.setSizeConstraint(QtWidgets.QLayout.SetDefaultConstraint) vlayoutBase.setContentsMargins(0, 0, 0, 0) vlayoutBase.setSpacing(0) radioGroup = gui.radioButtons(None, self, "source", box=True, addSpace=False, callback=self.OnFileTypeChanged, addToLayout=False) # Folder section hbox_folderbutton = gui.hBox(None, addToLayout=False, margin=0) folderButton = gui.appendRadioButton(radioGroup, "Folder:", addToLayout=False) folderButton.setFixedSize(QtCore.QSize(85, 25)) hbox_folderbutton.layout().addWidget(folderButton) hbox_folder = gui.hBox(None, addToLayout=False, margin=0) hbox_folder.layout().setSpacing(0) hbox_folderEditor = gui.hBox(None, addToLayout=False, margin=0) hbox_folderEditor.layout().addWidget(self.edtFolder) hbox_folderEditor.layout().addWidget(self.btnSelFolder) vbox_folderRight = gui.vBox(None, addToLayout=False, margin=0) vbox_folderRight.layout().setSpacing(0) vbox_folderRight.layout().addWidget(hbox_folderEditor) vbox_folderRight.layout().addWidget(self.cboFileList) hbox_folder.layout().addWidget(hbox_folderbutton) hbox_folder.layout().addWidget(vbox_folderRight) # File section hbox_filebutton = gui.hBox(None, addToLayout=False, margin=0) fileButton = gui.appendRadioButton(radioGroup, "File:", addToLayout=False) fileButton.setFixedSize(QtCore.QSize(85, 25)) hbox_filebutton.layout().addWidget(fileButton) hbox_file = gui.hBox(None, addToLayout=False, margin=0) hbox_file.layout().setSpacing(0) fileArea = gui.hBox(None, addToLayout=False, margin=0) fileArea.layout().addWidget(self.edtCSVFile) fileArea.layout().addWidget(self.btnSelectFile) hbox_file.layout().addWidget(hbox_filebutton) hbox_file.layout().addWidget(fileArea) vlayoutBase.addWidget(hbox_folder) vlayoutBase.addWidget(hbox_file) #vlayoutBase.addWidget(info_box) self.controlArea.layout().addLayout(vlayoutBase) # set window size self.controlArea.setMinimumSize(500, 110) if not self.source: self.source = self.FROM_FOLDER self.OnFileTypeChanged()
def __init__(self): super().__init__() #: widget's runtime state self.__state = State.NoState self.corpus = None self.n_text_categories = 0 self.n_text_data = 0 self.n_skipped = 0 self.__invalidated = False self.__pendingTask = None vbox = gui.vBox(self.controlArea) hbox = gui.hBox(vbox) self.recent_cb = QComboBox( sizeAdjustPolicy=QComboBox.AdjustToMinimumContentsLengthWithIcon, minimumContentsLength=16, acceptDrops=True) self.recent_cb.installEventFilter(self) self.recent_cb.activated[int].connect(self.__onRecentActivated) browseaction = QAction( "Open/Load Documents", self, iconText="\N{HORIZONTAL ELLIPSIS}", icon=self.style().standardIcon(QStyle.SP_DirOpenIcon), toolTip="Select a folder from which to load the documents") browseaction.triggered.connect(self.__runOpenDialog) reloadaction = QAction("Reload", self, icon=self.style().standardIcon( QStyle.SP_BrowserReload), toolTip="Reload current document set") reloadaction.triggered.connect(self.reload) self.__actions = namespace( browse=browseaction, reload=reloadaction, ) browsebutton = QPushButton(browseaction.iconText(), icon=browseaction.icon(), toolTip=browseaction.toolTip(), clicked=browseaction.trigger) reloadbutton = QPushButton( reloadaction.iconText(), icon=reloadaction.icon(), clicked=reloadaction.trigger, default=True, ) hbox.layout().addWidget(self.recent_cb) hbox.layout().addWidget(browsebutton) hbox.layout().addWidget(reloadbutton) self.addActions([browseaction, reloadaction]) reloadaction.changed.connect( lambda: reloadbutton.setEnabled(reloadaction.isEnabled())) box = gui.vBox(vbox, "Info") self.infostack = QStackedWidget() self.info_area = QLabel(text="No document set selected", wordWrap=True) self.progress_widget = QProgressBar(minimum=0, maximum=100) self.cancel_button = QPushButton( "Cancel", icon=self.style().standardIcon(QStyle.SP_DialogCancelButton), ) self.cancel_button.clicked.connect(self.cancel) w = QWidget() vlayout = QVBoxLayout() vlayout.setContentsMargins(0, 0, 0, 0) hlayout = QHBoxLayout() hlayout.setContentsMargins(0, 0, 0, 0) hlayout.addWidget(self.progress_widget) hlayout.addWidget(self.cancel_button) vlayout.addLayout(hlayout) self.pathlabel = TextLabel() self.pathlabel.setTextElideMode(Qt.ElideMiddle) self.pathlabel.setAttribute(Qt.WA_MacSmallSize) vlayout.addWidget(self.pathlabel) w.setLayout(vlayout) self.infostack.addWidget(self.info_area) self.infostack.addWidget(w) box.layout().addWidget(self.infostack) self.__initRecentItemsModel() self.__invalidated = True self.__executor = ThreadExecutor(self) QApplication.postEvent(self, QEvent(RuntimeEvent.Init))
def __init__(self): super().__init__() self.data = None self.extra_data = None self.extra_data = None self.model = itemmodels.VariableListModel() self.model_unique_with_id = itemmodels.VariableListModel() self.extra_model_unique = itemmodels.VariableListModel() self.extra_model_unique_with_id = itemmodels.VariableListModel() box = gui.hBox(self.controlArea, box=None) self.infoBoxData = gui.label(box, self, self.dataInfoText(None), box="Data") self.infoBoxExtraData = gui.label(box, self, self.dataInfoText(None), box="Extra Data") grp = gui.radioButtonsInBox(self.controlArea, self, "merging", box="Merging", callback=self.change_merging) self.attr_boxes = [] radio_width = \ QApplication.style().pixelMetric(QStyle.PM_ExclusiveIndicatorWidth) def add_option(label, pre_label, between_label, merge_type, model, extra_model): gui.appendRadioButton(grp, label) vbox = gui.vBox(grp) box = gui.hBox(vbox) box.layout().addSpacing(radio_width) self.attr_boxes.append(box) gui.widgetLabel(box, pre_label) model[:] = [getattr(self, 'attr_{}_data'.format(merge_type))] extra_model[:] = [ getattr(self, 'attr_{}_extra'.format(merge_type)) ] cb = gui.comboBox(box, self, 'attr_{}_data'.format(merge_type), contentsLength=12, callback=self._invalidate, model=model) cb.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) cb.setFixedWidth(190) gui.widgetLabel(box, between_label) cb = gui.comboBox(box, self, 'attr_{}_extra'.format(merge_type), contentsLength=12, callback=self._invalidate, model=extra_model) cb.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) cb.setFixedWidth(190) vbox.layout().addSpacing(6) add_option("Append columns from Extra Data", "by matching", "with", "augment", self.model, self.extra_model_unique) add_option("Find matching rows", "where", "equals", "merge", self.model_unique_with_id, self.extra_model_unique_with_id) add_option("Concatenate tables, merge rows", "where", "equals", "combine", self.model_unique_with_id, self.extra_model_unique_with_id) self.set_merging() gui.auto_commit(self.controlArea, self, "auto_apply", "&Apply", box=False)
def __init__(self): super().__init__() RecentPathsWComboMixin.__init__(self) self.domain = None self.data = None self.loaded_file = "" layout = QtGui.QGridLayout() gui.widgetBox(self.controlArea, margin=0, orientation=layout) vbox = gui.radioButtons(None, self, "source", box=True, addSpace=True, callback=self.load_data, addToLayout=False) rb_button = gui.appendRadioButton(vbox, "File:", addToLayout=False) layout.addWidget(rb_button, 0, 0, QtCore.Qt.AlignVCenter) box = gui.hBox(None, addToLayout=False, margin=0) box.setSizePolicy(Policy.MinimumExpanding, Policy.Fixed) self.file_combo.setSizePolicy(Policy.MinimumExpanding, Policy.Fixed) self.file_combo.activated[int].connect(self.select_file) box.layout().addWidget(self.file_combo) layout.addWidget(box, 0, 1) file_button = gui.button(None, self, '...', callback=self.browse_file, autoDefault=False) file_button.setIcon(self.style().standardIcon( QtGui.QStyle.SP_DirOpenIcon)) file_button.setSizePolicy(Policy.Maximum, Policy.Fixed) layout.addWidget(file_button, 0, 2) reload_button = gui.button(None, self, "Reload", callback=self.reload, autoDefault=False) reload_button.setIcon(self.style().standardIcon( QtGui.QStyle.SP_BrowserReload)) reload_button.setSizePolicy(Policy.Fixed, Policy.Fixed) layout.addWidget(reload_button, 0, 3) self.sheet_box = gui.hBox(None, addToLayout=False, margin=0) self.sheet_combo = gui.comboBox(None, self, "xls_sheet", callback=self.load_data, sendSelectedValue=True) self.sheet_combo.setSizePolicy(Policy.MinimumExpanding, Policy.Fixed) self.sheet_label = QtGui.QLabel() self.sheet_label.setText('Sheet') self.sheet_label.setSizePolicy(Policy.MinimumExpanding, Policy.Fixed) self.sheet_box.layout().addWidget(self.sheet_label, QtCore.Qt.AlignLeft) self.sheet_box.layout().addWidget(self.sheet_combo, QtCore.Qt.AlignVCenter) layout.addWidget(self.sheet_box, 2, 1) self.sheet_box.hide() rb_button = gui.appendRadioButton(vbox, "URL:", addToLayout=False) layout.addWidget(rb_button, 3, 0, QtCore.Qt.AlignVCenter) self.url_combo = url_combo = QtGui.QComboBox() url_model = NamedURLModel(self.sheet_names) url_model.wrap(self.recent_urls) url_combo.setModel(url_model) url_combo.setSizePolicy(Policy.MinimumExpanding, Policy.Fixed) url_combo.setMaximumWidth(500) url_combo.setEditable(True) url_combo.setInsertPolicy(url_combo.InsertAtTop) url_edit = url_combo.lineEdit() l, t, r, b = url_edit.getTextMargins() url_edit.setTextMargins(l + 5, t, r, b) layout.addWidget(url_combo, 3, 1, 3, 3) url_combo.activated.connect(self._url_set) box = gui.vBox(self.controlArea, "Info") self.info = gui.widgetLabel(box, 'No data loaded.') self.warnings = gui.widgetLabel(box, '') box = gui.hBox(self.controlArea) gui.button(box, self, "Browse documentation data sets", callback=lambda: self.browse_file(True), autoDefault=False) gui.rubber(box) box.layout().addWidget(self.report_button) self.report_button.setFixedWidth(170) # Set word wrap, so long warnings won't expand the widget self.warnings.setWordWrap(True) self.warnings.setSizePolicy(Policy.Ignored, Policy.MinimumExpanding) self.set_file_list() if self.last_path() is not None: self.fill_sheet_combo(self.last_path()) # Must not call open_file from within __init__. open_file # explicitly re-enters the event loop (by a progress bar) QtCore.QTimer.singleShot(0, self.load_data) self.setAcceptDrops(True)
def _add_mark_box(self): hbox = gui.hBox(None, box=True) self.mainArea.layout().addWidget(hbox) vbox = gui.hBox(hbox) def spin(value, label, minv, maxv): return gui.spin(vbox, self, value, label=label, minv=minv, maxv=maxv, step=1, alignment=Qt.AlignRight, callback=self.update_marks).box def text_line(): def set_search_string_timer(): self.searchStringTimer.stop() self.searchStringTimer.start(300) return gui.lineEdit(gui.hBox(vbox), self, "mark_text", label="Text: ", orientation=Qt.Horizontal, minimumWidth=50, callback=set_search_string_timer, callbackOnType=True).box def _mark_by_labels(marker): txt = self.mark_text.lower() if not txt: return None labels = self.get_label_data() if labels is None: return None return marker(np.char.array(labels), txt) def mark_label_starts(): return _mark_by_labels(lambda labels, txt: np.flatnonzero( labels.lower().startswith(txt))) def mark_label_contains(): return _mark_by_labels(lambda labels, txt: np.flatnonzero( labels.lower().find(txt) != -1)) def mark_text(): txt = self.mark_text.lower() if not txt or self.data is None: return None return np.array([ i for i, inst in enumerate(self.data) if txt in "\x00".join(map(str, inst.list)).lower() ]) def mark_reachable(): selected = self.graph.get_selection() if selected is None: return None return self.get_reachable(selected) def mark_close(): selected = self.graph.get_selection() if selected is None: return None neighbours = set(selected) last_round = list(neighbours) for _ in range(self.mark_hops): next_round = set() for neigh in last_round: next_round |= set(self.network.neighbours(neigh)) neighbours |= next_round last_round = next_round neighbours -= set(selected) return np.array(list(neighbours)) def mark_from_input(): if self.subset_data is None or self.data is None: return None ids = set(self.subset_data.ids) return np.array( [i for i, ex in enumerate(self.data) if ex.id in ids]) def mark_most_connections(): n = self.mark_most_conn if n >= self.number_of_nodes: return np.arange(self.number_of_nodes) degrees = self.network.degrees() # pylint: disable=invalid-unary-operand-type min_degree = np.partition(degrees, -n)[-n] return np.flatnonzero(degrees >= min_degree) def mark_more_than_any_neighbour(): degrees = self.network.degrees() return np.array([ node for node, degree in enumerate(degrees) if degree > np.max(degrees[self.network.neighbours(node)], initial=0) ]) def mark_more_than_average_neighbour(): degrees = self.network.degrees() return np.array([ node for node, degree, neighbours in ( (node, degree, self.network.neighbours(node)) for node, degree in enumerate(degrees)) if degree > ( np.mean(degrees[neighbours]) if neighbours.size else 0) ]) self.mark_criteria = [ ("(Select criteria for marking)", None, lambda: np.zeros((0, ))), ("Mark nodes whose label starts with", text_line(), mark_label_starts), ("Mark nodes whose label contains", text_line(), mark_label_contains), ("Mark nodes whose data that contains", text_line(), mark_text), ("Mark nodes reachable from selected", None, mark_reachable), ("Mark nodes in vicinity of selection", spin("mark_hops", "Number of hops:", 1, 20), mark_close), ("Mark nodes from subset signal", None, mark_from_input), ("Mark nodes with few connections", spin("mark_max_conn", "Max. connections:", 0, 1000), lambda: np. flatnonzero(self.network.degrees() <= self.mark_max_conn)), ("Mark nodes with many connections", spin("mark_min_conn", "Min. connections:", 1, 1000), lambda: np. flatnonzero(self.network.degrees() >= self.mark_min_conn)), ("Mark nodes with most connections", spin("mark_most_conn", "Number of marked:", 1, 1000), mark_most_connections), ("Mark nodes with more connections than any neighbour", None, mark_more_than_any_neighbour), ("Mark nodes with more connections than average neighbour", None, mark_more_than_average_neighbour) ] cb = gui.comboBox(hbox, self, "mark_mode", items=[item for item, *_ in self.mark_criteria], maximumContentsLength=-1, callback=self.set_mark_mode) hbox.layout().insertWidget(0, cb) gui.rubber(hbox) self.btselect = gui.button(hbox, self, "Select", callback=self.select_marked) self.btadd = gui.button(hbox, self, "Add to Selection", callback=self.select_add_marked) self.btgroup = gui.button(hbox, self, "Add New Group", callback=self.select_as_group)
def __init__(self): super().__init__() self.data = None # type: Optional[Orange.data.Table] self.learner = None # type: Optional[Learner] self.default_learner = SimpleTreeLearner(min_instances=10, max_depth=10) self.modified = False self.executor = qconcurrent.ThreadExecutor(self) self.__task = None main_layout = self.controlArea.layout() box = gui.vBox(self.controlArea, "Default Method") box_layout = QGridLayout() box_layout.setSpacing(8) box.layout().addLayout(box_layout) button_group = QButtonGroup() button_group.idClicked.connect(self.set_default_method) for i, (method, _) in enumerate(list(METHODS.items())[1:-1]): imputer = self.create_imputer(method) button = QRadioButton(imputer.name) button.setChecked(method == self.default_method_index) button_group.addButton(button, method) box_layout.addWidget(button, i % 3, i // 3) def set_default_time(datetime): datetime = datetime.toSecsSinceEpoch() if datetime != self.default_time: self.default_time = datetime if self.default_method_index == Method.Default: self._invalidate() hlayout = QHBoxLayout() box.layout().addLayout(hlayout) button = QRadioButton("Fixed values; numeric variables:") button_group.addButton(button, Method.Default) button.setChecked(Method.Default == self.default_method_index) hlayout.addWidget(button) self.numeric_value_widget = DoubleSpinBox( minimum=DBL_MIN, maximum=DBL_MAX, singleStep=.1, value=self.default_numeric_value, alignment=Qt.AlignRight, enabled=self.default_method_index == Method.Default, ) self.numeric_value_widget.editingFinished.connect( self.__on_default_numeric_value_edited ) self.connect_control( "default_numeric_value", self.numeric_value_widget.setValue ) hlayout.addWidget(self.numeric_value_widget) hlayout.addWidget(QLabel(", time:")) self.time_widget = gui.DateTimeEditWCalendarTime(self) self.time_widget.setEnabled(self.default_method_index == Method.Default) self.time_widget.setKeyboardTracking(False) self.time_widget.setContentsMargins(0, 0, 0, 0) self.time_widget.set_datetime( QDateTime.fromSecsSinceEpoch(self.default_time) ) self.connect_control( "default_time", lambda value: self.time_widget.set_datetime( QDateTime.fromSecsSinceEpoch(value) ) ) self.time_widget.dateTimeChanged.connect(set_default_time) hlayout.addWidget(self.time_widget) self.default_button_group = button_group box = gui.hBox(self.controlArea, self.tr("Individual Attribute Settings"), flat=False) self.varview = ListViewSearch( selectionMode=QListView.ExtendedSelection, uniformItemSizes=True ) self.varview.setItemDelegate(DisplayFormatDelegate()) self.varmodel = itemmodels.VariableListModel() self.varview.setModel(self.varmodel) self.varview.selectionModel().selectionChanged.connect( self._on_var_selection_changed ) self.selection = self.varview.selectionModel() box.layout().addWidget(self.varview) vertical_layout = QVBoxLayout() self.methods_container = QWidget(enabled=False) method_layout = QVBoxLayout() method_layout.setContentsMargins(0, 0, 0, 0) self.methods_container.setLayout(method_layout) button_group = QButtonGroup() for method in Method: imputer = self.create_imputer(method) button = QRadioButton(text=imputer.name) button_group.addButton(button, method) method_layout.addWidget(button) self.value_combo = QComboBox( minimumContentsLength=8, sizeAdjustPolicy=QComboBox.AdjustToMinimumContentsLengthWithIcon, activated=self._on_value_selected ) self.value_double = DoubleSpinBox( editingFinished=self._on_value_selected, minimum=DBL_MIN, maximum=DBL_MAX, singleStep=.1, ) self.value_stack = value_stack = QStackedWidget() value_stack.addWidget(self.value_combo) value_stack.addWidget(self.value_double) method_layout.addWidget(value_stack) button_group.idClicked.connect( self.set_method_for_current_selection ) self.reset_button = QPushButton( "Restore All to Default", enabled=False, default=False, autoDefault=False, clicked=self.reset_variable_state, ) vertical_layout.addWidget(self.methods_container) vertical_layout.addStretch(2) vertical_layout.addWidget(self.reset_button) box.layout().addLayout(vertical_layout) self.variable_button_group = button_group gui.auto_apply(self.buttonsArea, self, "autocommit")
def __init__(self): self.data = None box = gui.vBox(self.controlArea, 'Moving Transform') def _disable_fixed_wlen(): fixed_wlen.setDisabled(not self.non_overlapping) self.view.repaint() self.on_changed() gui.checkBox(box, self, 'non_overlapping', label=self._NON_OVERLAPPING_WINDOWS, callback=_disable_fixed_wlen, tooltip='If this is checked, instead of rolling windows ' 'through the series, they are applied side-to-side, ' 'so the resulting output series will be some ' 'length-of-fixed-window-times shorter.') fixed_wlen = gui.spin(box, self, 'fixed_wlen', 2, 1000, label='Fixed window width:', callback=self.on_changed) fixed_wlen.setDisabled(not self.non_overlapping) # TODO: allow the user to choose left-aligned, right-aligned, or center-aligned window class TableView(gui.TableView): def __init__(self, parent): super().__init__(parent, editTriggers=(self.SelectedClicked | self.CurrentChanged | self.DoubleClicked | self.EditKeyPressed), ) self.horizontalHeader().setStretchLastSection(False) agg_functions = ListModel(AGG_FUNCTIONS + [Cumulative_sum, Cumulative_product], parent=self) self.setItemDelegateForColumn(0, self.VariableDelegate(parent)) self.setItemDelegateForColumn(1, self.SpinDelegate(parent)) self.setItemDelegateForColumn(2, self.ComboDelegate(self, agg_functions)) class _ItemDelegate(QStyledItemDelegate): def updateEditorGeometry(self, widget, option, _index): widget.setGeometry(option.rect) class ComboDelegate(_ItemDelegate): def __init__(self, parent=None, combo_model=None): super().__init__(parent) self._parent = parent if combo_model is not None: self._combo_model = combo_model def createEditor(self, parent, _QStyleOptionViewItem, index): combo = QComboBox(parent) combo.setModel(self._combo_model) return combo def setEditorData(self, combo, index): var = index.model().data(index, Qt.EditRole) combo.setCurrentIndex(self._combo_model.indexOf(var)) def setModelData(self, combo, model, index): var = self._combo_model[combo.currentIndex()] model.setData(index, var, Qt.EditRole) class VariableDelegate(ComboDelegate): @property def _combo_model(self): return self._parent.var_model class SpinDelegate(_ItemDelegate): def paint(self, painter, option, index): # Don't paint window length if non-overlapping windows set if not self.parent().non_overlapping: super().paint(painter, option, index) def createEditor(self, parent, _QStyleOptionViewItem, _index): # Don't edit window length if non-overlapping windows set if self.parent().non_overlapping: return None spin = QSpinBox(parent, minimum=1, maximum=1000) return spin def setEditorData(self, spin, index): spin.setValue(index.model().data(index, Qt.EditRole)) def setModelData(self, spin, model, index): spin.interpretText() model.setData(index, spin.value(), Qt.EditRole) self.var_model = VariableListModel(parent=self) self.table_model = model = PyTableModel(parent=self, editable=True) model.setHorizontalHeaderLabels(['Series', 'Window width', 'Aggregation function']) model.dataChanged.connect(self.on_changed) self.view = view = TableView(self) view.setModel(model) box.layout().addWidget(view) hbox = gui.hBox(box) from os.path import dirname, join self.add_button = button = gui.button( hbox, self, 'Add &Transform', callback=self.on_add_transform) button.setIcon(QIcon(join(dirname(__file__), 'icons', 'LineChart-plus.png'))) self.del_button = button = gui.button( hbox, self, '&Delete Selected', callback=self.on_del_transform) QIcon.setThemeName('gnome') # Works for me button.setIcon(QIcon.fromTheme('edit-delete')) gui.auto_commit(box, self, 'autocommit', '&Apply') self.settingsAboutToBePacked.connect(self.store_transformations)
def __init__(self): super().__init__() self.data = None # The following lists are of the same length as self.active_rules #: list of pairs with counts of matches for each patter when the # patterns are applied in order and when applied on the entire set, # disregarding the preceding patterns self.match_counts = [] #: list of list of QLineEdit: line edit pairs for each pattern self.line_edits = [] #: list of QPushButton: list of remove buttons self.remove_buttons = [] #: list of list of QLabel: pairs of labels with counts self.counts = [] combo = gui.comboBox(self.controlArea, self, "attribute", label="From column: ", box=True, orientation=Qt.Horizontal, callback=self.update_rules, model=DomainModel(valid_types=(StringVariable, DiscreteVariable))) # Don't use setSizePolicy keyword argument here: it applies to box, # not the combo combo.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) patternbox = gui.vBox(self.controlArea, box=True) #: QWidget: the box that contains the remove buttons, line edits and # count labels. The lines are added and removed dynamically. self.rules_box = rules_box = QGridLayout() patternbox.layout().addLayout(self.rules_box) box = gui.hBox(patternbox) gui.button(box, self, "+", callback=self.add_row, autoDefault=False, flat=True, minimumSize=(QSize(20, 20))) gui.rubber(box) self.rules_box.setColumnMinimumWidth(1, 70) self.rules_box.setColumnMinimumWidth(0, 10) self.rules_box.setColumnStretch(0, 1) self.rules_box.setColumnStretch(1, 1) self.rules_box.setColumnStretch(2, 100) rules_box.addWidget(QLabel("Name"), 0, 1) rules_box.addWidget(QLabel("Substring"), 0, 2) rules_box.addWidget(QLabel("#Instances"), 0, 3, 1, 2) self.update_rules() gui.lineEdit(self.controlArea, self, "class_name", label="Name for the new class:", box=True, orientation=Qt.Horizontal) optionsbox = gui.vBox(self.controlArea, box=True) gui.checkBox(optionsbox, self, "match_beginning", "Match only at the beginning", callback=self.options_changed) gui.checkBox(optionsbox, self, "case_sensitive", "Case sensitive", callback=self.options_changed) box = gui.hBox(self.controlArea) gui.rubber(box) gui.button(box, self, "Apply", autoDefault=False, width=180, callback=self.apply) # TODO: Resizing upon changing the number of rules does not work self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum)
def __init__(self): super().__init__() self._connection = None self.data_desc_table = None self.database_desc = None vbox = gui.vBox(self.controlArea, "Server", addSpace=True) box = gui.vBox(vbox) self.servertext = QtGui.QLineEdit(box) self.servertext.setPlaceholderText('Server') self.servertext.setToolTip('Server') if self.host: self.servertext.setText(self.host if not self.port else '{}:{}'. format(self.host, self.port)) box.layout().addWidget(self.servertext) self.databasetext = QtGui.QLineEdit(box) self.databasetext.setPlaceholderText('Database[/Schema]') self.databasetext.setToolTip('Database or optionally Database/Schema') if self.database: self.databasetext.setText( self.database if not self.schema else '{}/{}'. format(self.database, self.schema)) box.layout().addWidget(self.databasetext) self.usernametext = QtGui.QLineEdit(box) self.usernametext.setPlaceholderText('Username') self.usernametext.setToolTip('Username') if self.username: self.usernametext.setText(self.username) box.layout().addWidget(self.usernametext) self.passwordtext = QtGui.QLineEdit(box) self.passwordtext.setPlaceholderText('Password') self.passwordtext.setToolTip('Password') self.passwordtext.setEchoMode(QtGui.QLineEdit.Password) if self.password: self.passwordtext.setText(self.password) box.layout().addWidget(self.passwordtext) tables = gui.hBox(box) self.tablecombo = QtGui.QComboBox( tables, minimumContentsLength=35, sizeAdjustPolicy=QtGui.QComboBox.AdjustToMinimumContentsLength) self.tablecombo.setToolTip('table') tables.layout().addWidget(self.tablecombo) self.tablecombo.activated[int].connect(self.select_table) self.connectbutton = gui.button(tables, self, '↻', callback=self.connect) self.connectbutton.setSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) tables.layout().addWidget(self.connectbutton) self.custom_sql = gui.vBox(box) self.custom_sql.setVisible(False) self.sqltext = QtGui.QTextEdit(self.custom_sql) self.sqltext.setPlainText(self.sql) self.custom_sql.layout().addWidget(self.sqltext) mt = gui.hBox(self.custom_sql) cb = gui.checkBox(mt, self, 'materialize', 'Materialize to table ') cb.setToolTip('Save results of the query in a table') le = gui.lineEdit(mt, self, 'materialize_table_name') le.setToolTip('Save results of the query in a table') self.executebtn = gui.button(self.custom_sql, self, 'Execute', callback=self.open_table) box.layout().addWidget(self.custom_sql) gui.checkBox(box, self, "guess_values", "Auto-discover discrete variables", callback=self.open_table) gui.checkBox(box, self, "download", "Download data to local memory", callback=self.open_table) gui.rubber(self.buttonsArea) QTimer.singleShot(0, self.connect)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.api = WikipediaAPI(on_error=self.Error.api_error) self.result = None query_box = gui.hBox(self.controlArea, 'Query') # Queries configuration layout = QGridLayout() layout.setSpacing(7) row = 0 query_edit = ListEdit(self, 'query_list', "Each line represents a separate query.", None, self) layout.addWidget(QLabel('Query word list:'), row, 0, 1, self.label_width) layout.addWidget(query_edit, row, self.label_width, 1, self.widgets_width) # Language row += 1 language_edit = ComboBox(self, 'language', tuple(sorted(lang2code.items()))) layout.addWidget(QLabel('Language:'), row, 0, 1, self.label_width) layout.addWidget(language_edit, row, self.label_width, 1, self.widgets_width) # Articles per query row += 1 layout.addWidget(QLabel('Articles per query:'), row, 0, 1, self.label_width) slider = gui.valueSlider(query_box, self, 'articles_per_query', box='', values=[1, 3, 5, 10, 25]) layout.addWidget(slider.box, row, 1, 1, self.widgets_width) query_box.layout().addLayout(layout) self.controlArea.layout().addWidget(query_box) self.controlArea.layout().addWidget( CheckListLayout('Text includes', self, 'text_includes', self.attributes, cols=2, callback=self.set_text_features)) self.info_box = gui.hBox(self.controlArea, 'Info') self.result_label = gui.label(self.info_box, self, self.info_label.format(0)) self.button_box = gui.hBox(self.controlArea) self.button_box.layout().addWidget(self.report_button) self.search_button = gui.button(self.button_box, self, 'Search', self.start_stop) self.search_button.setFocusPolicy(Qt.NoFocus)
def __init__(self): super().__init__() self.table = None self._html = None def _loadFinished(is_ok): if is_ok: QTimer.singleShot(1, lambda: setattr(self, '_html', self.webview.html())) self.webview = WebviewWidget(loadFinished=_loadFinished) vb = gui.vBox(self.controlArea, 'Import Data') hb = gui.hBox(vb) self.combo = combo = URLComboBox( hb, self.recent, editable=True, minimumWidth=400, insertPolicy=QComboBox.InsertAtTop, toolTip='Format: ' + VALID_URL_HELP, editTextChanged=self.is_valid_url, # Indirect via QTimer because calling wait() -> processEvents, # while our currentIndexChanged event hadn't yet finished. # Avoids calling handler twice. currentIndexChanged=lambda: QTimer.singleShot(1, self.load_url)) hb.layout().addWidget(QLabel('Public link URL:', hb)) hb.layout().addWidget(combo) hb.layout().setStretch(1, 2) RELOAD_TIMES = ( ('No reload',), ('5 s', 5000), ('10 s', 10000), ('30 s', 30000), ('1 min', 60*1000), ('2 min', 2*60*1000), ('5 min', 5*60*1000), ) reload_timer = QTimer(self, timeout=lambda: self.load_url(from_reload=True)) def _on_reload_changed(): if self.reload_idx == 0: reload_timer.stop() return reload_timer.start(RELOAD_TIMES[self.reload_idx][1]) gui.comboBox(vb, self, 'reload_idx', label='Reload every:', orientation=Qt.Horizontal, items=[i[0] for i in RELOAD_TIMES], callback=_on_reload_changed) box = gui.widgetBox(self.controlArea, "Columns (Double-click to edit)") self.domain_editor = DomainEditor(self) editor_model = self.domain_editor.model() def editorDataChanged(): self.apply_domain_edit() self.commit() editor_model.dataChanged.connect(editorDataChanged) box.layout().addWidget(self.domain_editor) box = gui.widgetBox(self.controlArea, "Info", addSpace=True) info = self.data_info = gui.widgetLabel(box, '') info.setWordWrap(True) self.controlArea.layout().addStretch(1) gui.auto_commit(self.controlArea, self, 'autocommit', label='Commit') self.set_info()
def __init__(self): super().__init__() self.data = None self.km = None self.optimization_runs = [] box = gui.vBox(self.controlArea, "Number of Clusters") layout = QGridLayout() self.n_clusters = bg = gui.radioButtonsInBox(box, self, "optimize_k", [], orientation=layout, callback=self.update) layout.addWidget( gui.appendRadioButton(bg, "Fixed:", addToLayout=False), 1, 1) sb = gui.hBox(None, margin=0) self.fixedSpinBox = gui.spin(sb, self, "k", minv=2, maxv=30, controlWidth=60, alignment=Qt.AlignRight, callback=self.update_k) gui.rubber(sb) layout.addWidget(sb, 1, 2) layout.addWidget( gui.appendRadioButton(bg, "Optimized from", addToLayout=False), 2, 1) ftobox = gui.hBox(None) ftobox.layout().setContentsMargins(0, 0, 0, 0) layout.addWidget(ftobox) gui.spin(ftobox, self, "k_from", minv=2, maxv=29, controlWidth=60, alignment=Qt.AlignRight, callback=self.update_from) gui.widgetLabel(ftobox, "to") self.fixedSpinBox = gui.spin(ftobox, self, "k_to", minv=3, maxv=30, controlWidth=60, alignment=Qt.AlignRight, callback=self.update_to) gui.rubber(ftobox) layout.addWidget(gui.widgetLabel(None, "Scoring: "), 5, 1, Qt.AlignRight) layout.addWidget( gui.comboBox(None, self, "scoring", label="Scoring", items=list(zip(*self.SCORING_METHODS))[0], callback=self.update), 5, 2) box = gui.vBox(self.controlArea, "Initialization") gui.comboBox(box, self, "smart_init", items=self.INIT_METHODS, callback=self.update) layout = QGridLayout() box2 = gui.widgetBox(box, orientation=layout) box2.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum) layout.addWidget(gui.widgetLabel(None, "Re-runs: "), 0, 0, Qt.AlignLeft) sb = gui.hBox(None, margin=0) layout.addWidget(sb, 0, 1) gui.lineEdit(sb, self, "n_init", controlWidth=60, valueType=int, validator=QIntValidator(), callback=self.update) layout.addWidget(gui.widgetLabel(None, "Maximal iterations: "), 1, 0, Qt.AlignLeft) sb = gui.hBox(None, margin=0) layout.addWidget(sb, 1, 1) gui.lineEdit(sb, self, "max_iterations", controlWidth=60, valueType=int, validator=QIntValidator(), callback=self.update) box = gui.vBox(self.controlArea, "Output") gui.comboBox(box, self, "place_cluster_ids", label="Append cluster ID as:", orientation=Qt.Horizontal, callback=self.send_data, items=self.OUTPUT_METHODS) gui.lineEdit(box, self, "output_name", label="Name:", orientation=Qt.Horizontal, callback=self.send_data) gui.separator(self.buttonsArea, 30) self.apply_button = gui.auto_commit(self.buttonsArea, self, "auto_run", "Apply", box=None) gui.rubber(self.controlArea) self.table_model = QStandardItemModel(self) self.table_model.setHorizontalHeaderLabels(["k", "Score"]) self.table_model.setColumnCount(2) self.table_box = gui.vBox(self.mainArea, "Optimization Report", addSpace=0) table = self.table_view = QTableView(self.table_box) table.setHorizontalScrollMode(QTableView.ScrollPerPixel) table.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) table.setSelectionMode(QTableView.SingleSelection) table.setSelectionBehavior(QTableView.SelectRows) table.verticalHeader().hide() table.setItemDelegateForColumn(1, gui.TableBarItem(self)) table.setModel(self.table_model) table.selectionModel().selectionChanged.connect( self.table_item_selected) table.setColumnWidth(0, 40) table.setColumnWidth(1, 120) table.horizontalHeader().setStretchLastSection(True) self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) self.mainArea.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Preferred) self.table_box.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.MinimumExpanding) self.table_view.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.MinimumExpanding) self.table_box.layout().addWidget(self.table_view) self.hide_show_opt_results()
def __init__(self, parent=None, select=SELECTNONE): QWidget.__init__(self) OWComponent.__init__(self, parent) self.parent = parent self.selection_type = select self.saving_enabled = hasattr(self.parent, "save_graph") self.clear_data(init=True) self.subset = None # current subset input self.subset_indices = None # boolean index array with indices in self.data self.plotview = pg.PlotWidget(background="w", viewBox=InteractiveViewBoxC(self)) self.plot = self.plotview.getPlotItem() self.plot.setDownsampling(auto=True, mode="peak") self.markings = [] self.vLine = pg.InfiniteLine(angle=90, movable=False) self.hLine = pg.InfiniteLine(angle=0, movable=False) self.proxy = pg.SignalProxy(self.plot.scene().sigMouseMoved, rateLimit=20, slot=self.mouseMoved, delay=0.1) self.plot.scene().sigMouseMoved.connect(self.plot.vb.mouseMovedEvent) self.plot.vb.sigRangeChanged.connect(self.resized) self.pen_mouse = pg.mkPen(color=(0, 0, 255), width=2) self.pen_normal = defaultdict(lambda: pg.mkPen(color=(200, 200, 200, 127), width=1)) self.pen_subset = defaultdict(lambda: pg.mkPen(color=(0, 0, 0, 127), width=1)) self.pen_selected = defaultdict(lambda: pg.mkPen(color=(0, 0, 0, 127), width=2, style=Qt.DotLine)) self.label = pg.TextItem("", anchor=(1, 0)) self.label.setText("", color=(0, 0, 0)) self.discrete_palette = None QPixmapCache.setCacheLimit(max(QPixmapCache.cacheLimit(), 100 * 1024)) self.curves_cont = PlotCurvesItem() self.important_decimals = 4, 4 # whether to rescale at next update self.rescale_next = True self.MOUSE_RADIUS = 20 self.clear_graph() # interface settings self.location = True # show current position self.markclosest = True # mark self.crosshair = True self.crosshair_hidden = True layout = QVBoxLayout() self.setLayout(layout) self.layout().setContentsMargins(0, 0, 0, 0) self.layout().addWidget(self.plotview) actions = [] resample_curves = QAction( "Resample curves", self, shortcut=Qt.Key_R, triggered=lambda x: self.resample_curves(self.sample_seed+1) ) actions.append(resample_curves) reset_curves = QAction( "Resampling reset", self, shortcut=QKeySequence(Qt.ControlModifier | Qt.Key_R), triggered=lambda x: self.resample_curves(0) ) actions.append(reset_curves) zoom_in = QAction( "Zoom in", self, triggered=self.plot.vb.set_mode_zooming ) zoom_in.setShortcuts([Qt.Key_Z, QKeySequence(QKeySequence.ZoomIn)]) zoom_in.setShortcutContext(Qt.WidgetWithChildrenShortcut) actions.append(zoom_in) zoom_fit = QAction( "Zoom to fit", self, triggered=lambda x: (self.plot.vb.autoRange(), self.plot.vb.set_mode_panning()) ) zoom_fit.setShortcuts([Qt.Key_Backspace, QKeySequence(Qt.ControlModifier | Qt.Key_0)]) zoom_fit.setShortcutContext(Qt.WidgetWithChildrenShortcut) actions.append(zoom_fit) rescale_y = QAction( "Rescale Y to fit", self, shortcut=Qt.Key_D, triggered=self.rescale_current_view_y ) actions.append(rescale_y) self.view_average_menu = QAction( "Show averages", self, shortcut=Qt.Key_A, checkable=True, triggered=lambda x: self.viewtype_changed() ) actions.append(self.view_average_menu) self.show_grid = False self.show_grid_a = QAction( "Show grid", self, shortcut=Qt.Key_G, checkable=True, triggered=self.grid_changed ) actions.append(self.show_grid_a) self.invertX_menu = QAction( "Invert X", self, shortcut=Qt.Key_X, checkable=True, triggered=self.invertX_changed ) actions.append(self.invertX_menu) if self.selection_type == SELECTMANY: select_curves = QAction( "Select (line)", self, triggered=self.plot.vb.set_mode_select, ) select_curves.setShortcuts([Qt.Key_S]) select_curves.setShortcutContext(Qt.WidgetWithChildrenShortcut) actions.append(select_curves) if self.saving_enabled: save_graph = QAction( "Save graph", self, triggered=self.save_graph, ) save_graph.setShortcuts([QKeySequence(Qt.ControlModifier | Qt.Key_S)]) actions.append(save_graph) range_menu = MenuFocus("Define view range", self) range_action = QWidgetAction(self) layout = QGridLayout() range_box = gui.widgetBox(self, margin=5, orientation=layout) range_box.setFocusPolicy(Qt.TabFocus) self.range_e_x1 = lineEditFloatOrNone(None, self, "range_x1", label="e") range_box.setFocusProxy(self.range_e_x1) self.range_e_x2 = lineEditFloatOrNone(None, self, "range_x2", label="e") layout.addWidget(QLabel("X"), 0, 0, Qt.AlignRight) layout.addWidget(self.range_e_x1, 0, 1) layout.addWidget(QLabel("-"), 0, 2) layout.addWidget(self.range_e_x2, 0, 3) self.range_e_y1 = lineEditFloatOrNone(None, self, "range_y1", label="e") self.range_e_y2 = lineEditFloatOrNone(None, self, "range_y2", label="e") layout.addWidget(QLabel("Y"), 1, 0, Qt.AlignRight) layout.addWidget(self.range_e_y1, 1, 1) layout.addWidget(QLabel("-"), 1, 2) layout.addWidget(self.range_e_y2, 1, 3) b = gui.button(None, self, "Apply", callback=self.set_limits) layout.addWidget(b, 2, 3, Qt.AlignRight) range_action.setDefaultWidget(range_box) range_menu.addAction(range_action) layout = QGridLayout() self.plotview.setLayout(layout) self.button = QPushButton("View", self.plotview) self.button.setAutoDefault(False) layout.setRowStretch(1, 1) layout.setColumnStretch(1, 1) layout.addWidget(self.button, 0, 0) view_menu = MenuFocus(self) self.button.setMenu(view_menu) view_menu.addActions(actions) view_menu.addMenu(range_menu) self.addActions(actions) choose_color_action = QWidgetAction(self) choose_color_box = gui.hBox(self) choose_color_box.setFocusPolicy(Qt.TabFocus) model = VariableListModel() self.attrs = [] model.wrap(self.attrs) label = gui.label(choose_color_box, self, "Color by") label.setAlignment(Qt.AlignRight | Qt.AlignVCenter) self.attrCombo = gui.comboBox( choose_color_box, self, value="color_attr", contentsLength=12, callback=self.update_view) self.attrCombo.setModel(model) choose_color_box.setFocusProxy(self.attrCombo) choose_color_action.setDefaultWidget(choose_color_box) view_menu.addAction(choose_color_action) cycle_colors = QShortcut(Qt.Key_C, self, self.cycle_color_attr, context=Qt.WidgetWithChildrenShortcut) labels_action = QWidgetAction(self) layout = QGridLayout() labels_box = gui.widgetBox(self, margin=0, orientation=layout) t = gui.lineEdit(None, self, "label_title", label="Title:", callback=self.labels_changed, callbackOnType=self.labels_changed) layout.addWidget(QLabel("Title:"), 0, 0, Qt.AlignRight) layout.addWidget(t, 0, 1) t = gui.lineEdit(None, self, "label_xaxis", label="X-axis:", callback=self.labels_changed, callbackOnType=self.labels_changed) layout.addWidget(QLabel("X-axis:"), 1, 0, Qt.AlignRight) layout.addWidget(t, 1, 1) t = gui.lineEdit(None, self, "label_yaxis", label="Y-axis:", callback=self.labels_changed, callbackOnType=self.labels_changed) layout.addWidget(QLabel("Y-axis:"), 2, 0, Qt.AlignRight) layout.addWidget(t, 2, 1) labels_action.setDefaultWidget(labels_box) view_menu.addAction(labels_action) self.labels_changed() # apply saved labels self.invertX_apply() self.plot.vb.set_mode_panning() self.reports = {} # current reports self.viewhelpers_show()