def __init__(self): super().__init__() self.data = None self.learner = None self.preprocessor = None self.classifier = None gui.lineEdit(self.controlArea, self, 'model_name', box='Name', tooltip='The name will identify this model in other ' 'widgets') gui.comboBox(self.controlArea, self, "attribute_score", box='Feature selection', items=[name for name, _ in self.scores]) box = gui.widgetBox(self.controlArea, 'Pruning') gui.spin(box, self, "min_leaf", 1, 1000, label="Min. instances in leaves ", checked="limit_min_leaf") gui.spin(box, self, "min_internal", 1, 1000, label="Stop splitting nodes with less instances than ", checked="limit_min_internal") gui.spin(box, self, "max_depth", 1, 1000, label="Limit the depth to ", checked="limit_depth") self.btn_apply = gui.button(self.controlArea, self, "&Apply", callback=self.set_learner, disabled=0, default=True) gui.rubber(self.controlArea) self.resize(100, 100) self.set_learner()
def __init__(self): super().__init__() self.data = None self.feature_model = DomainModel(valid_types=DiscreteVariable) self.table = None box = gui.vBox(self.controlArea, "Rows") gui.comboBox(box, self, 'rows', sendSelectedValue=True, model=self.feature_model, callback=self._attribute_changed) box = gui.vBox(self.controlArea, "Columns") gui.comboBox(box, self, 'columns', sendSelectedValue=True, model=self.feature_model, callback=self._attribute_changed) gui.rubber(self.controlArea) box = gui.vBox(self.controlArea, "Scores") self.scores = gui.widgetLabel(box, "\n\n") self.apply_button = gui.auto_commit( self.controlArea, self, "auto_apply", "&Apply", box=False) self.tableview = ContingencyTable(self) self.mainArea.layout().addWidget(self.tableview)
def __init__(self): super().__init__() self.data = None self.discrete_data = None self.unprocessed_subset_data = None self.subset_data = None self.areas = [] self.canvas = QGraphicsScene() self.canvas_view = ViewWithPress(self.canvas, handler=self.clear_selection) self.mainArea.layout().addWidget(self.canvas_view) self.canvas_view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.canvas_view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.canvas_view.setRenderHint(QPainter.Antialiasing) box = gui.vBox(self.controlArea, box=True) self.attr_combos = [ gui.comboBox( box, self, value="variable{}".format(i), orientation=Qt.Horizontal, contentsLength=12, callback=self.reset_graph, sendSelectedValue=True, valueType=str) for i in range(1, 5)] self.rb_colors = gui.radioButtonsInBox( self.controlArea, self, "interior_coloring", self.interior_coloring_opts, box="Interior Coloring", callback=self.update_graph) self.bar_button = gui.checkBox( gui.indentedBox(self.rb_colors), self, 'use_boxes', label='Compare with total', callback=self._compare_with_total) gui.rubber(self.controlArea)
def __init__(self): super().__init__() # sets self.curvePoints, self.steps equidistant points from # 1/self.steps to 1 self.updateCurvePoints() # [start-snippet-2] self.scoring = [ ("Classification Accuracy", Orange.evaluation.scoring.CA), ("AUC", Orange.evaluation.scoring.AUC), ("Precision", Orange.evaluation.scoring.Precision), ("Recall", Orange.evaluation.scoring.Recall) ] # [end-snippet-2] #: input data on which to construct the learning curve self.data = None #: A {input_id: Learner} mapping of current learners from input channel self.learners = OrderedDict() #: A {input_id: List[Results]} mapping of input id to evaluation #: results list, one for each curve point self.results = OrderedDict() #: A {input_id: List[float]} mapping of input id to learning curve #: point scores self.curves = OrderedDict() # GUI box = gui.widgetBox(self.controlArea, "Info") self.infoa = gui.widgetLabel(box, 'No data on input.') self.infob = gui.widgetLabel(box, 'No learners.') gui.separator(self.controlArea) box = gui.widgetBox(self.controlArea, "Evaluation Scores") gui.comboBox(box, self, "scoringF", items=[x[0] for x in self.scoring], callback=self._invalidate_curves) gui.separator(self.controlArea) box = gui.widgetBox(self.controlArea, "Options") gui.spin(box, self, 'folds', 2, 100, step=1, label='Cross validation folds: ', keyboardTracking=False, callback=lambda: self._invalidate_results() if self.commitOnChange else None ) gui.spin(box, self, 'steps', 2, 100, step=1, label='Learning curve points: ', keyboardTracking=False, callback=[self.updateCurvePoints, lambda: self._invalidate_results() if self.commitOnChange else None]) gui.checkBox(box, self, 'commitOnChange', 'Apply setting on any change') self.commitBtn = gui.button(box, self, "Apply Setting", callback=self._invalidate_results, disabled=True) gui.rubber(self.controlArea) # table widget self.table = gui.table(self.mainArea, selectionMode=QTableWidget.NoSelection)
def __init__(self): super().__init__() self.data = None self.removedAttrs = "-" self.reducedAttrs = "-" self.resortedAttrs = "-" self.removedClasses = "-" self.reducedClasses = "-" self.resortedClasses = "-" boxAt = gui.vBox(self.controlArea, "Features") for not_first, (value, label) in enumerate(self.feature_options): if not_first: gui.separator(boxAt, 2) gui.checkBox(boxAt, self, value, label, callback=self.optionsChanged) boxAt = gui.vBox(self.controlArea, "Classes", addSpace=True) for not_first, (value, label) in enumerate(self.class_options): if not_first: gui.separator(boxAt, 2) gui.checkBox(boxAt, self, value, label, callback=self.optionsChanged) box3 = gui.vBox(self.controlArea, 'Statistics', addSpace=True) for label, value in self.stat_labels: gui.label(box3, self, "{}: %({})s".format(label, value)) gui.auto_commit(self.buttonsArea, self, "autoSend", "Send Data", checkbox_label="Send automatically", orientation=Qt.Horizontal) gui.rubber(self.controlArea)
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.widgetBox(self.mainArea, boxCaption) box = gui.widgetBox(buttBox, orientation="horizontal") 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.widgetBox(buttBox, "Pass-through colors", orientation="horizontal") 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 __init__(self): super().__init__() self.data = None self.db = None box = gui.widgetBox(self.controlArea, "Parameters") gui.spin(box, self, "min_samples", 1, 100, 1, callback=self._invalidate, label="Core point neighbors") gui.doubleSpin(box, self, "eps", 0.1, 0.9, 0.1, callback=self._invalidate, label="Neighborhood distance") box = gui.widgetBox(self.controlArea, self.tr("Distance Metric")) gui.comboBox(box, self, "metric_idx", items=list(zip(*self.METRICS))[0], callback=self._invalidate) box = gui.widgetBox(self.controlArea, "Output") gui.comboBox(box, self, "place_cluster_ids", label="Append cluster id as ", orientation="horizontal", callback=self.send_data, items=self.OUTPUT_METHODS) gui.lineEdit(box, self, "output_name", label="Name: ", orientation="horizontal", callback=self.send_data) gui.auto_commit(self.controlArea, self, "auto_run", "Run", checkbox_label="Run after any change ", orientation="horizontal") gui.rubber(self.controlArea) self.controlArea.setMinimumWidth(self.controlArea.sizeHint().width()) self.layout().setSizeConstraint(QtGui.QLayout.SetFixedSize)
def __init__(self): super().__init__() self.data = None self._effective_data = None self._matrix = None self._silhouette = None self._labels = None self._silplot = None gui.comboBox( self.controlArea, self, "distance_idx", box="Distance", items=[name for name, _ in OWSilhouettePlot.Distances], orientation=Qt.Horizontal, callback=self._invalidate_distances) box = gui.vBox(self.controlArea, "Cluster Label") self.cluster_var_cb = gui.comboBox( box, self, "cluster_var_idx", addSpace=4, callback=self._invalidate_scores) gui.checkBox( box, self, "group_by_cluster", "Group by cluster", callback=self._replot) self.cluster_var_model = itemmodels.VariableListModel(parent=self) self.cluster_var_cb.setModel(self.cluster_var_model) box = gui.vBox(self.controlArea, "Bars") gui.widgetLabel(box, "Bar width:") gui.hSlider( box, self, "bar_size", minValue=1, maxValue=10, step=1, callback=self._update_bar_size, addSpace=6) gui.widgetLabel(box, "Annotations:") self.annotation_cb = gui.comboBox( box, self, "annotation_var_idx", callback=self._update_annotations) self.annotation_var_model = itemmodels.VariableListModel(parent=self) self.annotation_var_model[:] = ["None"] self.annotation_cb.setModel(self.annotation_var_model) ibox = gui.indentedBox(box, 5) self.ann_hidden_warning = warning = gui.widgetLabel( ibox, "(increase the width to show)") ibox.setFixedWidth(ibox.sizeHint().width()) warning.setVisible(False) gui.rubber(self.controlArea) gui.separator(self.buttonsArea) box = gui.vBox(self.buttonsArea, "Output") # Thunk the call to commit to call conditional commit gui.checkBox(box, self, "add_scores", "Add silhouette scores", callback=lambda: self.commit()) gui.auto_commit( box, self, "auto_commit", "Commit", auto_label="Auto commit", box=False) # Ensure that the controlArea is not narrower than buttonsArea self.controlArea.layout().addWidget(self.buttonsArea) self.scene = QtGui.QGraphicsScene() self.view = QtGui.QGraphicsView(self.scene) self.view.setRenderHint(QtGui.QPainter.Antialiasing, True) self.view.setAlignment(Qt.AlignTop | Qt.AlignLeft) self.mainArea.layout().addWidget(self.view)
def __init__(self): super().__init__() # options box self.options_box = gui.widgetBox(self.controlArea, "Data") opts = dict( widget=self.options_box, master=self, orientation=Qt.Horizontal, callback=self.restart, sendSelectedValue=True, maximumContentsLength=15) self.cbx = gui.comboBox(value='attr_x', label='X: ', **opts) self.cby = gui.comboBox(value='attr_y', label='Y: ', **opts) self.centroids_box = gui.widgetBox(self.controlArea, "Centroids") self.centroid_numbers_spinner = gui.spin( self.centroids_box, self, 'number_of_clusters', minv=1, maxv=10, step=1, label='Number of centroids:', alignment=Qt.AlignRight, callback=self.number_of_clusters_change) self.restart_button = gui.button( self.centroids_box, self, "Randomize Positions", callback=self.restart) gui.separator(self.centroids_box) self.lines_checkbox = gui.checkBox( self.centroids_box, self, 'lines_to_centroids', 'Show membership lines', callback=self.complete_replot) # control box gui.separator(self.controlArea, 20, 20) self.step_box = gui.widgetBox(self.controlArea, "Manually step through") self.step_button = gui.button( self.step_box, self, self.STEP_BUTTONS[1], callback=self.step) self.step_back_button = gui.button( self.step_box, self, "Step Back", callback=self.step_back) self.run_box = gui.widgetBox(self.controlArea, "Run") self.auto_play_speed_spinner = gui.hSlider( self.run_box, self, 'auto_play_speed', label='Speed:', minValue=0, maxValue=1.91, step=0.1, intOnly=False, createLabel=False) self.auto_play_button = gui.button( self.run_box, self, self.AUTOPLAY_BUTTONS[0], callback=self.auto_play) gui.rubber(self.controlArea) # disable until data loaded self.set_disabled_all(True) # graph in mainArea self.scatter = Scatterplot( click_callback=self.graph_clicked, drop_callback=self.centroid_dropped, xAxis_gridLineWidth=0, yAxis_gridLineWidth=0, tooltip_enabled=False, debug=False) # Just render an empty chart so it shows a nice 'No data to display' self.scatter.chart() self.mainArea.layout().addWidget(self.scatter)
def __init__(self): self.data = None self.indices = [] box = gui.vBox(self.controlArea, 'Axes') self.combo_ax2 = gui.comboBox( box, self, 'ax2', label='Y axis:', callback=self.replot, sendSelectedValue=True, orientation='horizontal') self.combo_ax1 = gui.comboBox( box, self, 'ax1', label='Radial:', callback=self.replot, sendSelectedValue=True, orientation='horizontal') box = gui.vBox(self.controlArea, 'Aggregation') self.combo_func = gui.comboBox( box, self, 'agg_func', label='Function:', orientation='horizontal', callback=self.replot) func_model = ListModel(AGG_FUNCTIONS, parent=self) self.combo_func.setModel(func_model) self.attrlist_model = VariableListModel(parent=self) self.attrlist = QListView(selectionMode=QListView.ExtendedSelection) self.attrlist.setModel(self.attrlist_model) self.attrlist.selectionModel().selectionChanged.connect( self.attrlist_selectionChanged) box.layout().addWidget(self.attrlist) gui.rubber(self.controlArea) self.chart = chart = Spiralogram(self, selection_callback=self.on_selection) self.mainArea.layout().addWidget(chart)
def __init__(self): self.setFixedWidth(400) self.setFixedHeight(220) left_box_1 = ShadowGui.widgetBox(self.controlArea, "Loop Management", addSpace=True, orientation="vertical", width=370, height=100) ShadowGui.lineEdit(left_box_1, self, "number_of_new_beams", "Number of new Beams", labelWidth=250, valueType=int, orientation="horizontal") self.le_current_new_beam = ShadowGui.lineEdit(left_box_1, self, "current_new_beam", "Current New Beam", labelWidth=250, valueType=int, orientation="horizontal") self.le_current_new_beam.setReadOnly(True) font = QtGui.QFont(self.le_current_new_beam.font()) font.setBold(True) self.le_current_new_beam.setFont(font) palette = QtGui.QPalette(self.le_current_new_beam.palette()) # make a copy of the palette palette.setColor(QtGui.QPalette.Text, QtGui.QColor('dark blue')) palette.setColor(QtGui.QPalette.Base, QtGui.QColor(243, 240, 160)) self.le_current_new_beam.setPalette(palette) button_box = gui.widgetBox(self.controlArea, "", addSpace=True, orientation="horizontal") self.start_button = gui.button(button_box, self, "Start Loop", callback=self.startLoop) self.start_button.setFixedHeight(45) stop_button = gui.button(button_box, self, "Interrupt", callback=self.stopLoop) stop_button.setFixedHeight(45) font = QtGui.QFont(stop_button.font()) font.setBold(True) stop_button.setFont(font) palette = QtGui.QPalette(stop_button.palette()) # make a copy of the palette palette.setColor(QtGui.QPalette.ButtonText, QtGui.QColor('red')) stop_button.setPalette(palette) # assign new palette gui.rubber(self.controlArea)
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 restoreWidgetPosition(self): super().restoreWidgetPosition() self.table = QTableWidget(self.harmonic_maximum_index + 1, 3) self.table.setAlternatingRowColors(True) self.table.horizontalHeader().setResizeMode(QHeaderView.Fixed) for i in range(0, 3): self.table.setColumnWidth(i, 70) horHeaders = [] verHeaders = [] for n, key in enumerate(sorted(self.data.keys())): horHeaders.append(key) for m, item in enumerate(self.data[key]): table_item = QTableWidgetItem(str(item)) table_item.setTextAlignment(Qt.AlignRight) self.table.setItem(m, n, table_item) verHeaders.append(str(m)) self.table.setHorizontalHeaderLabels(horHeaders) self.table.setVerticalHeaderLabels(verHeaders) self.table.resizeRowsToContents() self.table.itemChanged.connect(self.table_item_changed) self.scrollarea.setWidget(self.table) self.scrollarea.setWidgetResizable(1) gui.rubber(self.controlArea)
def __init__(self, parent=None): super().__init__(parent) self.train_data = None self.test_data = None #: An Ordered dictionary with current inputs and their testing #: results. self.learners = OrderedDict() sbox = gui.widgetBox(self.controlArea, "Sampling") rbox = gui.radioButtons( sbox, self, "resampling", callback=self._param_changed ) gui.appendRadioButton(rbox, "Cross validation") ibox = gui.indentedBox(rbox) gui.spin(ibox, self, "k_folds", 2, 50, label="Number of folds:", callback=self.kfold_changed) gui.appendRadioButton(rbox, "Leave one out") gui.appendRadioButton(rbox, "Random sampling") ibox = gui.indentedBox(rbox) gui.spin(ibox, self, "n_repeat", 2, 50, label="Repeat train/test", callback=self.bootstrap_changed) gui.widgetLabel(ibox, "Relative training set size:") gui.hSlider(ibox, self, "sample_p", minValue=1, maxValue=100, ticks=20, vertical=False, labelFormat="%d %%", callback=self.bootstrap_changed) gui.appendRadioButton(rbox, "Test on train data") gui.appendRadioButton(rbox, "Test on test data") rbox.layout().addSpacing(5) gui.button(rbox, self, "Apply", callback=self.apply) self.cbox = gui.widgetBox(self.controlArea, "Target class") self.class_selection_combo = gui.comboBox(self.cbox, self, "class_selection", items=[], callback=self._select_class, sendSelectedValue=True, valueType=str) gui.rubber(self.controlArea) self.view = QTreeView( rootIsDecorated=False, uniformRowHeights=True, wordWrap=True, editTriggers=QTreeView.NoEditTriggers ) header = self.view.header() header.setResizeMode(QHeaderView.ResizeToContents) header.setDefaultAlignment(Qt.AlignCenter) header.setStretchLastSection(False) self.result_model = QStandardItemModel() self.view.setModel(self.result_model) self.view.setItemDelegate(ItemDelegate()) self._update_header() box = gui.widgetBox(self.mainArea, "Evaluation Results") box.layout().addWidget(self.view)
def __init__(self): super().__init__() box0 = gui.widgetBox(self.controlArea, " ",orientation="horizontal") #widget buttons: compute, set defaults, help gui.button(box0, self, "Compute", callback=self.compute) gui.button(box0, self, "Defaults", callback=self.defaults) gui.button(box0, self, "Help", callback=self.help1) self.process_showers() box = gui.widgetBox(self.controlArea, " ",orientation="vertical") idx = -1 #widget index 0 idx += 1 box1 = gui.widgetBox(box) gui.lineEdit(box1, self, "energyMin", label=self.unitLabels()[idx], addSpace=True, valueType=float, validator=QDoubleValidator()) self.show_at(self.unitFlags()[idx], box1) #widget index 1 idx += 1 box1 = gui.widgetBox(box) gui.lineEdit(box1, self, "energyMax", label=self.unitLabels()[idx], addSpace=True, valueType=float, validator=QDoubleValidator()) self.show_at(self.unitFlags()[idx], box1) self.process_showers() gui.rubber(self.controlArea)
def __init__(self): super().__init__() self.data = None self.component_x = 0 self.component_y = 1 box = gui.vBox(self.controlArea, "Variables") self.varlist = itemmodels.VariableListModel() self.varview = view = QListView(selectionMode=QListView.MultiSelection) view.setModel(self.varlist) view.selectionModel().selectionChanged.connect(self._var_changed) box.layout().addWidget(view) axes_box = gui.vBox(self.controlArea, "Axes") box = gui.vBox(axes_box, "Axis X", margin=0) box.setFlat(True) self.axis_x_cb = gui.comboBox( box, self, "component_x", callback=self._component_changed) box = gui.vBox(axes_box, "Axis Y", margin=0) box.setFlat(True) self.axis_y_cb = gui.comboBox( box, self, "component_y", callback=self._component_changed) self.infotext = gui.widgetLabel( gui.vBox(self.controlArea, "Contribution to Inertia"), "\n" ) gui.rubber(self.controlArea) self.plot = pg.PlotWidget(background="w") self.plot.setMenuEnabled(False) self.mainArea.layout().addWidget(self.plot)
def __init__(self): super().__init__() dbox = gui.widgetBox(self.controlArea, "Image values") rbox = gui.radioButtons( dbox, self, "value_type", callback=self._change_integration) gui.appendRadioButton(rbox, "From spectra") self.box_values_spectra = gui.indentedBox(rbox) gui.comboBox( self.box_values_spectra, self, "integration_method", valueType=int, items=(a.name for a in self.integration_methods), callback=self._change_integral_type) gui.rubber(self.controlArea) gui.appendRadioButton(rbox, "Use feature") self.box_values_feature = gui.indentedBox(rbox) self.feature_value_model = DomainModel(DomainModel.METAS | DomainModel.CLASSES, valid_types=DomainModel.PRIMITIVE) self.feature_value = gui.comboBox( self.box_values_feature, self, "attr_value", callback=self.update_feature_value, model=self.feature_value_model, sendSelectedValue=True, valueType=str) splitter = QSplitter(self) splitter.setOrientation(Qt.Vertical) self.imageplot = ImagePlot(self) self.imageplot.selection_changed.connect(self.output_image_selection) self.curveplot = CurvePlotHyper(self, select=SELECTONE) self.curveplot.selection_changed.connect(self.redraw_data) self.curveplot.plot.vb.x_padding = 0.005 # pad view so that lines are not hidden splitter.addWidget(self.imageplot) splitter.addWidget(self.curveplot) self.mainArea.layout().addWidget(splitter) self.line1 = MovableVline(position=self.lowlim, label="", report=self.curveplot) self.line1.sigMoved.connect(lambda v: setattr(self, "lowlim", v)) self.line2 = MovableVline(position=self.highlim, label="", report=self.curveplot) self.line2.sigMoved.connect(lambda v: setattr(self, "highlim", v)) self.line3 = MovableVline(position=self.choose, label="", report=self.curveplot) self.line3.sigMoved.connect(lambda v: setattr(self, "choose", v)) for line in [self.line1, self.line2, self.line3]: line.sigMoveFinished.connect(self.changed_integral_range) self.curveplot.add_marking(line) line.hide() self.data = None self.disable_integral_range = False self.resize(900, 700) self._update_integration_type() # prepare interface according to the new context self.contextAboutToBeOpened.connect(lambda x: self.init_interface_data(x[0]))
def _add_controls(self): infobox = gui.widgetBox(self.controlArea, "Info") self.infoLabel = gui.widgetLabel(infobox, "No data on input.") displaybox = gui.widgetBox(self.controlArea, "Display") gui.checkBox(displaybox, self, "show_profiles", "Lines", callback=self.__show_profiles_changed, tooltip="Plot lines") gui.checkBox(displaybox, self, "show_range", "Range", callback=self.__show_range_changed, tooltip="Plot range between 10th and 90th percentile") gui.checkBox(displaybox, self, "show_mean", "Mean", callback=self.__show_mean_changed, tooltip="Plot mean curve") gui.checkBox(displaybox, self, "show_error", "Error bars", callback=self.__show_error_changed, tooltip="Show standard deviation") self.group_vars = DomainModel( placeholder="None", separators=False, valid_types=DiscreteVariable) self.group_view = gui.listView( self.controlArea, self, "group_var", box="Group by", model=self.group_vars, callback=self.__group_var_changed) self.group_view.setEnabled(False) self.group_view.setMinimumSize(QSize(30, 100)) self.group_view.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Ignored) plot_gui = OWPlotGUI(self) plot_gui.box_zoom_select(self.controlArea) gui.rubber(self.controlArea) gui.auto_commit(self.controlArea, self, "auto_commit", "Send Selection", "Send Automatically")
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, parent=None): super().__init__(parent) # GUI box = gui.widgetBox(self.controlArea, "Info", addSpace=True) self.infoBox = gui.widgetLabel(box, "No data on input.") box = gui.widgetBox(self.controlArea, "Split by", addSpace=True) self.groupCombo = gui.comboBox( box, self, "selectedGroup", callback=self.onGroupSelection) gui.comboBox(self.controlArea, self, "selectedCenterMethod", box="Center Fold-change Using", items=[name for name, _ in self.CENTER_METHODS], callback=self.onCenterMethodChange, addSpace=True) gui.comboBox(self.controlArea, self, "selectedMergeMethod", box="Merge Replicates", items=[name for name, _ in self.MERGE_METHODS], tooltip="Select the method for replicate merging", callback=self.onMergeMethodChange, addSpace=True) box = gui.doubleSpin(self.controlArea, self, "zCutoff", 0.0, 3.0, 0.01, box="Z-Score Cutoff", callback=[self.replotMA, self.commitIf]) gui.separator(self.controlArea) box = gui.widgetBox(self.controlArea, "Ouput") gui.checkBox(box, self, "appendZScore", "Append Z-Scores", tooltip="Append calculated Z-Scores to output", callback=self.commitIf) gui.checkBox(box, self, "appendRIValues", "Append Log Ratio and Intensity values", tooltip="Append calculated Log Ratio and Intensity " "values to output data", callback=self.commitIf) gui.rubber(self.controlArea) gui.auto_commit(self.controlArea, self, "autoCommit", "Commit") self.graph = pg.PlotWidget(background="w") self.graph.getAxis("bottom").setLabel("Intensity: log<sub>10</sub>(R*G)") self.graph.getAxis("left").setLabel("Log ratio: log<sub>2</sub>(R/G)") self.mainArea.layout().addWidget(self.graph) self.groups = [] self.split_data = None, None self.merged_splits = None, None self.centered = None, None self.changedFlag = False self.data = None self._executor = concurrent.ThreadExecutor( threadPool=QThreadPool(maxThreadCount=1))
def __init__(self): super().__init__() self.data = {} # key: id, value: ExampleTable self.dist_color = QtGui.QColor(*self.dist_color_RGB) self.locale = QtCore.QLocale() info_box = gui.widgetBox(self.controlArea, "Info") self.info_ex = gui.widgetLabel(info_box, 'No data on input.', ) self.info_ex.setWordWrap(True) self.info_attr = gui.widgetLabel(info_box, ' ') self.info_attr.setWordWrap(True) self.info_class = gui.widgetLabel(info_box, ' ') self.info_class.setWordWrap(True) self.info_meta = gui.widgetLabel(info_box, ' ') self.info_meta.setWordWrap(True) gui.separator(info_box) gui.button(info_box, self, "Restore Original Order", callback=self.reset_sort_clicked, tooltip="Show rows in the original order") info_box.setMinimumWidth(200) gui.separator(self.controlArea) box = gui.widgetBox(self.controlArea, "Variables") self.c_show_attribute_labels = gui.checkBox( box, self, "show_attribute_labels", "Show variable labels (if present)", callback=self.c_show_attribute_labels_clicked) self.c_show_attribute_labels.setEnabled(True) gui.checkBox(box, self, "show_distributions", 'Visualize continuous values', callback=self.cb_show_distributions) gui.checkBox(box, self, "color_by_class", 'Color by instance classes', callback=self.cb_show_distributions) gui.button(box, self, "Set colors", self.set_colors, tooltip="Set the background color and color palette") gui.separator(self.controlArea) selection_box = gui.widgetBox(self.controlArea, "Selection") self.send_button = gui.button(selection_box, self, "Send selections", self.commit, default=True) cb = gui.checkBox(selection_box, self, "auto_commit", "Commit on any change", callback=self.commit_if) gui.setStopper(self, self.send_button, cb, "selectionChangedFlag", self.commit) gui.rubber(self.controlArea) dlg = self.create_color_dialog() self.discPalette = dlg.getDiscretePalette("discPalette") # GUI with tabs self.tabs = gui.tabWidget(self.mainArea) self.tabs.sizeHint = lambda: QtCore.QSize(600,500) self.id2table = {} # key: widget id, value: table self.table2id = {} # key: table, value: widget id self.tabs.currentChanged.connect(self.tab_clicked) self.selectionChangedFlag = False
def __init__(self, parent=None): super().__init__(parent) self.inputs = OrderedDict() self.dist_color = QtGui.QColor(*self.dist_color_RGB) info_box = gui.widgetBox(self.controlArea, "Info") self.info_ex = gui.widgetLabel(info_box, 'No data on input.', ) self.info_ex.setWordWrap(True) self.info_attr = gui.widgetLabel(info_box, ' ') self.info_attr.setWordWrap(True) self.info_class = gui.widgetLabel(info_box, ' ') self.info_class.setWordWrap(True) self.info_meta = gui.widgetLabel(info_box, ' ') self.info_meta.setWordWrap(True) gui.separator(info_box) gui.button(info_box, self, "Restore Original Order", callback=self.restore_order, tooltip="Show rows in the original order", autoDefault=False) info_box.setMinimumWidth(200) gui.separator(self.controlArea) box = gui.widgetBox(self.controlArea, "Variables") self.c_show_attribute_labels = gui.checkBox( box, self, "show_attribute_labels", "Show variable labels (if present)", callback=self._on_show_variable_labels_changed) gui.checkBox(box, self, "show_distributions", 'Visualize continuous values', callback=self._on_distribution_color_changed) gui.checkBox(box, self, "color_by_class", 'Color by instance classes', callback=self._on_distribution_color_changed) gui.button(box, self, "Set colors", self.set_colors, autoDefault=False, tooltip="Set the background color and color palette") box = gui.widgetBox(self.controlArea, "Selection") gui.checkBox(box, self, "select_rows", "Select full rows", callback=self._on_select_rows_changed) gui.rubber(self.controlArea) gui.auto_commit(self.controlArea, self, "auto_commit", "Send Selected Rows", "Auto send is on") dlg = self.create_color_dialog() self.discPalette = dlg.getDiscretePalette("discPalette") # GUI with tabs self.tabs = gui.tabWidget(self.mainArea) self.tabs.currentChanged.connect(self._on_current_tab_changed) copy = QtGui.QAction("Copy", self, shortcut=QtGui.QKeySequence.Copy, triggered=self.copy) self.addAction(copy)
def __init__(self, parent=None): super().__init__(parent) self.data = None self.preRemoveValues = 1 self.preRemoveClasses = 1 self.removedAttrs = "-" self.reducedAttrs = "-" self.resortedAttrs = "-" self.classAttr = "-" boxAt = gui.widgetBox(self.controlArea, "Attributes") gui.checkBox(boxAt, self, 'sortValues', 'Sort attribute values', callback=self.optionsChanged) gui.separator(boxAt, 2) rua = gui.checkBox( boxAt, self, "removeAttributes", "Remove attributes with less than two values", callback=self.removeAttributesChanged) ruv = gui.checkBox( gui.indentedBox(boxAt, sep=gui.checkButtonOffsetHint(rua)), self, "removeValues", "Remove unused attribute values", callback=self.optionsChanged ) rua.disables = [ruv] rua.makeConsistent() boxAt = gui.widgetBox(self.controlArea, "Classes", addSpace=True) gui.checkBox(boxAt, self, 'sortClasses', 'Sort classes', callback=self.optionsChanged) gui.separator(boxAt, 2) rua = gui.checkBox( boxAt, self, "removeClassAttribute", "Remove class attribute if there are less than two classes", callback=self.removeClassesChanged ) ruv = gui.checkBox( gui.indentedBox(boxAt, sep=gui.checkButtonOffsetHint(rua)), self, "removeClasses", "Remove unused class values", callback=self.optionsChanged ) rua.disables = [ruv] rua.makeConsistent() box3 = gui.widgetBox(self.controlArea, 'Statistics', addSpace=True) gui.label(box3, self, "Removed attributes: %(removedAttrs)s") gui.label(box3, self, "Reduced attributes: %(reducedAttrs)s") gui.label(box3, self, "Resorted attributes: %(resortedAttrs)s") gui.label(box3, self, "Class attribute: %(classAttr)s") gui.auto_commit(self.controlArea, self, "autoSend", "Send Data", checkbox_label="Send automatically", orientation="horizontal") gui.rubber(self.controlArea)
def __init__(self): super().__init__() self.data = None self.groups = None self.CVSettings = (self.stratified, self.numberOfFolds) infoBox = gui.widgetBox(self.controlArea, "Information") self.dataInfoLabel = gui.widgetLabel(infoBox, 'No data on input.') self.outputInfoLabel = gui.widgetLabel(infoBox, ' ') optionsBox = gui.widgetBox(self.controlArea, "Options") le = gui.lineEdit(optionsBox, self, "randomSeed", "Random seed: ", orientation=0, controlWidth=60, validator=QtGui.QIntValidator()) s = le.sizeHint().height() - 2 b = gui.toolButton(le.box, self, width=s, height=s, callback=lambda: le.setText("")) b.setIcon(b.style().standardIcon(b.style().SP_DialogCancelButton)) gui.rubber(le.box) gui.checkBox(optionsBox, self, "stratified", "Stratified, if possible") sampling = gui.radioButtons( self.controlArea, self, "samplingType", box="Sampling type", addSpace=True) gui.appendRadioButton(sampling, "Random Sampling:") indRndSmpl = gui.indentedBox(sampling) sizeType = gui.radioButtons( indRndSmpl, self, "sampleSizeType", callback=lambda: self.chooseSampling(0)) gui.appendRadioButton(sizeType, "Sample size:", insertInto=indRndSmpl) self.sampleSizeSpin = gui.spin( gui.indentedBox(indRndSmpl), self, "sampleSizeNumber", 1, 1000000000, callback=[lambda: self.chooseSampling(0), lambda: self.chooseSizeType(0)]) gui.appendRadioButton(sizeType, "Sample proportions:", insertInto=indRndSmpl) gui.hSlider(gui.indentedBox(indRndSmpl), self, "sampleSizePercentage", minValue=1, maxValue=100, ticks=10, labelFormat="%d%%", callback=[lambda: self.chooseSampling(0), lambda: self.chooseSizeType(1)]) gui.appendRadioButton(sampling, "Cross Validation:") crossValidIndent = gui.indentedBox(sampling) gui.spin( crossValidIndent, self, "numberOfFolds", 2, 100, label="Number of folds:", callback=[self.updateSelectedFoldSpin, lambda: self.chooseSampling(1)]) self.selectedFoldSpin = gui.spin( crossValidIndent, self, "selectedFold", 1, 100, label="Selected fold:", callback=[self.updateSelectedFoldSpin, lambda: self.chooseSampling(1)]) gui.button(self.controlArea, self, "Sample Data", callback=self.sendData)
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 _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): graphical_Options=ow_optical_element.GraphicalOptions(is_crystal=True) super().__init__(graphical_Options) gui.rubber(self.controlArea) gui.rubber(self.mainArea)
def __init__(self): graphical_Options = GraphicalOptions(is_screen_slit=True) super().__init__(graphical_Options) gui.rubber(self.controlArea) gui.rubber(self.mainArea)
def __init__(self): super().__init__() self.data = None self.allAttrs = [] self.stringAttrs = [] self.selectedIndices = [] #: List of _ImageItems self.items = [] self._errcount = 0 self._successcount = 0 self.info = gui.widgetLabel( gui.vBox(self.controlArea, "Info"), "Waiting for input.\n" ) self.imageAttrCB = gui.comboBox( self.controlArea, self, "imageAttr", box="Image Filename Attribute", tooltip="Attribute with image filenames", callback=[self.clearScene, self.setupScene], contentsLength=12, addSpace=True, ) self.titleAttrCB = gui.comboBox( self.controlArea, self, "titleAttr", box="Title Attribute", tooltip="Attribute with image title", callback=self.updateTitles, contentsLength=12, addSpace=True ) self.titleAttrCB.setStyleSheet("combobox-popup: 0;") gui.hSlider( self.controlArea, self, "imageSize", box="Image Size", minValue=32, maxValue=1024, step=16, callback=self.updateSize, createLabel=False ) gui.rubber(self.controlArea) gui.auto_commit(self.buttonsArea, self, "autoCommit", "Send", box=False) self.thumbnailView = ThumbnailView( alignment=Qt.AlignTop | Qt.AlignLeft, # scene alignment, focusPolicy=Qt.StrongFocus, verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn ) self.mainArea.layout().addWidget(self.thumbnailView) self.scene = self.thumbnailView.scene() self.scene.selectionChanged.connect(self.onSelectionChanged) self.loader = ImageLoader(self)
def _intbox(widget, attr, callback): box = gui.indentedBox(widget) s = gui.spin( box, self, attr, minv=2, maxv=10, label="Num. of intervals:", callback=callback) s.setMaximumWidth(60) s.setAlignment(Qt.AlignRight) gui.rubber(s.box) return box.box
def __init__(self): self.data = None self.output = None self.onehot_mapping = {} self._is_running = False self._antecedentMatch = self._consequentMatch = lambda x: True self.proxy_model = self.ProxyModel(self) owwidget = self class TableView(QTableView): def selectionChanged(self, selected, deselected): nonlocal owwidget super().selectionChanged(selected, deselected) mapping = owwidget.onehot_mapping if not mapping: return where = np.where X, Y = owwidget.X, owwidget.data.Y instances = set() selected_rows = self.selectionModel().selectedRows(0) for model_index in selected_rows: itemset, class_item = model_index.data( owwidget.ROW_DATA_ROLE) cols, vals = zip(*(mapping[i] for i in itemset)) if issparse(X): matching = (len(cols) == np.bincount( (X[:, cols] != 0).indices, minlength=X.shape[0])).nonzero()[0] else: matching = set( where((X[:, cols] == vals).all(axis=1))[0]) if class_item: matching &= set(where(Y == mapping[class_item][1])[0]) instances.update(matching) owwidget.nSelectedExamples = len(instances) owwidget.nSelectedRules = len(selected_rows) owwidget.output = owwidget.data[sorted(instances)] or None owwidget.commit() table = self.table = TableView( self, showGrid=False, sortingEnabled=True, alternatingRowColors=True, selectionBehavior=QTableView.SelectRows, selectionMode=QTableView.ExtendedSelection, horizontalScrollMode=QTableView.ScrollPerPixel, verticalScrollMode=QTableView.ScrollPerPixel, editTriggers=QTableView.NoEditTriggers) table.verticalHeader().setVisible(False) table.verticalHeader().setDefaultSectionSize( table.verticalHeader().minimumSectionSize()) table.horizontalHeader().setStretchLastSection(True) table.setModel(QStandardItemModel(table)) self.mainArea.layout().addWidget(table) box = gui.widgetBox(self.controlArea, "Info") self.nRules = self.nFilteredRules = self.nSelectedExamples = self.nSelectedRules = '' gui.label(box, self, "Number of rules: %(nRules)s") gui.label(box, self, "Filtered rules: %(nFilteredRules)s") gui.label(box, self, "Selected rules: %(nSelectedRules)s") gui.label(box, self, "Selected examples: %(nSelectedExamples)s") box = gui.widgetBox(self.controlArea, 'Find association rules') gui.valueSlider(box, self, 'minSupport', values=[.0001, .0005, .001, .005, .01, .05, .1, .5] + list(range(1, 101)), label='Minimal support:', labelFormat="%g%%", callback=lambda: self.find_rules()) gui.hSlider(box, self, 'minConfidence', minValue=1, maxValue=100, label='Minimal confidence:', labelFormat="%g%%", callback=lambda: self.find_rules()) gui.hSlider(box, self, 'maxRules', minValue=10000, maxValue=100000, step=10000, label='Max. number of rules:', callback=lambda: self.find_rules()) self.cb_classify = gui.checkBox( box, self, 'classify', label='Induce classification (itemset → class) rules') self.button = gui.auto_commit( box, self, 'autoFind', 'Find Rules', commit=self.find_rules, callback=lambda: self.autoFind and self.find_rules()) vbox = gui.widgetBox(self.controlArea, 'Filter rules') ## This is disabled because it's hard to make a scatter plot with ## selectable spots. Options: ## * PyQtGraph, which doesn't support selection OOTB (+is poorly ## contrived and under-documented); ## * Orange.widgets.visualize.ScatterPlotGraph, which comes without ## any documentation or comprehensible examples of use whatsoever; ## * QGraphicsView, which would work, but lacks graphing features, ## namely labels, axes, ticks. ## ## I don't feel like pursuing any of those right now, so I am letting ## it to be figured out at a later date. #~ button = self.scatter_button = gui.button(vbox, self, 'Scatter plot', #~ callback=self.show_scatter, #~ autoDefault=False) #~ button.setDisabled(True) #~ self.scatter = self.ScatterPlotWindow(self) box = gui.widgetBox(vbox, 'Antecedent') gui.lineEdit(box, self, 'filterKeywordsAntecedent', 'Contains:', callback=self.filter_change, orientation='horizontal', tooltip='A comma or space-separated list of regular ' 'expressions.') hbox = gui.widgetBox(box, orientation='horizontal') gui.spin(hbox, self, 'filterAntecedentMin', 1, 998, label='Min. items:', callback=self.filter_change) gui.spin(hbox, self, 'filterAntecedentMax', 2, 999, label='Max. items:', callback=self.filter_change) gui.rubber(hbox) box = gui.widgetBox(vbox, 'Consequent') gui.lineEdit(box, self, 'filterKeywordsConsequent', 'Contains:', callback=self.filter_change, orientation='horizontal', tooltip='A comma or space-separated list of regular ' 'expressions.') hbox = gui.widgetBox(box, orientation='horizontal') gui.spin(hbox, self, 'filterConsequentMin', 1, 998, label='Min. items:', callback=self.filter_change) gui.spin(hbox, self, 'filterConsequentMax', 2, 999, label='Max. items:', callback=self.filter_change) gui.checkBox(box, self, 'filterSearch', label='Apply these filters in search', tooltip='If checked, the rules are filtered according ' 'to these filter conditions already in the search ' 'phase. \nIf unchecked, the only filters applied ' 'during search are the ones above, ' 'and the generated rules \nare filtered afterwards ' 'only for display, i.e. only the matching association ' 'rules are shown.') gui.rubber(hbox) gui.rubber(self.controlArea) gui.auto_commit(self.controlArea, self, 'autoSend', 'Send selection') self.filter_change()
def __init__(self): """Widget creator.""" super().__init__() if INSTALLED_MODELS: self.model = INSTALLED_MODELS[0] else: self.model = "" # Other attributes... self.inputSeg = None self.nlp = None self.selectedModels = list() self.downloadableModelLabels = list() self.loadedComponents = list() self.mustLoad = True # Next two instructions are helpers from TextableUtils. Corresponding # interface elements are declared here and actually drawn below (at # their position in the UI)... self.infoBox = InfoBox(widget=self.controlArea) self.sendButton = SendButton( widget=self.controlArea, master=self, callback=self.sendData, infoBoxAttribute="infoBox", sendIfPreCallback=None, ) # User interface... # Tabs... self.tabs = QTabWidget() self.optionsTab = QWidget() self.modelManagerTab = QWidget() self.tabs.addTab(self.optionsTab, "Options") self.tabs.addTab(self.modelManagerTab, "Model manager") # Options tab... OptionsTabBox = QHBoxLayout() optionsBox = gui.widgetBox(widget=self.optionsTab) self.modelComboBox = gui.comboBox( widget=optionsBox, master=self, value='model', label='Model: ', tooltip='Select the spaCy language model you want to use.', items=INSTALLED_MODELS[:], sendSelectedValue=True, callback=self.modelComboboxChanged, ) gui.separator(widget=optionsBox, height=3) annotationsBox = gui.widgetBox( widget=optionsBox, box="Additional token annotations:", ) annotationsBoxLine1 = gui.widgetBox( widget=annotationsBox, orientation="horizontal", box=None, ) gui.checkBox( widget=annotationsBoxLine1, master=self, value='annotatePOSTags', label='part-of-speech tags', callback=self.updateDisabledComponents, tooltip=("Annotate output tokens with part-of-speech tags."), ) self.annotatePOSTagsReloadLabel = gui.label( annotationsBoxLine1, master=self, label="(reload needed)", ) self.annotatePOSTagsReloadLabel.setStyleSheet( "font-style: oblique; color: gray") annotationsBoxLine2 = gui.widgetBox( widget=annotationsBox, orientation="horizontal", box=None, ) gui.checkBox( widget=annotationsBoxLine2, master=self, value='annotateDependencies', label='syntactic dependencies', callback=self.updateDisabledComponents, tooltip=("Annotate output tokens with syntactic dependencies."), ) self.annotateDependenciesReloadLabel = gui.label( annotationsBoxLine2, master=self, label="(reload needed)", ) self.annotateDependenciesReloadLabel.setStyleSheet( "font-style: oblique; color: gray") annotationsBoxLine3 = gui.widgetBox( widget=annotationsBox, orientation="horizontal", box=None, ) gui.checkBox( widget=annotationsBoxLine3, master=self, value='annotateEntities', label='named entities', callback=self.updateDisabledComponents, tooltip=("Annotate output tokens with named entities."), ) self.annotateEntitiesReloadLabel = gui.label( annotationsBoxLine3, master=self, label="(reload needed)", ) self.annotateEntitiesReloadLabel.setStyleSheet( "font-style: oblique; color: gray") segmentationsBox = gui.widgetBox( widget=optionsBox, box="Additional segmentations:", ) segmentationsBoxLine1 = gui.widgetBox( widget=segmentationsBox, orientation="horizontal", box=None, ) gui.checkBox( widget=segmentationsBoxLine1, master=self, value='segmentEntities', label='named entities', callback=self.updateDisabledComponents, tooltip="Output named entity segmentation on separate channel.", ) self.segmentEntitiesReloadLabel = gui.label( segmentationsBoxLine1, master=self, label="(reload needed)", ) self.segmentEntitiesReloadLabel.setStyleSheet( "font-style: oblique; color: gray") segmentationsBoxLine2 = gui.widgetBox( widget=segmentationsBox, orientation="horizontal", box=None, ) gui.checkBox( widget=segmentationsBoxLine2, master=self, value='segmentChunks', label='noun chunks', callback=self.updateDisabledComponents, tooltip="Output noun chunk segmentation on separate channel.", ) self.segmentChunksReloadLabel = gui.label( segmentationsBoxLine2, master=self, label="(reload needed)", ) self.segmentChunksReloadLabel.setStyleSheet( "font-style: oblique; color: gray") segmentationsBoxLine3 = gui.widgetBox( widget=segmentationsBox, orientation="horizontal", box=None, ) gui.checkBox( widget=segmentationsBoxLine3, master=self, value='segmentSentences', label='sentences', callback=self.updateDisabledComponents, tooltip="Output sentence segmentation on separate channel.", ) self.segmentSentencesReloadLabel = gui.label( segmentationsBoxLine3, master=self, label="(reload needed)", ) self.segmentSentencesReloadLabel.setStyleSheet( "font-style: oblique; color: gray") self.updateReloadNeededLabels() gui.comboBox( widget=optionsBox, master=self, value='maxLen', items=["1 million"] + ["%i millions" % l for l in range(2, 10)] \ + ["no limit"], sendSelectedValue=True, label=u'Max number of input characters:', tooltip=( "The spaCy parser and NER models require roughly 1GB of\n" "temporary memory per 100'000 characters in the input.\n" "This means long texts may cause memory allocation errors.\n" "If you're not using the parser or NER, or have lots of \n" "RAM, it's probably safe to increase the default limit of\n" "1 million characters." ), ) gui.rubber(optionsBox) OptionsTabBox.addWidget(optionsBox) self.optionsTab.setLayout(OptionsTabBox) # Model manager tab... modelManagerTabBox = QHBoxLayout() modelManagerBox = gui.widgetBox(widget=self.modelManagerTab) gui.label(modelManagerBox, self, label="Available models:") self.downloadableModelsListbox = gui.listBox( widget=modelManagerBox, master=self, value="selectedModels", labels="downloadableModelLabels", callback=self.downloadableModelsListboxChanged, tooltip="Select language models then click Download.", ) self.downloadableModelsListbox.setSelectionMode(3) self.downloadableModelLabels = DOWNLOADABLE_MODELS[:] self.downloadableModelLabels = self.downloadableModelLabels self.downloadButton = gui.button( widget=modelManagerBox, master=self, label="Download", callback=self.downloadModels, tooltip="Download the selected language models.", ) self.downloadButton.setDisabled(True) modelManagerTabBox.addWidget(modelManagerBox) self.modelManagerTab.setLayout(modelManagerTabBox) self.controlArea.layout().addWidget(self.tabs) gui.rubber(self.controlArea) # Now Info box and Send button must be drawn... self.sendButton.draw() self.infoBox.draw() self.infoBox.setText("Widget needs input.", "warning") # Check that there's a model... if not self.model: self.infoBox.setText( "Please download a language model first.", "warning", ) self.tabs.setCurrentIndex(1) optionsBox.setDisabled(True)
def __init__(self): super().__init__() RecentPathsWComboMixin.__init__(self) self.domain = None self.data = None self.loaded_file = "" self.reader = None layout = 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, "文件:", addToLayout=False) layout.addWidget(rb_button, 0, 0, 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(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 = gui.comboBox( None, self, "xls_sheet", callback=self.select_sheet, sendSelectedValue=True, ) self.sheet_combo.setSizePolicy(Policy.MinimumExpanding, Policy.Fixed) 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.MinimumExpanding, 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, 3, 3) url_combo.activated.connect(self._url_set) box = gui.vBox(self.controlArea, "信息") self.info = gui.widgetLabel(box, '没有加载数据。') self.warnings = 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(self.controlArea) gui.button(box, self, "打开数据集", callback=lambda: self.browse_file(True), 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)) 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__() self.data = None self.test_data = None self.preprocessor = None self.train_data_missing_vals = False self.test_data_missing_vals = False self.scorers = [] #: 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[Task] 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], maximumContentsLength=3, 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], maximumContentsLength=3, 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], maximumContentsLength=5, 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, valueType=str, callback=self._on_target_class_changed, contentsLength=8) gui.rubber(self.controlArea) self.score_table = ScoreTable(self) self.score_table.shownScoresChanged.connect(self.update_stats_model) box = gui.vBox(self.mainArea, "Evaluation Results") box.layout().addWidget(self.score_table.view)
def __init__(self): self._task = None # type: Optional[self.Task] self._executor = ThreadExecutor(self) self.data = None self.test_type = '' self.discrete_model = DomainModel(separators=False, valid_types=(DiscreteVariable, ), parent=self) self.domain_model = DomainModel(valid_types=DomainModel.PRIMITIVE, parent=self) box = gui.vBox(self.controlArea, 'Hypotheses Testing') gui.listView( box, self, 'chosen_X', model=self.discrete_model, box='Grouping Variables', selectionMode=QListView.ExtendedSelection, callback=self.Error.no_vars_selected.clear, toolTip='Select multiple variables with Ctrl+ or Shift+Click.') target = gui.comboBox( box, self, 'chosen_y', sendSelectedValue=True, label='Test Variable', callback=[self.set_test_type, self.Error.no_class_selected.clear]) target.setModel(self.domain_model) gui.checkBox(box, self, 'is_permutation', label='Permutation test', callback=self.set_test_type) gui.comboBox(box, self, 'test_statistic', label='Statistic:', items=tuple(self.TEST_STATISTICS), orientation=Qt.Horizontal, sendSelectedValue=True, callback=self.set_test_type) gui.label(box, self, 'Test: %(test_type)s') box = gui.vBox(self.controlArea, 'Filter') gui.spin(box, self, 'min_count', 5, 1000, 5, label='Minimum group size (count):') self.btn_compute = gui.button(self.controlArea, self, '&Compute', callback=self.compute) gui.rubber(self.controlArea) class Model(PyTableModel): _n_vars = 0 _BACKGROUND = [QBrush(QColor('#eee')), QBrush(QColor('#ddd'))] def setHorizontalHeaderLabels(self, labels, n_vars): self._n_vars = n_vars super().setHorizontalHeaderLabels(labels) def data(self, index, role=Qt.DisplayRole): if role == Qt.BackgroundRole and index.column() < self._n_vars: return self._BACKGROUND[index.row() % 2] if role == Qt.DisplayRole or role == Qt.ToolTipRole: colname = self.headerData(index.column(), Qt.Horizontal) if colname.lower() in ('count', 'count | class'): row = self.mapToSourceRows(index.row()) return int(self[row][index.column()]) return super().data(index, role) owwidget = self class View(gui.TableView): _vars = None def set_vars(self, vars): self._vars = vars def selectionChanged(self, *args): super().selectionChanged(*args) rows = list({ index.row() for index in self.selectionModel().selectedRows(0) }) if not rows: owwidget.Outputs.data.send(None) return model = self.model().tolist() filters = [ Values([ FilterDiscrete(self._vars[col], {model[row][col]}) for col in range(len(self._vars)) ]) for row in self.model().mapToSourceRows(rows) ] data = Values(filters, conjunction=False)(owwidget.data) annotated = create_annotated_table(owwidget.data, data.ids) owwidget.Outputs.selected_data.send(data) owwidget.Outputs.data.send(annotated) self.view = view = View(self) self.model = Model(parent=self) view.setModel(self.model) view.horizontalHeader().setStretchLastSection(False) self.mainArea.layout().addWidget(view) self.set_test_type()
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, commit=self.commit ) 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): super().__init__() self.backend = None self.data_desc_table = None self.database_desc = None vbox = gui.vBox(self.controlArea, "Server", addSpace=True) box = gui.vBox(vbox) self.backendmodel = BackendModel(Backend.available_backends()) self.backendcombo = QComboBox(box) if len(self.backendmodel): self.backendcombo.setModel(self.backendmodel) else: self.Error.no_backends() box.setEnabled(False) box.layout().addWidget(self.backendcombo) self.servertext = QLineEdit(box) self.servertext.setPlaceholderText('Server') self.servertext.setToolTip('Server') self.servertext.editingFinished.connect(self._load_credentials) 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 = 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 = QLineEdit(box) self.usernametext.setPlaceholderText('Username') self.usernametext.setToolTip('Username') box.layout().addWidget(self.usernametext) self.passwordtext = QLineEdit(box) self.passwordtext.setPlaceholderText('Password') self.passwordtext.setToolTip('Password') self.passwordtext.setEchoMode(QLineEdit.Password) box.layout().addWidget(self.passwordtext) self._load_credentials() tables = gui.hBox(box) self.tablemodel = TableModel() self.tablecombo = QComboBox( minimumContentsLength=35, sizeAdjustPolicy=QComboBox.AdjustToMinimumContentsLength) self.tablecombo.setModel(self.tablemodel) 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(QSizePolicy.Fixed, QSizePolicy.Fixed) tables.layout().addWidget(self.connectbutton) self.custom_sql = gui.vBox(box) self.custom_sql.setVisible(False) self.sqltext = 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 categorical 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): super().__init__() # sets self.curvePoints, self.steps equidistant points from # 1/self.steps to 1 self.updateCurvePoints() self.scoring = [ ("Classification Accuracy", Orange.evaluation.scoring.CA), ("AUC", Orange.evaluation.scoring.AUC), ("Precision", Orange.evaluation.scoring.Precision), ("Recall", Orange.evaluation.scoring.Recall), ] #: input data on which to construct the learning curve self.data = None #: optional test data self.testdata = None #: A {input_id: Learner} mapping of current learners from input channel self.learners = OrderedDict() #: A {input_id: List[Results]} mapping of input id to evaluation #: results list, one for each curve point self.results = OrderedDict() #: A {input_id: List[float]} mapping of input id to learning curve #: point scores self.curves = OrderedDict() # [start-snippet-3] #: The current evaluating task (if any) self._task = None # type: Optional[Task] #: An executor we use to submit learner evaluations into a thread pool self._executor = ThreadExecutor() # [end-snippet-3] # GUI box = gui.widgetBox(self.controlArea, "Info") self.infoa = gui.widgetLabel(box, "No data on input.") self.infob = gui.widgetLabel(box, "No learners.") gui.separator(self.controlArea) box = gui.widgetBox(self.controlArea, "Evaluation Scores") gui.comboBox( box, self, "scoringF", items=[x[0] for x in self.scoring], callback=self._invalidate_curves, ) gui.separator(self.controlArea) box = gui.widgetBox(self.controlArea, "Options") gui.spin( box, self, "folds", 2, 100, step=1, label="Cross validation folds: ", keyboardTracking=False, callback=lambda: self._invalidate_results() if self.commitOnChange else None, ) gui.spin( box, self, "steps", 2, 100, step=1, label="Learning curve points: ", keyboardTracking=False, callback=[ self.updateCurvePoints, lambda: self._invalidate_results() if self.commitOnChange else None, ], ) gui.checkBox(box, self, "commitOnChange", "Apply setting on any change") self.commitBtn = gui.button(box, self, "Apply Setting", callback=self._invalidate_results, disabled=True) gui.rubber(self.controlArea) # table widget self.table = gui.table(self.mainArea, selectionMode=QTableWidget.NoSelection)
def __init__(self): super().__init__() self.data = None self._pca = None self._transformed = None self._variance_ratio = None self._cumulative = None self._init_projector() # Components Selection form = QFormLayout() box = gui.widgetBox(self.controlArea, "Components Selection", orientation=form) self.components_spin = gui.spin( box, self, "ncomponents", 1, MAX_COMPONENTS, callback=self._update_selection_component_spin, keyboardTracking=False, addToLayout=False) self.components_spin.setSpecialValueText("All") self.variance_spin = gui.spin( box, self, "variance_covered", 1, 100, callback=self._update_selection_variance_spin, keyboardTracking=False, addToLayout=False) self.variance_spin.setSuffix("%") form.addRow("Components:", self.components_spin) form.addRow("Explained variance:", self.variance_spin) # Options self.options_box = gui.vBox(self.controlArea, "Options") self.normalize_box = gui.checkBox(self.options_box, self, "normalize", "Normalize variables", callback=self._update_normalize, attribute=Qt.WA_LayoutUsesWidgetRect) self.maxp_spin = gui.spin(self.options_box, self, "maxp", 1, MAX_COMPONENTS, label="Show only first", callback=self._setup_plot, keyboardTracking=False) gui.rubber(self.controlArea) gui.auto_apply(self.buttonsArea, self, "auto_commit") self.plot = SliderGraph("Principal Components", "Proportion of variance", self._on_cut_changed) self.mainArea.layout().addWidget(self.plot) self._update_normalize()
def __init__(self): super().__init__() # Instance variables self.model = None self.instances = None self.clf_dataset = None # The tree adapter instance which is passed from the outside self.tree_adapter = None self.legend = None self.color_palette = None # Different methods to calculate the size of squares self.SIZE_CALCULATION = [ ('Normal', lambda x: x), ('Square root', lambda x: sqrt(x)), ('Logarithmic', lambda x: log(x * self.size_log_scale + 1)), ] # CONTROL AREA # Tree info area box_info = gui.widgetBox(self.controlArea, 'Tree Info') self.info = gui.widgetLabel(box_info) # Display settings area box_display = gui.widgetBox(self.controlArea, 'Display Settings') self.depth_slider = gui.hSlider(box_display, self, 'depth_limit', label='Depth', ticks=False, callback=self.update_depth) self.target_class_combo = gui.comboBox(box_display, self, 'target_class_index', label='Target class', orientation=Qt.Horizontal, items=[], contentsLength=8, callback=self.update_colors) self.size_calc_combo = gui.comboBox( box_display, self, 'size_calc_idx', label='Size', orientation=Qt.Horizontal, items=list(zip(*self.SIZE_CALCULATION))[0], contentsLength=8, callback=self.update_size_calc) self.log_scale_box = gui.hSlider(box_display, self, 'size_log_scale', label='Log scale factor', minValue=1, maxValue=100, ticks=False, callback=self.invalidate_tree) # Plot properties area box_plot = gui.widgetBox(self.controlArea, 'Plot Properties') self.cb_show_tooltips = gui.checkBox( box_plot, self, 'tooltips_enabled', label='Enable tooltips', callback=self.update_tooltip_enabled) self.cb_show_legend = gui.checkBox(box_plot, self, 'show_legend', label='Show legend', callback=self.update_show_legend) gui.button(self.controlArea, self, label="Redraw", callback=self.redraw) # Stretch to fit the rest of the unsused area gui.rubber(self.controlArea) self.controlArea.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) # MAIN AREA self.scene = TreeGraphicsScene(self) self.scene.selectionChanged.connect(self.commit) self.view = TreeGraphicsView(self.scene, padding=(150, 150)) self.view.setRenderHint(QPainter.Antialiasing, True) self.mainArea.layout().addWidget(self.view) self.ptree = PythagorasTreeViewer(self) self.scene.addItem(self.ptree) self.view.set_central_widget(self.ptree) self.resize(800, 500) # Clear the widget to correctly set the intial values self.clear()
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) layout = QGridLayout() gui.widgetBox(self.controlArea, orientation=layout) for i in range(3): layout.setColumnStretch(i, 1) layout.addWidget(self.report_button, 0, 0) apply = gui.button(None, self, "Apply", autoDefault=False, callback=self.apply) layout.addWidget(apply, 0, 2) # TODO: Resizing upon changing the number of rules does not work self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum)
def __init__(self): super().__init__() self.all_measures = SCORES self.selectedMeasures = dict( [(name, True) for name in _DEFAULT_SELECTED] + [(m.name, False) for m in self.all_measures[len(_DEFAULT_SELECTED):]]) # Discrete (0) or continuous (1) class mode self.rankMode = 0 self.data = None self.discMeasures = [ m for m in self.all_measures if m.supports_classification ] self.contMeasures = [ m for m in self.all_measures if m.supports_regression ] selMethBox = gui.widgetBox(self.controlArea, "Select attributes", addSpace=True) grid = QtGui.QGridLayout() grid.setContentsMargins(0, 0, 0, 0) self.selectButtons = QtGui.QButtonGroup() self.selectButtons.buttonClicked[int].connect(self.setSelectMethod) def button(text, buttonid, toolTip=None): b = QtGui.QRadioButton(text) self.selectButtons.addButton(b, buttonid) if toolTip is not None: b.setToolTip(toolTip) return b b1 = button(self.tr("None"), OWRank.SelectNone) b2 = button(self.tr("All"), OWRank.SelectAll) b3 = button(self.tr("Manual"), OWRank.SelectManual) b4 = button(self.tr("Best ranked"), OWRank.SelectNBest) s = gui.spin(selMethBox, self, "nSelected", 1, 100, callback=self.nSelectedChanged) grid.addWidget(b1, 0, 0) grid.addWidget(b2, 1, 0) grid.addWidget(b3, 2, 0) grid.addWidget(b4, 3, 0) grid.addWidget(s, 3, 1) self.selectButtons.button(self.selectMethod).setChecked(True) selMethBox.layout().addLayout(grid) gui.auto_commit(self.controlArea, self, "auto_apply", "Commit", checkbox_label="Commit on any change") gui.rubber(self.controlArea) # Discrete and continuous table views are stacked self.ranksViewStack = QtGui.QStackedLayout() self.mainArea.layout().addLayout(self.ranksViewStack) self.discRanksView = QtGui.QTableView() self.ranksViewStack.addWidget(self.discRanksView) self.discRanksView.setSelectionBehavior(QtGui.QTableView.SelectRows) self.discRanksView.setSelectionMode(QtGui.QTableView.MultiSelection) self.discRanksView.setSortingEnabled(True) self.discRanksModel = QtGui.QStandardItemModel(self) self.discRanksModel.setHorizontalHeaderLabels( ["#"] + [m.shortname for m in self.discMeasures]) self.discRanksProxyModel = MySortProxyModel(self) self.discRanksProxyModel.setSourceModel(self.discRanksModel) self.discRanksView.setModel(self.discRanksProxyModel) self.discRanksView.setColumnWidth(0, 20) self.discRanksView.sortByColumn(1, Qt.DescendingOrder) self.discRanksView.selectionModel().selectionChanged.connect( self.onSelectionChanged) self.discRanksView.pressed.connect(self.onSelectItem) self.discRanksView.horizontalHeader().sectionClicked.connect( self.headerClick) if self.headerState[0] is not None: self.discRanksView.horizontalHeader().restoreState( self.headerState[0]) self.contRanksView = QtGui.QTableView() self.ranksViewStack.addWidget(self.contRanksView) self.contRanksView.setSelectionBehavior(QtGui.QTableView.SelectRows) self.contRanksView.setSelectionMode(QtGui.QTableView.MultiSelection) self.contRanksView.setSortingEnabled(True) self.contRanksModel = QtGui.QStandardItemModel(self) self.contRanksModel.setHorizontalHeaderLabels( ["#"] + [m.shortname for m in self.contMeasures]) self.contRanksProxyModel = MySortProxyModel(self) self.contRanksProxyModel.setSourceModel(self.contRanksModel) self.contRanksView.setModel(self.contRanksProxyModel) self.discRanksView.setColumnWidth(0, 20) self.contRanksView.sortByColumn(1, Qt.DescendingOrder) self.contRanksView.selectionModel().selectionChanged.connect( self.onSelectionChanged) self.contRanksView.pressed.connect(self.onSelectItem) self.contRanksView.horizontalHeader().sectionClicked.connect( self.headerClick) if self.headerState[1] is not None: self.contRanksView.horizontalHeader().restoreState( self.headerState[1]) # Switch the current view to Discrete self.switchRanksMode(0) self.resetInternals() self.updateDelegates() self.updateVisibleScoreColumns() self.resize(690, 500) self.measure_scores = table((len(self.measures), 0), None)
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, *args, **kwargs): """Initialize a Variety widget""" super().__init__(*args, **kwargs) self.infoBox = InfoBox( widget=self.controlArea, stringClickSend=u", please click 'Send' when ready.", ) self.sendButton = SendButton( widget=self.controlArea, master=self, callback=self.sendData, infoBoxAttribute='infoBox', buttonLabel=u'Send', checkboxLabel=u'Send automatically', sendIfPreCallback=self.updateGUI, ) # GUI... # Units box self.unitsBox = gui.widgetBox( widget=self.controlArea, box=u'Units', orientation='vertical', addSpace=True, ) self.unitSegmentationCombo = gui.comboBox( widget=self.unitsBox, master=self, value='units', orientation='horizontal', label=u'Segmentation:', labelWidth=180, callback=self.sendButton.settingsChanged, tooltip=( u"The segmentation whose variety will be measured." ), ) self.unitSegmentationCombo.setMinimumWidth(120) gui.separator(widget=self.unitsBox, height=3) self.unitAnnotationCombo = gui.comboBox( widget=self.unitsBox, master=self, value='unitAnnotationKey', sendSelectedValue=True, emptyString=u'(none)', orientation='horizontal', label=u'Annotation key:', labelWidth=180, callback=self.sendButton.settingsChanged, tooltip=( u"Indicate whether the variety of the above\n" u"specified segmentation must be measured on the\n" u"segments' content (value 'none') or on their\n" u"annotation values for a specific annotation key." ), ) gui.separator(widget=self.unitsBox, height=3) self.sequenceLengthSpin = gui.spin( widget=self.unitsBox, master=self, value='sequenceLength', minv=1, maxv=1, step=1, orientation='horizontal', label=u'Sequence length:', labelWidth=180, callback=self.sendButton.settingsChanged, keyboardTracking=False, tooltip=( u"Indicate whether to measure the variety of\n" u"single segments or rather of sequences of 2,\n" u"3,... segments (n-grams).\n\n" u"Note that this parameter cannot be set to a\n" u"value larger than 1 if variety is to be\n" u"measured per category." ), ) gui.separator(widget=self.unitsBox, height=3) gui.checkBox( widget=self.unitsBox, master=self, value='unitWeighting', label=u'Weigh by frequency', callback=self.sendButton.settingsChanged, tooltip=( u"Check this box in order to apply unit frequency\n" u"weighting (i.e. use perplexity instead of variety)." ), ) gui.separator(widget=self.unitsBox, height=3) # Categories box self.categoriesBox = gui.widgetBox( widget=self.controlArea, box=u'Categories', orientation='vertical', addSpace=True, ) self.measurePerCategoryCheckbox = gui.checkBox( widget=self.categoriesBox, master=self, value='measurePerCategory', label=u'Measure variety per category', callback=self.sendButton.settingsChanged, tooltip=( u"Check this box in order to measure the average\n" u"variety per category." ), ) gui.separator(widget=self.categoriesBox, height=3) iBox = gui.indentedBox( widget=self.categoriesBox, ) self.categoryAnnotationCombo = gui.comboBox( widget=iBox, master=self, value='categoryAnnotationKey', sendSelectedValue=True, emptyString=u'(none)', orientation='horizontal', label=u'Annotation key:', labelWidth=160, callback=self.sendButton.settingsChanged, tooltip=( u"Indicate whether categories are defined by the\n" u"segments' content (value 'none') or by their\n" u"annotation values for a specific annotation key." ), ) gui.separator(widget=iBox, height=3) gui.checkBox( widget=iBox, master=self, value='categoryWeighting', label=u'Weigh by frequency', callback=self.sendButton.settingsChanged, tooltip=( u"Check this box in order to apply category\n" u"frequency weighting (i.e. compute a weighted\n" u"rather than unweighted average)." ), ) gui.separator(widget=iBox, height=3) gui.checkBox( widget=iBox, master=self, value='adjustSubsampleSize', label=u'Dynamically adjust subsample size', callback=self.sendButton.settingsChanged, tooltip=( u"Attempt to make variety estimation more robust\n" u"by using the RMSP subsample size adjustment method\n" u"described in Xanthos and Guex 2015." ), ) self.measurePerCategoryCheckbox.disables.append(iBox) if self.measurePerCategory: iBox.setDisabled(False) else: iBox.setDisabled(True) gui.separator(widget=self.categoriesBox, height=3) # Contexts box... self.contextsBox = gui.widgetBox( widget=self.controlArea, box=u'Contexts', orientation='vertical', addSpace=True, ) self.modeCombo = gui.comboBox( widget=self.contextsBox, master=self, value='mode', sendSelectedValue=True, items=[ u'No context', u'Sliding window', u'Containing segmentation', ], orientation='horizontal', label=u'Mode:', labelWidth=180, callback=self.sendButton.settingsChanged, tooltip=( u"Context specification mode.\n\n" u"Contexts define the rows of the resulting\n" u"table.\n\n" u"'No context': variety will be measured\n" u"irrespective of the context (hence the output\n" u"table contains a single row).\n\n" u"'Sliding window': contexts are defined as all the\n" u"successive, overlapping sequences of n segments\n" u"in the 'Units' segmentation.\n\n" u"'Containing segmentation': contexts are defined\n" u"as the distinct segments occurring in a given\n" u"segmentation." ), ) self.slidingWindowBox = gui.widgetBox( widget=self.contextsBox, orientation='vertical', ) gui.separator(widget=self.slidingWindowBox, height=3) self.windowSizeSpin = gui.spin( widget=self.slidingWindowBox, master=self, value='windowSize', minv=1, maxv=1, step=1, orientation='horizontal', label=u'Window size:', labelWidth=180, callback=self.sendButton.settingsChanged, keyboardTracking=False, tooltip=( u"The length of segment sequences defining contexts." ), ) self.containingSegmentationBox = gui.widgetBox( widget=self.contextsBox, orientation='vertical', ) gui.separator(widget=self.containingSegmentationBox, height=3) self.contextSegmentationCombo = gui.comboBox( widget=self.containingSegmentationBox, master=self, value='_contexts', orientation='horizontal', label=u'Segmentation:', labelWidth=180, callback=self.sendButton.settingsChanged, tooltip=( u"The segmentation whose segment types define\n" u"the contexts in which the variety of segments\n" u"in the 'Units' segmentation will be measured." ), ) gui.separator(widget=self.containingSegmentationBox, height=3) self.contextAnnotationCombo = gui.comboBox( widget=self.containingSegmentationBox, master=self, value='contextAnnotationKey', sendSelectedValue=True, emptyString=u'(none)', orientation='horizontal', label=u'Annotation key:', labelWidth=180, callback=self.sendButton.settingsChanged, tooltip=( u"Indicate whether context types are defined by\n" u"the content of segments in the above specified\n" u"segmentation (value 'none') or by their annotation\n" u"values for a specific annotation key." ), ) gui.separator(widget=self.containingSegmentationBox, height=3) gui.checkBox( widget=self.containingSegmentationBox, master=self, value='mergeContexts', label=u'Merge contexts', callback=self.sendButton.settingsChanged, tooltip=( u"Check this box if you want to treat all segments\n" u"of the above specified segmentation as forming\n" u"a single context (hence the resulting table\n" u"contains a single row)." ), ) gui.separator(widget=self.contextsBox, height=3) # Resampling box... self.resamplingBox = gui.widgetBox( widget=self.controlArea, box=u'Resampling', orientation='vertical', addSpace=True, ) applyResamplingCheckBox = gui.checkBox( widget=self.resamplingBox, master=self, value='applyResampling', label=u'Apply Resampling', callback=self.sendButton.settingsChanged, tooltip=( u"Check this box if you want to compute the average\n" u"(or expected) variety per subsample." ), ) # TODO: document RMSP! gui.separator(widget=self.resamplingBox, height=3) iBox2 = gui.indentedBox( widget=self.resamplingBox, ) self.subsampleSizeSpin = gui.spin( widget=iBox2, master=self, value='subsampleSize', minv=1, maxv=1, step=1, orientation='horizontal', label=u'Subsample size:', labelWidth=160, callback=self.sendButton.settingsChanged, keyboardTracking=False, tooltip=( u"The number of segments per subsample." ), ) gui.separator(widget=iBox2, height=3) self.numSubsampleSpin = gui.spin( widget=iBox2, master=self, value='numSubsamples', minv=1, maxv=100000, step=1, orientation='horizontal', label=u'Number of subsamples:', labelWidth=160, callback=self.sendButton.settingsChanged, keyboardTracking=False, tooltip=( u"The number of subsamples (per context)." ), ) applyResamplingCheckBox.disables.append(iBox2) if self.applyResampling: iBox2.setDisabled(False) else: iBox2.setDisabled(True) gui.separator(widget=self.resamplingBox, height=3) gui.rubber(self.controlArea) # Send button... self.sendButton.draw() # Info box... self.infoBox.draw() self.sendButton.sendIf() self.adjustSizeWithTimer()
def __init__(self): super().__init__() self.data = None self._effective_data = None self._matrix = None self._silhouette = None self._labels = None self._silplot = None box = gui.widgetBox( self.controlArea, "Settings", ) gui.comboBox(box, self, "distance_idx", label="Distance", items=[name for name, _ in OWSilhouettePlot.Distances], callback=self._invalidate_distances) self.cluster_var_cb = gui.comboBox(box, self, "cluster_var_idx", label="Cluster", callback=self._invalidate_scores) self.cluster_var_model = itemmodels.VariableListModel(parent=self) self.cluster_var_cb.setModel(self.cluster_var_model) gui.spin(box, self, "bar_size", minv=1, maxv=10, label="Bar Size", callback=self._update_bar_size) gui.checkBox(box, self, "group_by_cluster", "Group by cluster", callback=self._replot) self.annotation_cb = gui.comboBox(box, self, "annotation_var_idx", label="Annotations", callback=self._update_annotations) self.annotation_var_model = itemmodels.VariableListModel(parent=self) self.annotation_var_model[:] = ["None"] self.annotation_cb.setModel(self.annotation_var_model) gui.rubber(self.controlArea) box = gui.widgetBox(self.controlArea, "Output") gui.checkBox( box, self, "add_scores", "Add silhouette scores", ) gui.auto_commit(box, self, "auto_commit", "Commit", box=False) self.scene = QtGui.QGraphicsScene() self.view = QtGui.QGraphicsView(self.scene) self.view.setRenderHint(QtGui.QPainter.Antialiasing, True) self.view.setAlignment(Qt.AlignTop | Qt.AlignLeft) self.mainArea.layout().addWidget(self.view)
def __init__(self): """Widget creator.""" super().__init__() # ATTRIBUTS # searchFunction self.searchResults = None self.inputSeg = None # newQuery = attribut box lineEdit (search something) self.newQuery = '' self.nbr_results = 10 # Results box attributs self.titleLabels = list() self.selectedTitles = list() # selections box attributs self.myTitles = list() self.mytitleLabels = list() # stock all the inputs (songs) in a list self.createdInputs = list() # Next two instructions are helpers from TextableUtils. Corresponding # interface elements are declared here and actually drawn below (at # their position in the UI)... self.infoBox = InfoBox(widget=self.controlArea) self.sendButton = SendButton( widget=self.controlArea, master=self, callback=self.sendData, infoBoxAttribute="infoBox", ) #---------------------------------------------------------------------- # User interface... # Create the working area queryBox = gui.widgetBox( widget=self.controlArea, box="Search songs", orientation="vertical", ) # Allows to enter specific text to the research # Uses "newQuery" attribut gui.lineEdit( widget=queryBox, master=self, value='newQuery', orientation='horizontal', label=u"Query: ", labelWidth=120, tooltip=("Enter a string"), ) # Allows to choose the wanted results numberp (10 by 10) queryNbr = gui.comboBox( widget=queryBox, master=self, value="nbr_results", items=[ "10", "20", "30", "40", "50", "60", "70", "80", "90", "100", ], sendSelectedValue=True, orientation="horizontal", label="Number of results: ", labelWidth=120, tooltip=("Please select the desired search.\n"), ) # Reasearch button # Uses "searchFunction" attribut self.searchButton = gui.button( widget=queryBox, master=self, label="Search", callback=self.searchFunction, tooltip="Connect Genius and make a research", ) self.titleListbox = gui.listBox( widget=queryBox, master=self, value="selectedTitles", # setting (list) labels="titleLabels", # setting (list) callback=lambda: self.addButton.setDisabled(self.selectedTitles == list()), tooltip="The list of titles whose content will be imported", ) self.titleListbox.setMinimumHeight(150) self.titleListbox.setSelectionMode(3) boxbutton = gui.widgetBox( widget=queryBox, box=False, orientation='horizontal', ) # Add songs button self.addButton = gui.button( widget=boxbutton, master=self, label=u'Add to corpus', callback=self.add, tooltip=(u"Move the selected song downward in your corpus."), ) self.addButton.setDisabled(True) # Clear button # Uses "clearResults" function self.clearButton = gui.button( widget=boxbutton, master=self, label="Clear results", callback=self.clearResults, tooltip="Clear results", ) self.clearButton.setDisabled(True) gui.separator(widget=queryBox, height=3) # area where confirmed songs are moved and stocked mytitleBox = gui.widgetBox( widget=self.controlArea, box="Corpus", orientation="vertical", ) self.mytitleListbox = gui.listBox( widget=mytitleBox, master=self, value="myTitles", labels="mytitleLabels", callback=lambda: self.removeButton.setDisabled(self.myTitles == list()), tooltip="The list of titles whose content will be imported", ) self.mytitleListbox.setMinimumHeight(150) self.mytitleListbox.setSelectionMode(3) boxbutton2 = gui.widgetBox( widget=mytitleBox, box=False, orientation='horizontal', ) # Remove songs button self.removeButton = gui.button( widget=boxbutton2, master=self, label=u'Remove from corpus', callback=self.remove, tooltip=(u"Remove the selected song from your corpus."), ) self.removeButton.setDisabled(True) # Delete all confirmed songs button self.clearmyBasket = gui.button( widget=boxbutton2, master=self, label=u'Clear corpus', callback=self.clearmyBasket, tooltip=(u"Remove all songs from your corpus."), ) self.clearmyBasket.setDisabled(True) gui.separator(widget=mytitleBox, height=3) gui.rubber(self.controlArea) #---------------------------------------------------------------------- # Draw Info box and Send button self.sendButton.draw() self.searchButton.setDefault(True) self.infoBox.draw() # Update the selections list self.updateMytitleLabels() # Send data if autoSend. self.sendButton.sendIf()
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, enterPlaceholder=True, callback=self._attr_name_changed) gui.separator(hbox, 18) hbox = gui.hBox(namesBox, margin=0, spacing=0) attr2 = gui.lineEdit(hbox, self, "attr2", "Variable Y: ", controlWidth=80, orientation=Qt.Horizontal, enterPlaceholder=True, callback=self._attr_name_changed) gui.checkBox(hbox, self, "hasAttr2", '', disables=attr2, labelWidth=0, callback=self.set_dimensions) gui.separator(namesBox) gui.widgetLabel(namesBox, "Labels") self.classValuesView = listView = QListView( selectionMode=QListView.SingleSelection, sizePolicy=QSizePolicy(QSizePolicy.Ignored, QSizePolicy.Maximum)) 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=QtGui.QGridLayout()) self.toolActions = QtGui.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 = QtGui.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(QtGui.QKeySequence.Undo) redo.setShortcut(QtGui.QKeySequence.Redo) self.addActions([undo, redo]) self.undo_stack.indexChanged.connect(lambda _: self.invalidate()) gui.separator(tBox) indBox = gui.indentedBox(tBox, sep=8) form = QtGui.QFormLayout( formAlignment=Qt.AlignLeft, labelAlignment=Qt.AlignLeft, fieldGrowthPolicy=QtGui.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) self.btResetToInput = gui.button(tBox, self, "Reset to Input Data", self.reset_to_input) self.btResetToInput.setDisabled(True) gui.rubber(self.controlArea) gui.auto_commit(self.left_side, 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(QtGui.QPalette.Text) axis_pen = QtGui.QPen(axis_color) tickfont = QtGui.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__() #: input data self.data = None #: Current variable discretization state self.var_state = {} #: Saved variable discretization settings (context setting) self.saved_var_states = {} self.method = 0 self.k = 5 box = gui.vBox(self.controlArea, self.tr("Default Discretization")) self.default_bbox = rbox = gui.radioButtons( box, self, "default_method", callback=self._default_disc_changed) options = self.options = [ self.tr("Default"), self.tr("Leave numeric"), self.tr("Entropy-MDL discretization"), self.tr("Equal-frequency discretization"), self.tr("Equal-width discretization"), self.tr("Remove numeric variables") ] for opt in options[1:5]: gui.appendRadioButton(rbox, opt) s = gui.hSlider(gui.indentedBox(rbox), self, "default_k", minValue=2, maxValue=10, label="Num. of intervals:", callback=self._default_disc_changed) s.setTracking(False) gui.appendRadioButton(rbox, options[-1]) vlayout = QHBoxLayout() box = gui.widgetBox(self.controlArea, "Individual Attribute Settings", orientation=vlayout, spacing=8) # List view with all attributes self.varview = QListView(selectionMode=QListView.ExtendedSelection) self.varview.setItemDelegate(DiscDelegate()) self.varmodel = itemmodels.VariableListModel() self.varview.setModel(self.varmodel) self.varview.selectionModel().selectionChanged.connect( self._var_selection_changed) vlayout.addWidget(self.varview) # Controls for individual attr settings self.bbox = controlbox = gui.radioButtons( box, self, "method", callback=self._disc_method_changed) vlayout.addWidget(controlbox) for opt in options[:5]: gui.appendRadioButton(controlbox, opt) s = gui.hSlider(gui.indentedBox(controlbox), self, "k", minValue=2, maxValue=10, label="Num. of intervals:", callback=self._disc_method_changed) s.setTracking(False) gui.appendRadioButton(controlbox, "Remove attribute") gui.rubber(controlbox) controlbox.setEnabled(False) self.controlbox = controlbox box = gui.auto_commit(self.controlArea, self, "autosend", "Apply", orientation=Qt.Horizontal, checkbox_label="Send data after every change") box.layout().insertSpacing(0, 20) box.layout().insertWidget(0, self.report_button)
def _add_buttons(self): gui.rubber(self.controlArea) self.gui.box_zoom_select(self.buttonsArea) gui.auto_send(self.buttonsArea, self, "auto_commit")
def __init__(self): super().__init__() self.data = None # type: Optional[Table] self.__pending_selection = self.selection # type: Optional[int] self.clusterings = {} self.__executor = ThreadExecutor(parent=self) self.__task = None # type: Optional[Task] layout = QGridLayout() bg = gui.radioButtonsInBox( self.controlArea, self, "optimize_k", orientation=layout, box="Number of Clusters", callback=self.update_method, ) layout.addWidget( gui.appendRadioButton(bg, "Fixed:", addToLayout=False), 1, 1) sb = gui.hBox(None, margin=0) 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, "From", addToLayout=False), 2, 1) ftobox = gui.hBox(None) ftobox.layout().setContentsMargins(0, 0, 0, 0) layout.addWidget(ftobox, 2, 2) gui.spin(ftobox, self, "k_from", minv=2, maxv=29, controlWidth=60, alignment=Qt.AlignRight, callback=self.update_from) gui.widgetLabel(ftobox, "to") gui.spin(ftobox, self, "k_to", minv=3, maxv=30, controlWidth=60, alignment=Qt.AlignRight, callback=self.update_to) gui.rubber(ftobox) box = gui.vBox(self.controlArea, "Preprocessing") gui.checkBox(box, self, "normalize", "Normalize columns", callback=self.invalidate) box = gui.vBox(self.controlArea, "Initialization") gui.comboBox(box, self, "smart_init", items=[m[0] for m in self.INIT_METHODS], callback=self.invalidate) layout = QGridLayout() gui.widgetBox(box, orientation=layout) 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.invalidate) layout.addWidget(gui.widgetLabel(None, "Maximum 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.invalidate) box = gui.vBox(self.mainArea, box="Silhouette Scores") if self.optimize_k: self.mainArea.setVisible(True) self.left_side.setContentsMargins(0, 0, 0, 0) else: self.mainArea.setVisible(False) self.left_side.setContentsMargins(0, 0, 4, 0) self.table_model = ClusterTableModel(self) table = self.table_view = QTableView(self.mainArea) table.setModel(self.table_model) table.setSelectionMode(QTableView.SingleSelection) table.setSelectionBehavior(QTableView.SelectRows) table.setItemDelegate(gui.ColoredBarItemDelegate(self, color=Qt.cyan)) table.selectionModel().selectionChanged.connect(self.select_row) table.setMaximumWidth(200) table.horizontalHeader().setStretchLastSection(True) table.horizontalHeader().hide() table.setShowGrid(False) box.layout().addWidget(table) self.apply_button = gui.auto_apply(self.buttonsArea, self, "auto_commit", commit=self.commit)
def __init__(self): super().__init__() self.__pending_selection = self.selected_rows # A kingdom for a save_state/restore_state self.col_clustering = enum_get(Clustering, self.col_clustering_method, Clustering.None_) self.row_clustering = enum_get(Clustering, self.row_clustering_method, Clustering.None_) @self.settingsAboutToBePacked.connect def _(): self.col_clustering_method = self.col_clustering.name self.row_clustering_method = self.row_clustering.name self.keep_aspect = False #: The original data with all features (retained to #: preserve the domain on the output) self.input_data = None #: The effective data striped of discrete features, and often #: merged using k-means self.data = None self.effective_data = None #: kmeans model used to merge rows of input_data self.kmeans_model = None #: merge indices derived from kmeans #: a list (len==k) of int ndarray where the i-th item contains #: the indices which merge the input_data into the heatmap row i self.merge_indices = None self.parts: Optional[Parts] = None self.__rows_cache = {} self.__columns_cache = {} # GUI definition colorbox = gui.vBox(self.controlArea, "Color") self.color_cb = gui.palette_combo_box(self.palette_name) self.color_cb.currentIndexChanged.connect(self.update_color_schema) colorbox.layout().addWidget(self.color_cb) form = QFormLayout(formAlignment=Qt.AlignLeft, labelAlignment=Qt.AlignLeft, fieldGrowthPolicy=QFormLayout.AllNonFixedFieldsGrow) lowslider = gui.hSlider(colorbox, self, "threshold_low", minValue=0.0, maxValue=1.0, step=0.05, ticks=True, intOnly=False, createLabel=False, callback=self.update_lowslider) highslider = gui.hSlider(colorbox, self, "threshold_high", minValue=0.0, maxValue=1.0, step=0.05, ticks=True, intOnly=False, createLabel=False, callback=self.update_highslider) form.addRow("Low:", lowslider) form.addRow("High:", highslider) colorbox.layout().addLayout(form) mergebox = gui.vBox( self.controlArea, "Merge", ) gui.checkBox(mergebox, self, "merge_kmeans", "Merge by k-means", callback=self.__update_row_clustering) ibox = gui.indentedBox(mergebox) gui.spin(ibox, self, "merge_kmeans_k", minv=5, maxv=500, label="Clusters:", keyboardTracking=False, callbackOnReturn=True, callback=self.update_merge) cluster_box = gui.vBox(self.controlArea, "Clustering") # Row clustering self.row_cluster_cb = cb = ComboBox() cb.setModel(create_list_model(ClusteringModelData, self)) cbselect(cb, self.row_clustering, ClusteringRole) self.connect_control( "row_clustering", lambda value, cb=cb: cbselect(cb, value, ClusteringRole)) @cb.activated.connect def _(idx, cb=cb): self.set_row_clustering(cb.itemData(idx, ClusteringRole)) # Column clustering self.col_cluster_cb = cb = ComboBox() cb.setModel(create_list_model(ClusteringModelData, self)) cbselect(cb, self.col_clustering, ClusteringRole) self.connect_control( "col_clustering", lambda value, cb=cb: cbselect(cb, value, ClusteringRole)) @cb.activated.connect def _(idx, cb=cb): self.set_col_clustering(cb.itemData(idx, ClusteringRole)) form = QFormLayout( labelAlignment=Qt.AlignLeft, formAlignment=Qt.AlignLeft, fieldGrowthPolicy=QFormLayout.AllNonFixedFieldsGrow, ) form.addRow("Rows:", self.row_cluster_cb) form.addRow("Columns:", self.col_cluster_cb) cluster_box.layout().addLayout(form) box = gui.vBox(self.controlArea, "Split By") self.row_split_model = DomainModel( placeholder="(None)", valid_types=(Orange.data.DiscreteVariable, ), parent=self, ) self.row_split_cb = cb = ComboBoxSearch( enabled=not self.merge_kmeans, sizeAdjustPolicy=ComboBox.AdjustToMinimumContentsLengthWithIcon, minimumContentsLength=14, toolTip="Split the heatmap vertically by a categorical column") self.row_split_cb.setModel(self.row_split_model) self.connect_control("split_by_var", lambda value, cb=cb: cbselect(cb, value)) self.connect_control("merge_kmeans", self.row_split_cb.setDisabled) self.split_by_var = None self.row_split_cb.activated.connect(self.__on_split_rows_activated) box.layout().addWidget(self.row_split_cb) box = gui.vBox(self.controlArea, 'Annotation && Legends') gui.checkBox(box, self, 'legend', 'Show legend', callback=self.update_legend) gui.checkBox(box, self, 'averages', 'Stripes with averages', callback=self.update_averages_stripe) annotbox = QGroupBox("Row Annotations", flat=True) form = QFormLayout(annotbox, formAlignment=Qt.AlignLeft, labelAlignment=Qt.AlignLeft, fieldGrowthPolicy=QFormLayout.AllNonFixedFieldsGrow) self.annotation_model = DomainModel(placeholder="(None)") self.annotation_text_cb = ComboBoxSearch( minimumContentsLength=12, sizeAdjustPolicy=QComboBox.AdjustToMinimumContentsLength) self.annotation_text_cb.setModel(self.annotation_model) self.annotation_text_cb.activated.connect(self.set_annotation_var) self.connect_control("annotation_var", self.annotation_var_changed) self.row_side_color_model = DomainModel( order=(DomainModel.CLASSES, DomainModel.Separator, DomainModel.METAS), placeholder="(None)", valid_types=DomainModel.PRIMITIVE, flags=Qt.ItemIsSelectable | Qt.ItemIsEnabled, parent=self, ) self.row_side_color_cb = ComboBoxSearch( sizeAdjustPolicy=QComboBox.AdjustToMinimumContentsLength, minimumContentsLength=12) self.row_side_color_cb.setModel(self.row_side_color_model) self.row_side_color_cb.activated.connect(self.set_annotation_color_var) self.connect_control("annotation_color_var", self.annotation_color_var_changed) form.addRow("Text", self.annotation_text_cb) form.addRow("Color", self.row_side_color_cb) box.layout().addWidget(annotbox) posbox = gui.vBox(box, "Column Labels Position", addSpace=False) posbox.setFlat(True) cb = gui.comboBox(posbox, self, "column_label_pos", callback=self.update_column_annotations) cb.setModel(create_list_model(ColumnLabelsPosData, parent=self)) cb.setCurrentIndex(self.column_label_pos) gui.checkBox(self.controlArea, self, "keep_aspect", "Keep aspect ratio", box="Resize", callback=self.__aspect_mode_changed) gui.rubber(self.controlArea) gui.auto_send(self.controlArea, self, "auto_commit") # Scene with heatmap class HeatmapScene(QGraphicsScene): widget: Optional[HeatmapGridWidget] = None self.scene = self.scene = HeatmapScene(parent=self) self.view = GraphicsView( self.scene, verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn, horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOn, viewportUpdateMode=QGraphicsView.FullViewportUpdate, widgetResizable=True, ) self.view.setContextMenuPolicy(Qt.CustomContextMenu) self.view.customContextMenuRequested.connect( self._on_view_context_menu) self.mainArea.layout().addWidget(self.view) self.selected_rows = [] self.__font_inc = QAction("Increase Font", self, shortcut=QKeySequence("ctrl+>")) self.__font_dec = QAction("Decrease Font", self, shortcut=QKeySequence("ctrl+<")) self.__font_inc.triggered.connect(lambda: self.__adjust_font_size(1)) self.__font_dec.triggered.connect(lambda: self.__adjust_font_size(-1)) if hasattr(QAction, "setShortcutVisibleInContextMenu"): apply_all([self.__font_inc, self.__font_dec], lambda a: a.setShortcutVisibleInContextMenu(True)) self.addActions([self.__font_inc, self.__font_dec])
def __init__(self, parent=None): widget.OWWidget.__init__(self, parent) self.min_value, self.max_value = self.thresholds.get( self.Scores[self.score_index][0], (1, 0)) # threshold defining expressed genes (for Hypergeometric Test) self.expression_threshold_value = 1.0 #: Input data set self.data = None #: Current target group selection self.targets = [] #: The computed scores self.scores = None #: The computed scores from label permutations self.nulldist = None self.__scores_future = self.__scores_state = None self.__in_progress = False self.test_f = { OWDifferentialExpression.LowTail: test_low, OWDifferentialExpression.HighTail: test_high, OWDifferentialExpression.TwoTail: test_two_tail, } self.histogram = Histogram(enableMouse=False, enableMenu=False, background="w") self.histogram.enableAutoRange(enable=False) self.histogram.getPlotItem().hideButtons() # hide auto range button self.histogram.getViewBox().setMouseEnabled(False, False) self.histogram.selectionChanged.connect( self.__on_histogram_plot_selection_changed) self.histogram.selectionEdited.connect(self._invalidate_selection) self.mainArea.layout().addWidget(self.histogram) box = gui.widgetBox(self.controlArea, "Info") self.dataInfoLabel = gui.widgetLabel(box, "No data on input.\n") self.dataInfoLabel.setWordWrap(True) self.selectedInfoLabel = gui.widgetLabel(box, "\n") box1 = gui.widgetBox(self.controlArea, "Scoring Method") gui.comboBox( box1, self, "score_index", items=[sm[0] for sm in self.Scores], callback=[self.on_scoring_method_changed, self.update_scores], ) self.expression_threshold_box = gui.widgetBox(self.controlArea, 'Expression threshold') self.expression_threshold = gui.doubleSpin( self.expression_threshold_box, self, "expression_threshold_value", minv=0, maxv=1e2, step=1e-2, callback=self.update_scores, callbackOnReturn=True, ) box = gui.widgetBox(self.controlArea, "Target Labels") self.label_selection_widget = guiutils.LabelSelectionWidget() self.label_selection_widget.setMaximumHeight(150) box.layout().addWidget(self.label_selection_widget) self.label_selection_widget.groupChanged.connect( self.on_label_activated) self.label_selection_widget.groupSelectionChanged.connect( self.on_target_changed) box = gui.widgetBox(self.controlArea, "Selection") box.layout().setSpacing(0) self.max_value_spin = gui.doubleSpin( box, self, "max_value", minv=-1e6, maxv=1e6, step=1e-6, label="Upper threshold:", callback=self.update_boundary, callbackOnReturn=True, ) self.low_value_spin = gui.doubleSpin( box, self, "min_value", minv=-1e6, maxv=1e6, step=1e-6, label="Lower threshold:", callback=self.update_boundary, callbackOnReturn=True, ) check = gui.checkBox(box, self, "compute_null", "Compute null distribution", callback=self.update_scores) perm_spin = gui.spin( box, self, "permutations_count", minv=1, maxv=50, label="Permutations:", callback=self.update_scores, callbackOnReturn=True, ) check.disables.append(perm_spin) box1 = gui.widgetBox(box, orientation='horizontal') pval_spin = gui.doubleSpin(box1, self, "alpha_value", minv=2e-7, maxv=1.0, step=1e-7, label="α-value:") pval_select = gui.button(box1, self, "Select", callback=self.select_p_best, autoDefault=False) check.disables.append(pval_spin) check.disables.append(pval_select) check.makeConsistent() box1 = gui.widgetBox(box, orientation='horizontal') gui.spin(box1, self, "n_best", 0, 10000, step=1, label="Best Ranked:") gui.button(box1, self, "Select", callback=self.select_n_best, autoDefault=False) box = gui.widgetBox(self.controlArea, "Output") acbox = gui.auto_commit(box, self, "auto_commit", "Commit", box=None) acbox.button.setDefault(True) gui.rubber(self.controlArea) self.on_scoring_method_changed() self._executor = concurrent.ThreadExecutor()
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.texts = list() self.infoBox = InfoBox(widget=self.controlArea) self.sendButton = SendButton( widget=self.controlArea, master=self, callback=self.sendData, infoBoxAttribute='infoBox', sendIfPreCallback=self.updateGUI, ) # GUI... # Options box... optionsBox = gui.widgetBox( widget=self.controlArea, box=u'Options', orientation='vertical', addSpace=False, ) optionsBoxLine1 = gui.widgetBox( widget=optionsBox, box=False, orientation='horizontal', ) gui.checkBox( widget=optionsBoxLine1, master=self, value='importLabels', label=u'Import labels with key:', labelWidth=180, callback=self.sendButton.settingsChanged, tooltip=(u"Import labels of input segmentations as annotations."), ) self.labelKeyLineEdit = gui.lineEdit( widget=optionsBoxLine1, master=self, value='labelKey', orientation='horizontal', callback=self.sendButton.settingsChanged, tooltip=(u"Annotation key for importing input segmentation\n" u"labels."), ) gui.separator(widget=optionsBox, height=3) optionsBoxLine2 = gui.widgetBox( widget=optionsBox, box=False, orientation='horizontal', ) gui.checkBox( widget=optionsBoxLine2, master=self, value='autoNumber', label=u'Auto-number with key:', labelWidth=180, callback=self.sendButton.settingsChanged, tooltip=(u"Annotate input segments with increasing numeric\n" u"indices\n\n" u"Note that a distinct index will be assigned to\n" u"each segment of each input segmentation."), ) self.autoNumberKeyLineEdit = gui.lineEdit( widget=optionsBoxLine2, master=self, value='autoNumberKey', orientation='horizontal', callback=self.sendButton.settingsChanged, tooltip=(u"Annotation key for input segment auto-numbering."), ) gui.separator(widget=optionsBox, height=3) gui.checkBox( widget=optionsBox, master=self, value='copyAnnotations', label=u'Copy annotations', callback=self.sendButton.settingsChanged, tooltip=(u"Copy all annotations from input to output segments."), ) gui.separator(widget=optionsBox, height=3) gui.checkBox( widget=optionsBox, master=self, value='mergeDuplicates', label=u'Fuse duplicates', callback=self.sendButton.settingsChanged, tooltip=(u"Fuse segments that have the same address.\n\n" u"The annotation of merged segments will be fused\n" u"as well. In the case where fused segments have\n" u"distinct values for the same annotation key, only\n" u"the value of the last one (in address order)\n" u"will be kept."), ) gui.separator(widget=optionsBox, height=2) gui.separator(widget=self.controlArea, height=3) gui.rubber(self.controlArea) # Send button... self.sendButton.draw() # Info box... self.infoBox.draw() self.sendButton.sendIf()
def __init__(self): super().__init__() #: Input data table self.data = None # type: Optional[Orange.data.Table] #: A dict mapping input ids to PredictorSlot self.predictors = OrderedDict() # type: Dict[object, PredictorSlot] #: A class variable (prediction target) self.class_var = None # type: Optional[Orange.data.Variable] #: List of (discrete) class variable's values self.class_values = [] # type: List[str] box = gui.vBox(self.controlArea, "信息") self.infolabel = gui.widgetLabel( box, "没有输入数据。\n预测因子: 0\n任务: N/A") self.infolabel.setMinimumWidth(150) gui.button(box, self, "恢复原始顺序", callback=self._reset_order, tooltip="按原始顺序显示行") self.classification_options = box = gui.vBox( self.controlArea, "显示", spacing=-1, addSpace=False) gui.checkBox(box, self, "show_predictions", "预测类", callback=self._update_prediction_delegate) b = gui.checkBox(box, self, "show_probabilities", "预测概率:", callback=self._update_prediction_delegate) ibox = gui.indentedBox(box, sep=gui.checkButtonOffsetHint(b), addSpace=False) gui.listBox(ibox, self, "selected_classes", "class_values", callback=self._update_prediction_delegate, selectionMode=QListWidget.MultiSelection, addSpace=False) gui.checkBox(box, self, "draw_dist", "绘制分布条", callback=self._update_prediction_delegate) box = gui.vBox(self.controlArea, "数据视图") gui.checkBox(box, self, "show_attrs", "显示完整数据集", callback=self._update_column_visibility) box = gui.vBox(self.controlArea, "输出", spacing=-1) self.checkbox_class = gui.checkBox( box, self, "output_attrs", "原始数据", callback=self.commit) self.checkbox_class = gui.checkBox( box, self, "output_predictions", "预测", callback=self.commit) self.checkbox_prob = gui.checkBox( box, self, "output_probabilities", "可能性", callback=self.commit) gui.rubber(self.controlArea) self.splitter = QSplitter( orientation=Qt.Horizontal, childrenCollapsible=False, handleWidth=2, ) self.dataview = TableView( verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn, horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOn, horizontalScrollMode=QTableView.ScrollPerPixel, selectionMode=QTableView.NoSelection, focusPolicy=Qt.StrongFocus ) self.predictionsview = TableView( verticalScrollBarPolicy=Qt.ScrollBarAlwaysOff, horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOn, horizontalScrollMode=QTableView.ScrollPerPixel, selectionMode=QTableView.NoSelection, focusPolicy=Qt.StrongFocus, sortingEnabled=True, ) self.predictionsview.setItemDelegate(PredictionsItemDelegate()) self.dataview.verticalHeader().hide() dsbar = self.dataview.verticalScrollBar() psbar = self.predictionsview.verticalScrollBar() psbar.valueChanged.connect(dsbar.setValue) dsbar.valueChanged.connect(psbar.setValue) self.dataview.verticalHeader().setDefaultSectionSize(22) self.predictionsview.verticalHeader().setDefaultSectionSize(22) self.dataview.verticalHeader().sectionResized.connect( lambda index, _, size: self.predictionsview.verticalHeader().resizeSection(index, size) ) self.splitter.addWidget(self.predictionsview) self.splitter.addWidget(self.dataview) self.mainArea.layout().addWidget(self.splitter)
def add_main_layout(self): self.data = None self.preprocessors = None self.learner = None self.scatterplot_item = None self.plot_item = None self.x_label = 'x' self.y_label = 'y' self.rmse = "" self.mae = "" self.regressor_name = self.default_learner_name # info box info_box = gui.vBox(self.controlArea, "Info") self.regressor_label = gui.label( widget=info_box, master=self, label="Regressor: %(regressor_name).30s") gui.label(widget=info_box, master=self, label="Mean absolute error: %(mae).6s") gui.label(widget=info_box, master=self, label="Root mean square error: %(rmse).6s") box = gui.vBox(self.controlArea, "Variables") self.x_var_model = itemmodels.VariableListModel() self.comboBoxAttributesX = gui.comboBox(box, self, value='x_var_index', label="Input: ", orientation=Qt.Horizontal, callback=self.apply, maximumContentsLength=15) self.comboBoxAttributesX.setModel(self.x_var_model) self.expansion_spin = gui.doubleSpin(gui.indentedBox(box), self, "polynomialexpansion", 0, 10, label="Polynomial expansion:", callback=self.apply) gui.separator(box, height=8) self.y_var_model = itemmodels.VariableListModel() self.comboBoxAttributesY = gui.comboBox(box, self, value="y_var_index", label="Target: ", orientation=Qt.Horizontal, callback=self.apply, maximumContentsLength=15) self.comboBoxAttributesY.setModel(self.y_var_model) properties_box = gui.vBox(self.controlArea, "Properties") self.error_bars_checkbox = gui.checkBox(widget=properties_box, master=self, value='error_bars_enabled', label="Show error bars", callback=self.apply) gui.rubber(self.controlArea) # main area GUI self.plotview = pg.PlotWidget(background="w") 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.x_label) axis.setPen(axis_pen) axis.setTickFont(tickfont) axis = self.plot.getAxis("left") axis.setLabel(self.y_label) axis.setPen(axis_pen) axis.setTickFont(tickfont) self.plot.setRange(xRange=(0.0, 1.0), yRange=(0.0, 1.0), disableAutoRange=True) self.mainArea.layout().addWidget(self.plotview)
def _init_layout(self): """Initialize widget layout.""" # Control area info_box = gui.widgetBox(self.controlArea, "Info", addSpace=True) self._info_label = gui.widgetLabel(info_box, "Initializing\n\n") box = gui.vBox(self.controlArea, "Average intervals:") self.ch_month = gui.checkBox(box, self, "include_month", "Month", callback=self.commit_if) self.ch_year = gui.checkBox(box, self, "include_year", 'Year', callback=self.commit_if) self.ch_decade = gui.checkBox(box, self, "include_decade", 'Decade', callback=self.commit_if) box = gui.vBox(self.controlArea, "Data Types") gui.checkBox(box, self, "include_temperature", "Temperature", callback=self.commit_if) gui.checkBox(box, self, "include_precipitation", 'Precipitation', callback=self.commit_if) output_box = gui.widgetBox(self.controlArea, "Output", addSpace=True) gui.radioButtonsInBox(output_box, self, "output_type", ["Countries", "Time Series"], "Rows", callback=self.output_type_selected) gui.checkBox(output_box, self, "use_country_names", "Use Country names", callback=self.commit_if) self.output_type = 0 # pylint: disable=duplicate-code gui.separator(output_box) gui.auto_commit(self.controlArea, self, "auto_commit", "Commit", box="Commit") gui.rubber(self.controlArea) # Main area box = gui.widgetBox(self.mainArea, "Countries") self.country_tree = CountryTreeWidget( self.mainArea, self.country_selection, commit_callback=self.commit_if, default_colapse=True, default_select=False, ) self.country_tree.set_data(countries.get_countries_dict()) box.layout().addWidget(self.country_tree) self.resize(500, 400) # why does this not work
def __init__(self, parent=None): super().__init__(parent) self.train_data = None self.test_data = None #: An Ordered dictionary with current inputs and their testing #: results. self.learners = OrderedDict() sbox = gui.widgetBox(self.controlArea, "Sampling") rbox = gui.radioButtons(sbox, self, "resampling", callback=self._param_changed) gui.appendRadioButton(rbox, "Cross validation") ibox = gui.indentedBox(rbox) gui.spin(ibox, self, "k_folds", 2, 50, label="Number of folds:", callback=self._param_changed) gui.appendRadioButton(rbox, "Leave one out") gui.appendRadioButton(rbox, "Random sampling") ibox = gui.indentedBox(rbox) gui.spin(ibox, self, "n_repeat", 2, 50, label="Repeat train/test", callback=self._param_changed) gui.widgetLabel(ibox, "Relative training set size:") gui.hSlider(ibox, self, "sample_p", minValue=1, maxValue=100, ticks=20, vertical=False, callback=self._param_changed) gui.appendRadioButton(rbox, "Test on train data") gui.appendRadioButton(rbox, "Test on test data") rbox.layout().addSpacing(5) gui.button(rbox, self, "Apply", callback=self.apply) gui.rubber(self.controlArea) self.view = QTreeView(rootIsDecorated=False, uniformRowHeights=True, wordWrap=True, editTriggers=QTreeView.NoEditTriggers) self.result_model = QStandardItemModel() self.result_model.setHorizontalHeaderLabels( ["Method"] + classification_stats.headers) self.view.setModel(self.result_model) box = gui.widgetBox(self.mainArea, "Evaluation Results") box.layout().addWidget(self.view)
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 = [] #: 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[Task] 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], maximumContentsLength=3, 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], maximumContentsLength=3, 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], maximumContentsLength=5, 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, valueType=str, callback=self._on_target_class_changed, contentsLength=8) gui.rubber(self.controlArea) self.view = gui.TableView( wordWrap=True, editTriggers=gui.TableView.NoEditTriggers ) header = self.view.horizontalHeader() header.setSectionResizeMode(QHeaderView.ResizeToContents) header.setDefaultAlignment(Qt.AlignCenter) header.setStretchLastSection(False) header.setContextMenuPolicy(Qt.CustomContextMenu) header.customContextMenuRequested.connect(self.show_column_chooser) self.result_model = QStandardItemModel(self) self.result_model.setHorizontalHeaderLabels(["Method"]) self.view.setModel(self.result_model) self.view.setItemDelegate(ItemDelegate()) box = gui.vBox(self.mainArea, "Evaluation Results") box.layout().addWidget(self.view)
def __init__(self): super().__init__() self.data = None self.removedAttrs = "-" self.reducedAttrs = "-" self.resortedAttrs = "-" self.removedClasses = "-" self.reducedClasses = "-" self.resortedClasses = "-" self.removedMetas = "-" self.reducedMetas = "-" def add_line(parent): frame = QFrame() frame.setFrameShape(QFrame.HLine) frame.setFrameShadow(QFrame.Sunken) parent.layout().addSpacing(6) parent.layout().addWidget(frame) parent.layout().addSpacing(6) boxAt = gui.vBox(self.controlArea, "Features") for not_first, (value, label) in enumerate(self.feature_options): if not_first: gui.separator(boxAt, 2) gui.checkBox(boxAt, self, value, label, callback=self.optionsChanged) add_line(boxAt) gui.label( boxAt, self, "Sorted: %(resortedAttrs)s, " "reduced: %(reducedAttrs)s, removed: %(removedAttrs)s") boxAt = gui.vBox(self.controlArea, "Classes", addSpace=True) for not_first, (value, label) in enumerate(self.class_options): if not_first: gui.separator(boxAt, 2) gui.checkBox(boxAt, self, value, label, callback=self.optionsChanged) add_line(boxAt) gui.label( boxAt, self, "Sorted: %(resortedClasses)s," "reduced: %(reducedClasses)s, removed: %(removedClasses)s") boxAt = gui.vBox(self.controlArea, "Meta attributes", addSpace=True) for not_first, (value, label) in enumerate(self.meta_options): if not_first: gui.separator(boxAt, 2) gui.checkBox(boxAt, self, value, label, callback=self.optionsChanged) add_line(boxAt) gui.label(boxAt, self, "Reduced: %(reducedMetas)s, removed: %(removedMetas)s") gui.auto_send(self.buttonsArea, self, "autoSend") gui.rubber(self.controlArea) self.info.set_input_summary(self.info.NoInput) self.info.set_output_summary(self.info.NoOutput)
def __init__(self, *args, **kwargs): """Initialize a Length widget""" super().__init__(*args, **kwargs) self.windowSize = 1 self.infoBox = InfoBox( widget=self.controlArea, stringClickSend=u", please click 'Send' when ready.", ) self.sendButton = SendButton( widget=self.controlArea, master=self, callback=self.sendData, infoBoxAttribute='infoBox', buttonLabel=u'Send', checkboxLabel=u'Send automatically', sendIfPreCallback=self.updateGUI, ) # GUI... # Units box self.unitsBox = gui.widgetBox( widget=self.controlArea, box=u'Units', orientation='vertical', addSpace=True, ) self.unitSegmentationCombo = gui.comboBox( widget=self.unitsBox, master=self, value='units', orientation='horizontal', label=u'Segmentation:', labelWidth=190, callback=self.sendButton.settingsChanged, tooltip=( u"The segmentation whose segments constitute the\n" u"units of length." ), ) self.unitSegmentationCombo.setMinimumWidth(120) gui.separator(widget=self.unitsBox, height=3) # Averaging box... self.averagingBox = gui.widgetBox( widget=self.controlArea, box=u'Averaging', orientation='vertical', addSpace=True, ) averagingBoxLine1 = gui.widgetBox( widget=self.averagingBox, box=False, orientation='horizontal', addSpace=True, ) gui.checkBox( widget=averagingBoxLine1, master=self, value='computeAverage', label=u'Average over segmentation:', labelWidth=190, callback=self.sendButton.settingsChanged, tooltip=( u"Check this box in order to measure the average\n" u"length of segments.\n\n" u"Leaving this box unchecked implies that no\n" u"averaging will take place." ), ) self.averagingSegmentationCombo = gui.comboBox( widget=averagingBoxLine1, master=self, value='averagingSegmentation', orientation='horizontal', callback=self.sendButton.settingsChanged, tooltip=( u"The segmentation whose segment length will be\n" u"measured and averaged (if the box to the left\n" u"is checked)." ), ) self.computeStdevCheckBox = gui.checkBox( widget=self.averagingBox, master=self, value='computeStdev', label=u'Compute standard deviation', callback=self.sendButton.settingsChanged, tooltip=( u"Check this box to compute not only length average\n" u"but also standard deviation (if the above box\n" u"is checked).\n\n" u"Note that computing standard deviation can be a\n" u"lengthy operation for large segmentations." ), ) gui.separator(widget=self.averagingBox, height=2) # Contexts box... self.contextsBox = gui.widgetBox( widget=self.controlArea, box=u'Contexts', orientation='vertical', addSpace=True, ) self.modeCombo = gui.comboBox( widget=self.contextsBox, master=self, value='mode', sendSelectedValue=True, items=[ u'No context', u'Sliding window', u'Containing segmentation', ], orientation='horizontal', label=u'Mode:', labelWidth=190, callback=self.sendButton.settingsChanged, tooltip=( u"Context specification mode.\n\n" u"Contexts define the rows of the resulting table.\n\n" u"'No context': simply return the length of the\n" u"'Units' segmentation, or the average length of\n" u"segments in the 'Averaging' segmentation (if any),\n" u"so that the output table contains a single row.\n\n" u"'Sliding window': contexts are defined as all the\n" u"successive, overlapping sequences of n segments\n" u"in the 'Averaging' segmentation; this mode is\n" u"available only if the 'Averaging' box is checked.\n\n" u"'Containing segmentation': contexts are defined\n" u"as the distinct segments occurring in a given\n" u"segmentation (which may or may not be the same\n" u"as the 'Units' and/or 'Averaging' segmentation)." ), ) self.slidingWindowBox = gui.widgetBox( widget=self.contextsBox, orientation='vertical', ) gui.separator(widget=self.slidingWindowBox, height=3) self.windowSizeSpin = gui.spin( widget=self.slidingWindowBox, master=self, value='windowSize', minv=1, maxv=1, step=1, orientation='horizontal', label=u'Window size:', labelWidth=190, callback=self.sendButton.settingsChanged, keyboardTracking=False, tooltip=( u"The length of segment sequences defining contexts." ), ) self.containingSegmentationBox = gui.widgetBox( widget=self.contextsBox, orientation='vertical', ) gui.separator(widget=self.containingSegmentationBox, height=3) self.contextSegmentationCombo = gui.comboBox( widget=self.containingSegmentationBox, master=self, value='_contexts', orientation='horizontal', label=u'Segmentation:', labelWidth=190, callback=self.sendButton.settingsChanged, tooltip=( u"The segmentation whose segment types define\n" u"the contexts in which length will be measured." ), ) gui.separator(widget=self.containingSegmentationBox, height=3) self.contextAnnotationCombo = gui.comboBox( widget=self.containingSegmentationBox, master=self, value='contextAnnotationKey', sendSelectedValue=True, emptyString=u'(none)', orientation='horizontal', label=u'Annotation key:', labelWidth=190, callback=self.sendButton.settingsChanged, tooltip=( u"Indicate whether context types are defined by\n" u"the content of segments in the above specified\n" u"segmentation (value 'none') or by their\n" u"annotation values for a specific annotation key." ), ) gui.separator(widget=self.containingSegmentationBox, height=3) gui.checkBox( widget=self.containingSegmentationBox, master=self, value='mergeContexts', label=u'Merge contexts', callback=self.sendButton.settingsChanged, tooltip=( u"Check this box if you want to treat all segments\n" u"of the above specified segmentation as forming\n" u"a single context (hence the resulting table\n" u"contains a single row)." ), ) gui.separator(widget=self.contextsBox, height=3) gui.rubber(self.controlArea) # Send button... self.sendButton.draw() # Info box... self.infoBox.draw() self.sendButton.sendIf() self.adjustSizeWithTimer()