Example #1
0
    def __init__(self):
        super().__init__()
        self.data = None
        self.preprocessors = None

        box = gui.widgetBox(self.controlArea, "Learner/Classifier Name")
        gui.lineEdit(box, self, "learner_name")

        box = gui.widgetBox(self.controlArea, "Neighbors")
        gui.spin(box, self, "n_neighbors", 1, 100, label="Number of neighbors",
                 alignment=Qt.AlignRight)
        gui.comboBox(box, self, "metric_index", label="Metric",
                     orientation="horizontal",
                     items=[i.capitalize() for i in self.metrics])
        gui.comboBox(box, self, "weight_type", label='Weight',
                     orientation="horizontal",
                     items=[i.capitalize() for i in self.weights])

        g = QHBoxLayout()
        self.controlArea.layout().addLayout(g)
        apply = gui.button(None, self, "Apply",
                           callback=self.apply, default=True)
        g.layout().addWidget(self.report_button)
        g.layout().addWidget(apply)
        self.apply()
    def __init__(self):
        super().__init__()

        box = gui.widgetBox(self.controlArea, "Movie Selection (from %d)" % len(movielens.get_all_movie_names()))
        methodbox = gui.radioButtons(box, self, "method", callback=self._on_method_changed)

        gui.appendRadioButton(methodbox, "Fraction of movies")
        percent = gui.hSlider(
            gui.indentedBox(methodbox), self, "percent", minValue=1, maxValue=100, step=1, ticks=10, labelFormat="%d %%"
        )

        gui.appendRadioButton(methodbox, "Time period:")
        ibox = gui.indentedBox(methodbox)
        start = gui.spin(ibox, self, "start", 1907, 2015, 1, label="Starting year: ")
        end = gui.spin(ibox, self, "end", 1907, 2015, 1, label="Ending year: ")

        self.method_params = [percent, start, end]

        gui.button(self.controlArea, self, "&Apply", callback=self.send_output, default=True)

        self.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed))

        self.setMinimumWidth(250)
        self.setMaximumWidth(250)
        self._on_method_changed()
        self.send_output()
Example #3
0
    def __init__(self):
        super().__init__()

        self.net = None
        self.method = 0
        self.iterationHistory = 0
        self.autoApply = 0
        self.iterations = 1000
        self.hop_attenuation = 0.1

        commit = lambda: self.commit()
        gui.spin(self.controlArea, self, "iterations", 1,
                   100000, 1, label="Iterations: ",
                   callback=commit)
        ribg = gui.radioButtonsInBox(
            self.controlArea, self, "method",
            btnLabels=["Label propagation clustering (Raghavan et al., 2007)",
                    "Label propagation clustering (Leung et al., 2009)"],
            label="Method", callback=commit)

        gui.doubleSpin(gui.indentedBox(ribg), self, "hop_attenuation",
                         0, 1, 0.01, label="Hop attenuation (delta): ")

        self.info = gui.widgetLabel(self.controlArea, ' ')
        gui.checkBox(self.controlArea, self, "iterationHistory",
                       "Append clustering data on each iteration",
                       callback=commit)

        gui.auto_commit(self.controlArea, self, "autoApply", 'Commit',
                        checkbox_label='Auto-commit')
        commit()
Example #4
0
    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):
     self.data = None
     box = gui.vBox(self.controlArea, 'Differencing')
     self.order_spin = gui.spin(
         box, self, 'diff_order', 1, 2,
         label='Differencing order:',
         callback=self.on_changed,
         tooltip='The value corresponds to n-th order numerical '
                 'derivative of the series. \nThe order is fixed to 1 '
                 'if the shift period is other than 1.')
     gui.spin(box, self, 'shift_period', 1, 100,
              label='Shift:',
              callback=self.on_changed,
              tooltip='Set this to other than 1 if you don\'t want to '
                      'compute differences for subsequent values but for '
                      'values shifted number of spaces apart. \n'
                      'If this value is different from 1, differencing '
                      'order is fixed to 1.')
     gui.checkBox(box, self, 'invert_direction',
                  label='Invert differencing direction',
                  callback=self.on_changed,
                  tooltip='Influences where the series is padded with nan '
                          'values — at the beginning or at the end.')
     self.view = view = QListView(self,
                                  selectionMode=QListView.ExtendedSelection)
     self.model = model = VariableListModel(parent=self)
     view.setModel(model)
     view.selectionModel().selectionChanged.connect(self.on_changed)
     box.layout().addWidget(view)
     gui.auto_commit(box, self, 'autocommit', '&Apply')
Example #6
0
    def __init__(self):
        super().__init__()

        self.data = None
        self.reference = None
        self.distances = None

        box = gui.vBox(self.controlArea, "Info")
        self.data_info_label = gui.widgetLabel(box, "")
        self.reference_info_label = gui.widgetLabel(box, "")
        self._set_label_text("data")
        self._set_label_text("reference")

        box = gui.vBox(self.controlArea, box=True)
        gui.comboBox(
            box, self, "distance_index", orientation=Qt.Horizontal,
            label="Distance: ", items=[d[0] for d in METRICS],
            callback=self.recompute)
        gui.spin(
            box, self, "n_neighbors", label="Number of neighbors:",
            step=1, spinType=int, minv=0, maxv=100, callback=self.apply)
        gui.checkBox(
            box, self, "exclude_reference",
            label="Exclude rows (equal to) references",
            callback=self.apply)

        self.apply_button = gui.auto_commit(
            self.controlArea, self, "auto_apply", "&Apply", commit=self.apply)
Example #7
0
    def _add_controls_start_box(self):
        box = gui.vBox(self.controlArea, True)
        form = QFormLayout(
            labelAlignment=Qt.AlignLeft,
            formAlignment=Qt.AlignLeft,
            fieldGrowthPolicy=QFormLayout.AllNonFixedFieldsGrow,
            verticalSpacing=10
        )

        form.addRow(
            "Max iterations:",
            gui.spin(box, self, "max_iter", 1, 2000, step=50))

        form.addRow(
            "Perplexity:",
            gui.spin(box, self, "perplexity", 1, 100, step=1))

        box.layout().addLayout(form)

        gui.separator(box, 10)
        self.runbutton = gui.button(box, self, "Run", callback=self._toggle_run)

        gui.separator(box, 10)
        gui.hSlider(box, self, "pca_components", label="PCA components:",
                    minValue=2, maxValue=50, step=1)
Example #8
0
    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()
Example #9
0
    def __init__(self):
        super().__init__()

        self.preprocessors = None
        self.data = None

        box = gui.widgetBox(self.controlArea, "Learner/Model Name")
        gui.lineEdit(box, self, "learner_name")

        box = gui.widgetBox(self.controlArea, "Neighbors")
        gui.spin(box, self, "n_neighbors", 1, 100, label="Number of neighbors")

        box = gui.widgetBox(box, "Metric")
        box.setFlat(True)
        box.layout().setContentsMargins(0, 0, 0, 0)

        gui.comboBox(box, self, "metric_index",
                     items=["Euclidean", "Manhattan", "Maximal", "Mahalanobis"])
        self.metrics = ["euclidean", "manhattan", "chebyshev", "mahalanobis"]

        gui.button(self.controlArea, self, "Apply",
                   callback=self.apply, default=True)
        self.controlArea.layout().addWidget(self.report_button)

        layout = self.layout()
        self.layout().setSizeConstraint(layout.SetFixedSize)

        self.apply()
Example #10
0
    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)
Example #11
0
    def add_main_layout(self):
        box = gui.widgetBox(self.controlArea, "Parameters")
        self.base_estimator = self.DEFAULT_BASE_ESTIMATOR
        self.base_label = gui.label(
            box, self, "Base estimator: " + self.base_estimator.name.title())

        self.n_estimators_spin = gui.spin(
            box, self, "n_estimators", 1, 100, label="Number of estimators:",
            alignment=Qt.AlignRight, controlWidth=80,
            callback=self.settings_changed)
        self.learning_rate_spin = gui.doubleSpin(
            box, self, "learning_rate", 1e-5, 1.0, 1e-5,
            label="Learning rate:", decimals=5, alignment=Qt.AlignRight,
            controlWidth=80, callback=self.settings_changed)
        self.random_seed_spin = gui.spin(
            box, self, "random_seed", 0, 2 ** 31 - 1, controlWidth=80,
            label="Fixed seed for random generator:", alignment=Qt.AlignRight,
            callback=self.settings_changed, checked="use_random_seed",
            checkCallback=self.settings_changed)

        # Algorithms
        box = gui.widgetBox(self.controlArea, "Boosting method")
        self.cls_algorithm_combo = gui.comboBox(
            box, self, "algorithm_index", label="Classification algorithm:",
            items=self.algorithms,
            orientation=Qt.Horizontal, callback=self.settings_changed)
        self.reg_algorithm_combo = gui.comboBox(
            box, self, "loss_index", label="Regression loss function:",
            items=self.losses,
            orientation=Qt.Horizontal, callback=self.settings_changed)
Example #12
0
    def __init__(self):
        super().__init__()

        self.net = None

        commit = lambda: self.commit()
        gui.spin(self.controlArea, self, "iterations", 1, 100000, 1, label="Max. iterations:", callback=commit)
        ribg = gui.radioButtonsInBox(
            self.controlArea,
            self,
            "method",
            btnLabels=[
                "Label propagation clustering (Raghavan et al., 2007)",
                "Label propagation clustering (Leung et al., 2009)",
            ],
            box="Clustering method",
            callback=commit,
        )

        gui.doubleSpin(gui.indentedBox(ribg), self, "hop_attenuation", 0, 1, 0.01, label="Hop attenuation (delta): ")

        self.info = gui.widgetLabel(self.controlArea, " ")

        gui.auto_commit(self.controlArea, self, "autoApply", "Commit", checkbox_label="Auto-commit")
        commit()
Example #13
0
    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)
Example #14
0
    def __init__(self, parent=None):
        super().__init__(parent)
        self.data = None
        self.preprocessors = None

        box = gui.widgetBox(self.controlArea, "Learner/Classifier Name")
        gui.lineEdit(box, self, "learner_name")

        box = gui.widgetBox(self.controlArea, "Neighbors")
        gui.spin(box, self, "n_neighbors", 1, 100, label="Number of neighbors")

        box = gui.widgetBox(box, "Metric")
        box.setFlat(True)

        gui.comboBox(box, self, "metric_index",
                     items=["Euclidean", "Manhattan", "Maximal", "Mahalanobis"])
        self.metrics = ["euclidean", "manhattan", "chebyshev", "mahalanobis"]

        gui.button(self.controlArea, self, "Apply",
                   callback=self.apply, default=True)

        self.setMinimumWidth(250)
        layout = self.layout()
        self.layout().setSizeConstraint(layout.SetFixedSize)

        self.apply()
Example #15
0
    def add_main_layout(self):
        box = gui.vBox(self.controlArea, 'Basic Properties')
        self.n_estimators_spin = gui.spin(
            box, self, "n_estimators", minv=1, maxv=10000, controlWidth=50,
            label="Number of trees: ", callback=self.settings_changed)
        self.max_features_spin = gui.spin(
            box, self, "max_features", 2, 50, controlWidth=50,
            label="Number of attributes considered at each split: ",
            callback=self.settings_changed, checked="use_max_features",
            checkCallback=self.settings_changed)
        self.random_state_spin = gui.spin(
            box, self, "random_state", 0, 2 ** 31 - 1, controlWidth=50,
            label="Fixed seed for random generator: ",
            callback=self.settings_changed, checked="use_random_state",
            checkCallback=self.settings_changed)

        box = gui.vBox(self.controlArea, "Growth Control")
        self.max_depth_spin = gui.spin(
            box, self, "max_depth", 1, 50, controlWidth=50,
            label="Limit depth of individual trees: ",
            callback=self.settings_changed, checked="use_max_depth",
            checkCallback=self.settings_changed)
        self.min_samples_split_spin = gui.spin(
            box, self, "min_samples_split", 1, 1000, controlWidth=50,
            label="Do not split subsets smaller than: ",
            callback=self.settings_changed, checked="use_min_samples_split",
            checkCallback=self.settings_changed)
Example #16
0
    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_main_layout(self):
     box = gui.vBox(self.controlArea, True)
     # the checkbox is put into vBox for alignemnt with other checkboxes
     gui.checkBox(gui.vBox(box), self, "binary_trees", "Induce binary tree",
                  callback=self.settings_changed)
     for label, check, setting, fromv, tov in self.spin_boxes:
         gui.spin(box, self, setting, fromv, tov, label=label, checked=check,
                  alignment=Qt.AlignRight, callback=self.settings_changed,
                  checkCallback=self.settings_changed, controlWidth=80)
 def add_bottom_buttons(self):
     box = gui.vBox(self.controlArea, 'Forecast')
     gui.spin(box, self, 'forecast_steps', 1, 100,
              label='Forecast steps ahead:',
              callback=self.apply)
     gui.hSlider(box, self, 'forecast_confint',
                 None, 1, 99, label='Confidence intervals:',
                 callback=self.apply)
     gui.auto_commit(self.controlArea, self, 'autocommit', "&Apply")
Example #19
0
    def addHistogramControls(self, parent=None):
        if parent is None:
            parent = self.controlArea

        boxGeneral = gui.widgetBox(parent, box="Edges")
        ribg = gui.widgetBox(boxGeneral, None, orientation="horizontal", addSpace=False)
        ribg.layout().addWidget(QLabel("Distance threshold", self),
                                4, Qt.AlignVCenter | Qt.AlignLeft)
        self.spin_low = gui.doubleSpin(ribg, self, "spinLowerThreshold",
                         0.0, float("inf"), 0.001, decimals=3,
                         callback=self.changeLowerSpin,
                         keyboardTracking=False)
        ribg.layout().addWidget(QLabel("to", self), 1, Qt.AlignCenter)
        self.spin_high = gui.doubleSpin(ribg, self, "spinUpperThreshold",
                         0.0, float("inf"), 0.001, decimals=3,
                         callback=self.changeUpperSpin,
                         keyboardTracking=False)
        self.histogram.region.sigRegionChangeFinished.connect(self.spinboxFromHistogramRegion)
#         gui.lineEdit(ribg, self, "spinLowerThreshold", "Distance threshold   ", orientation='horizontal', callback=self.changeLowerSpin, valueType=float, validator=self.validator, enterPlaceholder=True, controlWidth=60)
#         gui.lineEdit(ribg, self, "spinUpperThreshold", "", orientation='horizontal', callback=self.changeUpperSpin, valueType=float, validator=self.validator, enterPlaceholder=True, controlWidth=60)
#         ribg.layout().addStretch(1)
        #ribg = gui.radioButtonsInBox(boxGeneral, self, "andor", [], orientation='horizontal', callback = self.generateGraph)
        #gui.appendRadioButton(ribg, self, "andor", "OR", callback = self.generateGraph)
        #b = gui.appendRadioButton(ribg, self, "andor", "AND", callback = self.generateGraph)
        #b.setEnabled(False)
        #ribg.hide(False)

        ribg = gui.widgetBox(boxGeneral, None, orientation="horizontal", addSpace=False)

        gui.doubleSpin(boxGeneral, self, "percentil", 0, 100, 0.1, label="Percentile", orientation='horizontal', callback=self.setPercentil, callbackOnReturn=1, controlWidth=60)
        gui.spin(boxGeneral, self, "kNN", 0, 1000, 1, label="Include closest neighbors", orientation='horizontal', callback=self.generateGraph, callbackOnReturn=1, controlWidth=60)
        ribg.layout().addStretch(1)
        # Options
        self.attrColor = ""
        ribg = gui.radioButtonsInBox(parent, self, "netOption", [], "Node selection", callback=self.generateGraph)
        gui.appendRadioButton(ribg, "Keep all nodes")
        hb = gui.widgetBox(ribg, None, orientation="horizontal", addSpace=False)
        gui.appendRadioButton(ribg, "Components with at least nodes", insertInto=hb)
        gui.spin(hb, self, "excludeLimit", 2, 100, 1, callback=(lambda h=True: self.generateGraph(h)), controlWidth=60)
        gui.appendRadioButton(ribg, "Largest connected component")
        #gui.appendRadioButton(ribg, self, "netOption", "Connected component with vertex")
        self.attribute = None

        ### FILTER NETWORK BY ATTRIBUTE IS OBSOLETE - USE SELECT DATA WIDGET ###
        #self.attributeCombo = gui.comboBox(parent, self, "attribute", box="Filter attribute", orientation='horizontal')#, callback=self.setVertexColor)
        #self.label = ''
        #self.searchString = gui.lineEdit(self.attributeCombo.box, self, "label", callback=self.setSearchStringTimer, callbackOnType=True)
        #self.searchStringTimer = QTimer(self)
        #self.connect(self.searchStringTimer, SIGNAL("timeout()"), self.generateGraph)
        #if str(self.netOption) != '3':
        #    self.attributeCombo.box.setEnabled(False)

        ribg = gui.radioButtonsInBox(parent, self, "dstWeight", [], "Edge weights", callback=self.generateGraph)
        hb = gui.widgetBox(ribg, None, orientation="horizontal", addSpace=False)
        gui.appendRadioButton(ribg, "Proportional to distance", insertInto=hb)
        gui.appendRadioButton(ribg, "Inverted distance", insertInto=hb)
    def add_main_layout(self):
        # var models
        self.x_var_model = itemmodels.VariableListModel()
        self.y_var_model = itemmodels.VariableListModel()

        # options box
        self.options_box = gui.widgetBox(self.controlArea, "Options")
        opts = dict(
            widget=self.options_box, master=self, orientation=Qt.Horizontal)
        opts_combo = dict(opts, **dict(sendSelectedValue=True,
                                       maximumContentsLength=15))
        self.cbx = gui.comboBox(
            value='attr_x', label='X: ', callback=self.apply, **opts_combo)
        self.cby = gui.comboBox(
            value='attr_y', label='Y: ', callback=self.apply, **opts_combo)
        self.target_class_combobox = gui.comboBox(
            value='target_class', label='Target: ',
            callback=self.apply, **opts_combo)
        self.degree_spin = gui.spin(
            value='degree', label='Polynomial expansion:',
            minv=1, maxv=5, step=1, callback=self.init_learner,
            alignment=Qt.AlignRight, controlWidth=70, **opts)

        self.cbx.setModel(self.x_var_model)
        self.cby.setModel(self.y_var_model)

        # plot properties box
        self.plot_properties_box = gui.widgetBox(
            self.controlArea, "Plot Properties")
        self.legend_enabled_checkbox = gui.checkBox(
            self.plot_properties_box, self, 'legend_enabled',
            label="Show legend", callback=self.replot)
        self.contours_enabled_checkbox = gui.checkBox(
            self.plot_properties_box, self, 'contours_enabled',
            label="Show contours", callback=self.plot_contour)
        self.contour_step_slider = gui.spin(
            self.plot_properties_box, self, 'contour_step',
            minv=0.10, maxv=0.50, step=0.05, callback=self.plot_contour,
            label='Contour step:', decimals=2, spinType=float,
            alignment=Qt.AlignRight, controlWidth=70)

        gui.rubber(self.controlArea)

        # chart
        self.scatter = Scatterplot(
            xAxis_gridLineWidth=0, yAxis_gridLineWidth=0,
            xAxis_startOnTick=False, xAxis_endOnTick=False,
            yAxis_startOnTick=False, yAxis_endOnTick=False,
            xAxis_lineWidth=0, yAxis_lineWidth=0,
            yAxis_tickWidth=1, title_text='', tooltip_shared=False)

        # Just render an empty chart so it shows a nice 'No data to display'
        self.scatter.chart()
        self.mainArea.layout().addWidget(self.scatter)

        self.init_learner()
Example #21
0
 def add_group_settings(self, parent):
     box = gui.vBox(parent, "Groups")
     box2 = gui.hBox(box)
     gui.checkBox(box2, self, "graph.group_lines", "Group lines into", tooltip="Show clusters instead of lines",
                  callback=self.update_graph)
     gui.spin(box2, self, "graph.number_of_groups", 0, 30, callback=self.update_graph)
     gui.label(box2, self, "groups")
     box2 = gui.hBox(box)
     gui.spin(box2, self, "graph.number_of_steps", 0, 100, label="In no more than", callback=self.update_graph)
     gui.label(box2, self, "steps")
Example #22
0
    def __init__(self):
        self.tree = QTreeWidget(self.mainArea,
                                columnCount=2,
                                allColumnsShowFocus=True,
                                alternatingRowColors=True,
                                selectionMode=QTreeWidget.ExtendedSelection,
                                uniformRowHeights=True)
        self.tree.setHeaderLabels(["Itemsets", "Support", "%"])
        self.tree.header().setStretchLastSection(True)
        self.tree.itemSelectionChanged.connect(self.selectionChanged)
        self.mainArea.layout().addWidget(self.tree)

        box = gui.widgetBox(self.controlArea, "Info")
        self.nItemsets = self.nSelectedExamples = self.nSelectedItemsets = ''
        gui.label(box, self, "Number of itemsets: %(nItemsets)s")
        gui.label(box, self, "Selected itemsets: %(nSelectedItemsets)s")
        gui.label(box, self, "Selected examples: %(nSelectedExamples)s")
        hbox = gui.widgetBox(box, orientation='horizontal')
        gui.button(hbox, self, "Expand all", callback=self.tree.expandAll)
        gui.button(hbox, self, "Collapse all", callback=self.tree.collapseAll)

        box = gui.widgetBox(self.controlArea, 'Find itemsets')
        gui.hSlider(box, self, 'minSupport', minValue=1, maxValue=100,
                    label='Minimal support:', labelFormat="%d%%",
                    callback=lambda: self.find_itemsets())
        gui.hSlider(box, self, 'maxItemsets', minValue=10000, maxValue=100000, step=10000,
                    label='Max. number of itemsets:', labelFormat="%d",
                    callback=lambda: self.find_itemsets())
        gui.checkBox(box, self, 'filterSearch',
                     label='Apply below filters in search',
                     tooltip='If checked, the itemsets are filtered according '
                             'to below filter conditions already in the search '
                             'phase. \nIf unchecked, the only filters applied '
                             'during search are the ones above, '
                             'and the itemsets are \nfiltered afterwards only for '
                             'display, i.e. only the matching itemsets are shown.')
        self.button = gui.auto_commit(
            box, self, 'autoFind', 'Find itemsets', commit=self.find_itemsets)

        box = gui.widgetBox(self.controlArea, 'Filter itemsets')
        gui.lineEdit(box, self, 'filterKeywords', '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, 'filterMinItems', 1, 998, label='Min. items:',
                 callback=self.filter_change)
        gui.spin(hbox, self, 'filterMaxItems', 2, 999, label='Max. items:',
                 callback=self.filter_change)
        gui.rubber(hbox)

        gui.rubber(self.controlArea)
        gui.auto_commit(self.controlArea, self, 'autoSend', 'Send selection')

        self.filter_change()
Example #23
0
    def add_main_layout(self):
        box = gui.widgetBox(self.controlArea, "Parameters")
        self.base_estimator = TreeLearner()
        self.base_label = gui.label(box, self, "Base estimator: " + self.base_estimator.name)

        gui.spin(box, self, "n_estimators", 1, 100, label="Number of estimators:",
                 alignment=Qt.AlignRight, callback=self.settings_changed)
        gui.doubleSpin(box, self, "learning_rate", 1e-5, 1.0, 1e-5,
                       label="Learning rate:", decimals=5, alignment=Qt.AlignRight,
                       controlWidth=90, callback=self.settings_changed)
        self.add_specific_parameters(box)
Example #24
0
    def __init__(self):
        super().__init__()

        self._nhops = 2

        ib = gui.widgetBox(self.controlArea, "Preferences", orientation="vertical")
        gui.spin(ib, self, "_nhops", 1, 6, 1, label="Number of hops: ", callback=self.update_view)

        self.inside_view = NxInsideView(self._nhops)
        self.send("Nx View", self.inside_view)

        self.warning('This widget, at best, does nothing at the moment. Check back later.')
Example #25
0
 def add_main_layout(self):
     box = gui.vBox(self.controlArea, "Neighbors")
     gui.spin(box, self, "n_neighbors", 1, 100, label="Number of neighbors:",
              alignment=Qt.AlignRight, callback=self.settings_changed)
     gui.comboBox(box, self, "metric_index", label="Metric:",
                  orientation=Qt.Horizontal,
                  items=[i.capitalize() for i in self.metrics],
                  callback=self.settings_changed)
     gui.comboBox(box, self, "weight_type", label="Weight:",
                  orientation=Qt.Horizontal,
                  items=[i.capitalize() for i in self.weights],
                  callback=self.settings_changed)
Example #26
0
    def create_configuration_layout(self):
        layout = QFormLayout()

        spin = gui.spin(self, self, 'f', minv=1,
                        maxv=SimhashVectorizer.max_f)
        spin.editingFinished.connect(self.on_change)
        layout.addRow('Simhash size:', spin)

        spin = gui.spin(self, self, 'shingle_len', minv=1, maxv=100)
        spin.editingFinished.connect(self.on_change)
        layout.addRow('Shingle length:', spin)
        return layout
Example #27
0
    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 add_main_layout(self):
     box = gui.vBox(self.controlArea, box='Parameters')
     gui.spin(box, self, 'maxlags', 1, 100, label='Maximum auto-regression order:',
              callback=self.apply)
     gui.radioButtons(
         box, self, 'ic',
         btnLabels=tuple(self.IC_LABELS.keys()),
         box='Information criterion', label='Optimize AR order by:',
         callback=self.apply)
     gui.radioButtons(
         box, self, 'trend',
         btnLabels=tuple(self.TREND_LABELS.keys()),
         box='Trend', label='Add trend vector(s):',
         callback=self.apply)
Example #29
0
    def __init__(self, parent=None):
        super().__init__(parent)
        self.data = None

        self._invalidated = False
        self._pca = None
        self._variance_ratio = None
        self._cumulative = None
        self._line = False

        box = gui.widgetBox(self.controlArea, "Components Selection")
        form = QFormLayout()
        box.layout().addLayout(form)

        self.components_spin = gui.spin(
            box, self, "max_components", 0, 1000,
            callback=self._update_selection,
            keyboardTracking=False
        )
        self.components_spin.setSpecialValueText("All")

        self.variance_spin = gui.spin(
            box, self, "variance_covered", 1, 100,
            callback=self._update_selection,
            keyboardTracking=False
        )
        self.variance_spin.setSuffix("%")

        form.addRow("Max components", self.components_spin)
        form.addRow("Variance covered", self.variance_spin)

        self.controlArea.layout().addStretch()

        box = gui.widgetBox(self.controlArea, "Commit")
        cb = gui.checkBox(box, self, "auto_commit", "Commit on any change")
        b = gui.button(box, self, "Commit", callback=self.commit, default=True)
        gui.setStopper(self, b, cb, "_invalidated", callback=self.commit)

        self.plot = pg.PlotWidget(background="w")

        axis = self.plot.getAxis("bottom")
        axis.setLabel("Principal Components")
        axis = self.plot.getAxis("left")
        axis.setLabel("Proportion of variance")

        self.plot.getViewBox().setMenuEnabled(False)
        self.plot.showGrid(True, True, alpha=0.5)
        self.plot.setRange(xRange=(0.0, 1.0), yRange=(0.0, 1.0))

        self.mainArea.layout().addWidget(self.plot)
Example #30
0
    def __init__(self, parent=None):
        super().__init__(parent)
        self.data = None

        self._pca = None
        self._transformed = None
        self._variance_ratio = None
        self._cumulative = None
        self._line = False

        box = gui.widgetBox(self.controlArea, "Components Selection")
        form = QFormLayout()
        box.layout().addLayout(form)

        self.components_spin = gui.spin(
            box, self, "ncomponents", 0, 1000,
            callback=self._update_selection_component_spin,
            keyboardTracking=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
        )
        self.variance_spin.setSuffix("%")

        form.addRow("Components", self.components_spin)
        form.addRow("Variance covered", self.variance_spin)

        self.controlArea.layout().addStretch()

        gui.auto_commit(self.controlArea, self, "auto_commit", "Send data",
                        checkbox_label="Auto send on change")

        self.plot = pg.PlotWidget(background="w")

        axis = self.plot.getAxis("bottom")
        axis.setLabel("Principal Components")
        axis = self.plot.getAxis("left")
        axis.setLabel("Proportion of variance")

        self.plot.getViewBox().setMenuEnabled(False)
        self.plot.getViewBox().setMouseEnabled(False, False)
        self.plot.showGrid(True, True, alpha=0.5)
        self.plot.setRange(xRange=(0.0, 1.0), yRange=(0.0, 1.0))

        self.mainArea.layout().addWidget(self.plot)
Example #31
0
    def __init__(self):
        super().__init__()
        self.out_domain_desc = None

        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 issubclass(DiscreteVariable, m.score.class_type)
        ]
        self.contMeasures = [
            m for m in self.all_measures
            if issubclass(ContinuousVariable, m.score.class_type)
        ]

        selMethBox = gui.vBox(self.controlArea,
                              "Select Attributes",
                              addSpace=True)

        grid = QtGui.QGridLayout()
        grid.setContentsMargins(6, 0, 6, 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.buttonsArea,
                        self,
                        "auto_apply",
                        "Send",
                        box=False)

        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.discRanksLabels = ["#"] + [m.shortname for m in self.discMeasures]
        self.discRanksModel = QtGui.QStandardItemModel(self)
        self.discRanksModel.setHorizontalHeaderLabels(self.discRanksLabels)

        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.commit)
        self.discRanksView.pressed.connect(self.onSelectItem)
        self.discRanksView.horizontalHeader().sectionClicked.connect(
            self.headerClick)
        self.discRanksView.verticalHeader().sectionClicked.connect(
            self.onSelectItem)

        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.contRanksLabels = ["#"] + [m.shortname for m in self.contMeasures]
        self.contRanksModel = QtGui.QStandardItemModel(self)
        self.contRanksModel.setHorizontalHeaderLabels(self.contRanksLabels)

        self.contRanksProxyModel = MySortProxyModel(self)
        self.contRanksProxyModel.setSourceModel(self.contRanksModel)
        self.contRanksView.setModel(self.contRanksProxyModel)

        self.contRanksView.setColumnWidth(0, 20)
        self.contRanksView.sortByColumn(1, Qt.DescendingOrder)
        self.contRanksView.selectionModel().selectionChanged.connect(
            self.commit)
        self.contRanksView.pressed.connect(self.onSelectItem)
        self.contRanksView.horizontalHeader().sectionClicked.connect(
            self.headerClick)
        self.contRanksView.verticalHeader().sectionClicked.connect(
            self.onSelectItem)

        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)
        self.learners = {}
Example #32
0
    def __init__(self):
        super().__init__()
        self.instances = None
        self.domain = None
        self.data = None
        self.classifier = None
        self.align = OWNomogram.ALIGN_ZERO
        self.log_odds_ratios = []
        self.log_reg_coeffs = []
        self.log_reg_coeffs_orig = []
        self.log_reg_cont_data_extremes = []
        self.p = None
        self.b0 = None
        self.points = []
        self.feature_items = {}
        self.feature_marker_values = []
        self.scale_marker_values = lambda x: x
        self.nomogram_main = None
        self.vertical_line = None
        self.hidden_vertical_line = None
        self.old_target_class_index = self.target_class_index
        self.repaint = False

        # GUI
        box = gui.vBox(self.controlArea, "Target class")
        self.class_combo = gui.comboBox(box,
                                        self,
                                        "target_class_index",
                                        callback=self._class_combo_changed,
                                        contentsLength=12)
        self.norm_check = gui.checkBox(
            box,
            self,
            "normalize_probabilities",
            "Normalize probabilities",
            hidden=True,
            callback=self.update_scene,
            tooltip="For multiclass data 1 vs. all probabilities do not"
            " sum to 1 and therefore could be normalized.")

        self.scale_radio = gui.radioButtons(self.controlArea,
                                            self,
                                            "scale",
                                            ["Point scale", "Log odds ratios"],
                                            box="Scale",
                                            callback=self.update_scene)

        box = gui.vBox(self.controlArea, "Display features")
        grid = QGridLayout()
        radio_group = gui.radioButtonsInBox(box,
                                            self,
                                            "display_index", [],
                                            orientation=grid,
                                            callback=self.update_scene)
        radio_all = gui.appendRadioButton(radio_group,
                                          "All",
                                          addToLayout=False)
        radio_best = gui.appendRadioButton(radio_group,
                                           "Best ranked:",
                                           addToLayout=False)
        spin_box = gui.hBox(None, margin=0)
        self.n_spin = gui.spin(spin_box,
                               self,
                               "n_attributes",
                               1,
                               self.MAX_N_ATTRS,
                               label=" ",
                               controlWidth=60,
                               callback=self._n_spin_changed)
        grid.addWidget(radio_all, 1, 1)
        grid.addWidget(radio_best, 2, 1)
        grid.addWidget(spin_box, 2, 2)

        self.sort_combo = gui.comboBox(box,
                                       self,
                                       "sort_index",
                                       label="Rank by:",
                                       items=SortBy.items(),
                                       orientation=Qt.Horizontal,
                                       callback=self.update_scene)

        self.cont_feature_dim_combo = gui.comboBox(
            box,
            self,
            "cont_feature_dim_index",
            label="Numeric features: ",
            items=["1D projection", "2D curve"],
            orientation=Qt.Horizontal,
            callback=self.update_scene)

        gui.rubber(self.controlArea)

        class _GraphicsView(QGraphicsView):
            def __init__(self, scene, parent, **kwargs):
                for k, v in dict(
                        verticalScrollBarPolicy=Qt.ScrollBarAlwaysOff,
                        horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOff,
                        viewportUpdateMode=QGraphicsView.
                        BoundingRectViewportUpdate,
                        renderHints=(QPainter.Antialiasing
                                     | QPainter.TextAntialiasing
                                     | QPainter.SmoothPixmapTransform),
                        alignment=(Qt.AlignTop | Qt.AlignLeft),
                        sizePolicy=QSizePolicy(
                            QSizePolicy.MinimumExpanding,
                            QSizePolicy.MinimumExpanding)).items():
                    kwargs.setdefault(k, v)

                super().__init__(scene, parent, **kwargs)

        class GraphicsView(_GraphicsView):
            def __init__(self, scene, parent):
                super().__init__(
                    scene,
                    parent,
                    verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn,
                    styleSheet='QGraphicsView {background: white}')
                self.viewport().setMinimumWidth(
                    300)  # XXX: This prevents some tests failing
                self._is_resizing = False

            w = self

            def resizeEvent(self, resizeEvent):
                # Recompute main scene on window width change
                if resizeEvent.size().width() != resizeEvent.oldSize().width():
                    self._is_resizing = True
                    self.w.update_scene()
                    self._is_resizing = False
                return super().resizeEvent(resizeEvent)

            def is_resizing(self):
                return self._is_resizing

            def sizeHint(self):
                return QSize(400, 200)

        class FixedSizeGraphicsView(_GraphicsView):
            def __init__(self, scene, parent):
                super().__init__(scene,
                                 parent,
                                 sizePolicy=QSizePolicy(
                                     QSizePolicy.MinimumExpanding,
                                     QSizePolicy.Minimum))

            def sizeHint(self):
                return QSize(400, 85)

        scene = self.scene = QGraphicsScene(self)

        top_view = self.top_view = FixedSizeGraphicsView(scene, self)
        mid_view = self.view = GraphicsView(scene, self)
        bottom_view = self.bottom_view = FixedSizeGraphicsView(scene, self)

        for view in (top_view, mid_view, bottom_view):
            self.mainArea.layout().addWidget(view)
    def __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()
Example #34
0
    def __init__(self):
        OWWidget.__init__(self)
        ConcurrentWidgetMixin.__init__(self)
        self.scorers: List[ScoreMeta] = []
        self.out_domain_desc = None
        self.data = None
        self.problem_type_mode = ProblemType.CLASSIFICATION

        # results caches
        self.scorers_results = {}
        self.methods_results = {}

        if not self.selected_methods:
            self.selected_methods = {
                method.name
                for method in SCORES if method.is_default
            }

        # GUI
        self.ranksModel = model = TableModel(parent=self)  # type: TableModel
        self.ranksView = view = TableView(self)  # type: TableView
        self.mainArea.layout().addWidget(view)
        view.setModel(model)
        view.setColumnWidth(NVAL_COL, 30)
        view.selectionModel().selectionChanged.connect(self.on_select)

        def _set_select_manual():
            self.setSelectionMethod(OWRank.SelectManual)

        view.manualSelection.connect(_set_select_manual)
        view.verticalHeader().sectionClicked.connect(_set_select_manual)
        view.horizontalHeader().sectionClicked.connect(self.headerClick)

        self.measuresStack = stacked = QStackedWidget(self)
        self.controlArea.layout().addWidget(stacked)

        for scoring_methods in (CLS_SCORES, REG_SCORES, []):
            box = gui.vBox(None, "评分方法" if scoring_methods else None)
            stacked.addWidget(box)
            for method in scoring_methods:
                box.layout().addWidget(
                    QCheckBox(
                        method.zh_name,
                        self,
                        objectName=method.
                        shortname,  # To be easily found in tests
                        checked=method.name in self.selected_methods,
                        stateChanged=partial(self.methodSelectionChanged,
                                             method_name=method.name)))
            gui.rubber(box)

        gui.rubber(self.controlArea)

        self.switchProblemType(ProblemType.CLASSIFICATION)

        selMethBox = gui.vBox(self.buttonsArea, "选择特征")

        grid = QGridLayout()
        grid.setContentsMargins(0, 0, 0, 0)
        grid.setSpacing(6)
        self.selectButtons = QButtonGroup()
        self.selectButtons.buttonClicked[int].connect(self.setSelectionMethod)

        def button(text, buttonid, toolTip=None):
            b = QRadioButton(text)
            self.selectButtons.addButton(b, buttonid)
            if toolTip is not None:
                b.setToolTip(toolTip)
            return b

        b1 = button(self.tr("无"), OWRank.SelectNone)
        b2 = button(self.tr("所有"), OWRank.SelectAll)
        b3 = button(self.tr("手动"), OWRank.SelectManual)
        b4 = button(self.tr("最佳排名:"), OWRank.SelectNBest)

        s = gui.spin(
            selMethBox,
            self,
            "nSelected",
            1,
            999,
            callback=lambda: self.setSelectionMethod(OWRank.SelectNBest),
            addToLayout=False)

        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.selectionMethod).setChecked(True)

        selMethBox.layout().addLayout(grid)

        gui.auto_send(self.buttonsArea, self, "auto_apply")

        self.resize(690, 500)
Example #35
0
    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)
Example #36
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.api = None
        self.corpus = None
        self.api_dlg = self.APICredentialsDialog(self)
        self.api_dlg.accept(silent=True)

        # Set API key button
        gui.button(self.controlArea,
                   self,
                   'Twitter API Key',
                   callback=self.open_key_dialog,
                   tooltip='Set the API key for this widget.',
                   focusPolicy=Qt.NoFocus)

        # Query
        query_box = gui.hBox(self.controlArea, 'Query')
        layout = QGridLayout()
        layout.setVerticalSpacing(5)
        layout.setColumnStretch(2, 1)  # stretch last columns
        layout.setColumnMinimumWidth(1, 15)  # add some space for checkbox
        ROW = 0
        COLUMNS = 3

        def add_row(label, items):
            nonlocal ROW, COLUMNS
            layout.addWidget(QLabel(label), ROW, 0)
            if isinstance(items, tuple):
                for i, item in enumerate(items):
                    layout.addWidget(item, ROW, 1 + i)
            else:
                layout.addWidget(items, ROW, 1, 1, COLUMNS - 1)
            ROW += 1

        # Query input
        add_row(
            'Query word list:',
            ListEdit(self, 'word_list', 'Multiple lines are joined with OR.',
                     80, self))

        # Search mode
        add_row(
            'Search by:',
            gui.comboBox(self,
                         self,
                         'mode',
                         items=self.MODES,
                         callback=self.mode_toggle))

        # Language
        self.language_combo = ComboBox(self,
                                       'language',
                                       items=(('Any', None), ) +
                                       tuple(sorted(lang2code.items())))
        add_row('Language:', self.language_combo)

        # Max tweets
        add_row(
            'Max tweets:',
            gui.spin(self,
                     self,
                     'max_tweets',
                     minv=1,
                     maxv=10000,
                     checked='limited_search'))

        # Retweets
        self.retweets_checkbox = gui.checkBox(self,
                                              self,
                                              'allow_retweets',
                                              '',
                                              minimumHeight=30)
        add_row('Allow retweets:', self.retweets_checkbox)

        # Collect Results
        add_row('Collect results:', gui.checkBox(self, self, 'collecting', ''))

        query_box.layout().addLayout(layout)

        self.controlArea.layout().addWidget(
            CheckListLayout('Text includes',
                            self,
                            'text_includes',
                            self.attributes,
                            cols=2,
                            callback=self.set_text_features))

        self.tweets_info_label = gui.label(self.controlArea,
                                           self,
                                           self.tweets_info.format(0),
                                           box='Info')

        # Buttons
        self.button_box = gui.hBox(self.controlArea)

        self.search_button = gui.button(self.button_box,
                                        self,
                                        'Search',
                                        self.start_stop,
                                        focusPolicy=Qt.NoFocus)

        self.mode_toggle()
        self.setFocus()  # to widget itself to show placeholder for query_edit
Example #37
0
    def __init__(self):
        super().__init__()

        self.results = None
        self.classifier_names = []
        self.perf_line = None
        self.colors = []
        self._curve_data = {}
        self._plot_curves = {}
        self._rocch = None
        self._perf_line = None
        self._tooltip_cache = None

        box = gui.vBox(self.controlArea, "绘制")
        self.target_cb = gui.comboBox(box,
                                      self,
                                      "target_index",
                                      label="目标",
                                      orientation=Qt.Horizontal,
                                      callback=self._on_target_changed,
                                      contentsLength=8,
                                      searchable=True)

        gui.widgetLabel(box, "分类器")
        line_height = 4 * QFontMetrics(self.font()).lineSpacing()
        self.classifiers_list_box = gui.listBox(
            box,
            self,
            "selected_classifiers",
            "classifier_names",
            selectionMode=QListView.MultiSelection,
            callback=self._on_classifiers_changed,
            sizeHint=QSize(0, line_height))

        abox = gui.vBox(self.controlArea, "曲线")
        gui.comboBox(abox,
                     self,
                     "roc_averaging",
                     items=["合并折叠预测", "平均真阳性率", "阈值处的平均真阳性率和假阳性率", "显示单个曲线"],
                     callback=self._replot)

        gui.checkBox(abox,
                     self,
                     "display_convex_curve",
                     "显示凸ROC曲线",
                     callback=self._replot)
        gui.checkBox(abox,
                     self,
                     "display_convex_hull",
                     "显示ROC凸包",
                     callback=self._replot)

        box = gui.vBox(self.controlArea, "分析")

        gui.checkBox(box,
                     self,
                     "display_def_threshold",
                     "默认阈值(0.5)点",
                     callback=self._on_display_def_threshold_changed)

        gui.checkBox(box,
                     self,
                     "display_perf_line",
                     "显示性能线",
                     callback=self._on_display_perf_line_changed)
        grid = QGridLayout()
        gui.indentedBox(box, orientation=grid)

        sp = gui.spin(box,
                      self,
                      "fp_cost",
                      1,
                      1000,
                      10,
                      alignment=Qt.AlignRight,
                      callback=self._on_display_perf_line_changed)
        grid.addWidget(QLabel("假阳性率损失:"), 0, 0)
        grid.addWidget(sp, 0, 1)

        sp = gui.spin(box,
                      self,
                      "fn_cost",
                      1,
                      1000,
                      10,
                      alignment=Qt.AlignRight,
                      callback=self._on_display_perf_line_changed)
        grid.addWidget(QLabel("假阴性率损失:"))
        grid.addWidget(sp, 1, 1)
        self.target_prior_sp = gui.spin(box,
                                        self,
                                        "target_prior",
                                        1,
                                        99,
                                        alignment=Qt.AlignRight,
                                        spinType=float,
                                        callback=self._on_target_prior_changed)
        self.target_prior_sp.setSuffix(" %")
        self.target_prior_sp.addAction(QAction("Auto", sp))
        grid.addWidget(QLabel("先验概率:"))
        grid.addWidget(self.target_prior_sp, 2, 1)

        self.plotview = GraphicsView(background=None)
        self.plotview.setFrameStyle(QFrame.StyledPanel)
        self.plotview.scene().sigMouseMoved.connect(self._on_mouse_moved)

        self.plot = PlotItem(enableMenu=False)
        self.plot.setMouseEnabled(False, False)
        self.plot.hideButtons()

        tickfont = QFont(self.font())
        tickfont.setPixelSize(max(int(tickfont.pixelSize() * 2 // 3), 11))

        axis = self.plot.getAxis("bottom")
        axis.setTickFont(tickfont)
        axis.setLabel("假阳性率 (1-特异度)")
        axis.setGrid(16)

        axis = self.plot.getAxis("left")
        axis.setTickFont(tickfont)
        axis.setLabel("真阳性率 (灵敏度)")
        axis.setGrid(16)

        self.plot.showGrid(True, True, alpha=0.2)
        self.plot.setRange(xRange=(0.0, 1.0), yRange=(0.0, 1.0), padding=0.05)

        self.plotview.setCentralItem(self.plot)
        self.mainArea.layout().addWidget(self.plotview)
Example #38
0
    def __init__(self):
        super().__init__()

        self.data = None
        self.plotdata = None

        box = gui.widgetBox(self.controlArea, "Optimization", spacing=10)
        form = QtGui.QFormLayout(
            labelAlignment=Qt.AlignLeft,
            formAlignment=Qt.AlignLeft,
            fieldGrowthPolicy=QtGui.QFormLayout.AllNonFixedFieldsGrow,
            verticalSpacing=10)
        form.addRow(
            "Force law",
            gui.comboBox(box,
                         self,
                         "force_law",
                         items=[text for text, _ in OWFreeViz.ForceLaw],
                         callback=self.__reset_update_interval))
        form.addRow("Max iterations", gui.spin(box, self, "maxiter", 10,
                                               10**4))
        form.addRow(
            "Initialization",
            gui.comboBox(box,
                         self,
                         "initialization",
                         items=["Circular", "Random"],
                         callback=self.__reset_initialization))
        form.addRow(
            "Replot",
            gui.comboBox(box,
                         self,
                         "replot_interval",
                         items=[text for text, _ in OWFreeViz.ReplotIntervals],
                         callback=self.__reset_update_interval))
        box.layout().addLayout(form)

        self.start_button = gui.button(box, self, "Optimize",
                                       self._toogle_start)

        self.color_varmodel = itemmodels.VariableListModel(parent=self)
        self.shape_varmodel = itemmodels.VariableListModel(parent=self)
        self.size_varmodel = itemmodels.VariableListModel(parent=self)
        self.label_varmodel = itemmodels.VariableListModel(parent=self)

        box = gui.widgetBox(self.controlArea, "Plot")
        form = QtGui.QFormLayout(
            formAlignment=Qt.AlignLeft,
            labelAlignment=Qt.AlignLeft,
            fieldGrowthPolicy=QtGui.QFormLayout.AllNonFixedFieldsGrow,
            spacing=8,
        )
        box.layout().addLayout(form)
        color_cb = gui.comboBox(box,
                                self,
                                "color_var",
                                sendSelectedValue=True,
                                emptyString="(Same color)",
                                contentsLength=10,
                                callback=self._update_color)

        color_cb.setModel(self.color_varmodel)
        form.addRow("Color", color_cb)
        opacity_slider = gui.hSlider(box,
                                     self,
                                     "opacity",
                                     minValue=50,
                                     maxValue=255,
                                     ticks=True,
                                     createLabel=False,
                                     callback=self._update_color)
        opacity_slider.setTickInterval(0)
        opacity_slider.setPageStep(10)
        form.addRow("Opacity", opacity_slider)

        shape_cb = gui.comboBox(box,
                                self,
                                "shape_var",
                                contentsLength=10,
                                sendSelectedValue=True,
                                emptyString="(Same shape)",
                                callback=self._update_shape)
        shape_cb.setModel(self.shape_varmodel)
        form.addRow("Shape", shape_cb)

        size_cb = gui.comboBox(box,
                               self,
                               "size_var",
                               contentsLength=10,
                               sendSelectedValue=True,
                               emptyString="(Same size)",
                               callback=self._update_size)
        size_cb.setModel(self.size_varmodel)
        form.addRow("Size", size_cb)
        size_slider = gui.hSlider(box,
                                  self,
                                  "point_size",
                                  minValue=3,
                                  maxValue=20,
                                  ticks=True,
                                  createLabel=False,
                                  callback=self._update_size)
        form.addRow(None, size_slider)

        label_cb = gui.comboBox(box,
                                self,
                                "label_var",
                                contentsLength=10,
                                sendSelectedValue=True,
                                emptyString="(No labels)",
                                callback=self._update_labels)
        label_cb.setModel(self.label_varmodel)
        form.addRow("Label", label_cb)

        form.addRow(
            "Jitter",
            gui.comboBox(box,
                         self,
                         "jitter",
                         items=[text for text, _ in self.JitterAmount],
                         callback=self._update_xy))
        self.class_density_cb = gui.checkBox(box,
                                             self,
                                             "class_density",
                                             "",
                                             callback=self._update_density)
        form.addRow("Class density", self.class_density_cb)

        box = gui.widgetBox(self.controlArea, "Hide anchors")
        rslider = gui.hSlider(box,
                              self,
                              "min_anchor_radius",
                              minValue=0,
                              maxValue=100,
                              step=5,
                              label="Hide radius",
                              createLabel=False,
                              ticks=True,
                              callback=self._update_anchor_visibility)
        rslider.setTickInterval(0)
        rslider.setPageStep(10)

        box = gui.widgetBox(self.controlArea, "Zoom/Select")
        hlayout = QtGui.QHBoxLayout()
        box.layout().addLayout(hlayout)

        toolbox = PlotToolBox(self)
        hlayout.addWidget(toolbox.button(PlotToolBox.SelectTool))
        hlayout.addWidget(toolbox.button(PlotToolBox.ZoomTool))
        hlayout.addWidget(toolbox.button(PlotToolBox.PanTool))
        hlayout.addSpacing(2)
        hlayout.addWidget(toolbox.button(PlotToolBox.ZoomReset))
        toolbox.standardAction(PlotToolBox.ZoomReset).triggered.connect(
            lambda: self.plot.setRange(QtCore.QRectF(-1.05, -1.05, 2.1, 2.1)))
        toolbox.standardAction(PlotToolBox.ZoomIn).triggered.connect(
            lambda: self.plot.getViewBox().scaleBy((1.25, 1.25)))
        toolbox.standardAction(PlotToolBox.ZoomIn).triggered.connect(
            lambda: self.plot.getViewBox().scaleBy((1 / 1.25, 1 / 1.25)))
        selecttool = toolbox.plotTool(PlotToolBox.SelectTool)
        selecttool.selectionFinished.connect(self.__select_area)
        self.addActions(toolbox.actions())

        self.controlArea.layout().addStretch(1)

        box = gui.widgetBox(self.controlArea, "Output")
        gui.comboBox(box,
                     self,
                     "embedding_domain_role",
                     items=[
                         "Original features only", "Coordinates as features",
                         "Coordinates as meta attributes"
                     ])
        gui.auto_commit(box,
                        self,
                        "autocommit",
                        "Commit",
                        box=False,
                        callback=self.commit)

        self.plot = pg.PlotWidget(enableMouse=False, enableMenu=False)
        self.plot.setFrameStyle(QtGui.QFrame.StyledPanel)
        self.plot.plotItem.hideAxis("bottom")
        self.plot.plotItem.hideAxis("left")
        self.plot.plotItem.hideButtons()
        self.plot.setAspectLocked(True)
        self.plot.scene().installEventFilter(self)

        self.legend = linproj.LegendItem()
        self.legend.setParentItem(self.plot.getViewBox())
        self.legend.anchor((1, 0), (1, 0))

        self.plot.setRenderHint(QtGui.QPainter.Antialiasing, True)
        self.mainArea.layout().addWidget(self.plot)
        viewbox = self.plot.getViewBox()
        viewbox.grabGesture(Qt.PinchGesture)
        pinchtool = linproj.PlotPinchZoomTool(parent=self)
        pinchtool.setViewBox(viewbox)

        toolbox.setViewBox(viewbox)

        self._loop = AsyncUpdateLoop(parent=self)
        self._loop.yielded.connect(self.__set_projection)
        self._loop.finished.connect(self.__freeviz_finished)
        self._loop.raised.connect(self.__on_error)
    def __init__(self):
        super().__init__()

        self.data = None  # type: Optional[Table]
        self.graph = None  # type: Optional[nx.Graph]
        self.partition = None  # type: Optional[np.array]

        self.__executor = ThreadExecutor(parent=self)
        self.__future = None  # type: Optional[Future]
        self.__state = self.State.Pending

        pca_box = gui.vBox(self.controlArea, 'PCA Preprocessing')
        self.apply_pca_cbx = gui.checkBox(
            pca_box,
            self,
            'apply_pca',
            label='Apply PCA preprocessing',
            callback=self._invalidate_graph,
        )  # type: QCheckBox
        self.pca_components_slider = gui.hSlider(
            pca_box,
            self,
            'pca_components',
            label='Components: ',
            minValue=2,
            maxValue=_MAX_PCA_COMPONENTS,
            callback=self._invalidate_pca_projection,
        )  # type: QSlider

        graph_box = gui.vBox(self.controlArea, 'Graph parameters')
        self.metric_combo = gui.comboBox(
            graph_box,
            self,
            'metric_idx',
            label='Distance metric',
            items=[m[0] for m in METRICS],
            callback=self._invalidate_graph,
            orientation=Qt.Horizontal,
        )  # type: gui.OrangeComboBox
        self.k_neighbours_spin = gui.spin(
            graph_box,
            self,
            'k_neighbours',
            minv=1,
            maxv=_MAX_K_NEIGBOURS,
            label='k neighbours',
            controlWidth=80,
            alignment=Qt.AlignRight,
            callback=self._invalidate_graph,
        )  # type: gui.SpinBoxWFocusOut
        self.cls_epsilon_spin = gui.spin(
            graph_box,
            self,
            'resolution',
            0,
            5.,
            1e-2,
            spinType=float,
            label='Resolution',
            controlWidth=80,
            alignment=Qt.AlignRight,
            callback=self._invalidate_partition,
        )  # type: gui.SpinBoxWFocusOut

        self.apply_button = gui.auto_commit(
            self.controlArea,
            self,
            'auto_commit',
            'Apply',
            box=False,
            commit=lambda: self.commit(force=True),
            callback=self.commit,
        )  # type: QWidget
Example #40
0
    def __init__(self):
        super().__init__()
        self._delta = 0
        self.play_timer = QTimer(self,
                                 interval=self.playback_interval,
                                 timeout=self.play_single_step)
        slider = self.slider = Slider(
            Qt.Horizontal,
            self,
            minimum=0,
            maximum=self.MAX_SLIDER_VALUE,
            tracking=False,
            valuesChanged=self.valuesChanged,
            minimumValue=self.slider_values[0],
            maximumValue=self.slider_values[1],
        )
        slider.setShowText(False)
        box = gui.vBox(self.controlArea, 'Time Slice')
        box.layout().addWidget(slider)

        hbox = gui.hBox(box)

        def _dateTimeChanged(editted):
            def handler():
                minTime = self.date_from.dateTime().toMSecsSinceEpoch() / 1000
                maxTime = self.date_to.dateTime().toMSecsSinceEpoch() / 1000
                if minTime > maxTime:
                    minTime = maxTime = minTime if editted == self.date_from else maxTime
                    other = self.date_to if editted == self.date_from else self.date_from
                    with blockSignals(other):
                        other.setDateTime(editted.dateTime())

                with blockSignals(self.slider):
                    self.slider.setValues(self.slider.unscale(minTime),
                                          self.slider.unscale(maxTime))
                self.send_selection(minTime, maxTime)

            return handler

        kwargs = dict(calendarPopup=True,
                      displayFormat=' '.join(self.DATE_FORMATS),
                      timeSpec=Qt.UTC)
        date_from = self.date_from = QDateTimeEdit(self, **kwargs)
        date_to = self.date_to = QDateTimeEdit(self, **kwargs)
        date_from.dateTimeChanged.connect(_dateTimeChanged(date_from))
        date_to.dateTimeChanged.connect(_dateTimeChanged(date_to))
        hbox.layout().addStretch(100)
        hbox.layout().addWidget(date_from)
        hbox.layout().addWidget(QLabel(' – '))
        hbox.layout().addWidget(date_to)
        hbox.layout().addStretch(100)

        vbox = gui.vBox(self.controlArea, 'Step / Play Through')
        gui.checkBox(vbox, self, 'loop_playback', label='Loop playback')
        hbox = gui.hBox(vbox)
        gui.checkBox(hbox,
                     self,
                     'steps_overlap',
                     label='Stepping overlaps by:',
                     toolTip='If enabled, the active interval moves forward '
                     '(backward) by half of the interval at each step.')
        gui.comboBox(hbox,
                     self,
                     'overlap_amount',
                     items=tuple(self.OVERLAP_AMOUNTS.keys()),
                     sendSelectedValue=True)
        gui.spin(vbox,
                 self,
                 'playback_interval',
                 label='Playback delay (msec):',
                 minv=100,
                 maxv=30000,
                 step=200,
                 callback=lambda: self.play_timer.setInterval(
                     self.playback_interval))

        hbox = gui.hBox(vbox)
        self.step_backward = gui.button(
            hbox,
            self,
            '⏮',
            callback=lambda: self.play_single_step(backward=True),
            autoDefault=False)
        self.play_button = gui.button(hbox,
                                      self,
                                      '▶',
                                      callback=self.playthrough,
                                      toggleButton=True,
                                      default=True)
        self.step_forward = gui.button(hbox,
                                       self,
                                       '⏭',
                                       callback=self.play_single_step,
                                       autoDefault=False)

        gui.rubber(self.controlArea)
Example #41
0
    def __init__(self):
        super().__init__()

        self.data = None  # type: Optional[Table]
        self.preprocessed_data = None  # type: Optional[Table]
        self.pca_projection = None  # type: Optional[Table]
        self.graph = None  # type: Optional[nx.Graph]
        self.partition = None  # type: Optional[np.array]
        # Use a executor with a single worker, to limit CPU overcommitment for
        # cancelled tasks. The method does not have a fine cancellation
        # granularity so we assure that there are not N - 1 jobs executing
        # for no reason only to be thrown away. It would be better to use the
        # global pool but implement a limit on jobs from this source.
        self.__executor = futures.ThreadPoolExecutor(max_workers=1)
        self.__task = None  # type: Optional[TaskState]
        self.__invalidated = False
        # coalescing commit timer
        self.__commit_timer = QTimer(self, singleShot=True)
        self.__commit_timer.timeout.connect(self.commit)

        # Set up UI
        info_box = gui.vBox(self.controlArea, "Info")
        self.info_label = gui.widgetLabel(info_box,
                                          "No data on input.")  # type: QLabel

        preprocessing_box = gui.vBox(self.controlArea, "Preprocessing")
        self.normalize_cbx = gui.checkBox(
            preprocessing_box,
            self,
            "normalize",
            label="Normalize data",
            callback=self._invalidate_preprocessed_data,
            attribute=Qt.WA_LayoutUsesWidgetRect)  # type: QCheckBox
        self.apply_pca_cbx = gui.checkBox(
            preprocessing_box,
            self,
            "apply_pca",
            label="Apply PCA preprocessing",
            callback=self._apply_pca_changed,
            attribute=Qt.WA_LayoutUsesWidgetRect)  # type: QCheckBox
        self.pca_components_slider = gui.hSlider(
            preprocessing_box,
            self,
            "pca_components",
            label="PCA Components: ",
            minValue=2,
            maxValue=_MAX_PCA_COMPONENTS,
            callback=self._invalidate_pca_projection,
            tracking=False)  # type: QSlider

        graph_box = gui.vBox(self.controlArea, "Graph parameters")
        self.metric_combo = gui.comboBox(
            graph_box,
            self,
            "metric_idx",
            label="Distance metric",
            items=[m[0] for m in METRICS],
            callback=self._invalidate_graph,
            orientation=Qt.Horizontal,
        )
        self.k_neighbors_spin = gui.spin(
            graph_box,
            self,
            "k_neighbors",
            minv=1,
            maxv=_MAX_K_NEIGBOURS,
            label="k neighbors",
            controlWidth=80,
            alignment=Qt.AlignRight,
            callback=self._invalidate_graph,
        )
        self.resolution_spin = gui.hSlider(
            graph_box,
            self,
            "resolution",
            minValue=0,
            maxValue=5.,
            step=1e-1,
            label="Resolution",
            intOnly=False,
            labelFormat="%.1f",
            callback=self._invalidate_partition,
            tracking=False,
        )  # type: QSlider
        self.resolution_spin.parent().setToolTip(
            "The resolution parameter affects the number of clusters to find. "
            "Smaller values tend to produce more clusters and larger values "
            "retrieve less clusters.")
        self.apply_button = gui.auto_apply(
            self.buttonsArea,
            self,
            "auto_commit",
            commit=lambda: self.commit(),
            callback=lambda: self._on_auto_commit_changed())  # type: QWidget
Example #42
0
    def add_main_layout(self):
        # top-level control procedure
        top_box = gui.hBox(widget=self.controlArea, box=None, addSpace=2)

        rule_ordering_box = gui.hBox(widget=top_box, box="Rule ordering")
        rule_ordering_rbs = gui.radioButtons(
            widget=rule_ordering_box, master=self, value="rule_ordering",
            callback=self.settings_changed, btnLabels=("Ordered", "Unordered"))
        rule_ordering_rbs.layout().setSpacing(7)

        covering_algorithm_box = gui.hBox(
            widget=top_box, box="Covering algorithm")
        covering_algorithm_rbs = gui.radioButtons(
            widget=covering_algorithm_box, master=self,
            value="covering_algorithm",
            callback=self.settings_changed,
            btnLabels=("Exclusive", "Weighted"))
        covering_algorithm_rbs.layout().setSpacing(7)

        insert_gamma_box = gui.vBox(widget=covering_algorithm_box, box=None)
        gui.separator(insert_gamma_box, 0, 14)
        self.gamma_spin = gui.doubleSpin(
            widget=insert_gamma_box, master=self, value="gamma", minv=0.0,
            maxv=1.0, step=0.01, label="γ:", orientation=Qt.Horizontal,
            callback=self.settings_changed, alignment=Qt.AlignRight,
            enabled=self.storage_covers[self.covering_algorithm] == "weighted")

        # bottom-level search procedure (search bias)
        middle_box = gui.vBox(widget=self.controlArea, box="Rule search")

        evaluation_measure_box = gui.comboBox(
            widget=middle_box, master=self, value="evaluation_measure",
            label="Evaluation measure:", orientation=Qt.Horizontal,
            items=("Entropy", "Laplace accuracy", "WRAcc"),
            callback=self.settings_changed, contentsLength=3)

        beam_width_box = gui.spin(
            widget=middle_box, master=self, value="beam_width", minv=1,
            maxv=100, step=1, label="Beam width:", orientation=Qt.Horizontal,
            callback=self.settings_changed, alignment=Qt.AlignRight,
            controlWidth=80)

        # bottom-level search procedure (over-fitting avoidance bias)
        bottom_box = gui.vBox(widget=self.controlArea, box="Rule filtering")

        min_covered_examples_box = gui.spin(
            widget=bottom_box, master=self, value="min_covered_examples", minv=1,
            maxv=10000, step=1, label="Minimum rule coverage:",
            orientation=Qt.Horizontal, callback=self.settings_changed,
            alignment=Qt.AlignRight, controlWidth=80)

        max_rule_length_box = gui.spin(
            widget=bottom_box, master=self, value="max_rule_length",
            minv=1, maxv=100, step=1, label="Maximum rule length:",
            orientation=Qt.Horizontal, callback=self.settings_changed,
            alignment=Qt.AlignRight, controlWidth=80)

        default_alpha_spin = gui.doubleSpin(
            widget=bottom_box, master=self, value="default_alpha", minv=0.0,
            maxv=1.0, step=0.01, label="Statistical significance\n(default α):",
            orientation=Qt.Horizontal, callback=self.settings_changed,
            alignment=Qt.AlignRight, controlWidth=80,
            checked="checked_default_alpha")

        parent_alpha_spin = gui.doubleSpin(
            widget=bottom_box, master=self, value="parent_alpha", minv=0.0,
            maxv=1.0, step=0.01, label="Relative significance\n(parent α):",
            orientation=Qt.Horizontal, callback=self.settings_changed,
            alignment=Qt.AlignRight, controlWidth=80,
            checked="checked_parent_alpha")
    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)
Example #44
0
    def __init__(self):
        super().__init__()
        self.data = None
        self.indices = None
        self.sampled_instances = self.remaining_instances = None

        box = gui.vBox(self.controlArea, "Information")
        self.dataInfoLabel = gui.widgetLabel(box, 'No data on input.')
        self.outputInfoLabel = gui.widgetLabel(box, ' ')

        self.sampling_box = gui.vBox(self.controlArea, "Sampling Type")
        sampling = gui.radioButtons(self.sampling_box,
                                    self,
                                    "sampling_type",
                                    callback=self.sampling_type_changed)

        def set_sampling_type(i):
            def f():
                self.sampling_type = i
                self.sampling_type_changed()

            return f

        gui.appendRadioButton(sampling, "Fixed proportion of data:")
        self.sampleSizePercentageSlider = gui.hSlider(
            gui.indentedBox(sampling),
            self,
            "sampleSizePercentage",
            minValue=0,
            maxValue=99,
            ticks=10,
            labelFormat="%d %%",
            callback=set_sampling_type(self.FixedProportion),
            addSpace=12)

        gui.appendRadioButton(sampling, "Fixed sample size")
        ibox = gui.indentedBox(sampling)
        self.sampleSizeSpin = gui.spin(ibox,
                                       self,
                                       "sampleSizeNumber",
                                       label="Instances: ",
                                       minv=1,
                                       maxv=2**31 - 1,
                                       callback=set_sampling_type(
                                           self.FixedSize))
        gui.checkBox(ibox,
                     self,
                     "replacement",
                     "Sample with replacement",
                     callback=set_sampling_type(self.FixedSize),
                     addSpace=12)

        gui.appendRadioButton(sampling, "Cross validation")
        form = QFormLayout(formAlignment=Qt.AlignLeft | Qt.AlignTop,
                           labelAlignment=Qt.AlignLeft,
                           fieldGrowthPolicy=QFormLayout.AllNonFixedFieldsGrow)
        ibox = gui.indentedBox(sampling, addSpace=True, orientation=form)
        form.addRow(
            "Number of folds:",
            gui.spin(ibox,
                     self,
                     "number_of_folds",
                     2,
                     100,
                     addToLayout=False,
                     callback=self.number_of_folds_changed))
        self.selected_fold_spin = gui.spin(ibox,
                                           self,
                                           "selectedFold",
                                           1,
                                           self.number_of_folds,
                                           addToLayout=False,
                                           callback=self.fold_changed)
        form.addRow("Selected fold:", self.selected_fold_spin)

        gui.appendRadioButton(sampling, "Bootstrap")

        self.sql_box = gui.vBox(self.controlArea, "Sampling Type")
        sampling = gui.radioButtons(self.sql_box,
                                    self,
                                    "sampling_type",
                                    callback=self.sampling_type_changed)
        gui.appendRadioButton(sampling, "Time:")
        ibox = gui.indentedBox(sampling)
        spin = gui.spin(ibox,
                        self,
                        "sampleSizeSqlTime",
                        minv=1,
                        maxv=3600,
                        callback=set_sampling_type(self.SqlTime))
        spin.setSuffix(" sec")
        gui.appendRadioButton(sampling, "Percentage")
        ibox = gui.indentedBox(sampling)
        spin = gui.spin(ibox,
                        self,
                        "sampleSizeSqlPercentage",
                        spinType=float,
                        minv=0.0001,
                        maxv=100,
                        step=0.1,
                        decimals=4,
                        callback=set_sampling_type(self.SqlProportion))
        spin.setSuffix(" %")
        self.sql_box.setVisible(False)

        self.options_box = gui.vBox(self.controlArea, "Options")
        self.cb_seed = gui.checkBox(self.options_box,
                                    self,
                                    "use_seed",
                                    "Replicable (deterministic) sampling",
                                    callback=self.settings_changed)
        self.cb_stratify = gui.checkBox(self.options_box,
                                        self,
                                        "stratify",
                                        "Stratify sample (when possible)",
                                        callback=self.settings_changed)
        self.cb_sql_dl = gui.checkBox(self.options_box,
                                      self,
                                      "sql_dl",
                                      "Download data to local memory",
                                      callback=self.settings_changed)
        self.cb_sql_dl.setVisible(False)

        gui.button(self.buttonsArea, self, "Sample Data", callback=self.commit)
Example #45
0
    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()
Example #46
0
    def __init__(self):
        super().__init__()
        self.data = None
        self.source_id = None
        self._mas = None
        self._Ws = None
        self._transformed = None
        self._components = None
        self._use_genes = None
        self._shared_correlations = None
        self._transformed_table = None
        self._line = False
        self._feature_model = DomainModel(valid_types=DiscreteVariable, separators=False)
        self._feature_model.set_domain(None)
        self._init_mas()
        self._legend = None
        form = QFormLayout(
            labelAlignment=Qt.AlignLeft,
            formAlignment=Qt.AlignLeft,
            fieldGrowthPolicy=QFormLayout.AllNonFixedFieldsGrow,
            verticalSpacing=10
        )
        # Data source indicator
        box = gui.vBox(self.controlArea, "Data source indicator")

        gui.comboBox(
            box, self, "source_id", sendSelectedValue=True,
            callback=self._update_combo_source_id,
            model=self._feature_model,
        )

        # Canonical correlation analysis
        box = gui.vBox(self.controlArea, "Canonical correlation analysis")
        gui.spin(
            box, self, "ncomponents", 1, MAX_COMPONENTS,
            callback=self._update_selection_component_spin,
            keyboardTracking=False,
            label="Num. of components"
        )

        # Shared genes
        box = gui.vBox(self.controlArea, "Shared genes")
        gui.spin(
            box, self, "ngenes", 1, MAX_GENES,
            callback=self._update_ngenes_spin,
            keyboardTracking=False,
        )
        form.addRow(
            "Num. of genes",
            self.controls.ngenes
        )

        gui.comboBox(
            box, self, "scoring",
            callback=self._update_scoring_combo,
            items=list(SCORINGS.keys()), sendSelectedValue=True,
            editable=False,
        )
        form.addRow(
            "Scoring:",
            self.controls.scoring
        )

        box.layout().addLayout(form)

        # Post-processing
        box = gui.vBox(self.controlArea, "Post-processing")
        gui.doubleSpin(
            box, self, "quantile_normalization_perc", minv=0, maxv=49, step=5e-1,
            callback=self._update_quantile_normalization,
            checkCallback=self._update_quantile_normalization,
            controlWidth=80, alignment=Qt.AlignRight,
            label="Quantile normalization", checked="quantile_normalization",
        )
        self.controls.quantile_normalization_perc.setSuffix("%")
        gui.checkBox(
            box, self, "dynamic_time_warping",
            callback=self._update_dynamic_time_warping,
            label="Dynamic time warping"
        )

        self.controlArea.layout().addStretch()

        gui.auto_commit(self.controlArea, self, "auto_commit", "Apply",
                        callback=self._invalidate_selection(),
                        checkbox_label="Apply automatically")

        self.plot = pg.PlotWidget(background="w")

        axis = self.plot.getAxis("bottom")
        axis.setLabel("Correlation components")
        axis = self.plot.getAxis("left")
        axis.setLabel("Correlation strength")
        self.plot_horlabels = []
        self.plot_horlines = []

        self.plot.getViewBox().setMenuEnabled(False)
        self.plot.getViewBox().setMouseEnabled(False, False)
        self.plot.showGrid(True, True, alpha=0.5)
        self.plot.setRange(xRange=(0.0, 1.0), yRange=(0.0, 1.0))

        self.mainArea.layout().addWidget(self.plot)
Example #47
0
    def __init__(self):
        super().__init__()
        self.data = None

        self._pca = None
        self._transformed = None
        self._variance_ratio = None
        self._cumulative = None
        self._line = False
        self._init_projector()

        # Components Selection
        box = gui.vBox(self.controlArea, "Components Selection")
        form = QFormLayout()
        box.layout().addLayout(form)

        self.components_spin = gui.spin(
            box,
            self,
            "ncomponents",
            1,
            MAX_COMPONENTS,
            callback=self._update_selection_component_spin,
            keyboardTracking=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)
        self.variance_spin.setSuffix("%")

        form.addRow("Components:", self.components_spin)
        form.addRow("Variance covered:", self.variance_spin)

        # Incremental learning
        self.sampling_box = gui.vBox(self.controlArea, "Incremental learning")
        self.addresstext = QLineEdit(box)
        self.addresstext.setPlaceholderText('Remote server')
        if self.address:
            self.addresstext.setText(self.address)
        self.sampling_box.layout().addWidget(self.addresstext)

        form = QFormLayout()
        self.sampling_box.layout().addLayout(form)
        self.batch_spin = gui.spin(self.sampling_box,
                                   self,
                                   "batch_size",
                                   50,
                                   100000,
                                   step=50,
                                   keyboardTracking=False)
        form.addRow("Batch size ~ ", self.batch_spin)

        self.start_button = gui.button(
            self.sampling_box,
            self,
            "Start remote computation",
            callback=self.start,
            autoDefault=False,
            tooltip="Start/abort computation on the server")
        self.start_button.setEnabled(False)

        gui.checkBox(self.sampling_box,
                     self,
                     "auto_update",
                     "Periodically fetch model",
                     callback=self.update_model)
        self.__timer = QTimer(self, interval=2000)
        self.__timer.timeout.connect(self.get_model)

        self.sampling_box.setVisible(remotely)

        # Decomposition
        self.decomposition_box = gui.radioButtons(
            self.controlArea,
            self,
            "decomposition_idx", [d.name for d in DECOMPOSITIONS],
            box="Decomposition",
            callback=self._update_decomposition)

        # Options
        self.options_box = gui.vBox(self.controlArea, "Options")
        self.normalize_box = gui.checkBox(self.options_box,
                                          self,
                                          "normalize",
                                          "Normalize data",
                                          callback=self._update_normalize)

        self.maxp_spin = gui.spin(self.options_box,
                                  self,
                                  "maxp",
                                  1,
                                  MAX_COMPONENTS,
                                  label="Show only first",
                                  callback=self._setup_plot,
                                  keyboardTracking=False)

        self.controlArea.layout().addStretch()

        gui.auto_commit(self.controlArea,
                        self,
                        "auto_commit",
                        "Apply",
                        checkbox_label="Apply automatically")

        self.plot = pg.PlotWidget(background="w")

        axis = self.plot.getAxis("bottom")
        axis.setLabel("Principal Components")
        axis = self.plot.getAxis("left")
        axis.setLabel("Proportion of variance")
        self.plot_horlabels = []
        self.plot_horlines = []

        self.plot.getViewBox().setMenuEnabled(False)
        self.plot.getViewBox().setMouseEnabled(False, False)
        self.plot.showGrid(True, True, alpha=0.5)
        self.plot.setRange(xRange=(0.0, 1.0), yRange=(0.0, 1.0))

        self.mainArea.layout().addWidget(self.plot)
        self._update_normalize()
Example #48
0
    def __init__(self):
        super().__init__()

        self.data = None  # type: Optional[Table]
        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, "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)

        self.apply_button = gui.auto_commit(self.buttonsArea,
                                            self,
                                            "auto_commit",
                                            "Apply",
                                            box=None,
                                            commit=self.commit)
        gui.rubber(self.controlArea)

        box = gui.vBox(self.mainArea, box="Silhouette Scores")
        self.mainArea.setVisible(self.optimize_k)
        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)
Example #49
0
    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):
        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)
Example #51
0
    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])
Example #52
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # Other attributes...
        self.segmentation = None
        self.operation = "no"
        self.applyInclusion = False
        self.applyExclusion = False
        self.applySampling = True
        self.samplingRate = 100
        self.createdInputs = list()
        self.folderLabels = list()
        self.selectedFolderLabels = list()
        self.rootFolderPath = u''
        self.inclusionsUser = u''
        self.exclusionsUser = u''
        self.newAnnotationKey = u''
        self.newAnnotationValue = u''

        # self.folder is a dictionary whose keys are :'rootPath', 'maxDepth','inclusionsUser','exclusionsUser', ...
        # ... 'samplingRate' and 'fileList'
        self.folder = dict()

        # self.folders is a list of previously defined "self.folder" dictionaries
        self.folders = list()

        # self.inclusionList is the default inclusion list (used in minimal mode, ...
        # ... and in advanced mode when no inclusion has been selected)
        self.inclusionList = [".txt", ".html", ".xml", ".csv", ".rtf"]

        # self.inclusionList is the default null inclusion list (used in minimal mode, ...
        # ... and in advanced mode when no inclusion has been selected)
        self.exclusionList = []

        self.infoBox = InfoBox(widget=self.controlArea)

        self.sendButton = SendButton(
            widget=self.controlArea,
            master=self,
            callback=self.sendData,
            infoBoxAttribute='infoBox',
            sendIfPreCallback=self.updateGUI,
        )
        self.advancedSettings = AdvancedSettings(
            widget=self.controlArea,
            master=self,
            callback=self.sendButton.settingsChanged,
        )

        # GUI...

        # Advanced settings checkbox...
        self.advancedSettings.draw()

        # BASIC GUI...

        # Basic folder box
        basicFolderBox = gui.widgetBox(
            widget=self.controlArea,
            box=u'Source',
            orientation='vertical',
            addSpace=False,
        )
        basicFolderBoxLine1 = gui.widgetBox(
            widget=basicFolderBox,
            box=False,
            orientation='horizontal',
        )
        gui.lineEdit(
            widget=basicFolderBoxLine1,
            master=self,
            value='rootFolderPath',
            orientation='horizontal',
            label=u'Folder path:',
            labelWidth=101,
            callback=self.add,
            tooltip=(u"The path of the folder."),
        )
        gui.separator(widget=basicFolderBoxLine1, width=5)
        gui.button(
            widget=basicFolderBoxLine1,
            master=self,
            label=u'Browse',
            callback=self.browse,
            tooltip=(u"Open a dialog for selecting a top folder."),
        )

        gui.separator(widget=basicFolderBox, width=3)
        self.advancedSettings.basicWidgets.append(basicFolderBox)
        self.advancedSettings.basicWidgetsAppendSeparator()

        # ADVANCED GUI...

        # folder box
        folderBox = gui.widgetBox(
            widget=self.controlArea,
            box=u'Sources',
            orientation='vertical',
            addSpace=False,
        )
        folderBoxLine1 = gui.widgetBox(
            widget=folderBox,
            box=False,
            orientation='horizontal',
            addSpace=True,
        )
        self.folderListbox = gui.listBox(
            widget=folderBoxLine1,
            master=self,
            value='selectedFolderLabels',
            labels='folderLabels',
            callback=self.updatefolderBoxButtons,
            tooltip=(u"The list of folders whose content will be imported.\n"
                     u"\nIn the output segmentation, the content of each\n"
                     u"folder appears in the same position as in the list.\n"
                     u"\nColumn 1 shows the folder's name.\n"
                     u"Column 2 shows the folder's depth.\n"
                     u"Column 3 shows the inclusions filter.\n"
                     u"Column 4 shows the exclusions filter.\n"
                     u"Column 5 shows the folder's level of sampling."),
        )
        font = QFont()
        font.setFamily('Courier')
        font.setStyleHint(QFont.Courier)
        font.setPixelSize(12)
        self.folderListbox.setFont(font)
        folderBoxCol2 = gui.widgetBox(
            widget=folderBoxLine1,
            orientation='vertical',
        )
        self.moveUpButton = gui.button(
            widget=folderBoxCol2,
            master=self,
            label=u'Move Up',
            callback=self.moveUp,
            tooltip=(u"Move the selected folder upward in the list."),
        )
        self.moveDownButton = gui.button(
            widget=folderBoxCol2,
            master=self,
            label=u'Move Down',
            callback=self.moveDown,
            tooltip=(u"Move the selected folder downward in the list."),
        )
        self.removeButton = gui.button(
            widget=folderBoxCol2,
            master=self,
            label=u'Remove',
            callback=self.remove,
            tooltip=(u"Remove the selected folder from the list."),
        )
        self.clearAllButton = gui.button(
            widget=folderBoxCol2,
            master=self,
            label=u'Clear All',
            callback=self.clearAll,
            tooltip=(u"Remove all folders from the list."),
        )
        self.exportButton = gui.button(
            widget=folderBoxCol2,
            master=self,
            label=u'',
            callback=self.exportList,
            disabled=True,
            tooltip=(u"Open a dialog for selecting a folder where the folder\n"
                     u"list can be exported in JSON format."),
        )
        self.importButton = gui.button(
            widget=folderBoxCol2,
            master=self,
            label=u'',
            callback=self.importList,
            disabled=True,
            tooltip=(u"Open a dialog for selecting a folder list to\n"
                     u"import (in JSON format). folders from this list\n"
                     u"will be added to those already imported."),
        )
        folderBoxLine2 = gui.widgetBox(
            widget=folderBox,
            box=False,
            orientation='vertical',
        )
        # Add folder box
        addFolderBox = gui.widgetBox(
            widget=folderBoxLine2,
            box=True,
            orientation='vertical',
        )
        addFolderBoxLine1 = gui.widgetBox(
            widget=addFolderBox,
            orientation='horizontal',
        )
        # Folder path input
        gui.lineEdit(
            widget=addFolderBoxLine1,
            master=self,
            value='rootFolderPath',
            orientation='horizontal',
            label=u'Folder path:',
            labelWidth=101,
            callback=self.updateGUI,
            tooltip=(u"The paths of the folders that will be added to the\n"
                     u"list when button 'Add' is clicked.\n\n"
                     u"Successive paths must be separated with ' / ' \n"
                     u"(whitespace + slash + whitespace). Their order in\n"
                     u"the list will be the same as in this field."),
        )
        gui.separator(widget=addFolderBoxLine1, width=5)
        # Button Browse
        gui.button(
            widget=addFolderBoxLine1,
            master=self,
            label=u'Browse',
            callback=self.browse,
            tooltip=(u"Open a dialog for selecting a top folder.\n\n"
                     u"Selected folder paths will appear in the field to\n"
                     u"the left of this button afterwards, ready to be\n"
                     u"added to the list when button 'Add' is clicked."),
        )
        gui.separator(widget=addFolderBox, width=10)

        # Filter box to input include
        gui.separator(widget=addFolderBox, width=3)
        includeBoxLine1 = gui.widgetBox(
            widget=addFolderBox,
            box=False,
            orientation='horizontal',
        )

        # Include box
        gui.checkBox(
            widget=includeBoxLine1,
            master=self,
            value='applyInclusion',
            label=u'Include',
            labelWidth=100,
            callback=lambda: includeLineEdit.setDisabled(not self.
                                                         applyInclusion),
            tooltip=(u"Choose the inclusion(s)"),
        )
        includeLineEdit = gui.lineEdit(
            widget=includeBoxLine1,
            master=self,
            value='inclusionsUser',
            orientation='horizontal',
            label=u'',
            disabled=True,
            labelWidth=101,
            tooltip=(u"This field lets you specify a custom filter\n"
                     u"to select the folders to be\n"
                     u"added to the list."),
        )

        # Filter box to exclude
        gui.separator(widget=addFolderBox, width=3)
        excludeBoxLine1 = gui.widgetBox(
            widget=addFolderBox,
            box=False,
            orientation='horizontal',
        )
        # Exclude box
        gui.checkBox(
            widget=excludeBoxLine1,
            master=self,
            value='applyExclusion',
            label=u'Exclude',
            labelWidth=100,
            disabled=False,
            callback=lambda: includeLineEdit2.setDisabled(not self.
                                                          applyExclusion),
            tooltip=(u"Exclude the inclusion(s)"),
        )
        includeLineEdit2 = gui.lineEdit(
            widget=excludeBoxLine1,
            master=self,
            value='exclusionsUser',
            orientation='horizontal',
            label=u'',
            disabled=True,
            labelWidth=101,
            tooltip=(u"This field lets you specify a custom filter\n"
                     u"to select the folders to be\n"
                     u"added to the list."),
        )

        # Sampling box to input the level of sampling
        gui.separator(widget=addFolderBox, width=3)
        samplingBoxLine1 = gui.widgetBox(
            widget=addFolderBox,
            box=False,
            orientation='horizontal',
        )
        # Check box for sampling
        gui.checkBox(
            widget=samplingBoxLine1,
            master=self,
            value='applySampling',
            label=u'Sampling',
            labelWidth=100,
            disabled=False,
            callback=lambda: samplingSpin.setDisabled(not self.applySampling),
            tooltip=(u"Choose the sampling level"),
        )

        samplingSpin = gui.spin(
            widget=samplingBoxLine1,
            master=self,
            value='samplingRate',
            minv=10,
            maxv=100,
            labelWidth=50,
            orientation='horizontal',
            tooltip=(u"sampling level"),
        )
        gui.separator(widget=addFolderBox, width=3)
        self.addButton = gui.button(
            widget=addFolderBox,
            master=self,
            label=u'Add',
            callback=self.add,
            tooltip=(u"Add the folder(s) currently displayed in the\n"
                     u"'folders' text field to the list.\n\n"
                     u"Each of these folders will be associated with the\n"
                     u"specified encoding and annotation (if any).\n\n"
                     u"Other folders may be selected afterwards and\n"
                     u"assigned a different encoding and annotation."),
        )
        self.advancedSettings.advancedWidgets.append(folderBox)
        self.advancedSettings.advancedWidgetsAppendSeparator()

        # 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.separator(widget=optionsBox, width=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 folders with increasing numeric indices."),
        )
        self.autoNumberKeyLineEdit = gui.lineEdit(
            widget=optionsBoxLine2,
            master=self,
            value='autoNumberKey',
            orientation='horizontal',
            callback=self.sendButton.settingsChanged,
            tooltip=(u"Annotation key for folder auto-numbering."),
        )
        gui.separator(widget=optionsBox, width=3)
        self.advancedSettings.advancedWidgets.append(optionsBox)
        self.advancedSettings.advancedWidgetsAppendSeparator()

        gui.rubber(self.controlArea)

        # Send button...
        self.sendButton.draw()

        # Info box...
        self.infoBox.draw()

        self.adjustSizeWithTimer()
        QTimer.singleShot(0, self.sendButton.sendIf)
Example #53
0
    def __init__(self):
        super().__init__()
        self.data = None
        self.n_inliers = self.n_outliers = None

        box = gui.widgetBox(self.controlArea, "Information")
        self.data_info_label = gui.widgetLabel(box, self.data_info_default)
        self.in_out_info_label = gui.widgetLabel(box, self.in_out_info_default)

        box = gui.widgetBox(self.controlArea, "Outlier detection method")
        detection = gui.radioButtons(box, self, "outlier_method")

        gui.appendRadioButton(detection,
                              "One class SVM with non-linear kernel (RBF):")
        ibox = gui.indentedBox(detection)
        tooltip = "An upper bound on the fraction of training errors and a " \
                  "lower bound of the fraction of support vectors"
        gui.widgetLabel(ibox, 'Nu:', tooltip=tooltip)
        self.nu_slider = gui.hSlider(ibox,
                                     self,
                                     "nu",
                                     minValue=1,
                                     maxValue=100,
                                     ticks=10,
                                     labelFormat="%d %%",
                                     callback=self.nu_changed,
                                     tooltip=tooltip)
        self.gamma_spin = gui.spin(ibox,
                                   self,
                                   "gamma",
                                   label="Kernel coefficient:",
                                   step=1e-2,
                                   spinType=float,
                                   minv=0,
                                   maxv=10,
                                   callback=self.gamma_changed)
        gui.separator(detection, 12)

        self.rb_cov = gui.appendRadioButton(detection, "Covariance estimator:")
        ibox = gui.indentedBox(detection)
        self.l_cov = gui.widgetLabel(ibox, 'Contamination:')
        self.cont_slider = gui.hSlider(ibox,
                                       self,
                                       "cont",
                                       minValue=0,
                                       maxValue=100,
                                       ticks=10,
                                       labelFormat="%d %%",
                                       callback=self.cont_changed)

        ebox = gui.widgetBox(ibox, box=None, orientation='horizontal')
        self.cb_emp_cov = gui.checkBox(ebox,
                                       self,
                                       "empirical_covariance",
                                       "Support fraction:",
                                       callback=self.empirical_changed)
        self.support_fraction_spin = gui.spin(
            ebox,
            self,
            "support_fraction",
            step=1e-1,
            spinType=float,
            minv=0.1,
            maxv=10,
            callback=self.support_fraction_changed)

        gui.separator(detection, 12)

        gui.button(self.controlArea,
                   self,
                   "Detect Outliers",
                   callback=self.commit)
        self.layout().setSizeConstraint(QtGui.QLayout.SetFixedSize)
Example #54
0
    def __init__(self):
        super().__init__()

        # var models
        self.x_var_model = itemmodels.VariableListModel()
        self.y_var_model = itemmodels.VariableListModel()

        # info box
        self.info_box = gui.widgetBox(self.controlArea, "Info")
        self.learner_label = gui.label(
            widget=self.info_box, master=self, label="")

        # options box
        policy = QSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed)

        self.options_box = gui.widgetBox(self.controlArea, "Data")
        opts = dict(
            widget=self.options_box, master=self, orientation=Qt.Horizontal,
            callback=self.change_attributes, 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.target_class_combobox = gui.comboBox(
            value='target_class', label='Target class: ', **opts)

        self.cbx.setModel(self.x_var_model)
        self.cby.setModel(self.y_var_model)

        gui.separator(self.controlArea, 20, 20)

        # properties box
        self.properties_box = gui.widgetBox(self.controlArea, "Properties")
        self.alpha_spin = gui.spin(
            widget=self.properties_box, master=self, callback=self.change_alpha,
            value="alpha", label="Learning rate: ",
            minv=0.001, maxv=100, step=0.001, spinType=float, decimals=3,
            alignment=Qt.AlignRight, controlWidth=80)
        self.stochastic_checkbox = gui.checkBox(
            widget=self.properties_box, master=self,
            callback=self.change_stochastic, value="stochastic",
            label="Stochastic ")
        self.step_size_spin = gui.spin(
            widget=self.properties_box, master=self, callback=self.change_step,
            value="step_size", label="Step size: ",
            minv=1, maxv=100, step=1, alignment=Qt.AlignRight, controlWidth=80)
        self.restart_button = gui.button(
            widget=self.properties_box, master=self,
            callback=self.restart, label="Restart")

        self.alpha_spin.setSizePolicy(policy)
        self.step_size_spin.setSizePolicy(policy)

        gui.separator(self.controlArea, 20, 20)

        # step box
        self.step_box = gui.widgetBox(self.controlArea, "Manually step through")
        self.step_button = gui.button(
            widget=self.step_box, master=self, callback=self.step, label="Step",
            default=True)
        self.step_back_button = gui.button(
            widget=self.step_box, master=self, callback=self.step_back,
            label="Step back")

        gui.separator(self.controlArea, 20, 20)

        # run box
        self.run_box = gui.widgetBox(self.controlArea, "Run")
        self.auto_play_button = gui.button(
            widget=self.run_box, master=self,
            label=self.auto_play_button_text[0], callback=self.auto_play)
        self.auto_play_speed_spinner = gui.hSlider(
            widget=self.run_box, master=self, value='auto_play_speed',
            minValue=0, maxValue=1.91, step=0.1,
            intOnly=False, createLabel=False, label='Speed:')

        # graph in mainArea
        self.scatter = Scatterplot(click_callback=self.change_theta,
                                   xAxis_gridLineWidth=0,
                                   yAxis_gridLineWidth=0,
                                   title_text='',
                                   tooltip_shared=False,
                                   legend=dict(enabled=False),)

        gui.rubber(self.controlArea)

        # Just render an empty chart so it shows a nice 'No data to display'
        self.scatter.chart()
        self.mainArea.layout().addWidget(self.scatter)

        self.step_size_lock()
        self.step_back_button_lock()
Example #55
0
    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()
Example #56
0
    def __init__(self):
        super().__init__()
        self.scorers = OrderedDict()
        self.out_domain_desc = None
        self.data = None
        self.problem_type_mode = ProblemType.CLASSIFICATION

        if not self.selected_methods:
            self.selected_methods = {
                method.name
                for method in SCORES if method.is_default
            }

        # GUI

        self.ranksModel = model = TableModel(parent=self)  # type: TableModel
        self.ranksView = view = TableView(self)  # type: TableView
        self.mainArea.layout().addWidget(view)
        view.setModel(model)
        view.setColumnWidth(0, 30)
        view.selectionModel().selectionChanged.connect(self.on_select)

        def _set_select_manual():
            self.setSelectionMethod(OWRank.SelectManual)

        view.pressed.connect(_set_select_manual)
        view.verticalHeader().sectionClicked.connect(_set_select_manual)
        view.horizontalHeader().sectionClicked.connect(self.headerClick)

        self.measuresStack = stacked = QStackedWidget(self)
        self.controlArea.layout().addWidget(stacked)

        for scoring_methods in (CLS_SCORES, REG_SCORES, []):
            box = gui.vBox(None,
                           "Scoring Methods" if scoring_methods else None)
            stacked.addWidget(box)
            for method in scoring_methods:
                box.layout().addWidget(
                    QCheckBox(
                        method.name,
                        self,
                        objectName=method.
                        shortname,  # To be easily found in tests
                        checked=method.name in self.selected_methods,
                        stateChanged=partial(self.methodSelectionChanged,
                                             method_name=method.name)))
            gui.rubber(box)

        gui.rubber(self.controlArea)
        self.switchProblemType(ProblemType.CLASSIFICATION)

        selMethBox = gui.vBox(self.controlArea,
                              "Select Attributes",
                              addSpace=True)

        grid = QGridLayout()
        grid.setContentsMargins(6, 0, 6, 0)
        self.selectButtons = QButtonGroup()
        self.selectButtons.buttonClicked[int].connect(self.setSelectionMethod)

        def button(text, buttonid, toolTip=None):
            b = 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=lambda: self.setSelectionMethod(OWRank.SelectNBest))

        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.selectionMethod).setChecked(True)

        selMethBox.layout().addLayout(grid)

        gui.auto_commit(selMethBox, self, "auto_apply", "Send", box=False)

        self.resize(690, 500)
    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()
Example #58
0
    def __init__(self):
        super().__init__()

        self.results = None
        self.classifier_names = []
        self.perf_line = None
        self.colors = []
        self._curve_data = {}
        self._plot_curves = {}
        self._rocch = None
        self._perf_line = None
        self._tooltip_cache = None

        box = gui.vBox(self.controlArea, "Plot")
        self.target_cb = gui.comboBox(box,
                                      self,
                                      "target_index",
                                      label="Target",
                                      orientation=Qt.Horizontal,
                                      callback=self._on_target_changed,
                                      contentsLength=8,
                                      searchable=True)

        gui.widgetLabel(box, "Classifiers")
        line_height = 4 * QFontMetrics(self.font()).lineSpacing()
        self.classifiers_list_box = gui.listBox(
            box,
            self,
            "selected_classifiers",
            "classifier_names",
            selectionMode=QListView.MultiSelection,
            callback=self._on_classifiers_changed,
            sizeHint=QSize(0, line_height))

        abox = gui.vBox(self.controlArea, "Curves")
        gui.comboBox(abox,
                     self,
                     "roc_averaging",
                     items=[
                         "Merge Predictions from Folds", "Mean TP Rate",
                         "Mean TP and FP at Threshold",
                         "Show Individual Curves"
                     ],
                     callback=self._replot)

        gui.checkBox(abox,
                     self,
                     "display_convex_curve",
                     "Show convex ROC curves",
                     callback=self._replot)
        gui.checkBox(abox,
                     self,
                     "display_convex_hull",
                     "Show ROC convex hull",
                     callback=self._replot)

        box = gui.vBox(self.controlArea, "Analysis")

        gui.checkBox(box,
                     self,
                     "display_def_threshold",
                     "Default threshold (0.5) point",
                     callback=self._on_display_def_threshold_changed)

        gui.checkBox(box,
                     self,
                     "display_perf_line",
                     "Show performance line",
                     callback=self._on_display_perf_line_changed)
        grid = QGridLayout()
        gui.indentedBox(box, orientation=grid)

        sp = gui.spin(box,
                      self,
                      "fp_cost",
                      1,
                      1000,
                      10,
                      alignment=Qt.AlignRight,
                      callback=self._on_display_perf_line_changed)
        grid.addWidget(QLabel("FP Cost:"), 0, 0)
        grid.addWidget(sp, 0, 1)

        sp = gui.spin(box,
                      self,
                      "fn_cost",
                      1,
                      1000,
                      10,
                      alignment=Qt.AlignRight,
                      callback=self._on_display_perf_line_changed)
        grid.addWidget(QLabel("FN Cost:"))
        grid.addWidget(sp, 1, 1)
        self.target_prior_sp = gui.spin(box,
                                        self,
                                        "target_prior",
                                        1,
                                        99,
                                        alignment=Qt.AlignRight,
                                        spinType=float,
                                        callback=self._on_target_prior_changed)
        self.target_prior_sp.setSuffix(" %")
        self.target_prior_sp.addAction(QAction("Auto", sp))
        grid.addWidget(QLabel("Prior probability:"))
        grid.addWidget(self.target_prior_sp, 2, 1)

        self.plotview = GraphicsView(background=None)
        self.plotview.setFrameStyle(QFrame.StyledPanel)
        self.plotview.scene().sigMouseMoved.connect(self._on_mouse_moved)

        self.plot = PlotItem(enableMenu=False)
        self.plot.setMouseEnabled(False, False)
        self.plot.hideButtons()

        tickfont = QFont(self.font())
        tickfont.setPixelSize(max(int(tickfont.pixelSize() * 2 // 3), 11))

        axis = self.plot.getAxis("bottom")
        axis.setTickFont(tickfont)
        axis.setLabel("FP Rate (1-Specificity)")
        axis.setGrid(16)

        axis = self.plot.getAxis("left")
        axis.setTickFont(tickfont)
        axis.setLabel("TP Rate (Sensitivity)")
        axis.setGrid(16)

        self.plot.showGrid(True, True, alpha=0.2)
        self.plot.setRange(xRange=(0.0, 1.0), yRange=(0.0, 1.0), padding=0.05)

        self.plotview.setCentralItem(self.plot)
        self.mainArea.layout().addWidget(self.plotview)
Example #59
0
    def __init__(self, parent=None):
        super().__init__(parent)

        self.matrix = None
        self.items = None
        self.linkmatrix = None
        self.root = None
        self._displayed_root = None
        self.cutoff_height = 0.0
        self._invalidated = False

        gui.comboBox(gui.widgetBox(self.controlArea, "Linkage"),
                     self,
                     "linkage",
                     items=LINKAGE,
                     callback=self._invalidate_clustering)

        box = gui.widgetBox(self.controlArea, "Annotation")
        self.label_cb = gui.comboBox(box,
                                     self,
                                     "annotation_idx",
                                     callback=self._update_labels)

        self.label_cb.setModel(itemmodels.VariableListModel())
        self.label_cb.model()[:] = ["None", "Enumeration"]

        box = gui.radioButtons(self.controlArea,
                               self,
                               "pruning",
                               box="Pruning",
                               callback=self._invalidate_pruning)
        grid = QGridLayout()
        box.layout().addLayout(grid)
        grid.addWidget(gui.appendRadioButton(box, "None", addToLayout=False),
                       0, 0)
        self.max_depth_spin = gui.spin(box,
                                       self,
                                       "max_depth",
                                       minv=1,
                                       maxv=100,
                                       callback=self._invalidate_pruning,
                                       keyboardTracking=False)

        grid.addWidget(
            gui.appendRadioButton(box, "Max depth", addToLayout=False), 1, 0)
        grid.addWidget(self.max_depth_spin, 1, 1)

        box = gui.radioButtons(self.controlArea,
                               self,
                               "selection_method",
                               box="Selection",
                               callback=self._selection_method_changed)

        grid = QGridLayout()
        box.layout().addLayout(grid)
        grid.addWidget(gui.appendRadioButton(box, "Manual", addToLayout=False),
                       0, 0)
        grid.addWidget(
            gui.appendRadioButton(box, "Height ratio", addToLayout=False), 1,
            0)
        self.cut_ratio_spin = gui.spin(box,
                                       self,
                                       "cut_ratio",
                                       0,
                                       100,
                                       step=1e-1,
                                       spinType=float,
                                       callback=self._selection_method_changed)
        self.cut_ratio_spin.setSuffix("%")

        grid.addWidget(self.cut_ratio_spin, 1, 1)

        grid.addWidget(gui.appendRadioButton(box, "Top N", addToLayout=False),
                       2, 0)
        self.top_n_spin = gui.spin(box,
                                   self,
                                   "top_n",
                                   1,
                                   20,
                                   callback=self._selection_method_changed)
        grid.addWidget(self.top_n_spin, 2, 1)
        box.layout().addLayout(grid)

        self.controlArea.layout().addStretch()

        box = gui.widgetBox(self.controlArea, "Output")
        gui.checkBox(box,
                     self,
                     "append_clusters",
                     "Append cluster IDs",
                     callback=self._invalidate_output)

        ibox = gui.indentedBox(box)
        name_edit = gui.lineEdit(ibox, self, "cluster_name")
        name_edit.editingFinished.connect(self._invalidate_output)

        cb = gui.comboBox(
            ibox,
            self,
            "cluster_role",
            callback=self._invalidate_output,
            items=["Attribute", "Class variable", "Meta variable"])
        form = QFormLayout(fieldGrowthPolicy=QFormLayout.AllNonFixedFieldsGrow,
                           labelAlignment=Qt.AlignLeft,
                           spacing=8)
        form.addRow("Name", name_edit)
        form.addRow("Place", cb)

        ibox.layout().addSpacing(5)
        ibox.layout().addLayout(form)
        ibox.layout().addSpacing(5)

        cb = gui.checkBox(box, self, "autocommit", "Commit automatically")
        b = gui.button(box, self, "Commit", callback=self.commit, default=True)
        gui.setStopper(self, b, cb, "_invalidated", callback=self.commit)

        self.scene = QGraphicsScene()
        self.view = QGraphicsView(
            self.scene,
            horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOff,
            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn,
            alignment=Qt.AlignLeft | Qt.AlignVCenter)

        def axis_view(orientation):
            ax = pg.AxisItem(orientation=orientation, maxTickLength=7)
            scene = QGraphicsScene()
            scene.addItem(ax)
            view = QGraphicsView(
                scene,
                horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOff,
                verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn,
                alignment=Qt.AlignLeft | Qt.AlignVCenter)
            view.setFixedHeight(ax.size().height())
            ax.line = SliderLine(orientation=Qt.Horizontal,
                                 length=ax.size().height())
            scene.addItem(ax.line)
            return view, ax

        axview, self.top_axis = axis_view("top")
        self.mainArea.layout().setSpacing(1)
        self.mainArea.layout().addWidget(axview)
        self.mainArea.layout().addWidget(self.view)
        axview, self.bottom_axis = axis_view("bottom")
        self.mainArea.layout().addWidget(axview)

        self._main_graphics = QGraphicsWidget()
        self._main_layout = QGraphicsLinearLayout(Qt.Horizontal)
        self._main_layout.setSpacing(1)

        self._main_graphics.setLayout(self._main_layout)
        self.scene.addItem(self._main_graphics)

        self.dendrogram = DendrogramWidget()
        self.dendrogram.setSizePolicy(QSizePolicy.MinimumExpanding,
                                      QSizePolicy.MinimumExpanding)
        self.dendrogram.selectionChanged.connect(self._invalidate_output)
        self.dendrogram.selectionEdited.connect(self._selection_edited)

        fm = self.fontMetrics()
        self.dendrogram.setContentsMargins(5,
                                           fm.lineSpacing() / 2, 5,
                                           fm.lineSpacing() / 2)
        self.labels = GraphicsSimpleTextList()
        self.labels.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        self.labels.setAlignment(Qt.AlignLeft)
        self.labels.setMaximumWidth(200)
        self.labels.layout().setSpacing(0)

        self._main_layout.addItem(self.dendrogram)
        self._main_layout.addItem(self.labels)

        self._main_layout.setAlignment(self.dendrogram,
                                       Qt.AlignLeft | Qt.AlignVCenter)
        self._main_layout.setAlignment(self.labels,
                                       Qt.AlignLeft | Qt.AlignVCenter)

        self.view.viewport().installEventFilter(self)
        self._main_graphics.installEventFilter(self)

        self.cut_line = SliderLine(self.dendrogram, orientation=Qt.Horizontal)
        self.cut_line.valueChanged.connect(self._dendrogram_slider_changed)
        self.cut_line.hide()

        self.bottom_axis.line.valueChanged.connect(self._axis_slider_changed)
        self.top_axis.line.valueChanged.connect(self._axis_slider_changed)
        self.dendrogram.geometryChanged.connect(self._dendrogram_geom_changed)
        self._set_cut_line_visible(self.selection_method == 1)
Example #60
0
    def __init__(self):
        super().__init__()

        self.data = None
        self.km = None
        self.optimization_runs = []

        box = gui.vBox(self.controlArea, "Number of Clusters")
        layout = QGridLayout()
        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", 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)
        gui.auto_commit(self.buttonsArea, self, "auto_run", "Run",
                        "Run on change", box=None)
        gui.rubber(self.controlArea)

        self.table_model = QStandardItemModel(self)
        self.table_model.setHorizontalHeaderLabels(["k", "Score"])
        self.table_model.setColumnCount(2)

        self.table_box = gui.vBox(
            self.mainArea, "Optimization Report", addSpace=0)
        table = self.table_view = QTableView(self.table_box)
        table.setHorizontalScrollMode(QTableView.ScrollPerPixel)
        table.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        table.setSelectionMode(QTableView.SingleSelection)
        table.setSelectionBehavior(QTableView.SelectRows)
        table.verticalHeader().hide()
        table.setItemDelegateForColumn(1, gui.TableBarItem(self))
        table.setModel(self.table_model)
        table.selectionModel().selectionChanged.connect(
            self.table_item_selected)
        table.setColumnWidth(0, 40)
        table.setColumnWidth(1, 120)
        table.horizontalHeader().setStretchLastSection(True)

        self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        self.mainArea.setSizePolicy(QSizePolicy.Maximum,
                                    QSizePolicy.Preferred)
        self.table_box.setSizePolicy(QSizePolicy.Fixed,
                                     QSizePolicy.MinimumExpanding)
        self.table_view.setSizePolicy(QSizePolicy.Preferred,
                                      QSizePolicy.MinimumExpanding)
        self.table_box.layout().addWidget(self.table_view)
        self.hide_show_opt_results()