Beispiel #1
0
    def encode_setting(self, context, setting, value):
        if setting.name != 'conditions':
            return super().encode_settings(context, setting, value)

        encoded = []
        CONTINUOUS = vartype(ContinuousVariable("x"))
        for attr, op, values in value:
            if isinstance(attr, str):
                if OWSelectRows.AllTypes.get(attr) == CONTINUOUS:
                    values = [QLocale().toDouble(v)[0] for v in values]
                # None will match the value returned by all_vars.get
                encoded.append((attr, None, op, values))
            else:
                # check for exact match, pylint: disable=unidiomatic-typecheck
                if type(attr) is ContinuousVariable \
                        and values and isinstance(values[0], str):
                    values = [QLocale().toDouble(v)[0] for v in values]
                elif isinstance(attr, DiscreteVariable):
                    values = [attr.values[i - 1] if i else "" for i in values]
                encoded.append((
                    attr.name,
                    context.attributes.get(attr.name)
                    or context.metas.get(attr.name),
                    op,
                    values
                ))
        return encoded
Beispiel #2
0
        def merge_data_with_predictions():
            data_model = self.dataview.model()
            predictions_view = self.predictionsview
            predictions_model = predictions_view.model()

            # use ItemDelegate to style prediction values
            delegates = [
                predictions_view.itemDelegateForColumn(i)
                for i in range(predictions_model.columnCount())
            ]

            # iterate only over visible columns of data's QTableView
            iter_data_cols = list(
                filter(lambda x: not self.dataview.isColumnHidden(x),
                       range(data_model.columnCount())))

            # print header
            yield [''] + \
                  [predictions_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)
                   for col in range(predictions_model.columnCount())] + \
                  [data_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)
                   for col in iter_data_cols]

            # print data & predictions
            for i in range(data_model.rowCount()):
                yield [data_model.headerData(i, Qt.Vertical, Qt.DisplayRole)] + \
                      [delegate.displayText(
                          predictions_model.data(predictions_model.index(i, j)),
                          QLocale())
                       for j, delegate in enumerate(delegates)] + \
                      [data_model.data(data_model.index(i, j))
                       for j in iter_data_cols]
Beispiel #3
0
 def create_imputer(self, method, *args):
     # type: (Method, ...) -> impute.BaseImputeMethod
     if method == Method.Model:
         if self.learner is not None:
             return impute.Model(self.learner)
         else:
             return impute.Model(self.default_learner)
     elif method == Method.AsAboveSoBelow:
         assert self.default_method_index != Method.AsAboveSoBelow
         default = self.create_imputer(Method(self.default_method_index))
         m = AsDefault()
         m.method = default
         return m
     elif method == Method.Default and not args:  # global default values
         if self.default_numeric == "":
             default_num = np.nan
         else:
             default_num, ok = QLocale().toDouble(self.default_numeric)
             if not ok:
                 default_num = np.nan
         return impute.FixedValueByType(default_continuous=default_num,
                                        default_time=self.default_time
                                        or np.nan)
     else:
         return METHODS[method](*args)
Beispiel #4
0
 def decode_setting(self, setting, value, domain=None, *_args):
     value = super().decode_setting(setting, value, domain)
     if setting.name == 'conditions':
         CONTINUOUS = vartype(ContinuousVariable("x"))
         # Use this after 2022/2/2:
         # for i, (attr, tpe, op, values) in enumerate(value):
         #     if tpe is not None:
         for i, (attr, *tpe, op, values) in enumerate(value):
             if tpe != [None] \
                     or not tpe and attr not in OWSelectRows.AllTypes:
                 attr = domain[attr]
             # check for exact match, pylint: disable=unidiomatic-typecheck
             if type(attr) is ContinuousVariable \
                     or OWSelectRows.AllTypes.get(attr) == CONTINUOUS:
                 values = [
                     QLocale().toString(float(i), 'f') for i in values
                 ]
             elif isinstance(attr, DiscreteVariable):
                 # After 2022/2/2, use just the expression in else clause
                 if values and isinstance(values[0], int):
                     # Backwards compatibility. Reset setting if we detect
                     # that the number of values decreased. Still broken if
                     # they're reordered or we don't detect the decrease.
                     #
                     # indices start with 1, thus >, not >=
                     if max(values) > len(attr.values):
                         values = (0, )
                 else:
                     values = tuple(attr.to_val(val) + 1 if val else 0
                                    for val in values if val in attr.values) \
                              or (0, )
             value[i] = (attr, op, values)
     return value
Beispiel #5
0
 def __init__(self, parent, allow_empty, bottom, top, default_text):
     super().__init__(parent)
     self.allow_empty = allow_empty
     self.default_text = default_text
     self.dv.setLocale(QLocale.c())
     self.setBottom(bottom)
     self.setTop(top)
Beispiel #6
0
 def __init__(self, parent, allow_empty, bottom, top, default_text):
     super().__init__(parent)
     self.allow_empty = allow_empty
     self.default_text = default_text
     self.dv.setLocale(QLocale.c())
     self.setBottom(bottom)
     self.setTop(top)
Beispiel #7
0
 def encode_setting(self, context, setting, value):
     if setting.name == 'conditions':
         CONTINUOUS = vartype(ContinuousVariable())
         for i, (attr, op, values) in enumerate(value):
             if context.attributes.get(attr) == CONTINUOUS:
                 if values and isinstance(values[0], str):
                     values = [QLocale().toDouble(v)[0] for v in values]
                     value[i] = (attr, op, values)
     return super().encode_setting(context, setting, value)
Beispiel #8
0
 def __init__(self, parent, allow_empty=False, bottom=float("-inf"), top=float("inf"),
              default_text=""):
     super().__init__(parent)
     self.dv = QDoubleValidator(parent)
     self.allow_empty = allow_empty
     self.default_text = default_text
     self.dv.setLocale(QLocale.c())
     self.setBottom(bottom)
     self.setTop(top)
Beispiel #9
0
 def decode_setting(self, setting, value, domain=None):
     value = super().decode_setting(setting, value, domain)
     if setting.name == 'conditions':
         for i, (attr, op, values) in enumerate(value):
             var = attr in domain and domain[attr]
             if var and var.is_continuous and not isinstance(var, TimeVariable):
                 value[i] = (attr, op,
                             list([QLocale().toString(float(i), 'f')
                                   for i in values]))
     return value
Beispiel #10
0
    def encode_setting(self, context, setting, value):
        if setting.name != 'conditions':
            return super().encode_settings(context, setting, value)

        encoded = []
        CONTINUOUS = vartype(ContinuousVariable("x"))
        for attr, op, values in value:
            vtype = context.attributes.get(attr)
            if vtype == CONTINUOUS and values and isinstance(values[0], str):
                values = [QLocale().toDouble(v)[0] for v in values]
            encoded.append((attr, vtype, op, values))
        return encoded
Beispiel #11
0
    def decode_setting(self, setting, value, domain=None):
        value = super().decode_setting(setting, value, domain)
        if setting.name == 'conditions':
            # Use this after 2022/2/2:
            # for i, (attr, _, op, values) in enumerate(value):
            for i, condition in enumerate(value):
                attr = condition[0]
                op, values = condition[-2:]

                var = attr in domain and domain[attr]
                if var and var.is_continuous and not isinstance(var, TimeVariable):
                    values = [QLocale().toString(float(i), 'f') for i in values]
                value[i] = (attr, op, values)
        return value
Beispiel #12
0
    def _values_to_floats(self, attr, values):
        if not all(values):
            return None
        if isinstance(attr, TimeVariable):
            parse = lambda x: (attr.parse(x), True)
        else:
            parse = QLocale().toDouble

        try:
            floats, ok = zip(*[parse(v) for v in values])
            if not all(ok):
                raise ValueError('Some values could not be parsed as floats'
                                 'in the current locale: {}'.format(values))
        except TypeError:
            floats = values  # values already floats
        assert all(isinstance(v, float) for v in floats)
        return floats
Beispiel #13
0
    def test_display_text(self):
        delegate = StyledItemDelegate()
        locale = QLocale.c()
        displayText = lambda value: delegate.displayText(value, locale)
        self.assertEqual(displayText(None), "")
        self.assertEqual(displayText(1), "1")
        self.assertEqual(displayText(np.int64(1)), "1")
        self.assertEqual(displayText(np.int64(1)), "1")
        self.assertEqual(displayText(1.5), "1.5")
        self.assertEqual(displayText(np.float16(1.5)), "1.5")
        self.assertEqual(displayText("A"), "A")
        self.assertEqual(displayText(np.str_("A")), "A")

        self.assertEqual(displayText(date(1999, 12, 31)), "1999-12-31")
        self.assertEqual(displayText(datetime(1999, 12, 31, 23, 59, 59)),
                         "1999-12-31 23:59:59")

        self.assertEqual(displayText(np.datetime64(0, "s")),
                         "1970-01-01 00:00:00")
Beispiel #14
0
 def decode_setting(self, setting, value, domain=None, *_args):
     value = super().decode_setting(setting, value, domain)
     if setting.name == 'conditions':
         CONTINUOUS = vartype(ContinuousVariable("x"))
         for i, (attr, tpe, op, values) in enumerate(value):
             if tpe is not None:
                 attr = domain[attr]
             # check for exact match, pylint: disable=unidiomatic-typecheck
             if type(attr) is ContinuousVariable \
                     or OWSelectRows.AllTypes.get(attr) == CONTINUOUS:
                 values = [
                     QLocale().toString(float(i), 'f') for i in values
                 ]
             elif isinstance(attr, DiscreteVariable):
                 values = tuple(
                     attr.to_val(val) + 1 if val else 0
                     for val in values if val in attr.values) or (0, )
             value[i] = (attr, op, values)
     return value
Beispiel #15
0
    def _values_to_floats(attr, values):
        if len(values) == 0:
            return values
        if not all(values):
            return None
        if isinstance(attr, TimeVariable):
            values = (value.toString(format=Qt.ISODate) for value in values)

            def parse(x):
                return (attr.parse(x), True)
        else:
            parse = QLocale().toDouble

        try:
            floats, ok = zip(*[parse(v) for v in values])
            if not all(ok):
                raise ValueError('Some values could not be parsed as floats'
                                 'in the current locale: {}'.format(values))
        except TypeError:
            floats = values  # values already floats
        assert all(isinstance(v, float) for v in floats)
        return floats
Beispiel #16
0
    def test_overall_default(self):
        domain = Domain(
            [ContinuousVariable(f"c{i}") for i in range(3)]
            + [TimeVariable(f"t{i}") for i in range(3)],
            [])
        n = np.nan
        x = np.array([
            [1, 2, n, 1000, n, n],
            [2, n, 1, n, 2000, 2000]
        ])
        data = Table(domain, x, np.empty((2, 0)))

        widget = self.widget
        widget.default_numeric = QLocale().toString(3.14)
        widget.default_time = 42
        widget.default_method_index = Method.Default

        self.send_signal(self.widget.Inputs.data, data)
        imp_data = self.get_output(self.widget.Outputs.data)
        np.testing.assert_almost_equal(
            imp_data.X,
            [[1, 2, 3.14, 1000, 42, 42],
             [2, 3.14, 1, 42, 2000, 2000]]
        )
 def wrap(*args, **kwargs):
     locale = QLocale()
     QLocale.setDefault(QLocale(language))
     result = f(*args, **kwargs)
     QLocale.setDefault(locale)
     return result
Beispiel #18
0
    def __init__(self):
        super().__init__()
        self.data = None  # type: Optional[Orange.data.Table]
        self.learner = None  # type: Optional[Learner]
        self.default_learner = SimpleTreeLearner(min_instances=10,
                                                 max_depth=10)
        self.modified = False
        self.executor = qconcurrent.ThreadExecutor(self)
        self.__task = None

        main_layout = QVBoxLayout()
        main_layout.setContentsMargins(10, 10, 10, 10)
        self.controlArea.layout().addLayout(main_layout)

        box = gui.vBox(None, "Default Method")
        main_layout.addWidget(box)

        box_layout = QGridLayout()
        box_layout.setSpacing(8)
        box.layout().addLayout(box_layout)

        button_group = QButtonGroup()
        button_group.buttonClicked[int].connect(self.set_default_method)

        for i, (method, _) in enumerate(list(METHODS.items())[1:-1]):
            imputer = self.create_imputer(method)
            button = QRadioButton(imputer.name)
            button.setChecked(method == self.default_method_index)
            button_group.addButton(button, method)
            box_layout.addWidget(button, i % 3, i // 3)

        def set_default_time(datetime):
            datetime = datetime.toSecsSinceEpoch()
            if datetime != self.default_time:
                self.default_time = datetime
                if self.default_method_index == Method.Default:
                    self._invalidate()

        hlayout = QHBoxLayout()
        box.layout().addLayout(hlayout)
        button = QRadioButton("Fixed values; numeric variables:")
        button_group.addButton(button, Method.Default)
        button.setChecked(Method.Default == self.default_method_index)
        hlayout.addWidget(button)

        locale = QLocale()
        locale.setNumberOptions(locale.NumberOption.RejectGroupSeparator)
        validator = QDoubleValidator()
        validator.setLocale(locale)
        self.numeric_value_widget = le = gui.lineEdit(
            None,
            self,
            "default_numeric",
            validator=validator,
            alignment=Qt.AlignRight,
            callback=self._invalidate,
            enabled=self.default_method_index == Method.Default)
        hlayout.addWidget(le)

        hlayout.addWidget(QLabel(", time:"))

        self.time_widget = gui.DateTimeEditWCalendarTime(self)
        self.time_widget.setEnabled(
            self.default_method_index == Method.Default)
        self.time_widget.setKeyboardTracking(False)
        self.time_widget.setContentsMargins(0, 0, 0, 0)
        self.time_widget.set_datetime(
            QDateTime.fromSecsSinceEpoch(self.default_time))
        self.connect_control(
            "default_time", lambda value: self.time_widget.set_datetime(
                QDateTime.fromSecsSinceEpoch(value)))
        self.time_widget.dateTimeChanged.connect(set_default_time)
        hlayout.addWidget(self.time_widget)

        self.default_button_group = button_group

        box = QGroupBox(title=self.tr("Individual Attribute Settings"),
                        flat=False)
        main_layout.addWidget(box)

        horizontal_layout = QHBoxLayout(box)
        main_layout.addWidget(box)

        self.varview = ListViewSearch(
            selectionMode=QListView.ExtendedSelection, uniformItemSizes=True)
        self.varview.setItemDelegate(DisplayFormatDelegate())
        self.varmodel = itemmodels.VariableListModel()
        self.varview.setModel(self.varmodel)
        self.varview.selectionModel().selectionChanged.connect(
            self._on_var_selection_changed)
        self.selection = self.varview.selectionModel()

        horizontal_layout.addWidget(self.varview)
        vertical_layout = QVBoxLayout(margin=0)

        self.methods_container = QWidget(enabled=False)
        method_layout = QVBoxLayout(margin=0)
        self.methods_container.setLayout(method_layout)

        button_group = QButtonGroup()
        for method in Method:
            imputer = self.create_imputer(method)
            button = QRadioButton(text=imputer.name)
            button_group.addButton(button, method)
            method_layout.addWidget(button)

        self.value_combo = QComboBox(
            minimumContentsLength=8,
            sizeAdjustPolicy=QComboBox.AdjustToMinimumContentsLength,
            activated=self._on_value_selected)
        self.value_double = QDoubleSpinBox(
            editingFinished=self._on_value_selected,
            minimum=-1000.,
            maximum=1000.,
            singleStep=.1,
            decimals=3,
        )
        self.value_stack = value_stack = QStackedWidget()
        value_stack.addWidget(self.value_combo)
        value_stack.addWidget(self.value_double)
        method_layout.addWidget(value_stack)

        button_group.buttonClicked[int].connect(
            self.set_method_for_current_selection)

        self.reset_button = QPushButton(
            "Restore All to Default",
            enabled=False,
            default=False,
            autoDefault=False,
            clicked=self.reset_variable_state,
        )

        vertical_layout.addWidget(self.methods_container)
        vertical_layout.addStretch(2)
        vertical_layout.addWidget(self.reset_button)

        horizontal_layout.addLayout(vertical_layout)

        self.variable_button_group = button_group

        box = gui.auto_apply(self.controlArea, self, "autocommit")
        box.button.setFixedWidth(180)
        box.layout().insertStretch(0)

        self.info.set_input_summary(self.info.NoInput)
        self.info.set_output_summary(self.info.NoOutput)
Beispiel #19
0
 def __init__(self, parent):
     super().__init__(parent)
     self.dv = QDoubleValidator(parent)
     self.dv.setLocale(QLocale.c())
Beispiel #20
0
 def wrap(*args, **kwargs):
     locale = QLocale()
     QLocale.setDefault(QLocale(language))
     result = f(*args, **kwargs)
     QLocale.setDefault(locale)
     return result
Beispiel #21
0
 def __init__(self, parent):
     super().__init__(parent)
     self.dv = QIntValidator(parent)
     self.dv.setLocale(QLocale.c())